float.TryParse(string, System.Globalization.NumberStyles, System.IFormatProvider, out float)

Here are the examples of the csharp api float.TryParse(string, System.Globalization.NumberStyles, System.IFormatProvider, out float) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

630 Examples 7

19 Source : InternalExtensions.cs
with MIT License
from 2881099

public static object FromObject(this Type targetType, object value, Encoding encoding = null)
    {
        if (targetType == typeof(object)) return value;
        if (encoding == null) encoding = Encoding.UTF8;
        var valueIsNull = value == null;
        var valueType = valueIsNull ? typeof(string) : value.GetType();
        if (valueType == targetType) return value;
        if (valueType == typeof(byte[])) //byte[] -> guid
        {
            if (targetType == typeof(Guid))
            {
                var bytes = value as byte[];
                return Guid.TryParse(BitConverter.ToString(bytes, 0, Math.Min(bytes.Length, 36)).Replace("-", ""), out var tryguid) ? tryguid : Guid.Empty;
            }
            if (targetType == typeof(Guid?))
            {
                var bytes = value as byte[];
                return Guid.TryParse(BitConverter.ToString(bytes, 0, Math.Min(bytes.Length, 36)).Replace("-", ""), out var tryguid) ? (Guid?)tryguid : null;
            }
        }
        if (targetType == typeof(byte[])) //guid -> byte[]
        {
            if (valueIsNull) return null;
            if (valueType == typeof(Guid) || valueType == typeof(Guid?))
            {
                var bytes = new byte[16];
                var guidN = ((Guid)value).ToString("N");
                for (var a = 0; a < guidN.Length; a += 2)
                    bytes[a / 2] = byte.Parse($"{guidN[a]}{guidN[a + 1]}", NumberStyles.HexNumber);
                return bytes;
            }
            return encoding.GetBytes(value.ToInvariantCultureToString());
        }
        else if (targetType.IsArray)
        {
            if (value is Array valueArr)
            {
                var targetElementType = targetType.GetElementType();
                var sourceArrLen = valueArr.Length;
                var target = Array.CreateInstance(targetElementType, sourceArrLen);
                for (var a = 0; a < sourceArrLen; a++) target.SetValue(targetElementType.FromObject(valueArr.GetValue(a), encoding), a);
                return target;
            }
            //if (value is IList valueList)
            //{
            //    var targetElementType = targetType.GetElementType();
            //    var sourceArrLen = valueList.Count;
            //    var target = Array.CreateInstance(targetElementType, sourceArrLen);
            //    for (var a = 0; a < sourceArrLen; a++) target.SetValue(targetElementType.FromObject(valueList[a], encoding), a);
            //    return target;
            //}
        }
        var func = _dicFromObject.GetOrAdd(targetType, tt =>
        {
            if (tt == typeof(object)) return vs => vs;
            if (tt == typeof(string)) return vs => vs;
            if (tt == typeof(char[])) return vs => vs == null ? null : vs.ToCharArray();
            if (tt == typeof(char)) return vs => vs == null ? default(char) : vs.ToCharArray(0, 1).FirstOrDefault();
            if (tt == typeof(bool)) return vs =>
            {
                if (vs == null) return false;
                switch (vs.ToLower())
                {
                    case "true":
                    case "1":
                        return true;
                }
                return false;
            };
            if (tt == typeof(bool?)) return vs =>
            {
                if (vs == null) return false;
                switch (vs.ToLower())
                {
                    case "true":
                    case "1":
                        return true;
                    case "false":
                    case "0":
                        return false;
                }
                return null;
            };
            if (tt == typeof(byte)) return vs => vs == null ? 0 : (byte.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(byte?)) return vs => vs == null ? null : (byte.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (byte?)tryval : null);
            if (tt == typeof(decimal)) return vs => vs == null ? 0 : (decimal.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(decimal?)) return vs => vs == null ? null : (decimal.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (decimal?)tryval : null);
            if (tt == typeof(double)) return vs => vs == null ? 0 : (double.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(double?)) return vs => vs == null ? null : (double.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (double?)tryval : null);
            if (tt == typeof(float)) return vs => vs == null ? 0 : (float.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(float?)) return vs => vs == null ? null : (float.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (float?)tryval : null);
            if (tt == typeof(int)) return vs => vs == null ? 0 : (int.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(int?)) return vs => vs == null ? null : (int.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (int?)tryval : null);
            if (tt == typeof(long)) return vs => vs == null ? 0 : (long.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(long?)) return vs => vs == null ? null : (long.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (long?)tryval : null);
            if (tt == typeof(sbyte)) return vs => vs == null ? 0 : (sbyte.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(sbyte?)) return vs => vs == null ? null : (sbyte.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (sbyte?)tryval : null);
            if (tt == typeof(short)) return vs => vs == null ? 0 : (short.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(short?)) return vs => vs == null ? null : (short.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (short?)tryval : null);
            if (tt == typeof(uint)) return vs => vs == null ? 0 : (uint.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(uint?)) return vs => vs == null ? null : (uint.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (uint?)tryval : null);
            if (tt == typeof(ulong)) return vs => vs == null ? 0 : (ulong.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(ulong?)) return vs => vs == null ? null : (ulong.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (ulong?)tryval : null);
            if (tt == typeof(ushort)) return vs => vs == null ? 0 : (ushort.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(ushort?)) return vs => vs == null ? null : (ushort.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (ushort?)tryval : null);
            if (tt == typeof(DateTime)) return vs => vs == null ? DateTime.MinValue : (DateTime.TryParse(vs, out var tryval) ? tryval : DateTime.MinValue);
            if (tt == typeof(DateTime?)) return vs => vs == null ? null : (DateTime.TryParse(vs, out var tryval) ? (DateTime?)tryval : null);
            if (tt == typeof(DateTimeOffset)) return vs => vs == null ? DateTimeOffset.MinValue : (DateTimeOffset.TryParse(vs, out var tryval) ? tryval : DateTimeOffset.MinValue);
            if (tt == typeof(DateTimeOffset?)) return vs => vs == null ? null : (DateTimeOffset.TryParse(vs, out var tryval) ? (DateTimeOffset?)tryval : null);
            if (tt == typeof(TimeSpan)) return vs => vs == null ? TimeSpan.Zero : (TimeSpan.TryParse(vs, out var tryval) ? tryval : TimeSpan.Zero);
            if (tt == typeof(TimeSpan?)) return vs => vs == null ? null : (TimeSpan.TryParse(vs, out var tryval) ? (TimeSpan?)tryval : null);
            if (tt == typeof(Guid)) return vs => vs == null ? Guid.Empty : (Guid.TryParse(vs, out var tryval) ? tryval : Guid.Empty);
            if (tt == typeof(Guid?)) return vs => vs == null ? null : (Guid.TryParse(vs, out var tryval) ? (Guid?)tryval : null);
            if (tt == typeof(BigInteger)) return vs => vs == null ? 0 : (BigInteger.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(BigInteger?)) return vs => vs == null ? null : (BigInteger.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (BigInteger?)tryval : null);
            if (tt.NullableTypeOrThis().IsEnum)
            {
                var tttype = tt.NullableTypeOrThis();
                var ttdefval = tt.CreateInstanceGetDefaultValue();
                return vs =>
                {
                    if (string.IsNullOrWhiteSpace(vs)) return ttdefval;
                    return Enum.Parse(tttype, vs, true);
                };
            }
            var localTargetType = targetType;
            var localValueType = valueType;
            return vs =>
            {
                if (vs == null) return null;
                throw new NotSupportedException($"convert failed {localValueType.DisplayCsharp()} -> {localTargetType.DisplayCsharp()}");
            };
        });
        var valueStr = valueIsNull ? null : (valueType == typeof(byte[]) ? encoding.GetString(value as byte[]) : value.ToInvariantCultureToString());
        return func(valueStr);
    }

19 Source : Half.cs
with MIT License
from 91Act

public static bool TryParse(string value, NumberStyles style, IFormatProvider provider, out Half result)
        {
            bool parseResult = false;
            float f;
            if (float.TryParse(value, style, provider, out f))
            {
                result = (Half)f;
                parseResult = true;
            }
            else
            {
                result = new Half();
            }

            return parseResult;
        }

19 Source : MicroVM.Assembler.cs
with MIT License
from a-downing

bool Tokenize() {       
            for(int i = 0; i < statements.Count; i++) {
                var statement = statements[i];

                for(int j = 0; j < statement.line.Length; j++) {
                    string arg = statement.line[j];

                    statement.tokens[j].offset = 0;
                    statement.tokens[j].type = Token.Type.NONE;

                    Match directiveMatch = directiveRegex.Match(arg);
                    Match labelMatch = labelRegex.Match(arg);
                    Match identifierMatch = identifierRegex.Match(arg);
                    Match instructionMatch = instructionRegex.Match(arg);
                    Match floatMatch = floatRegex.Match(arg);

                    if(directiveMatch.Success) {
                        statement.tokens[j].type = Token.Type.DIRECTIVE;
                        statement.tokens[j].stringValue = directiveMatch.Groups[1].ToString();
                    } else if(labelMatch.Success) {
                        statement.tokens[j].type = Token.Type.LABEL;
                        statement.tokens[j].stringValue = labelMatch.Groups[1].ToString();
                    } else if(identifierMatch.Success) {
                        statement.tokens[j].type = (j == 0) ? Token.Type.INSTRUCTION : Token.Type.IDENTIFIER;
                        statement.tokens[j].stringValue = identifierMatch.Groups[0].ToString();

                        if(statement.tokens[j].type == Token.Type.INSTRUCTION) {
                            statement.tokens[j].cond = "al";
                        }
                    } else if(instructionMatch.Success) {
                        statement.tokens[j].type = Token.Type.INSTRUCTION;
                        statement.tokens[j].stringValue = instructionMatch.Groups[1].ToString();
                        statement.tokens[j].cond = instructionMatch.Groups[2].ToString();
                    } else if(floatMatch.Success && floatMatch.Groups[0].ToString() != ".") {
                        statement.tokens[j].type = Token.Type.FLOAT;
                        statement.tokens[j].stringValue = floatMatch.Groups[0].ToString();
                        float.TryParse(statement.tokens[j].stringValue, out statement.tokens[j].var.val32.Float);
                        statement.tokens[j].var.type = Variable.Type.FLOAT;
                    } else if(TryParseIntegerLiteral(arg, out statement.tokens[j].var.val32.Int)) {
                        statement.tokens[j].type = Token.Type.INTEGER;
                        statement.tokens[j].stringValue = arg;
                        statement.tokens[j].var.type = Variable.Type.INT;
                    }
                }
            }

            return true;
        }

19 Source : ProCamsLensDataTable.cs
with Apache License 2.0
from A7ocin

public void LoadLensData()
	{
		_filmFormats = new List<FilmFormatData>();
		
		// Load in the data from Resources/CinemaSuite_LensData.txt
		Textreplacedet textreplacedet = (Textreplacedet)(Resources.Load("CinemaSuite_LensData", typeof(Textreplacedet)));
		if(textreplacedet == null)
		{
			Debug.LogError("File 'CinemaSuite_LensData.txt' is not found in Resources folder. Unable to load lens data.");
			return;
		}
		
		FilmFormatData currentFormat = null;
		
		string[] lines = textreplacedet.text.Split("\n"[0]);
		int numLines = lines.Length;
		for(int i = 0; i < numLines; ++i)
		{
			//Debug.Log("Line: " + i + "= " + lines[i]);
			
			string line = lines[i].Trim();
			if(line.StartsWith("#"))
			{
				continue;	
			}
			
			int length = line.Length;
			
			if(currentFormat == null)
			{
				// Look for "Name="
				if(line.StartsWith("Name="))
				{
					// New section

					int index = line.IndexOf("=") + 1;
					if(index < length)
					{
						string name = line.Substring(index).Trim();
						if(name.Length != 0)
						{
							// Create new film format with valid name
							currentFormat = new FilmFormatData();
							currentFormat._formatName = name;
						}
					}
				}
				else if(length != 0)
				{
					Debug.LogError("Invalid data at line: " + i);
				}
			}
			else
			{
				// Look for film format section entries
				
				if(length == 0)
				{
					// End of section
					_filmFormats.Add(currentFormat);
					//Debug.Log ("Added film format " + currentFormat._formatName);
					currentFormat = null;
				}
				else if(line.StartsWith("Aspect="))
				{
					int index = line.IndexOf("=") + 1;
					if(index < length)
					{
						string strAspect = line.Substring(index).Trim();
						int colon = strAspect.IndexOf(":");
						if(colon > 0 && colon < length)
						{
							string first = strAspect.Substring(0, colon).Trim();
							string second = strAspect.Substring(colon + 1).Trim();
							float w = 0;
							float h = 0;
							
							if(!float.TryParse(first, System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out w) || w <= 0)
							{
								Debug.LogError("Invalid number: " + first + " at line " + (i + 1));
								return;
							}
							if(!float.TryParse(second, System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out h) || h <= 0)
							{
								Debug.LogError("Invalid number: " + second + " at line " + (i + 1));
								return;
							}
							currentFormat._aspect = w / h;
							//Debug.Log ("Aspect: " + currentFormat._aspect);
						}
					}
				}
				else if(line.StartsWith("ScreenSize"))
				{
					int index = line.IndexOf("=") + 1;
					if(index < length)
					{
						// ScreenSize=DI,1024
						string[] strSizes = line.Substring(index).Split(","[0]);
						if(strSizes == null || strSizes.Length != 2)
						{
							Debug.LogError("Invalid screen size entry at line " + (i + 1));
							return;
						}
						
						string sizeName = strSizes[0].Trim();
						int sizeValue = 0;
						if(!int.TryParse(strSizes[1].Trim(), System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out sizeValue) || sizeValue <= 0)
						{
							Debug.LogError("Invalid screen size at line " + (i + 1));
							return;
						}
						currentFormat._screenSizes.Add(new ScreenSize(sizeName, sizeValue));
						//Debug.Log ("Screensize: " + sizeName + ", " + sizeValue);
					}
				}
				else if(line.StartsWith("FocalLength"))
				{
					int index = line.IndexOf("=") + 1;
					if(index < length)
					{
						// FocalLength=Cooke S4/i - T2,12mm,4.980,00.000,00.000
						string[] strData = line.Substring(index).Split(","[0]);
						if(strData == null || strData.Length != 5)
						{
							Debug.LogError("Invalid data for focal length at line " + (i + 1));
							return;
						}
						
						string lensKit = strData[0].Trim();
						if(lensKit.Length == 0)
						{
							Debug.LogError("Invalid lens kit name at line " + (i + 1));
							return;
						}
						
						int focal = 0;
						if(!int.TryParse(strData[1].TrimEnd('m'), System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out focal) || focal <= 0)
						{
							Debug.LogError("Invalid focal length at line " + (i + 1));
							return;
						}
						
						float nodal = 0;
						if(!float.TryParse(strData[2].Trim(), System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out nodal) || nodal < 0)
						{
							Debug.LogError("Invalid nodal offset at line " + (i + 1));
							return;
						}
						
						float realFOV = 0;
						if(!float.TryParse(strData[3].Trim(), System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out realFOV) || realFOV <= 0)
						{
							Debug.LogError("Invalid real FOV at line " + (i + 1));
							return;
						}
						
						float unityFOV = 0;
						if(!float.TryParse(strData[4].Trim(), System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out unityFOV) || unityFOV <= 0)
						{
							Debug.LogError("Invalid Unity FOV at line " + (i + 1));
							return;
						}
						
						currentFormat.AddFocalLengthData(lensKit, focal, nodal, realFOV, unityFOV);
						//Debug.Log ("Focal Data: " + lensKit + ", " + focal + ", " + nodal + ", " + realFOV + ", " + unityFOV);
					}
				}
			}
		}
	}

19 Source : PackageManifestUpdater.cs
with Apache License 2.0
from abist-co-ltd

internal static bool TryGetVersionComponents(
            string packageVersion,
            out Version version,
            out float prerelease)
        {
            char[] trimChars = new char[] { ' ', '\"', ',' };

            // Note: The version is in the following format Major.Minor.Revision[-Date.Build]

            // Attempt to split the version string into version and float components
            string[] versionComponents = packageVersion.Split(new char[] { '-' }, 2);

            // Parse the version component.
            string versionString = versionComponents[0].Trim(trimChars);
            if (Version.TryParse(versionString, out version))
            {
                if (versionComponents.Length == 2)
                {
                    // Parse the float component
                    string prereleaseString = versionComponents[1].Trim(trimChars);
                    if (float.TryParse(prereleaseString, NumberStyles.AllowDecimalPoint, NumberFormatInfo.InvariantInfo, out prerelease))
                    {
                        return true;
                    }
                }
                else
                {
                    prerelease = 0f;
                    return true;
                }
            }

            version = null;
            prerelease = float.NaN;
            return false;
        }

19 Source : FormMain.cs
with MIT License
from Abneed

private void toolStripComboBoxTamanoFuente_SelectedIndexChanged(object sender, EventArgs e)
        {
            float NuevoTamano;

            float.TryParse(toolStripComboBoxTamanoFuente.SelectedItem.ToString(), out NuevoTamano);

            Font NuevaFuente = new Font(ObtenerDoreplacedentoActual.SelectionFont.Name, NuevoTamano,
                ObtenerDoreplacedentoActual.SelectionFont.Style);

            this.m_fontFamiliaFuenteSeleccionada = NuevaFuente;
            ObtenerDoreplacedentoActual.SelectionFont = NuevaFuente;
        }

19 Source : MutationCache.cs
with GNU Affero General Public License v3.0
from ACEmulator

private static EffectArgument ParseEffectArgument(string filename, Effect effect, string operand)
        {
            var effectArgument = new EffectArgument();

            effectArgument.Type = GetEffectArgumentType(effect, operand);

            switch (effectArgument.Type)
            {
                case EffectArgumentType.Int:

                    if (!int.TryParse(operand, out effectArgument.IntVal))
                    {
                        if (effect.Quality != null && effect.Quality.StatType == StatType.Int && effect.Quality.StatIdx == (int)PropertyInt.ImbuedEffect && Enum.TryParse(operand, out ImbuedEffectType imbuedEffectType))
                            effectArgument.IntVal = (int)imbuedEffectType;
                        else if (Enum.TryParse(operand, out WieldRequirement wieldRequirement))
                            effectArgument.IntVal = (int)wieldRequirement;
                        else if (Enum.TryParse(operand, out Skill skill))
                            effectArgument.IntVal = (int)skill;
                        else
                            log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse IntVal {operand}");
                    }
                    break;

                case EffectArgumentType.Int64:

                    if (!long.TryParse(operand, out effectArgument.LongVal))
                    {
                        log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse Int64Val {operand}");
                    }
                    break;

                case EffectArgumentType.Double:

                    if (!double.TryParse(operand, out effectArgument.DoubleVal))
                    {
                        log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse DoubleVal {operand}");
                    }
                    break;

                case EffectArgumentType.Quality:

                    effectArgument.StatType = GetStatType(operand);

                    switch (effectArgument.StatType)
                    {
                        case StatType.Int:

                            if (Enum.TryParse(operand, out PropertyInt propInt))
                                effectArgument.StatIdx = (int)propInt;
                            else
                                log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse PropertyInt.{operand}");
                            break;

                        case StatType.Int64:

                            if (Enum.TryParse(operand, out PropertyInt64 propInt64))
                                effectArgument.StatIdx = (int)propInt64;
                            else
                                log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse PropertyInt64.{operand}");
                            break;

                        case StatType.Float:

                            if (Enum.TryParse(operand, out PropertyFloat propFloat))
                                effectArgument.StatIdx = (int)propFloat;
                            else
                                log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse PropertyFloat.{operand}");
                            break;

                        case StatType.Bool:

                            if (Enum.TryParse(operand, out PropertyBool propBool))
                                effectArgument.StatIdx = (int)propBool;
                            else
                                log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse PropertyBool.{operand}");
                            break;

                        case StatType.DataID:

                            if (Enum.TryParse(operand, out PropertyDataId propDID))
                                effectArgument.StatIdx = (int)propDID;
                            else
                                log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse PropertyBool.{operand}");
                            break;

                        default:
                            log.Error($"MutationCache.BuildMutation({filename}) - unknown PropertyType.{operand}");
                            break;
                    }
                    break;

                case EffectArgumentType.Random:

                    var match = Regex.Match(operand, @"Random\(([\d.-]+), ([\d.-]+)\)");

                    if (!match.Success || !float.TryParse(match.Groups[1].Value, out effectArgument.MinVal) || !float.TryParse(match.Groups[2].Value, out effectArgument.MaxVal))
                        log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse {operand}");

                    break;

                case EffectArgumentType.Variable:

                    match = Regex.Match(operand, @"\[(\d+)\]");

                    if (!match.Success || !int.TryParse(match.Groups[1].Value, out effectArgument.IntVal))
                        log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse {operand}");

                    break;

                default:
                    log.Error($"MutationCache.BuildMutation({filename}) - unknown EffectArgumentType from {operand}");
                    break;
            }
            return effectArgument;
        }

19 Source : IntComponent.xaml.cs
with MIT License
from ADeltaX

private void TxBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            switch (_dataType)
            {
                case DataTypeEnum.RegUwpByte:
                    if (byte.TryParse(txBox.Text, out _))
                        FlagDataAsValid();
                    else
                        FlagDataAsInvalid();
                    break;
                case DataTypeEnum.RegUwpInt16:
                    if (Int16.TryParse(txBox.Text, out _))
                        FlagDataAsValid();
                    else
                        FlagDataAsInvalid();
                    break;
                case DataTypeEnum.RegUwpUint16:
                    if (UInt16.TryParse(txBox.Text, out _))
                        FlagDataAsValid();
                    else
                        FlagDataAsInvalid();
                    break;
                case DataTypeEnum.RegUwpInt32:
                    if (Int32.TryParse(txBox.Text, out _))
                        FlagDataAsValid();
                    else
                        FlagDataAsInvalid();
                    break;
                case DataTypeEnum.RegUwpUint32:
                    if (UInt32.TryParse(txBox.Text, out _))
                        FlagDataAsValid();
                    else
                        FlagDataAsInvalid();
                    break;
                case DataTypeEnum.RegUwpInt64:
                    if (Int64.TryParse(txBox.Text, out _))
                        FlagDataAsValid();
                    else
                        FlagDataAsInvalid();
                    break;
                case DataTypeEnum.RegUwpUint64:
                    if (UInt64.TryParse(txBox.Text, out _))
                        FlagDataAsValid();
                    else
                        FlagDataAsInvalid();
                    break;
                case DataTypeEnum.RegUwpSingle:
                    if (Single.TryParse(txBox.Text, out _))
                        FlagDataAsValid();
                    else
                        FlagDataAsInvalid();
                    break;
                case DataTypeEnum.RegUwpDouble:
                    if (Double.TryParse(txBox.Text, out _))
                        FlagDataAsValid();
                    else
                        FlagDataAsInvalid();
                    break;
                default:
                    break;
            }
        }

19 Source : GUI.cs
with GNU General Public License v3.0
from aelariane

public static void TextField(Rect position, Setting<float> val, string label, float offset)
        {
            if (offset > 0f)
            {
                UGUI.Label(position, label, Style.Label);
                position.x += offset;
                position.width -= offset;
            }
            if (!floats.ContainsKey(val))
            {
                floats.Add(val, val.Value.ToString());
            }

            string text = floats[val];
            text = UGUI.TextField(position, text, Style.TextField);
            float.TryParse(text, out val.Value);
            floats[val] = text;
        }

19 Source : GUI.cs
with GNU General Public License v3.0
from aelariane

public static void TextField(SmartRect position, Setting<float> val, string label, float offset, bool move = false)
        {
            if (offset > 0f)
            {
                UGUI.Label(position.ToRect(), label, Style.Label);
                position.MoveOffsetX(offset);
            }
            if (!floats.ContainsKey(val))
            {
                floats.Add(val, val.Value.ToString());
            }

            string text = floats[val];
            text = UGUI.TextField(position.ToRect(), text, Style.TextField);
            float.TryParse(text, out val.Value);
            floats[val] = text;
            position.ResetX();
            if (move)
            {
                position.MoveY();
            }
        }

19 Source : GUILayout.cs
with GNU General Public License v3.0
from aelariane

public static void TextField(Setting<float> val)
        {
            if (!setFloats.ContainsKey(val))
            {
                setFloats.Add(val, val.Value.ToString());
            }

            string text = setFloats[val];
            text = UGUI.TextField(text, Style.TextField, DefaultOption);
            float.TryParse(text, out val.Value);
            setFloats[val] = text;
        }

19 Source : GUILayout.cs
with GNU General Public License v3.0
from aelariane

public static void TextField(Setting<float> val, GUILayoutOption[] opts)
        {
            if (!setFloats.ContainsKey(val))
            {
                setFloats.Add(val, val.Value.ToString());
            }

            string text = setFloats[val];
            text = UGUI.TextField(text, Style.TextField, opts);
            float.TryParse(text, out val.Value);
            setFloats[val] = text;
        }

19 Source : ObjLoader.MaterialLibrary.cs
with The Unlicense
from aeroson

void Parse(ref string str, ref float t)
			{
				if (!float.TryParse(str, System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo, out t))
					failedParse++;
			}

19 Source : ObjLoader.cs
with The Unlicense
from aeroson

void Parse(ref string str, ref float t)
        {
            if (!float.TryParse(str, System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo, out t))
                failedParse++;
        }

19 Source : NumericConverters.cs
with MIT License
from Aiko-IT-Systems

Task<Optional<float>> IArgumentConverter<float>.ConvertAsync(string value, CommandContext ctx)
        {
            return float.TryParse(value, NumberStyles.Number, CultureInfo.InvariantCulture, out var result)
                ? Task.FromResult(Optional.FromValue(result))
                : Task.FromResult(Optional.FromNoValue<float>());
        }

19 Source : SteamVR_Menu.cs
with MIT License
from ajayyy

void OnGUI()
	{
		if (overlay == null)
			return;

		var texture = overlay.texture as RenderTexture;

		var prevActive = RenderTexture.active;
		RenderTexture.active = texture;

		if (Event.current.type == EventType.Repaint)
			GL.Clear(false, true, Color.clear);

		var area = new Rect(0, 0, texture.width, texture.height);

		// Account for screen smaller than texture (since mouse position gets clamped)
		if (Screen.width < texture.width)
		{
			area.width = Screen.width;
			overlay.uvOffset.x = -(float)(texture.width - Screen.width) / (2 * texture.width);
		}
		if (Screen.height < texture.height)
		{
			area.height = Screen.height;
			overlay.uvOffset.y = (float)(texture.height - Screen.height) / (2 * texture.height);
		}

		GUILayout.BeginArea(area);

		if (background != null)
		{
			GUI.DrawTexture(new Rect(
				(area.width - background.width) / 2,
				(area.height - background.height) / 2,
				background.width, background.height), background);
		}

		GUILayout.BeginHorizontal();
		GUILayout.FlexibleSpace();
		GUILayout.BeginVertical();

		if (logo != null)
		{
			GUILayout.Space(area.height / 2 - logoHeight);
			GUILayout.Box(logo);
		}

		GUILayout.Space(menuOffset);

		bool bHideMenu = GUILayout.Button("[Esc] - Close menu");

		GUILayout.BeginHorizontal();
		GUILayout.Label(string.Format("Scale: {0:N4}", scale));
		{
			var result = GUILayout.HorizontalSlider(scale, scaleLimits.x, scaleLimits.y);
			if (result != scale)
			{
				SetScale(result);
			}
		}
		GUILayout.EndHorizontal();

		GUILayout.BeginHorizontal();
		GUILayout.Label(string.Format("Scale limits:"));
		{
			var result = GUILayout.TextField(scaleLimitX);
			if (result != scaleLimitX)
			{
				if (float.TryParse(result, out scaleLimits.x))
					scaleLimitX = result;
			}
		}
		{
			var result = GUILayout.TextField(scaleLimitY);
			if (result != scaleLimitY)
			{
				if (float.TryParse(result, out scaleLimits.y))
					scaleLimitY = result;
			}
		}
		GUILayout.EndHorizontal();

		GUILayout.BeginHorizontal();
		GUILayout.Label(string.Format("Scale rate:"));
		{
			var result = GUILayout.TextField(scaleRateText);
			if (result != scaleRateText)
			{
				if (float.TryParse(result, out scaleRate))
					scaleRateText = result;
			}
		}
		GUILayout.EndHorizontal();

		if (SteamVR.active)
		{
			var vr = SteamVR.instance;

			GUILayout.BeginHorizontal();
			{
				var t = SteamVR_Camera.sceneResolutionScale;
				int w = (int)(vr.sceneWidth * t);
				int h = (int)(vr.sceneHeight * t);
				int pct = (int)(100.0f * t);
				GUILayout.Label(string.Format("Scene quality: {0}x{1} ({2}%)", w, h, pct));
				var result = Mathf.RoundToInt(GUILayout.HorizontalSlider(pct, 50, 200));
				if (result != pct)
				{
					SteamVR_Camera.sceneResolutionScale = (float)result / 100.0f;
				}
			}
			GUILayout.EndHorizontal();
		}

		overlay.highquality = GUILayout.Toggle(overlay.highquality, "High quality");

		if (overlay.highquality)
		{
			overlay.curved = GUILayout.Toggle(overlay.curved, "Curved overlay");
			overlay.antialias = GUILayout.Toggle(overlay.antialias, "Overlay RGSS(2x2)");
		}
		else
		{
			overlay.curved = false;
			overlay.antialias = false;
		}

		var tracker = SteamVR_Render.Top();
		if (tracker != null)
		{
			tracker.wireframe = GUILayout.Toggle(tracker.wireframe, "Wireframe");

			var render = SteamVR_Render.instance;
			if (render.trackingSpace == ETrackingUniverseOrigin.TrackingUniverseSeated)
			{
				if (GUILayout.Button("Switch to Standing"))
					render.trackingSpace = ETrackingUniverseOrigin.TrackingUniverseStanding;
				if (GUILayout.Button("Center View"))
				{
					var system = OpenVR.System;
					if (system != null)
						system.ResetSeatedZeroPose();
				}
			}
			else
			{
				if (GUILayout.Button("Switch to Seated"))
					render.trackingSpace = ETrackingUniverseOrigin.TrackingUniverseSeated;
			}
		}

#if !UNITY_EDITOR
		if (GUILayout.Button("Exit"))
			Application.Quit();
#endif
		GUILayout.Space(menuOffset);

		var env = System.Environment.GetEnvironmentVariable("VR_OVERRIDE");
		if (env != null)
		{
			GUILayout.Label("VR_OVERRIDE=" + env);
		}

		GUILayout.Label("Graphics device: " + SystemInfo.graphicsDeviceVersion);

		GUILayout.EndVertical();
		GUILayout.FlexibleSpace();
		GUILayout.EndHorizontal();

		GUILayout.EndArea();

		if (cursor != null)
		{
			float x = Input.mousePosition.x, y = Screen.height - Input.mousePosition.y;
			float w = cursor.width, h = cursor.height;
			GUI.DrawTexture(new Rect(x, y, w, h), cursor);
		}

		RenderTexture.active = prevActive;

		if (bHideMenu)
			HideMenu();
	}

19 Source : LocationLogReader.cs
with MIT License
from alen-smajic

public IEnumerator<Location> GetLocations()
		{

			while (true)
			{
				string line = string.Empty;

				while (1 == 1)
				{
					line = _textReader.ReadLine();
					// rewind if end of log (or last empty line) reached
					if (null == line || string.IsNullOrEmpty(line))
					{
						((StreamReader)_textReader).BaseStream.Position = 0;
						((StreamReader)_textReader).DiscardBufferedData();
						continue;
					}

					// skip comments
					if (line.StartsWith("#")) { continue; } else { break; }
				}

				string[] tokens = line.Split(Delimiter.ToCharArray());
				//simple safety net: check if number of columns matches
				if (tokens.Length != HeaderNames.Length)
				{
					Debug.LogError("unsupported log file");
					yield return new Location();
				}

				Location location = new Location();

				location.IsLocationServiceEnabled = bool.Parse(tokens[(int)LogfileColumns.LocationServiceEnabled]);
				location.IsLocationServiceInitializing = bool.Parse(tokens[(int)LogfileColumns.LocationServiceInitializing]);
				location.IsLocationUpdated = bool.Parse(tokens[(int)LogfileColumns.LocationUpdated]);
				location.IsUserHeadingUpdated = bool.Parse(tokens[(int)LogfileColumns.UserHeadingUpdated]);
				location.Provider = tokens[(int)LogfileColumns.LocationProvider];
				location.ProviderClreplaced = tokens[(int)LogfileColumns.LocationProviderClreplaced];

				DateTime dtDevice;
				string dtDeviceTxt = tokens[(int)LogfileColumns.UtcTimeDevice];
				if (DateTime.TryParseExact(dtDeviceTxt, "yyyyMMdd-HHmmss.fff", _invariantCulture, DateTimeStyles.replacedumeUniversal, out dtDevice))
				{
					location.TimestampDevice = UnixTimestampUtils.To(dtDevice);
				}

				DateTime dtLocation;
				string dtLocationTxt = tokens[(int)LogfileColumns.UtcTimeOfLocation];
				if (DateTime.TryParseExact(dtLocationTxt, "yyyyMMdd-HHmmss.fff", _invariantCulture, DateTimeStyles.replacedumeUniversal, out dtLocation))
				{
					location.Timestamp = UnixTimestampUtils.To(dtLocation);
				}

				double lat;
				string latTxt = tokens[(int)LogfileColumns.Lareplacedude];
				double lng;
				string lngTxt = tokens[(int)LogfileColumns.Longitude];
				if (
					!double.TryParse(latTxt, NumberStyles.Any, _invariantCulture, out lat)
					|| !double.TryParse(lngTxt, NumberStyles.Any, _invariantCulture, out lng)
				)
				{
					location.LareplacedudeLongitude = Vector2d.zero;
				}
				else
				{
					location.LareplacedudeLongitude = new Vector2d(lat, lng);
				}


				float accuracy;
				location.Accuracy = float.TryParse(tokens[(int)LogfileColumns.Accuracy], NumberStyles.Any, _invariantCulture, out accuracy) ? accuracy : 0;
				float userHeading;
				location.UserHeading = float.TryParse(tokens[(int)LogfileColumns.UserHeading], NumberStyles.Any, _invariantCulture, out userHeading) ? userHeading : 0;
				float deviceOrientation;
				location.DeviceOrientation = float.TryParse(tokens[(int)LogfileColumns.DeviceOrientation], NumberStyles.Any, _invariantCulture, out deviceOrientation) ? deviceOrientation : 0;
				float speed;
				location.SpeedMetersPerSecond = float.TryParse(tokens[(int)LogfileColumns.Speed], NumberStyles.Any, _invariantCulture, out speed) ? speed / 3.6f : (float?)null;
				bool hasGpsFix;
				location.HasGpsFix = bool.TryParse(tokens[(int)LogfileColumns.HasGpsFix], out hasGpsFix) ? hasGpsFix : (bool?)null;
				int satellitesUsed;
				location.SatellitesUsed = int.TryParse(tokens[(int)LogfileColumns.SatellitesUsed], out satellitesUsed) ? satellitesUsed : (int?)null;
				int satellitesInView;
				location.SatellitesInView = int.TryParse(tokens[(int)LogfileColumns.SatellitesInView], out satellitesInView) ? satellitesInView : (int?)null;

				yield return location;
			}
		}

19 Source : LightDataTableShared.cs
with MIT License
from AlenToma

protected void TypeValidation(ref object value, Type dataType, bool loadDefaultOnError, object defaultValue = null)
        {
            try
            {
                ValidateCulture();
                if (value == null || value is DBNull)
                {
                    value = ValueByType(dataType, defaultValue);
                    return;
                }

                if (IgnoreTypeValidation)
                    return;

                if (dataType == typeof(byte[]) && value.GetType() == typeof(string))
                {
                    if (value.ToString().Length % 4 == 0) // its a valid base64string
                        value = Convert.FromBase64String(value.ToString());
                    return;
                }

                if (dataType == typeof(int?) || dataType == typeof(int))
                {
                    if (double.TryParse(CleanValue(dataType, value).ToString(), NumberStyles.Float, Culture, out var douTal))
                        value = Convert.ToInt32(douTal);
                    else
                        if (loadDefaultOnError)
                        value = ValueByType(dataType, defaultValue);

                    return;
                }

                if (dataType == typeof(long?) || dataType == typeof(long))
                {
                    if (double.TryParse(CleanValue(dataType, value).ToString(), NumberStyles.Float, Culture, out var douTal))
                        value = Convert.ToInt64(douTal);
                    else
                    if (loadDefaultOnError)
                        value = ValueByType(dataType, defaultValue);

                    return;
                }

                if (dataType == typeof(float?) || dataType == typeof(float))
                {
                    if (float.TryParse(CleanValue(dataType, value).ToString(), NumberStyles.Float, Culture, out var douTal))
                        value = RoundingSettings.Round(douTal);
                    else
                    if (loadDefaultOnError)
                        value = ValueByType(dataType, defaultValue);

                    return;
                }

                if (dataType == typeof(decimal?) || dataType == typeof(decimal))
                {
                    if (decimal.TryParse(CleanValue(dataType, value).ToString(), NumberStyles.Float, Culture, out var decTal))
                        value = RoundingSettings.Round(decTal);
                    else
                    if (loadDefaultOnError)
                        value = ValueByType(dataType, defaultValue);
                    return;

                }

                if (dataType == typeof(double?) || dataType == typeof(double))
                {
                    if (double.TryParse(CleanValue(dataType, value).ToString(), NumberStyles.Float, Culture, out var douTal))
                        value = RoundingSettings.Round(douTal);
                    else
                    if (loadDefaultOnError)
                        value = ValueByType(dataType, defaultValue);
                    return;

                }

                if (dataType == typeof(DateTime?) || dataType == typeof(DateTime))
                {
                    if (DateTime.TryParse(value.ToString(), Culture, DateTimeStyles.None, out var dateValue))
                    {
                        if (dateValue < SqlDateTime.MinValue)
                            dateValue = SqlDateTime.MinValue.Value;
                        value = dateValue;

                    }
                    else
                    if (loadDefaultOnError)
                        value = ValueByType(dataType, defaultValue);
                    return;

                }

                if (dataType == typeof(bool?) || dataType == typeof(bool))
                {
                    if (bool.TryParse(value.ToString(), out var boolValue))
                        value = boolValue;
                    else
                    if (loadDefaultOnError)
                        value = ValueByType(dataType, defaultValue);
                    return;
                }

                if (dataType == typeof(TimeSpan?) || dataType == typeof(TimeSpan))
                {
                    if (TimeSpan.TryParse(value.ToString(), Culture, out var timeSpanValue))
                        value = timeSpanValue;
                    else
                    if (loadDefaultOnError)
                        value = ValueByType(dataType, defaultValue);
                    return;


                }

                if (dataType.IsEnum || (dataType.GenericTypeArguments?.FirstOrDefault()?.IsEnum ?? false))
                {

                    var type = dataType;
                    if ((dataType.GenericTypeArguments?.FirstOrDefault()?.IsEnum ?? false))
                        type = (dataType.GenericTypeArguments?.FirstOrDefault());
                    if (value is int || value is long)
                    {
                        if (Enum.IsDefined(type, Convert.ToInt32(value)))
                            value = Enum.ToObject(type, Convert.ToInt32(value));
                    }
                    else if (Enum.IsDefined(type, value))
                        value = Enum.Parse(type, value.ToString(), true);
                    else if (loadDefaultOnError)
                        value = Activator.CreateInstance(dataType);
                }
                else if (dataType == typeof(Guid) || dataType == typeof(Guid?))
                {
                    if (Guid.TryParse(value.ToString(), out Guid v))
                        value = v;
                    else if (loadDefaultOnError)
                        value = ValueByType(dataType, defaultValue);
                } else if (dataType == typeof(string))
                {
                    value = value.ToString();

                }


            }
            catch (Exception ex)
            {
                throw new Exception($"Error: InvalidType. ColumnType is {dataType.FullName} and the given value is of type {value.GetType().FullName} Original Exception {ex.Message}");

            }
        }

19 Source : ParameterValidator.cs
with MIT License
from AlexanderFroemmgen

public static bool IsValid(ParameterType type, string value)
        {
            if (type == ParameterType.Int)
            {
                int _;
                return int.TryParse(value, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out _);
            }

            if (type == ParameterType.Float)
            {
                float _;
                return float.TryParse(value, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out _);
            }

            if (type == ParameterType.String)
            {
                return true;
            }

            throw new ArgumentException("Invalid parameter type.");
        }

19 Source : ParseUtils.cs
with MIT License
from AlexanderFroemmgen

public static object ParseToClosestPossibleValueType(string value)
        {
            int maybeIntValue;
            if (int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out maybeIntValue))
            {
                return maybeIntValue;
            }

            float maybeFloatValue;
            if (float.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out maybeFloatValue))
            {
                return maybeFloatValue;
            }

            return value;
        }

19 Source : PersistentSettings.cs
with MIT License
from AlexGyver

public float GetValue(string name, float value) {
      string str;
      if (settings.TryGetValue(name, out str)) {
        float parsedValue;
        if (float.TryParse(str, NumberStyles.Float, 
          CultureInfo.InvariantCulture, out parsedValue))
          return parsedValue;
        else
          return value;
      } else {
        return value;
      }
    }

19 Source : MeasuredDuration.cs
with MIT License
from AlFasGD

public static bool TryParse(string s, out MeasuredDuration duration)
        {
            duration = default;
            var split = s.Split(':');
            if (!int.TryParse(split[0], NumberStyles.Integer, CultureInfo.InvariantCulture, out int measures))
                return false;
            if (!float.TryParse(split[1], NumberStyles.Float, CultureInfo.InvariantCulture, out float fraction))
                return false;
            int beats = (int)fraction;
            fraction -= beats;
            duration = new MeasuredDuration(measures, beats, fraction);
            return true;
        }

19 Source : MeasuredTimePosition.cs
with MIT License
from AlFasGD

public static bool TryParse(string s, out MeasuredTimePosition timePosition)
        {
            timePosition = default;
            var split = s.Split(':');
            if (!int.TryParse(split[0], NumberStyles.Integer, CultureInfo.InvariantCulture, out int measure))
                return false;
            if (!float.TryParse(split[1], NumberStyles.Float, CultureInfo.InvariantCulture, out float fraction))
                return false;
            int beat = (int)fraction;
            fraction -= beat;
            timePosition = new MeasuredTimePosition(measure, beat, fraction);
            return true;
        }

19 Source : Lexer.cs
with MIT License
from Alprog

public IEnumerator<Token> Tokenize(string line)
        {
            var token = new Token(TokenType.Invalid, 0, line.Length);
            int i = 0;
            while (i < line.Length)
            {
                var c = line[i];
                if (Char.IsWhiteSpace(c))
                {
                    // WhiteSpace
                    i++;
                    continue;
                }
                else if (Char.IsLetter(c) || c.Equals('_'))
                {
                    // Identifier or Keyword
                    int si = i; i++;
                    while (i < line.Length)
                    {
                        c = line[i];
                        if (Char.IsLetterOrDigit(c) || c.Equals('_'))
                        {
                            i++;
                        }
                        else
                        {
                            break;
                        }
                    }
                    var tokenText = line.Substring(si, i - si);
                    if (tokenText.ToLower() == "true")
                    {
                        token = ValueToken(si, i - si, true);
                    }
                    else if (tokenText.ToLower() == "false")
                    {
                        token = ValueToken(si, i - si, false);
                    }
                    else if (tokenText.ToLower() == "null")
                    {
                        token = ValueToken(si, i - si, null);
                    }
                    else
                    {
                        if (i < line.Length && line[i].Equals('…'))
                        {
                            token = new Token(TokenType.Autocomplete, si, i - si, tokenText);
                            i++;
                        }
                        else
                        {
                            token = new Token(TokenType.Identifier, si, i - si, tokenText);
                        }
                    }
                }
                else if (c.Equals('\"'))
                {
                    // String
                    int si = i; i++;
                    bool ended = false;
                    while (i < line.Length)
                    {
                        c = line[i];
                        if (!c.Equals('\"'))
                        {
                            i++;
                        }
                        else
                        {
                            ended = true;
                            i++;
                            break;
                        }
                    }
                    if (ended)
                    {
                        var text = line.Substring(si + 1, i - si - 2);
                        token = ValueToken(si, i - si, text);
                    }
                    else
                    {
                        token = new Token(TokenType.Invalid, si, i - si);
                    }
                }
                else if (Char.IsDigit(c) || c.Equals('-'))
                {
                    // Minus or digit
                    if (c.Equals('-'))
                    {
                        if (token.Type == TokenType.Value ||
                            token.Type == TokenType.Identifier ||
                            token.Type == TokenType.ClosedBracket)
                        {
                            // force minus operator
                            i++;
                            token = new Token(TokenType.Operator, i, 1, Operator.Get("-"));
                            yield return token;
                            continue;
                        }
                    }

                    int si = i; i++;
                    while (i < line.Length)
                    {
                        c = line[i];
                        if (Char.IsDigit(c) || c.Equals('.'))
                        {
                            i++;
                        }
                        else
                        {
                            break;
                        }
                    }
                    var tokenText = line.Substring(si, i - si);
                    if (tokenText == "-")
                    {
                        token = new Token(TokenType.Operator, si, i - si, Operator.Get(tokenText));
                        i++;
                    }
                    else
                    {
                        float number;
                        if (Single.TryParse(tokenText, NumberStyles.Any, CultureInfo.InvariantCulture, out number))
                        {
                            token = ValueToken(si, i - si, number);
                        }
                        else
                        {
                            token = new Token(TokenType.Invalid, si, i - si);
                        }
                    }
                }
                else if (operators.Contains(c.ToString()))
                {
                    // Operator
                    int si = i; i++;
                    while (i < line.Length)
                    {
                        c = line[i];
                        if (operators.Contains(c.ToString()))
                        {
                            i++;
                        }
                        else
                        {
                            break;
                        }
                    }
                    var tokenText = line.Substring(si, i - si);
                    if (tokenText == "=")
                    {
                        token = new Token(TokenType.replacedignmentOperator, si, i - si);
                    }
                    else
                    {
                        token = new Token(TokenType.Operator, si, i - si, Operator.Get(tokenText));
                    }
                }
                else if (c.Equals('.'))
                {
                    token = new Token(TokenType.Dot, i, 1);
                    i++;
                }
                else if (c.Equals('('))
                {
                    token = new Token(TokenType.OpenBracket, i, 1);
                    i++;
                }
                else if (c.Equals(')'))
                {
                    token = new Token(TokenType.ClosedBracket, i, 1);
                    i++;
                }
                else if (c.Equals(','))
                {
                    token = new Token(TokenType.Comma, i, 1);
                    i++;
                }
                else if (c.Equals('…'))
                {
                    token = new Token(TokenType.Autocomplete, i, 1, String.Empty);
                    i++;
                }
                else
                {
                    token = new Token(TokenType.Invalid, i, 1);
                    i++;
                }

                yield return token;
            }

            yield return new Token(TokenType.EndOfLine, i, 0);
        }

19 Source : VectorReader.cs
with MIT License
from altimesh

private static void ReadData(string[] lineSplitted, out float data)
        {
            if (!Single.TryParse(lineSplitted[0], NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out data))
            {
                throw new ApplicationException("invalid line");
            }
        }

19 Source : SparseMatrixReader.cs
with MIT License
from altimesh

private static void ReadData(string[] lineSplitted, out uint row, out uint col, out float data)
        {
            if (!UInt32.TryParse(lineSplitted[0], out row))
            {
                throw new ApplicationException("invalid line");
            }
            if (!UInt32.TryParse(lineSplitted[1], out col))
            {
                throw new ApplicationException("invalid line");
            }
            if (!Single.TryParse(lineSplitted[2], NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out data))
            {
                throw new ApplicationException("invalid line");
            }
        }

19 Source : SparseMatrixReader.cs
with MIT License
from altimesh

private static void ReadData(string[] lineSplitted, out int row, out int col, out float data)
        {
            if (!Int32.TryParse(lineSplitted[0], out row))
            {
                throw new ApplicationException("invalid line");
            }
            if (!Int32.TryParse(lineSplitted[1], out col))
            {
                throw new ApplicationException("invalid line");
            }
            if (!Single.TryParse(lineSplitted[2], NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out data))
            {
                throw new ApplicationException("invalid line");
            }
        }

19 Source : ModInputMenu.cs
with MIT License
from amazingalek

private bool OnValidateNumber() =>
			float.TryParse(_inputMenu.GetInputText(), out _);

19 Source : InstanceRef.cs
with GNU General Public License v3.0
from Amebis

public void ReadXml(XmlReader reader)
        {
            string v;

            Base = (v = reader[nameof(Base)]) != null ? new Uri(v) : null;
            Popularity = (v = reader[nameof(Popularity)]) != null && float.TryParse(v, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out var v_popularity) ? Popularity = v_popularity : 1.0f;

            if (reader.IsEmptyElement)
                return;

            while (reader.Read() &&
                !(reader.NodeType == XmlNodeType.EndElement && reader.LocalName == GetType().Name))
            {
                if (reader.NodeType == XmlNodeType.Element && reader.Name == nameof(ProfileRefList))
                {
                    if (reader["Key"] == nameof(Profiles))
                    {
                        Profiles = new ProfileRefList();
                        Profiles.ReadXml(reader);
                    }
                }
            }
        }

19 Source : ProfileRef.cs
with GNU General Public License v3.0
from Amebis

public void ReadXml(XmlReader reader)
        {
            string v;

            Id = reader[nameof(Id)];
            DisplayName = !string.IsNullOrWhiteSpace(v = reader[nameof(DisplayName)]) ? v : null;
            Popularity = (v = reader[nameof(Popularity)]) != null && float.TryParse(v, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out var v_popularity) ? Popularity = v_popularity : 1.0f;
        }

19 Source : Tools.cs
with MIT License
from AmigoCap

public static float ParseField_f(UnityEngine.UI.InputField field, float ifEmpty = 0f) {
            if (field.text == "")
                return ifEmpty;
            if (float.TryParse(field.text.Replace(',', '.'), System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out float result))
                return result;
            return field.text[0] == '-' ? float.MinValue : float.MaxValue;
        }

19 Source : FastPointChart.cs
with MIT License
from AngeloCresta

virtual public void Paint( 
			ChartGraphics graph, 
			CommonElements common, 
			ChartArea area, 
			Series seriesToDraw )
		{	
			this.Common = common;
			this.Graph = graph;
			if(area.Area3DStyle.Enable3D)
			{
				// Initialize variables
				this.chartArea3DEnabled = true;
				matrix3D = area.matrix3D;
			}
			else
			{
				this.chartArea3DEnabled = false;
			}
			
			//************************************************************
			//** Loop through all series
			//************************************************************
			foreach( Series series in common.DataManager.Series )
			{
				// Process non empty series of the area with FastPoint chart type
				if( String.Compare( series.ChartTypeName, this.Name, true, System.Globalization.CultureInfo.CurrentCulture ) != 0 
					|| series.ChartArea != area.Name || 
					!series.IsVisible())
				{
					continue;
				}

				// Get 3D series depth and Z position
				if(this.chartArea3DEnabled)
				{
					float seriesDepth;
					area.GetSeriesZPositionAndDepth(series, out seriesDepth, out this.seriesZCoordinate);
					this.seriesZCoordinate += seriesDepth/2.0f;
				}

				// Set active horizontal/vertical axis
				Axis hAxis = area.GetAxis(AxisName.X, series.XAxisType, (area.Area3DStyle.Enable3D) ? string.Empty : series.XSubAxisName);
				Axis vAxis = area.GetAxis(AxisName.Y, series.YAxisType, (area.Area3DStyle.Enable3D) ? string.Empty : series.YSubAxisName);
				double hAxisMin = hAxis.ViewMinimum;
				double hAxisMax = hAxis.ViewMaximum;
				double vAxisMin = vAxis.ViewMinimum;
				double vAxisMax = vAxis.ViewMaximum;

				// Get "PermittedPixelError" attribute.
				// By default use 1/3 of the marker size.
				float	permittedPixelError = series.MarkerSize / 3f;
                if (series.IsCustomPropertySet(CustomPropertyName.PermittedPixelError))
				{
                    string attrValue = series[CustomPropertyName.PermittedPixelError];

                    float pixelError;
                    bool parseSucceed = float.TryParse(attrValue, NumberStyles.Any, CultureInfo.CurrentCulture, out pixelError);

                    if (parseSucceed)
                    {
                        permittedPixelError = pixelError;
                    }
                    else
                    {
                        throw (new InvalidOperationException(SR.ExceptionCustomAttributeValueInvalid2("PermittedPixelError")));
                    }

                    // "PermittedPixelError" attribute value should be in range from zero to 1
                    if (permittedPixelError < 0f || permittedPixelError > 1f)
                    {
                        throw (new InvalidOperationException(SR.ExceptionCustomAttributeIsNotInRange0to1("PermittedPixelError")));
                    }
				}

				// Get pixel size in axes coordinates
				SizeF pixelSize = graph.GetRelativeSize(new SizeF(permittedPixelError, permittedPixelError));
				SizeF axesMin = graph.GetRelativeSize(new SizeF((float)hAxisMin, (float)vAxisMin));
				double axesValuesPixelSizeX = Math.Abs(hAxis.PositionToValue(axesMin.Width + pixelSize.Width, false) - hAxis.PositionToValue(axesMin.Width, false));
				double axesValuesPixelSizeY = Math.Abs(vAxis.PositionToValue(axesMin.Height + pixelSize.Height, false) - vAxis.PositionToValue(axesMin.Height, false));

				// Create point marker brush
				SolidBrush	markerBrush = new SolidBrush( ((series.MarkerColor.IsEmpty) ? series.Color : series.MarkerColor) );
				SolidBrush	emptyMarkerBrush = new SolidBrush( ((series.EmptyPointStyle.MarkerColor.IsEmpty) ? series.EmptyPointStyle.Color : series.EmptyPointStyle.MarkerColor) );

				// Create point marker border pen
				Pen	borderPen = null;
				Pen	emptyBorderPen = null;
				if(!series.MarkerBorderColor.IsEmpty && series.MarkerBorderWidth > 0)
				{
					borderPen = new Pen(series.MarkerBorderColor, series.MarkerBorderWidth);
				}
				if(!series.EmptyPointStyle.MarkerBorderColor.IsEmpty && series.EmptyPointStyle.MarkerBorderWidth > 0)
				{
					emptyBorderPen = new Pen(series.EmptyPointStyle.MarkerBorderColor, series.EmptyPointStyle.MarkerBorderWidth);
				}

				// Check if series is indexed
				bool indexedSeries = ChartHelper.IndexedSeries(this.Common, series.Name );

                // Get marker size taking in consideration current DPIs
                int markerSize = series.MarkerSize;
                if (graph != null && graph.Graphics != null)
                {
                    // Marker size is in pixels and we do the mapping for higher DPIs
                    markerSize = (int)Math.Max(markerSize * graph.Graphics.DpiX / 96, markerSize * graph.Graphics.DpiY / 96);
                }

				// Loop through all ponts in the series
				int		index = 0;
				double	xValue = 0.0;
				double	yValue = 0.0;
				double	xValuePrev = 0.0;
				double	yValuePrev = 0.0;
				PointF	currentPoint = PointF.Empty;
				bool	currentPointIsEmpty = false;
				double	xPixelConverter = (graph.Common.ChartPicture.Width - 1.0) / 100.0;
				double	yPixelConverter = (graph.Common.ChartPicture.Height - 1.0) / 100.0;
				MarkerStyle	markerStyle = series.MarkerStyle;
				MarkerStyle	emptyMarkerStyle = series.EmptyPointStyle.MarkerStyle;
				foreach( DataPoint point in series.Points )
				{
					// Get point X and Y values
					xValue = (indexedSeries) ? index + 1 : point.XValue;
					xValue = hAxis.GetLogValue(xValue);
					yValue = vAxis.GetLogValue(point.YValues[0]);
					currentPointIsEmpty = point.IsEmpty;

					// Check if point is completly out of the data scaleView
					if( xValue < hAxisMin ||
						xValue > hAxisMax ||
						yValue < vAxisMin ||
						yValue > vAxisMax )
					{
						xValuePrev = xValue;
						yValuePrev = yValue;
						++index;
						continue;
					}

					// Check if point may be skipped
					if(index > 0)
					{
						// Check if current point location is in the specified distance from the 
						// preious data location.
						if(Math.Abs(xValue - xValuePrev) < axesValuesPixelSizeX &&
							Math.Abs(yValue - yValuePrev) < axesValuesPixelSizeY)
						{
							// Increase counter and proceed to the next data point
							++index;
							continue;
						}
					}

					// Get point pixel position
					currentPoint.X = (float)
						(hAxis.GetLinearPosition( xValue ) * xPixelConverter);
					currentPoint.Y = (float)
						(vAxis.GetLinearPosition( yValue ) * yPixelConverter);

					// Draw point marker
                    MarkerStyle	currentMarkerStyle = (currentPointIsEmpty) ? emptyMarkerStyle : markerStyle;
                    if(currentMarkerStyle != MarkerStyle.None)
                    {
					    this.DrawMarker(
						    graph,
						    point,
						    index,
						    currentPoint,
                            currentMarkerStyle,
						    markerSize,
						    (currentPointIsEmpty) ? emptyMarkerBrush : markerBrush,
						    (currentPointIsEmpty) ? emptyBorderPen : borderPen);
                    }

					// Remember last point coordinates
					xValuePrev = xValue;
					yValuePrev = yValue;
					++index;
				}

				// Dispose used brushes and pens
				markerBrush.Dispose();
				emptyMarkerBrush.Dispose();
				if(borderPen != null)
				{
					borderPen.Dispose();
				}
				if(emptyBorderPen != null)
				{
					emptyBorderPen.Dispose();
				}
			}
		}

19 Source : FastLineChart.cs
with MIT License
from AngeloCresta

virtual public void Paint( 
			ChartGraphics graph, 
			CommonElements common, 
			ChartArea area, 
			Series seriesToDraw )
		{	
			this.Common = common;
			this.Graph = graph;
			bool	clipRegionSet = false;
			if(area.Area3DStyle.Enable3D)
			{
				// Initialize variables
				this.chartArea3DEnabled = true;
				matrix3D = area.matrix3D;
			}
			else
			{
				this.chartArea3DEnabled = false;
			}
			
			//************************************************************
			//** Loop through all series
			//************************************************************
			foreach( Series series in common.DataManager.Series )
			{
				// Process non empty series of the area with FastLine chart type
				if( String.Compare( series.ChartTypeName, this.Name, true, System.Globalization.CultureInfo.CurrentCulture ) != 0 
					|| series.ChartArea != area.Name || 
					!series.IsVisible())
				{
					continue;
				}

				// Get 3D series depth and Z position
				if(this.chartArea3DEnabled)
				{
					float seriesDepth;
					area.GetSeriesZPositionAndDepth(series, out seriesDepth, out seriesZCoordinate);
					this.seriesZCoordinate += seriesDepth/2.0f;
				}

				// Set active horizontal/vertical axis
				Axis hAxis = area.GetAxis(AxisName.X, series.XAxisType, (area.Area3DStyle.Enable3D) ? string.Empty : series.XSubAxisName);
				Axis vAxis = area.GetAxis(AxisName.Y, series.YAxisType, (area.Area3DStyle.Enable3D) ? string.Empty : series.YSubAxisName);
				double hAxisMin = hAxis.ViewMinimum;
				double hAxisMax = hAxis.ViewMaximum;
				double vAxisMin = vAxis.ViewMinimum;
				double vAxisMax = vAxis.ViewMaximum;

				// Get "PermittedPixelError" attribute
				float	permittedPixelError = 1.0f;
                if (series.IsCustomPropertySet(CustomPropertyName.PermittedPixelError))
                {
                    string attrValue = series[CustomPropertyName.PermittedPixelError];

                    float pixelError;
                    bool parseSucceed = float.TryParse(attrValue, NumberStyles.Any, CultureInfo.CurrentCulture, out pixelError);

                    if (parseSucceed)
                    {
                        permittedPixelError = pixelError;
                    }
                    else
                    {
                        throw (new InvalidOperationException(SR.ExceptionCustomAttributeValueInvalid2("PermittedPixelError")));
                    }

                    // "PermittedPixelError" attribute value should be in range from zero to 1
                    if (permittedPixelError < 0f || permittedPixelError > 1f)
                    {
                        throw (new InvalidOperationException(SR.ExceptionCustomAttributeIsNotInRange0to1("PermittedPixelError")));
                    }
                }

				// Get pixel size in axes coordinates
				SizeF pixelSize = graph.GetRelativeSize(new SizeF(permittedPixelError, permittedPixelError));
				SizeF axesMin = graph.GetRelativeSize(new SizeF((float)hAxisMin, (float)vAxisMin));
				double axesValuesPixelSizeX = Math.Abs(hAxis.PositionToValue(axesMin.Width + pixelSize.Width, false) - hAxis.PositionToValue(axesMin.Width, false));

				// Create line pen
				Pen	linePen = new Pen(series.Color, series.BorderWidth);
				linePen.DashStyle = graph.GetPenStyle( series.BorderDashStyle );
				linePen.StartCap = LineCap.Round;
				linePen.EndCap = LineCap.Round;

				// Create empty line pen
				Pen	emptyLinePen = new Pen(series.EmptyPointStyle.Color, series.EmptyPointStyle.BorderWidth);
				emptyLinePen.DashStyle = graph.GetPenStyle( series.EmptyPointStyle.BorderDashStyle );
				emptyLinePen.StartCap = LineCap.Round;
				emptyLinePen.EndCap = LineCap.Round;

				// Check if series is indexed
				bool indexedSeries = ChartHelper.IndexedSeries(this.Common, series.Name );

				// Loop through all ponts in the series
				int		index = 0;
				double	yValueRangeMin = double.NaN;
				double	yValueRangeMax = double.NaN;
				DataPoint pointRangeMin = null;
				DataPoint pointRangeMax = null;
				double	xValue = 0;
				double	yValue = 0;
				double	xValuePrev = 0;
				double	yValuePrev = 0;
				DataPoint prevDataPoint = null;
				PointF	lastVerticalSegmentPoint = PointF.Empty;
				PointF	prevPoint = PointF.Empty;
				PointF	currentPoint = PointF.Empty;
				bool	prevPointInAxesCoordinates = false;
				bool	verticalLineDetected = false;
				bool	prevPointIsEmpty = false;
				bool	currentPointIsEmpty = false;
                bool    firstNonEmptyPoint = false;
				double	xPixelConverter = (graph.Common.ChartPicture.Width - 1.0) / 100.0;
				double	yPixelConverter = (graph.Common.ChartPicture.Height - 1.0) / 100.0;
				foreach( DataPoint point in series.Points )
				{
					// Get point X and Y values
					xValue = (indexedSeries) ? index + 1 : point.XValue;
					xValue = hAxis.GetLogValue(xValue);
					yValue = vAxis.GetLogValue(point.YValues[0]);
					currentPointIsEmpty = point.IsEmpty;

                    // NOTE: Fixes issue #7094
                    // If current point is non-empty but the previous one was, 
                    // use empty point style properties to draw it.
                    if (prevPointIsEmpty && !currentPointIsEmpty && !firstNonEmptyPoint)
                    {
                        firstNonEmptyPoint = true;
                        currentPointIsEmpty = true;
                    }
                    else
                    {
                        firstNonEmptyPoint = false;
                    }

					// Check if line is completly out of the data scaleView
					if( !verticalLineDetected &&
						((xValue < hAxisMin && xValuePrev < hAxisMin) ||
						(xValue > hAxisMax && xValuePrev > hAxisMax) ||
						(yValue < vAxisMin && yValuePrev < vAxisMin) ||
						(yValue > vAxisMax && yValuePrev > vAxisMax) ))
					{
						xValuePrev = xValue;
						yValuePrev = yValue;
						prevPointInAxesCoordinates = true;
						++index;
						continue;
					}
					else if(!clipRegionSet)
					{
						// Check if line is partialy in the data scaleView
						if(xValuePrev < hAxisMin || xValuePrev > hAxisMax || 
							xValue > hAxisMax || xValue < hAxisMin ||
							yValuePrev < vAxisMin || yValuePrev > vAxisMax ||
							yValue < vAxisMin || yValue > vAxisMax )
						{
							// Set clipping region for line drawing 
							graph.SetClip( area.PlotAreaPosition.ToRectangleF() );
							clipRegionSet = true;
						}
					}

					// Check if point may be skipped
					if(index > 0 &&
						currentPointIsEmpty == prevPointIsEmpty)
					{
						// Check if points X value in acceptable error boundary
						if( Math.Abs(xValue - xValuePrev) < axesValuesPixelSizeX)
						{
							if(!verticalLineDetected)
							{
								verticalLineDetected = true;
								if(yValue > yValuePrev)
								{
									yValueRangeMax = yValue;
									yValueRangeMin = yValuePrev;
									pointRangeMax = point;
									pointRangeMin = prevDataPoint;
								}
								else
								{
									yValueRangeMax = yValuePrev;
									yValueRangeMin = yValue;
									pointRangeMax = prevDataPoint;
									pointRangeMin = point;
								}

								// NOTE: Prev. version code - A.G.
//								yValueRangeMin = Math.Min(yValue, yValuePrev);
//								yValueRangeMax = Math.Max(yValue, yValuePrev);
							}
							else
							{
								if(yValue > yValueRangeMax)
								{
									yValueRangeMax = yValue;
									pointRangeMax = point;
								}

								else if(yValue < yValueRangeMin)
								{
									yValueRangeMin = yValue;
									pointRangeMin = point;
								}

								// NOTE: Prev. version code - A.G.
//								yValueRangeMin = Math.Min(yValue, yValueRangeMin);
//								yValueRangeMax = Math.Max(yValue, yValueRangeMax);
							}

							// Remember last point
							prevDataPoint = point;

							// Remember last vertical range point
							// Note! Point is in axes coordinate.
							lastVerticalSegmentPoint.Y = (float)yValue;

							// Increase counter and proceed to next data point
							++index;
							continue;
						}
					}

					// Get point pixel position
					currentPoint.X = (float)
						(hAxis.GetLinearPosition( xValue ) * xPixelConverter);
					currentPoint.Y = (float)
						(vAxis.GetLinearPosition( yValue ) * yPixelConverter); 

					// Check if previous point must be converted from axes values to pixels
					if(prevPointInAxesCoordinates)
					{
						prevPoint.X = (float)
							(hAxis.GetLinearPosition( xValuePrev ) * xPixelConverter);
						prevPoint.Y = (float)
							(vAxis.GetLinearPosition( yValuePrev ) * yPixelConverter); 
					}

					// Draw acreplacedulated vertical line (with minimal X values differences)
					if(verticalLineDetected)
					{
						// Convert Y coordinates to pixels
						yValueRangeMin = (vAxis.GetLinearPosition( yValueRangeMin ) * yPixelConverter); 
						yValueRangeMax = (vAxis.GetLinearPosition( yValueRangeMax ) * yPixelConverter); 

						// Draw acreplacedulated vertical line
						DrawLine(
							series,
							prevDataPoint,
							pointRangeMin,
							pointRangeMax,
							index,
							(prevPointIsEmpty) ? emptyLinePen : linePen, 
							prevPoint.X, 
							(float)yValueRangeMin, 
							prevPoint.X,
							(float)yValueRangeMax);
						
						// Reset vertical line detected flag
						verticalLineDetected = false;

						// Convert last point of the vertical line segment to pixel coordinates
						prevPoint.Y = (float)
							(vAxis.GetLinearPosition( lastVerticalSegmentPoint.Y ) * yPixelConverter); 
					}
					
					// Draw line from previous to current point
					if(index > 0)
					{
						DrawLine(
							series,
							point,
							pointRangeMin,
							pointRangeMax,
							index,
							(currentPointIsEmpty) ? emptyLinePen : linePen,  
							prevPoint.X, 
							prevPoint.Y, 
							currentPoint.X,
							currentPoint.Y);
					}

					// Remember last point coordinates
					xValuePrev = xValue;
					yValuePrev = yValue;
					prevDataPoint = point;
					prevPoint = currentPoint;
					prevPointInAxesCoordinates = false;
					prevPointIsEmpty = currentPointIsEmpty;
					++index;
				}

				// Draw last acreplacedulated line segment
				if(verticalLineDetected)
				{
					// Check if previous point must be converted from axes values to pixels
					if(prevPointInAxesCoordinates)
					{
						prevPoint.X = (float)
							(hAxis.GetLinearPosition( xValuePrev ) * xPixelConverter);
						prevPoint.Y = (float)
							(vAxis.GetLinearPosition( yValuePrev ) * yPixelConverter); 
					}

					// Convert Y coordinates to pixels
					yValueRangeMin = (vAxis.GetLinearPosition( yValueRangeMin ) * yPixelConverter); 
					yValueRangeMax = (vAxis.GetLinearPosition( yValueRangeMax ) * yPixelConverter); 

					// Draw acreplacedulated vertical line
					DrawLine(
						series,
						prevDataPoint,
						pointRangeMin,
						pointRangeMax,
						index - 1,
						(prevPointIsEmpty) ? emptyLinePen : linePen, 
						prevPoint.X, 
						(float)yValueRangeMin, 
						prevPoint.X,
						(float)yValueRangeMax);
						
					verticalLineDetected = false;
					yValueRangeMin = double.NaN;
					yValueRangeMax = double.NaN;
					pointRangeMin = null;
					pointRangeMax = null;
				}

			}

			// Reset Clip Region
			if(clipRegionSet)
			{
				graph.ResetClip();
			}
	
		}

19 Source : CommonElements.cs
with MIT License
from AngeloCresta

[System.Diagnostics.Codereplacedysis.SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", MessageId = "System.Single.TryParse(System.String,System.Globalization.NumberStyles,System.IFormatProvider,System.Single@)")]
        internal static float ParseFloat(string stringToParse)
        {
            float result = 0f;
            bool parseSucceed = float.TryParse(stringToParse, NumberStyles.Any, CultureInfo.InvariantCulture, out result);

            if (!parseSucceed)
            {
                float.TryParse(stringToParse, NumberStyles.Any, CultureInfo.CurrentCulture, out result);
            }

            return result;
        }

19 Source : songdatabase.cs
with GNU Lesser General Public License v3.0
from angturil

public async Task GetPPData()
        {
            if (pploading) return;

            pploading = true;

            //Instance.QueueChatMessage("Getting PP Data");
            var StarTime = DateTime.UtcNow;
            string requestUrl = "https://cdn.wes.cloud/beatstar/bssb/v2-ranked.json";
            //public const String SCRAPED_SCORE_SABER_ALL_JSON_URL = "https://cdn.wes.cloud/beatstar/bssb/v2-all.json";

            string result;

            System.Globalization.NumberStyles style = System.Globalization.NumberStyles.AllowDecimalPoint;

            var resp = await Plugin.WebClient.GetAsync(requestUrl, System.Threading.CancellationToken.None);

            if (resp.IsSuccessStatusCode)
            {
                result = resp.ContentToString();
            }
            else
            {
                Plugin.Log("Failed to get pp");
                pploading = false;
                return;
            }

            //Instance.QueueChatMessage($"Parsing PP Data {result.Length}");

            JSONNode rootNode = JSON.Parse(result);

            listcollection.ClearList("pp.deck");

            foreach (KeyValuePair<string, JSONNode> kvp in rootNode)
            {
                JSONNode difficultyNodes = kvp.Value;

                string id = "";
                float maxpp = 0;
                float maxstar = 0;

                //Instance.QueueChatMessage($"{kvp.Value}");

                id = difficultyNodes["key"];

                //Instance.QueueChatMessage($"{id}");

                foreach (var innerKvp in difficultyNodes["diffs"])
                {
                    JSONNode node = innerKvp.Value;

                    //Instance.QueueChatMessage($"{node}");

                    float.TryParse(node["pp"], style, System.Globalization.CultureInfo.InvariantCulture, out float pp);
                    if (pp > maxpp) maxpp = pp;

                    float.TryParse(node["star"], style, System.Globalization.CultureInfo.InvariantCulture, out float starDifficulty);
                    if (starDifficulty > maxstar) maxstar = starDifficulty;
                }

                if (maxpp > 0)
                {
                    //Instance.QueueChatMessage($"{id} = {maxpp}");

                    ppmap.TryAdd(id, (int)(maxpp));

                    if (id != "" && maxpp > RequestBotConfig.Instance.PPDeckMiniumumPP) listcollection.add("pp.deck", id);

                    if (MapDatabase.MapLibrary.TryGetValue(id, out SongMap map))
                    {
                        map.pp = (int)(maxpp);
                        map.song.Add("pp", maxpp);
                        map.IndexSong(map.song);

                    }
                }
            }

            COMMAND.Parse(ChatHandler.Self, "!deck pp", RequestBot.CmdFlags.Local);
            Instance.QueueChatMessage("PP Data indexed");
            pploading = false;
        }

19 Source : NumericTextbox.cs
with GNU General Public License v3.0
from anotak

public float GetResultFloat(float original)
		{
			string textpart = this.Text;
			float result;

			// Strip prefixes
			textpart = textpart.Replace("+", "");
			textpart = textpart.Replace("-", "");

			// Any numbers left?
			if(textpart.Length > 0)
			{
				// Prefixed with ++?
				if(this.Text.StartsWith("++"))
				{
					// Add number to original
					if(!float.TryParse(textpart, out result)) result = 0;
					return original + result;
				}
				// Prefixed with --?
				else if(this.Text.StartsWith("--"))
				{
					// Subtract number from original
					if(!float.TryParse(textpart, out result)) result = 0;
					float newvalue = original - result;
					if(!allownegative && (newvalue < 0)) newvalue = 0;
					return newvalue;
				}
				else
				{
					// Return the new value
					return float.TryParse(this.Text, out result) ? result : original;
				}
			}
			else
			{
				// Nothing given, keep original value
				return original;
			}
		}

19 Source : AngleDegreesFloatHandler.cs
with GNU General Public License v3.0
from anotak

public override void SetValue(object value)
		{
			float result;
			
			// Null?
			if(value == null)
			{
				this.value = 0.0f;
			}
			// Compatible type?
			else if((value is int) || (value is float) || (value is bool))
			{
				// Set directly
				this.value = Convert.ToSingle(value);
			}
			else
			{
				// Try parsing as string
				if(float.TryParse(value.ToString(), NumberStyles.Float, CultureInfo.CurrentCulture, out result))
				{
					this.value = result;
				}
				else
				{
					this.value = 0.0f;
				}
			}
		}

19 Source : AngleRadiansHandler.cs
with GNU General Public License v3.0
from anotak

public override void SetValue(object value)
		{
			float result;

			// Null?
			if(value == null)
			{
				this.value = 0.0f;
			}
			// Compatible type?
			else if((value is int) || (value is float) || (value is bool))
			{
				// Set directly
				this.value = Convert.ToSingle(value);
			}
			else
			{
				// Try parsing as string
				if(float.TryParse(value.ToString(), NumberStyles.Float, CultureInfo.CurrentCulture, out result))
				{
					this.value = result;
				}
				else
				{
					this.value = 0.0f;
				}
			}
		}

19 Source : ActorStructure.cs
with GNU General Public License v3.0
from anotak

public float GetPropertyValueFloat(string propname, int valueindex)
		{
			string str = GetPropertyValueString(propname, valueindex);
			
			float fvalue;
			if(float.TryParse(str, NumberStyles.Float, CultureInfo.InvariantCulture, out fvalue))
				return fvalue;
			else
				return 0.0f;
		}

19 Source : PatchStructure.cs
with GNU General Public License v3.0
from anotak

private bool ReadTokenFloat(TexturesParser parser, string propertyname, out float value)
		{
			// Next token is the property value to set
			parser.SkipWhitespace(true);
			string strvalue = parser.ReadToken();
			if(!string.IsNullOrEmpty(strvalue))
			{
				// Try parsing as value
				if(!float.TryParse(strvalue, NumberStyles.Float, CultureInfo.InvariantCulture, out value))
				{
					parser.ReportError("Expected numeric value for property '" + propertyname + "'");
					return false;
				}
				else
				{
					// Success
					return true;
				}
			}
			else
			{
				// Can't find the property value!
				parser.ReportError("Expected a value for property '" + propertyname + "'");
				value = 0.0f;
				return false;
			}
		}

19 Source : BasketProductCardViewModel.cs
with Apache License 2.0
from AppRopio

protected virtual async Task OnQuanreplacedyChangedExecute()
        {
            if (Model == null)
                return;
            
            replacedyticsNotifyingService.NotifyEventIsHandled("catalog", replacedyticsPrefix + "_change_quanreplacedy_text_field", Model.Id);

            if (float.TryParse(QuanreplacedyString.Replace(" ", ""), NumberStyles.Any, NumberFormatInfo.InvariantInfo, out float result))
            {
                _quanreplacedy = result;

                if (_quanreplacedy - Model.UnitStep <= 0)
                {
                    await DeleteProductFromBasket();
                    return;
                }

                await OnQuanreplacedyChanged();

                SetQuanreplacedyString();

                var confirmed = await UserDialogs.Confirm($"{LocalizationService.GetLocalizableString(BasketConstants.RESX_NAME, "Basket_ProductsCount")} {QuanreplacedyString} {UnitName}", LocalizationService.GetLocalizableString(BasketConstants.RESX_NAME, "Basket_AddedToBasketButton"), true);
                if (confirmed)
                    NavigationVmService.NavigateToBasket(new BaseBundle(Base.Core.Models.Navigation.NavigationType.ClearAndPush));
            }
            else
            {
                SetQuanreplacedyString();
            }
        }

19 Source : EditValueVM.cs
with MIT License
from Aragas

public void ExecuteDone()
        {
            switch (SettingProperty.SettingType)
            {
                case SettingType.Int when int.TryParse(TextInput, out var intVal):
                    SettingProperty.URS.Do(new SetValueTypeAction<int>(SettingProperty.PropertyReference, intVal));
                    break;
                case SettingType.Float when float.TryParse(TextInput, out var floatVal):
                    SettingProperty.URS.Do(new SetValueTypeAction<float>(SettingProperty.PropertyReference, floatVal));
                    break;
                case SettingType.String:
                    SettingProperty.URS.Do(new SetStringAction(SettingProperty.PropertyReference, TextInput));
                    break;
            }

            ScreenManager.PopScreen();
        }

19 Source : EditValueTextWidget.cs
with MIT License
from Aragas

public override void HandleInput(IReadOnlyList<int> lastKeysPressed)
        {
            if (Input.IsKeyDown(InputKey.LeftControl) && Input.IsKeyPressed(InputKey.V))
            {
                base.HandleInput(lastKeysPressed);
                return;
            }

            if (lastKeysPressed.Count > 0)
            {
                foreach (var key in lastKeysPressed)
                {
                    if (SettingType == SettingType.String)
                    {
                        base.HandleInput(lastKeysPressed);
                    }
                    else if (Enum.IsDefined(typeof(KeyCodes), key))
                    {
                        if (key == (int) KeyCodes.Minus)
                        {
                            if (_editableWidget?.SelectedTextBegin != 0)
                                continue;
                        }
                        else if (SettingType == SettingType.Float)
                        {
                            // Handle input for float types
                            if (key == (int) KeyCodes.Decimal)
                            {
                                if (RealText.Any(ch => ch == '.'))
                                    continue;
                            }
                        }
                        else if (SettingType == SettingType.Int)
                        {
                            // Handle input for int types.
                            if (key == (int) KeyCodes.Decimal)
                                continue;
                        }
                        base.HandleInput(lastKeysPressed);

                        if (SettingType == SettingType.Float)
                        {
                            if (float.TryParse(RealText, out var value))
                            {
                                var newVal = value;
                                if (value > MaxValue)
                                    newVal = MaxValue;
                                else if (value < MinValue)
                                    newVal = MinValue;
                                if (newVal != value)
                                {
                                    var format = SettingType == SettingType.Int ? "0" : "0.00";
                                    RealText = newVal.ToString(format);
                                    _editableWidget?.SetCursorPosition(0, true);
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                base.HandleInput(lastKeysPressed);
            }
        }

19 Source : AssDocumentItem.cs
with MIT License
from arcusmaximus

public float GetFloat(string field, float defaultValue = 0)
        {
            return float.TryParse(GetString(field), NumberStyles.Any, CultureInfo.InvariantCulture, out float result) ? result : defaultValue;
        }

19 Source : AssFileSection.cs
with MIT License
from arcusmaximus

public float GereplacedemFloat(string type, float defaultValue = 0)
        {
            return float.TryParse(GereplacedemString(type), NumberStyles.Any, CultureInfo.InvariantCulture, out float result) ? result : defaultValue;
        }

19 Source : AssTagHandlerBase.cs
with MIT License
from arcusmaximus

protected static bool TryParseFloat(string arg, out float value)
        {
            arg = arg.Replace("(", "")
                     .Replace(")", "")
                     .Replace(" ", "");
            return float.TryParse(arg, NumberStyles.Float, CultureInfo.InvariantCulture, out value);
        }

19 Source : AssTagHandlerBase.cs
with MIT License
from arcusmaximus

protected static List<float> ParseFloatList(string arg)
        {
            List<string> items = ParseStringList(arg);
            if (items == null)
                return null;

            List<float> list = new List<float>();
            foreach (string item in items)
            {
                float.TryParse(item.Replace(" ", ""), NumberStyles.Float, CultureInfo.InvariantCulture, out float value);
                list.Add(value);
            }
            return list;
        }

19 Source : AltitudeUI.cs
with MIT License
from Atknssl

public void UpdateTarget()
    {
        if(float.TryParse(this.TarAlt.text, out float number))
        {
            rod.GetComponent<AlreplacedudeController>().alreplacedude = number;
        }
        else
        {
            this.TarAlt.text = rod.GetComponent<AlreplacedudeController>().alreplacedude.ToString();;
        }
    }

19 Source : AltitudeUI.cs
with MIT License
from Atknssl

public void Updatereplacedpeed()
    {
        if(float.TryParse(this.AsValue.text, out float number))
        {
            rod.GetComponent<AlreplacedudeController>().ascendMaxSpeed = number;
        }
        else
        {
            this.AsValue.text = rod.GetComponent<AlreplacedudeController>().ascendMaxSpeed.ToString();;
        }
    }

19 Source : AltitudeUI.cs
with MIT License
from Atknssl

public void UpdateDesSpeed()
    {
        if(float.TryParse(this.DesValue.text, out float number))
        {
            rod.GetComponent<AlreplacedudeController>().descendMaxSpeed = number;
        }
        else
        {
            this.DesValue.text = rod.GetComponent<AlreplacedudeController>().descendMaxSpeed.ToString();;
        }
    }

See More Examples