double.TryParse(string, out double)

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

1089 Examples 7

19 View Source File : FormConvert.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public double? ToNullDouble(string name)
        {
            if (string.IsNullOrWhiteSpace(GetValue(name))) return null;
            if (!double.TryParse(GetValue(name), out var vl))
            {
                AddMessage(name, "值无法转为小数");
                Failed = true;
                return null;
            }

            return vl;
        }

19 View Source File : GraphCLI.Parser.cs
License : MIT License
Project Creator : alelievr

static object TryParseGraphAttr(string s)
		{
			object value = null;
			int vi;
			long vl;
			float vf;
			double vd;
			bool vb;

			if (int.TryParse(s, out vi))
				value = vi;
			else if (long.TryParse(s, out vl))
				value = vl;
			else if (float.TryParse(s, out vf))
				value = vf;
			else if (double.TryParse(s, out vd))
				value = vd;
			else if (bool.TryParse(s, out vb))
				value = vb;
			
			return value;
		}

19 View Source File : MiniJson.cs
License : MIT License
Project Creator : AdamCarballo

object ParseNumber() {
				string number = NextWord;
				
				if (number.IndexOf('.') == -1) {
					long parsedInt;
					Int64.TryParse(number, out parsedInt);
					return parsedInt;
				}
				
				double parsedDouble;
				Double.TryParse(number, out parsedDouble);
				return parsedDouble;
			}

19 View Source File : ConfigurationManager.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public double GetDouble(string key, double def = 0.0)
        {
            if (key == null)
            {
                return def;
            }

            var value = this[key];
            if (string.IsNullOrWhiteSpace(value))
            {
                return def;
            }
            return !double.TryParse(value, out var vl) ? def : vl;
        }

19 View Source File : DoubleControlTemplate.cs
License : MIT License
Project Creator : Adoxio

private static ServerValidateEventHandler GetRangeValidationHandler(double minValue, double maxValue)
		{
			return (sender, args) =>
			{
				double value;

				args.IsValid = double.TryParse(args.Value, out value) && (value >= Convert.ToDouble(minValue)) && (value <= Convert.ToDouble(maxValue));
			};
		}

19 View Source File : DegreeToScalarConverter.cs
License : MIT License
Project Creator : Actipro

public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
		#endif
			var angle = (double)value;

			var stepValue = 1.0;
			var parameterText = parameter as string;
			if (!string.IsNullOrEmpty(parameterText))
				double.TryParse(parameterText, out stepValue);

			return Math.Round(angle / stepValue);
		}

19 View Source File : QueryGetResults.cs
License : MIT License
Project Creator : akaskela

protected virtual void SetSingleValueResults(DataTable table, CodeActivityContext context)
        {
            string innerValue = String.Empty;
            if (table.Rows.Count > 0)
            {
                this.QueryResult_Text.Set(context, table.Rows[0][0].ToString());
                innerValue = table.Rows[0][1].ToString();
            }

            Guid id = new Guid();
            if (Guid.TryParse(innerValue, out id))
            {
                this.QueryResult_Guid.Set(context, innerValue);
            }

            DateTime dateTime = new DateTime();
            if (DateTime.TryParse(innerValue, out dateTime))
            {
                this.QueryResult_DateTime.Set(context, dateTime);
            }

            decimal decimalValue = new decimal();
            if (decimal.TryParse(innerValue, out decimalValue))
            {
                this.QueryResult_Decimal.Set(context, decimalValue);
                try
                {
                    this.QueryResult_Money.Set(context, new Money(decimalValue));
                }
                catch { }
            }

            double doubleValue = new double();
            if (double.TryParse(innerValue, out doubleValue))
            {
                this.QueryResult_Double.Set(context, doubleValue);
            }

            int intValue = 0;
            if (int.TryParse(innerValue, out intValue))
            {
                this.QueryResult_WholeNumber.Set(context, intValue);
            }
        }

19 View Source File : ReaderHelper.cs
License : GNU General Public License v3.0
Project Creator : 9vult

public static Chapter[] SortChapters(List<Chapter> aList)
        {
            Chapter[] items = aList.ToArray();
            // Get the numeric values of the items.
            int num_items = items.Length;
            const string float_pattern = @"-?\d+\.?\d*";
            double[] values = new double[num_items];
            for (int i = 0; i < num_items; i++)
            {
                string match = Regex.Match(items[i].GetNum(), float_pattern).Value;
                if (!double.TryParse(match, out double value))
                    value = double.MinValue;
                values[i] = value;
            }

            // Sort the items array using the keys to determine order.
            Array.Sort(values, items);
            return items;
        }

19 View Source File : BPM.cs
License : MIT License
Project Creator : AlFasGD

public static bool TryParse(string s, out BPM bpm)
        {
            bpm = default;
            if (!double.TryParse(s, out double value))
                return false;
            bpm = new BPM(value);
            return true;
        }

19 View Source File : Field.cs
License : MIT License
Project Creator : a1xd

private void TextToData()
        {
            if (double.TryParse(Box.Text, out double value) && 
                value <= MaxData && value >= MinData)
            {
                _data = value;
            }

            Box.Text = DecimalString(Data);
            
            if (string.Equals(Box.Text, DefaultText))
            {
                SetToDefault();
            }
            else
            {
                SetToEntered();
            }
        }

19 View Source File : FormConvert.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public double ToDouble(string name, double def)
        {
            if (string.IsNullOrWhiteSpace(GetValue(name)))
            {
                return def;
            }
            double vl;
            if (!double.TryParse(GetValue(name), out vl))
            {
                AddMessage(name, "值无法转为小数");
                Failed = true;
                return 0;
            }
            return vl;
        }

19 View Source File : AduDoubleUpDown.cs
License : GNU General Public License v3.0
Project Creator : aduskin

protected override double ParseValue(string value)
        {
            double temp = 0;
            if (double.TryParse(value, out temp))
            {
                return temp;
            }
            else
            {
                return double.MinValue;
            }
        }

19 View Source File : RoomFilterItem.cs
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas

private static int ParameterComparedToString(Parameter param, string value)
        {
            // ReSharper disable once InconsistentNaming
            const int Result = 441976;
            if (!param.HasValue || string.IsNullOrWhiteSpace(value))
            {
                return Result;
            }
            switch (param.StorageType)
            {
                case StorageType.Double:
                    if (double.TryParse(value, out var parse))
                    {
                        return param.AsDouble().CompareTo(parse);
                    }
                    break;

                case StorageType.String:
                #pragma warning disable CA1307 // Specify StringComparison
                return string.Compare(param.replacedtring(), value, StringComparison.Ordinal);
                #pragma warning restore CA1307 // Specify StringComparison

                case StorageType.Integer:
                    if (int.TryParse(value, out var iparse))
                    {
                        return param.AsInteger().CompareTo(iparse);
                    }
                    break;

                case StorageType.ElementId:
                    return Result;

                default:
                    return Result;
            }
            return Result;
        }

19 View Source File : FormConvert.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public double ToDouble(string name)
        {
            if (string.IsNullOrWhiteSpace(GetValue(name)))
            {
                AddMessage(name, "值不能为空");
                Failed = true;
                return 0;
            }

            if (!double.TryParse(GetValue(name), out var vl))
            {
                AddMessage(name, "值无法转为小数");
                Failed = true;
                return 0;
            }

            return vl;
        }

19 View Source File : FrmDoublePageReader.cs
License : GNU General Public License v3.0
Project Creator : 9vult

private Chapter[] SortChapters(Chapter[] items)
        {
            // Get the numeric values of the items.
            int num_items = items.Length;
            const string float_pattern = @"-?\d+\.?\d*";
            double[] values = new double[num_items];
            for (int i = 0; i < num_items; i++)
            {
                string match = Regex.Match(items[i].num.ToString(), float_pattern).Value;
#pragma warning disable IDE0018 // Inline variable declaration
                double value;
#pragma warning restore IDE0018 // Inline variable declaration
                if (!double.TryParse(match, out value))
                    value = double.MinValue;
                values[i] = value;
            }

            // Sort the items array using the keys to determine order.
            Array.Sort(values, items);
            return items;
        }

19 View Source File : CSVCell.cs
License : GNU General Public License v3.0
Project Creator : AHeroicLlama

public void Validate()
		{
			switch (columnName)
			{
				case "enreplacedyFormID":
				case "referenceFormID":
				case "cellFormID":
				case "junkFormID":
					// FormID Cells must only contain the FormID alone
					if (!Validation.matchFormID.IsMatch(data))
					{
						ReportValidationError();
					}
					return;

				case "locationFormID":
					// locationFormID may be empty if not a FormID
					if (data != string.Empty && !Validation.matchFormID.IsMatch(data))
					{
						ReportValidationError();
					}
					return;

				case "signature":
					// Signatures are always exactly 4 letters or underscores
					if (!Validation.validSignature.IsMatch(data))
					{
						ReportValidationError();
					}
					return;

				case "editorID":
				case "cellEditorID":
				case "displayName":
				case "cellDisplayName":
					// editorID and displayName must have had any double quotes escaped by now
					if (Validation.unescapedDoubleQuote.IsMatch(data))
					{
						ReportValidationError();
					}
					return;

				case "componentQuanreplacedy":
					// Component quanreplacedy must be an integer
					if (!int.TryParse(data, out _))
					{
						ReportValidationError();
					}
					return;

				case "chance":
					// Spawn chances must be exactly doubles
					if (!double.TryParse(data, out _))
					{
						ReportValidationError();
					}
					return;

				case "x":
				case "y":
				case "z":
					// Coordinate cells must be exactly integers
					if (!int.TryParse(data, out _))
					{
						ReportValidationError();
					}
					return;

				case "boundX":
				case "boundY":
				case "boundZ":
				case "rotZ":
					// Boundary dimensions or rotations may be blank or otherwise integers
					if (data != string.Empty && !int.TryParse(data, out _))
					{
						ReportValidationError();
					}
					return;

				case "primitiveShape":
					// A primitive shape can only be these known types or empty
					if (data != string.Empty && !Validation.validPrimitiveShape.IsMatch(data))
					{
						ReportValidationError();
					}
					return;

				case "lockLevel":
					// Lock level must come from a set of strings or be empty
					if (data != string.Empty && !Validation.validLockLevel.IsMatch(data))
					{
						ReportValidationError();
					}
					return;

				case "spawnClreplaced":
					// Clreplaced (monster) can only be two exact strings or empty
					if (data != string.Empty && !Validation.validNpcClreplaced.IsMatch(data))
					{
						ReportValidationError();
					}
					return;

				case "npc":
				case "component":
					// Nothing really to validate for here since they're just in-game strings
					return;

				default:
					throw new Exception("Column " + columnName + " was not accounted for in validation");
			}
		}

19 View Source File : AdditionConverter.cs
License : MIT License
Project Creator : Actipro

public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
			if (!(value is double))
				throw new ArgumentException("The value preplaceded to this converter must be a Double.");

			double parameterValue = 0;
			string parameterStringValue = parameter as string;
			if (parameterStringValue != null)
				double.TryParse(parameterStringValue, out parameterValue);

			return (double)value + parameterValue;
		}

19 View Source File : NumericManipulator.cs
License : MIT License
Project Creator : akaskela

public string RoundToSignificantDigits(string input, int places)
        {
            string displayValue = String.Empty;
            double inputAsDouble = new double();
            if (double.TryParse(input, out inputAsDouble))
            {
                displayValue = ToString(inputAsDouble, places);
            }

            return displayValue;
        }

19 View Source File : JsonReader.cs
License : MIT License
Project Creator : 404Lcc

private void ProcessNumber (string number)
        {
            if (number.IndexOf ('.') != -1 ||
                number.IndexOf ('e') != -1 ||
                number.IndexOf ('E') != -1) {

                double n_double;
                if (Double.TryParse (number, out n_double)) {
                    token = JsonToken.Double;
                    token_value = n_double;

                    return;
                }
            }

            int n_int32;
            if (Int32.TryParse (number, out n_int32)) {
                token = JsonToken.Int;
                token_value = n_int32;

                return;
            }

            long n_int64;
            if (Int64.TryParse (number, out n_int64)) {
                token = JsonToken.Long;
                token_value = n_int64;

                return;
            }

            ulong n_uint64;
            if (UInt64.TryParse(number, out n_uint64))
            {
                token = JsonToken.Long;
                token_value = n_uint64;

                return;
            }

            // Shouldn't happen, but just in case, return something
            token = JsonToken.Int;
            token_value = 0;
        }

19 View Source File : Program.Commands.cs
License : MIT License
Project Creator : alexanderdna

private static void cmd_send(string[] arr)
        {
            if (arr.Length != 3)
            {
                cmd_help("send");
                return;
            }

            if (_app.WalletLoggedIn is false)
            {
                Console.WriteLine("You have not logged in your wallet.");
                Console.WriteLine("Enter `wallet` command to log in.");
                return;
            }

            string recipientAddress = arr[1];
            if (recipientAddress == _app.WalletAddress)
            {
                Console.WriteLine("Recipient address seems to be your own address.");
                return;
            }

            if (!AddressUtils.VerifyAddress(recipientAddress))
            {
                Console.WriteLine("Recipient address seems to be invalid.");
                return;
            }

            if (!double.TryParse(arr[2], out double amount)
                || amount <= (Config.FeeNekoshiPerTx / (double)Config.NekoshiPerCoin)
                || amount > (Config.MaxSendableNekoshi / (double)Config.NekoshiPerCoin))
            {
                Console.WriteLine("Amount value is invalid.");
                return;
            }

            var sendResult = _app.Send(recipientAddress, (long)(amount * 100_000_000));
            if (sendResult.Error == ChainManager.SendResult.ErrorType.None)
            {
                Console.WriteLine("\tDone, TxId: {0}", sendResult.TxId);
            }
            else
            {
                Console.WriteLine("\tError: {0}", sendResult.Error);
            }
        }

19 View Source File : EntityListDataAdapter.cs
License : MIT License
Project Creator : Adoxio

protected static Condition GetSearchFilterConditionForAttribute(string attribute, string query, EnreplacedyMetadata enreplacedyMetadata)
		{
			var attributeMetadata = enreplacedyMetadata.Attributes.FirstOrDefault(a => a.LogicalName == attribute);

			if (attributeMetadata == null)
			{
				return null;
			}

			switch (attributeMetadata.AttributeType)
			{
				case AttributeTypeCode.String:
					return new Condition(attribute, ConditionOperator.Like, "{0}%".FormatWith(query));

				case AttributeTypeCode.Lookup:
				case AttributeTypeCode.Customer:
				case AttributeTypeCode.Picklist:
				case AttributeTypeCode.State:
				case AttributeTypeCode.Status:
				case AttributeTypeCode.Owner:
					return new Condition("{0}name".FormatWith(attribute), ConditionOperator.Like, "{0}%".FormatWith(query));

				case AttributeTypeCode.BigInt:
					long parsedLong;
					return long.TryParse(query, out parsedLong)
						? new Condition(attribute, ConditionOperator.Equal, parsedLong)
						: null;

				case AttributeTypeCode.Integer:
					int parsedInt;
					return int.TryParse(query, out parsedInt)
						? new Condition(attribute, ConditionOperator.Equal, parsedInt)
						: null;

				case AttributeTypeCode.Double:
					double parsedDouble;
					return double.TryParse(query, out parsedDouble)
						? new Condition(attribute, ConditionOperator.Equal, parsedDouble)
						: null;

				case AttributeTypeCode.Decimal:
				case AttributeTypeCode.Money:
					decimal parsedDecimal;
					return decimal.TryParse(query, out parsedDecimal)
						? new Condition(attribute, ConditionOperator.Equal, parsedDecimal)
						: null;

				case AttributeTypeCode.DateTime:
					DateTime parsedDate;
					return DateTime.TryParse(query, out parsedDate)
						? new Condition(attribute, ConditionOperator.On, parsedDate.ToString("yyyy-MM-dd"))
						: null;

				default:
					return null;
			}
		}

19 View Source File : DoubleControlTemplate.cs
License : MIT License
Project Creator : Adoxio

protected override void InstantiateControlIn(Control container)
		{
			var textbox = new TextBox { ID = ControlID, TextMode = TextBoxMode.SingleLine, CssClreplaced = string.Join(" ", "text", CssClreplaced, Metadata.CssClreplaced), ToolTip = Metadata.ToolTip };
			textbox.Attributes["data-numberdecimalseparator"] = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;

			if (Metadata.IsRequired || Metadata.WebFormForceFieldIsRequired)
			{
				textbox.Attributes.Add("required", string.Empty);
			}

			if (Metadata.ReadOnly)
			{
				textbox.CssClreplaced += " readonly";
				textbox.Attributes["readonly"] = "readonly";
			}

			textbox.Attributes["onchange"] = "setIsDirty(this.id);";

			container.Controls.Add(textbox);

			RegisterClientSideDependencies(container);

			Bindings[Metadata.DataFieldName] = new CellBinding
			{
				Get = () =>
				{
					double value;

					return double.TryParse(textbox.Text, out value) ? new double?(value) : null;
				},
				Set = obj =>
				{
					var value = (double)obj;

					textbox.Text = value.ToString("N{0}".FormatWith(Metadata.Precision.GetValueOrDefault(2)));
				}
			};
		}

19 View Source File : JSONParser.cs
License : MIT License
Project Creator : 5minlab

internal static object ParseValue(Type type, string json) {
            if (type == typeof(string)) {
                if (json.Length <= 2)
                    return string.Empty;
                string str = json.Substring(1, json.Length - 2);
                return str.Replace("\\\\", "\"\"").Replace("\\", string.Empty).Replace("\"\"", "\\");
            }
            if (type == typeof(int)) {
                int result;
                int.TryParse(json, out result);
                return result;
            }
            if (type == typeof(float)) {
                float result;
                float.TryParse(json, out result);
                return result;
            }
            if (type == typeof(double)) {
                double result;
                double.TryParse(json, out result);
                return result;
            }
            if (type == typeof(bool)) {
                return json.ToLower() == "true";
            }
            if (json == "null") {
                return null;
            }
            if (type.IsArray) {
                Type arrayType = type.GetElementType();
                if (json[0] != '[' || json[json.Length - 1] != ']')
                    return null;

                List<string> elems = Split(json);
                Array newArray = Array.CreateInstance(arrayType, elems.Count);
                for (int i = 0; i < elems.Count; i++)
                    newArray.SetValue(ParseValue(arrayType, elems[i]), i);
                splitArrayPool.Push(elems);
                return newArray;
            }
            if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>)) {
                Type listType = type.GetGenericArguments()[0];
                if (json[0] != '[' || json[json.Length - 1] != ']')
                    return null;

                List<string> elems = Split(json);
                var list = (IList)type.GetConstructor(new Type[] { typeof(int) }).Invoke(new object[] { elems.Count });
                for (int i = 0; i < elems.Count; i++)
                    list.Add(ParseValue(listType, elems[i]));
                splitArrayPool.Push(elems);
                return list;
            }
            if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<,>)) {
                Type keyType, valueType;
                {
                    Type[] args = type.GetGenericArguments();
                    keyType = args[0];
                    valueType = args[1];
                }

                //Refuse to parse dictionary keys that aren't of type string
                if (keyType != typeof(string))
                    return null;
                //Must be a valid dictionary element
                if (json[0] != '{' || json[json.Length - 1] != '}')
                    return null;
                //The list is split into key/value pairs only, this means the split must be divisible by 2 to be valid JSON
                List<string> elems = Split(json);
                if (elems.Count % 2 != 0)
                    return null;

                var dictionary = (IDictionary)type.GetConstructor(new Type[] { typeof(int) }).Invoke(new object[] { elems.Count / 2 });
                for (int i = 0; i < elems.Count; i += 2) {
                    if (elems[i].Length <= 2)
                        continue;
                    string keyValue = elems[i].Substring(1, elems[i].Length - 2);
                    object val = ParseValue(valueType, elems[i + 1]);
                    dictionary.Add(keyValue, val);
                }
                return dictionary;
            }
            if (type == typeof(object)) {
                return ParseAnonymousValue(json);
            }
            if (json[0] == '{' && json[json.Length - 1] == '}') {
                return ParseObject(type, json);
            }

            return null;
        }

19 View Source File : DoubleControlTemplate.cs
License : MIT License
Project Creator : Adoxio

private static void OnDoubleFormatValidate(object source, ServerValidateEventArgs args)
		{
			double value;

			args.IsValid = double.TryParse(args.Value, out value);
		}

19 View Source File : Converters.cs
License : MIT License
Project Creator : ABTSoftware

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        { 
            return double.TryParse(value?.ToString(), out double result) ? result : 1d;
        }

19 View Source File : FormConvert.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public double ToDouble(string name)
        {
            if (string.IsNullOrWhiteSpace(GetValue(name)))
            {
                AddMessage(name, "值不能为空");
                Failed = true;
                return 0;
            }
            double vl;
            if (!double.TryParse(GetValue(name), out vl))
            {
                AddMessage(name, "值无法转为小数");
                Failed = true;
                return 0;
            }
            return vl;
        }

19 View Source File : RatingBar.cs
License : GNU General Public License v3.0
Project Creator : aduskin

private static object ValueCoerce(DependencyObject d, object baseValue)
      {
         RatingBar ratingBar = d as RatingBar;
         double value = 0.0;
         if (double.TryParse(Convert.ToString(baseValue), out value))
         {
            if (value < ratingBar.Minimum)
            {
               value = 0;
            }
            else if (value > ratingBar.Maximum)
            {
               value = ratingBar.Maximum;
            }
         }
         return value;
      }

19 View Source File : Hatch.cs
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas

private bool replacedignFillGridsFromString(string[] grids, double scale, double rotationAngle)
        {
            var newFillGrids = new List<FillGrid>();
            foreach (string s in grids) {
                if (string.IsNullOrEmpty(s.Trim()))
                {
                    continue;
                }
                string[] segs = s.Split(',');
                if (segs.Count() < 5)
                {
                    return false;
                }
                var f = new FillGrid();
                List<double> lineSegs = new List<double>();
                if (!double.TryParse(segs[0], out var angle)) {
                    return false;
                }
                if (!double.TryParse(segs[1], out var x)) {
                    return false;
                }
                if (!double.TryParse(segs[2], out var y)) {
                    return false;
                }
                if (!double.TryParse(segs[3], out var shift)) {
                    return false;
                }
                if (!double.TryParse(segs[4], out var offset)) {
                    return false;
                }
                for (int i = 5; i < segs.Length; i++)
                {
                    if (!double.TryParse(segs[i], out var individualSeg))
                    {
                        return false;
                    }
                    individualSeg *= scale;
                    lineSegs.Add(Math.Abs(individualSeg.ToFeet()));
                }
                x *= scale;
                y *= scale;
                shift *= scale;
                offset *= scale;
                angle += rotationAngle;
                f.Angle = angle.ToRad();
                f.Origin = new UV(x.ToFeet(), y.ToFeet());
                f.Shift = shift.ToFeet();
                f.Offset = offset.ToFeet();
                f.SetSegments(lineSegs);
                newFillGrids.Add(f);              
            }
            fillPattern.SetFillGrids(newFillGrids);
            return true;
        }

19 View Source File : FormConvert.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public double? ToNullDouble(string name)
        {
            if (string.IsNullOrWhiteSpace(GetValue(name)))
            {
                return null;
            }
            double vl;
            if (!double.TryParse(GetValue(name), out vl))
            {
                AddMessage(name, "值无法转为小数");
                Failed = true;
                return null;
            }
            return vl;
        }

19 View Source File : Utility.Convertor.cs
License : MIT License
Project Creator : 7Bytes-Studio

public static object Convert(string typeStr,string typeValue)
            {
                Type type = Convert(typeStr);
                if (null!=type)
                {
                    var typeObject = Reflection.New(type);
                    if (type==typeof(int))
                    {
                        int v;
                        if (int.TryParse(typeValue,out v))
                        {
                            typeObject = v;
                        }
                    }
                    else if (type == typeof(Int16))
                    {
                        Int16 v;
                        if (Int16.TryParse(typeValue, out v))
                        {
                            typeObject = v;
                        }
                    }
                    else if (type == typeof(Int64))
                    {
                        Int64 v;
                        if (Int64.TryParse(typeValue, out v))
                        {
                            typeObject = v;
                        }
                    }
                    else if (type == typeof(float))
                    {
                        float v;
                        if (float.TryParse(typeValue, out v))
                        {
                            typeObject = v;
                        }
                    }
                    else if (type == typeof(double))
                    {
                        double v;
                        if (double.TryParse(typeValue, out v))
                        {
                            typeObject = v;
                        }
                    }
                    else if (type == typeof(decimal))
                    {
                        decimal v;
                        if (decimal.TryParse(typeValue, out v))
                        {
                            typeObject = v;
                        }
                    }
                    else if (type == typeof(char))
                    {
                        char v;
                        if (char.TryParse(typeValue, out v))
                        {
                            typeObject = v;
                        }
                    }
                    else if (type == typeof(string))
                    {
                        typeObject = typeValue;
                    }
                }
                return null;
            }

19 View Source File : AppConfigHelper.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static double GetAppSettingDouble(string key, double def = 0.0)
        {
            string value = ConfigurationManager.AppSettings[key];
            if (string.IsNullOrWhiteSpace(value))
            {
                return def;
            }
            double.TryParse(value, out def);
            return def;
        }

19 View Source File : ModelSetupWizard.cs
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas

public static void SetParameterValue(Parameter param, string value)
        {
            if (param.StorageType == StorageType.Double) {
                double d = 0;
                if (double.TryParse(value, out d)) {
                    param.Set(d);
                }
            } else if (param.StorageType == StorageType.Integer) {
                int i = 0;
                if (int.TryParse(value, out i))
                {
                    param.Set(i);
                }
            } else {
                param.Set(value);
            }
        }

19 View Source File : FormConvert.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public double ToDouble(string name, double def)
        {
            if (string.IsNullOrWhiteSpace(GetValue(name))) return def;
            if (!double.TryParse(GetValue(name), out var vl))
            {
                AddMessage(name, "值无法转为小数");
                Failed = true;
                return 0;
            }

            return vl;
        }

19 View Source File : RedisClient.cs
License : MIT License
Project Creator : 2881099

internal T DeserializeRedisValue<T>(byte[] valueRaw, Encoding encoding)
        {
            if (valueRaw == null) return default(T);
            var type = typeof(T);
            var typename = type.ToString().TrimEnd(']');
            if (typename == "System.Byte[") return (T)Convert.ChangeType(valueRaw, type);
            if (typename == "System.String") return (T)Convert.ChangeType(encoding.GetString(valueRaw), type);
            if (typename == "System.Boolean[") return (T)Convert.ChangeType(valueRaw.Select(a => a == 49).ToArray(), type);
            if (valueRaw.Length == 0) return default(T);

            string valueStr = null;
            if (type.IsValueType)
            {
                valueStr = encoding.GetString(valueRaw);
                bool isNullable = typename.StartsWith("System.Nullable`1[");
                var basename = isNullable ? typename.Substring(18) : typename;

                bool isElse = false;
                object obj = null;
                switch (basename)
                {
                    case "System.Boolean":
                        if (valueStr == "1") obj = true;
                        else if (valueStr == "0") obj = false;
                        break;
                    case "System.Byte":
                        if (byte.TryParse(valueStr, out var trybyte)) obj = trybyte;
                        break;
                    case "System.Char":
                        if (valueStr.Length > 0) obj = valueStr[0];
                        break;
                    case "System.Decimal":
                        if (Decimal.TryParse(valueStr, out var trydec)) obj = trydec;
                        break;
                    case "System.Double":
                        if (Double.TryParse(valueStr, out var trydb)) obj = trydb;
                        break;
                    case "System.Single":
                        if (Single.TryParse(valueStr, out var trysg)) obj = trysg;
                        break;
                    case "System.Int32":
                        if (Int32.TryParse(valueStr, out var tryint32)) obj = tryint32;
                        break;
                    case "System.Int64":
                        if (Int64.TryParse(valueStr, out var tryint64)) obj = tryint64;
                        break;
                    case "System.SByte":
                        if (SByte.TryParse(valueStr, out var trysb)) obj = trysb;
                        break;
                    case "System.Int16":
                        if (Int16.TryParse(valueStr, out var tryint16)) obj = tryint16;
                        break;
                    case "System.UInt32":
                        if (UInt32.TryParse(valueStr, out var tryuint32)) obj = tryuint32;
                        break;
                    case "System.UInt64":
                        if (UInt64.TryParse(valueStr, out var tryuint64)) obj = tryuint64;
                        break;
                    case "System.UInt16":
                        if (UInt16.TryParse(valueStr, out var tryuint16)) obj = tryuint16;
                        break;
                    case "System.DateTime":
                        if (DateTime.TryParse(valueStr, out var trydt)) obj = trydt;
                        break;
                    case "System.DateTimeOffset":
                        if (DateTimeOffset.TryParse(valueStr, out var trydtos)) obj = trydtos;
                        break;
                    case "System.TimeSpan":
                        if (Int64.TryParse(valueStr, out tryint64)) obj = new TimeSpan(tryint64);
                        break;
                    case "System.Guid":
                        if (Guid.TryParse(valueStr, out var tryguid)) obj = tryguid;
                        break;
                    default:
                        isElse = true;
                        break;
                }

                if (isElse == false)
                {
                    if (obj == null) return default(T);
                    return (T)obj;
                }
            }

            if (Adapter.TopOwner.DeserializeRaw != null) return (T)Adapter.TopOwner.DeserializeRaw(valueRaw, typeof(T));

            if (valueStr == null) valueStr = encoding.GetString(valueRaw);
            if (Adapter.TopOwner.Deserialize != null) return (T)Adapter.TopOwner.Deserialize(valueStr, typeof(T));
            return valueStr.ConvertTo<T>();
        }

19 View Source File : TextBoxNumericHelper.cs
License : MIT License
Project Creator : ahmed-abdelrazek

private static void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            var textBox = (TextBox)sender;

            string newText;

            if (textBox.SelectionLength == 0)
            {
                newText = textBox.Text.Insert(textBox.SelectionStart, e.Text);
            }
            else
            {
                var textAfterDelete = textBox.Text.Remove(textBox.SelectionStart, textBox.SelectionLength);

                newText = textAfterDelete.Insert(textBox.SelectionStart, e.Text);
            }

            var evenOddConstraint = GetEvenOddConstraint(textBox);

            switch (GetOnlyNumeric(textBox))
            {
                case NumericFormat.Decimal:
                    {
                        if (decimal.TryParse(newText, out decimal number))
                        {
                            switch (evenOddConstraint)
                            {
                                case EvenOddConstraint.OnlyEven:
                                    {
                                        e.Handled = number % 2 != 0;
                                        break;
                                    }
                                case EvenOddConstraint.OnlyOdd:
                                    {
                                        e.Handled = number % 2 == 0;
                                        break;
                                    }
                            }
                        }
                        else
                        {
                            e.Handled = true;
                        }
                        break;
                    }

                case NumericFormat.Double:
                    {
                        if (double.TryParse(newText, out double number))
                        {
                            switch (evenOddConstraint)
                            {
                                case EvenOddConstraint.OnlyEven:
                                    {
                                        e.Handled = number % 2 != 0;
                                        break;
                                    }
                                case EvenOddConstraint.OnlyOdd:
                                    {
                                        e.Handled = number % 2 == 0;
                                        break;
                                    }
                            }
                        }
                        else
                        {
                            e.Handled = true;
                        }
                        break;
                    }

                case NumericFormat.Int:
                    {
                        if (int.TryParse(newText, out int number))
                        {
                            switch (evenOddConstraint)
                            {
                                case EvenOddConstraint.OnlyEven:
                                    {
                                        e.Handled = number % 2 != 0;
                                        break;
                                    }
                                case EvenOddConstraint.OnlyOdd:
                                    {
                                        e.Handled = number % 2 == 0;
                                        break;
                                    }
                            }
                        }
                        else
                        {
                            e.Handled = true;
                        }
                        break;
                    }

                case NumericFormat.Uint:
                    {
                        if (uint.TryParse(newText, out uint number))
                        {
                            switch (evenOddConstraint)
                            {
                                case EvenOddConstraint.OnlyEven:
                                    {
                                        e.Handled = number % 2 != 0;
                                        break;
                                    }
                                case EvenOddConstraint.OnlyOdd:
                                    {
                                        e.Handled = number % 2 == 0;
                                        break;
                                    }
                            }
                        }
                        else
                        {
                            e.Handled = true;
                        }
                        break;
                    }

                case NumericFormat.Natural:
                    {
                        if (uint.TryParse(newText, out uint number))
                        {
                            if (number == 0)
                            {
                                e.Handled = true;
                            }
                            else
                            {
                                switch (evenOddConstraint)
                                {
                                    case EvenOddConstraint.OnlyEven:
                                        {
                                            e.Handled = number % 2 != 0;
                                            break;
                                        }
                                    case EvenOddConstraint.OnlyOdd:
                                        {
                                            e.Handled = number % 2 == 0;
                                            break;
                                        }
                                }
                            }
                        }
                        else
                        {
                            e.Handled = true;
                        }
                        break;
                    }
            }
        }

19 View Source File : DelimitedDoubleListTypeConverter.cs
License : MIT License
Project Creator : Actipro

public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) {
			var delimitedString = value as string;
			if (!string.IsNullOrEmpty(delimitedString)) {
				double numberValue;
				var list = new List<double>();
				var numberStrings = delimitedString.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
				foreach (var numberString in numberStrings) {
					if (double.TryParse(numberString, out numberValue))
						list.Add(numberValue);
				}

				return list;
			}

			return base.ConvertFrom(context, culture, value);
		}

19 View Source File : GetValueFromJsonString.cs
License : MIT License
Project Creator : akaskela

protected override void Execute(CodeActivityContext context)
        {
            var workflowContext = context.GetExtension<IWorkflowContext>();
            if (!string.IsNullOrEmpty(JsonString.Get<string>(context)) && !string.IsNullOrEmpty(JsonPath.Get<string>(context)))
            {
                JObject jsonObject = JObject.Parse(JsonString.Get<string>(context));
                JToken token = jsonObject.SelectToken(JsonPath.Get<string>(context));
                if(token != null)
                {
                    string value = (string)token;
                    Result_Text.Set(context, value);

                    Guid id = new Guid();
                    if (Guid.TryParse(value, out id))
                    {
                        this.Result_Guid.Set(context, value);
                    }

                    DateTime dateTime = new DateTime();
                    if (DateTime.TryParse(value, out dateTime))
                    {
                        this.Result_DateTime.Set(context, dateTime);
                    }

                    decimal decimalValue = new decimal();
                    if (decimal.TryParse(value, out decimalValue))
                    {
                        this.Result_Decimal.Set(context, decimalValue);
                        try
                        {
                            this.Result_Money.Set(context, new Money(decimalValue));
                        }
                        catch { }
                    }

                    double doubleValue = new double();
                    if (double.TryParse(value, out doubleValue))
                    {
                        this.Result_Double.Set(context, doubleValue);
                    }

                    int intValue = 0;
                    if (int.TryParse(value, out intValue))
                    {
                        this.Result_WholeNumber.Set(context, intValue);
                    }
                }
            }
        }

19 View Source File : FrmDoublePageReader.cs
License : GNU General Public License v3.0
Project Creator : 9vult

private Page[] SortPages(Page[] items)
        {
            // Get the numeric values of the items.
            int num_items = items.Length;
            const string float_pattern = @"-?\d+\.?\d*";
            double[] values = new double[num_items];
            for (int i = 0; i < num_items; i++)
            {
                string match = Regex.Match(items[i].num.ToString(), float_pattern).Value;
#pragma warning disable IDE0018 // Inline variable declaration
                double value;
#pragma warning restore IDE0018 // Inline variable declaration
                if (!double.TryParse(match, out value))
                    value = double.MinValue;
                values[i] = value;
            }

            // Sort the items array using the keys to determine order.
            Array.Sort(values, items);
            return items;
        }

19 View Source File : NumericManipulator.cs
License : MIT License
Project Creator : akaskela

public string RoundToDecimalPlaces(string input, int places)
        {
            string displayValue = String.Empty;
            double inputAsDouble = new double();
            if (double.TryParse(input, out inputAsDouble))
            {
                displayValue = Math.Round(inputAsDouble, places, MidpointRounding.AwayFromZero).ToString("N" + places.ToString());
            }

            return displayValue;
        }

19 View Source File : Program.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : ActuarialIntelligence

static void Main(string[] args)
        {
            bool DonotLoadGrid = true;
            var grid = new List<IList<double>>();
            if (!DonotLoadGrid)
            {
                Console.WriteLine("Loading Stream: " + DateTime.Now.ToString());
                var sr = new StreamReader(@"C:\data\table.csv");

                while (!sr.EndOfStream)
                {
                    var line = sr.ReadLine();
                    var fieldValues = line.Split(',');
                    var fields = new List<double>();
                    var rdm = new Random(100000);
                    foreach (var field in fieldValues)
                    {
                        var res = 0d;
                        var add = double.TryParse(field, out res) == true ? res : rdm.NextDouble();
                        fields.Add(add);
                    }
                    grid.Add(fields);
                }
                Console.WriteLine("Grid loaded successfully!! " + DateTime.Now.ToString());
            }
            var keepProcessing = true;
            while (keepProcessing)
            {
                Console.WriteLine(DateTime.Now.ToString());
                Console.WriteLine("Enter Expression:");
                var expression = Console.ReadLine();
                if (expression.ToLower() == "exit")
                {
                    keepProcessing = false;
                }
                else
                {
                    try
                    {
                        if(expression.Equals("zspread"))
                        {
                            var result = ConnectedInstruction.GetZSpread(grid,3,503);
                        }
                        if (expression.Substring(0, 19).ToLower().Equals("logisticregression "))
                        {
                            keepProcessing = true;
                            var paths = expression.Split(' '); 
                            #region Python
                                var script [email protected]"
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.cross_validation import train_test_split
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score

creditData = pd.read_csv("+paths[1][email protected]")

print(creditData.head())
print(creditData.describe())
print(creditData.corr())

features = creditData[['income', 'age', 'loan']]
target = creditData.default

feature_train, feature_test, target_train, target_test = train_test_split(features, target, test_size = 0.3)

model = LogisticRegression()
model.fit = model.fit(feature_train, target_train)
predictions = model.fit.predict(feature_test)

print(confusion_matrix(target_test, predictions))
print(accuracy_score(target_test, predictions))
";
                            var sw = new StreamWriter(@"c:\data\logistic.py");
                            sw.Write(script);
                            sw.Close();
                            #endregion
                            ProcessStartInfo start = new ProcessStartInfo();
                            Console.WriteLine("Starting Python Engine...");
                            start.FileName = @"C:\Users\rajiyer\PycharmProjects\TestPlot\venv\Scripts\python.exe";
                            start.Arguments = string.Format("{0} {1}", @"c:\data\logistic.py", args);
                            start.UseShellExecute = false;
                            start.RedirectStandardOutput = true;
                            Console.WriteLine("Starting Process..."+ DateTime.Now.ToString());
                            using (Process process = Process.Start(start))
                            {
                                using (StreamReader reader = process.StandardOutput)
                                {
                                    string result = reader.ReadToEnd();
                                    Console.Write(result);
                                }
                            }
                            Console.WriteLine("Process Succeeded..." + DateTime.Now.ToString());
                        }
                        if(expression.Substring(0,12) == "videoreplacedyse")
                        {
                            #region python
                            var python = @"
from keras.preprocessing.image import img_to_array
import imutils
import cv2
from keras.models import load_model
import numpy as np
import geocoder
#import mysql.connector as con

#mydb = con.connect(
#  host=""localhost"",
#  user=""yourusername"",
#  preplacedwd=""yourpreplacedword"",
# database=""mydatabase""
#)
#mycursor = mydb.cursor()

g = geocoder.ip('me')

# parameters for loading data and images
detection_model_path = 'C:\\Users\\rajiyer\\Doreplacedents\\Test Data\\Sentiment replacedysis\\Emotion-recognition-master\\haarcascade_files\\haarcascade_frontalface_default.xml'
emotion_model_path = 'C:\\Users\\rajiyer\\Doreplacedents\\Test Data\\Sentiment replacedysis\\Emotion-recognition-master\\models\\_mini_XCEPTION.102-0.66.hdf5'

# hyper-parameters for bounding boxes shape
# loading models
face_detection = cv2.CascadeClreplacedifier(detection_model_path)
emotion_clreplacedifier = load_model(emotion_model_path, compile = False)
EMOTIONS = [""angry"", ""disgust"", ""scared"", ""happy"", ""sad"", ""surprised"",
""neutral""]


# feelings_faces = []
# for index, emotion in enumerate(EMOTIONS):
# feelings_faces.append(cv2.imread('emojis/' + emotion + '.png', -1))

# starting video streaming
cv2.namedWindow('your_face')
camera = cv2.VideoCapture(0)
f = open(""C:\\Users\\rajiyer\\Doreplacedents\\Test Data\\Probability.txt"", ""a+"")

while True:
frame = camera.read()[1]
#reading the frame
frame = imutils.resize(frame, width = 300)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_detection.detectMultiScale(gray, scaleFactor = 1.1, minNeighbors = 5, minSize = (30, 30), flags = cv2.CASCADE_SCALE_IMAGE)


canvas = np.zeros((250, 300, 3), dtype = ""uint8"")
frameClone = frame.copy()
if len(faces) > 0:
faces = sorted(faces, reverse = True,
key = lambda x: (x[2] - x[0]) * (x[3] - x[1]))[0]
(fX, fY, fW, fH) = faces
# Extract the ROI of the face from the grayscale image, resize it to a fixed 28x28 pixels, and then prepare
# the ROI for clreplacedification via the CNN
roi = gray[fY: fY + fH, fX: fX + fW]
roi = cv2.resize(roi, (64, 64))
roi = roi.astype(""float"") / 255.0
roi = img_to_array(roi)
roi = np.expand_dims(roi, axis = 0)



preds = emotion_clreplacedifier.predict(roi)[0]
emotion_probability = np.max(preds)
label = EMOTIONS[preds.argmax()]
else: continue



for (i, (emotion, prob)) in enumerate(zip(EMOTIONS, preds)):
# construct the label text
text = ""{}: {:.2f}%"".format(emotion, prob * 100)
#sql = ""INSERT INTO predData (Metadata, Probability) VALUES (%s, %s)""
#val = (""Meta"", prob * 100)
f.write(text)
#str1 = ''.join(str(e) for e in g.latlng)
#f.write(str1)
#mycursor.execute(sql, val)
#mydb.commit()
# draw the label + probability bar on the canvas
# emoji_face = feelings_faces[np.argmax(preds)]

                
w = int(prob * 300)
cv2.rectangle(canvas, (7, (i * 35) + 5),
(w, (i * 35) + 35), (0, 0, 255), -1)
cv2.putText(canvas, text, (10, (i * 35) + 23),
cv2.FONT_HERSHEY_SIMPLEX, 0.45,
(255, 255, 255), 2)
cv2.putText(frameClone, label, (fX, fY - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 0, 255), 2)
cv2.rectangle(frameClone, (fX, fY), (fX + fW, fY + fH),
(0, 0, 255), 2)


#    for c in range(0, 3):
#        frame[200:320, 10:130, c] = emoji_face[:, :, c] * \
#        (emoji_face[:, :, 3] / 255.0) + frame[200:320,
#        10:130, c] * (1.0 - emoji_face[:, :, 3] / 255.0)


cv2.imshow('your_face', frameClone)
cv2.imshow(""Probabilities"", canvas)
if cv2.waitKey(1) & 0xFF == ord('q'):
break

camera.release()
cv2.destroyAllWindows()
";
                            var sw = new StreamWriter(@"c:\data\face.py");
                            sw.Write(python);
                            sw.Close();
                            #endregion
                            ProcessStartInfo start = new ProcessStartInfo();
                            Console.WriteLine("Starting Python Engine...");
                            start.FileName = @"C:\Users\rajiyer\PycharmProjects\TestPlot\venv\Scripts\python.exe";
                            start.Arguments = string.Format("{0} {1}", @"c:\data\face.py", args);
                            start.UseShellExecute = false;
                            start.RedirectStandardOutput = true;
                            Console.WriteLine("Starting Process..." + DateTime.Now.ToString());
                            using (Process process = Process.Start(start))
                            {
                                using (StreamReader reader = process.StandardOutput)
                                {
                                    string result = reader.ReadToEnd();
                                    Console.Write(result);
                                }
                            }
                            Console.WriteLine("Process Succeeded..." + DateTime.Now.ToString());
                        }
                        if (expression.Substring(0,12).ToLower().Equals("kaplanmeier "))
                        {
                            keepProcessing = true;
                            var columnsOfconcern = expression.Split(' ');
                            Console.WriteLine("Preparing...");
                            var observations = new List<PairedObservation>();
                            var ca = GetColumn(grid,int.Parse(columnsOfconcern[1]));
                            var cb = GetColumn(grid, int.Parse(columnsOfconcern[2]));
                            var cc = GetColumn(grid, int.Parse(columnsOfconcern[3]));
                            for(int i=0;i<ca.Count;i++)
                            {
                                observations.Add(new PairedObservation((decimal)ca[i], (decimal)cb[i], (decimal)cc[i]));
                            }
                            var kp = new KaplanMeier(observations);
                        }
                        if (expression.Equals("write"))
                        {
                            keepProcessing = true;
                            ConnectedInstruction.WritetoCsvu(grid, @"c:\data\temp.csv");
                        }
                        if (expression.Substring(0, 9) == "getvalue(")
                        {
                            keepProcessing = true;
                            Regex r = new Regex(@"\(([^()]+)\)*");
                            var res = r.Match(expression);
                            var val = res.Value.Split(',');
                            try
                            {
                                var gridVal = grid[int.Parse(val[0].Replace("(", "").Replace(")", ""))]
                                    [int.Parse(val[1].Replace("(", "").Replace(")", ""))];
                                Console.WriteLine(gridVal.ToString() + "\n");
                            }
                            catch (ArgumentOutOfRangeException)
                            {
                                Console.WriteLine("Hmmm,... apologies, can't seem to find that within range...");
                            }
                        }
                        else
                        {
                            keepProcessing = true;
                            Console.WriteLine("Process Begin:" + DateTime.Now.ToString());
                            var result = ConnectedInstruction.ParseExpressionAndRunAgainstInMemmoryModel(grid, expression);
                            Console.WriteLine("Process Ended:" + DateTime.Now.ToString());
                        }
                    }
                    catch (ArgumentOutOfRangeException)
                    {

                    }
                }
            }
        }

19 View Source File : NumericValidationRule.cs
License : Apache License 2.0
Project Creator : AKruimink

public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            var strValue = Convert.ToString(value);

            if (string.IsNullOrEmpty(strValue))
            {
                if (AllowNull)
                {
                    return new ValidationResult(true, null);
                }
                return new ValidationResult(false, $"Value cannot be converted to string");
            }

            var canConvert = (ValidationType?.Name) switch
            {
                nameof(Boolean) => bool.TryParse(strValue, out var boolValue),
                nameof(Double) => double.TryParse(strValue, out var doubleValue),
                nameof(Int32) => int.TryParse(strValue, out var intValue),
                nameof(Int64) => long.TryParse(strValue, out var longValue),
                _ => throw new InvalidCastException($"{ValidationType?.Name} is not a supported type"),
            };

19 View Source File : MainWindow.xaml.cs
License : GNU General Public License v3.0
Project Creator : 1RedOne

private void TextBox_OnEndingButtonTextInput(object sender, TextCompositionEventArgs e)
        {
            var textBox = sender as TextBox;
            // Use SelectionStart property to find the caret position.
            // Insert the previewed text into the existing text in the textbox.
            var fullText = textBox.Text.Insert(textBox.SelectionStart, e.Text);

            double val;
            // If parsing is successful, set Handled to false
            e.Handled = !double.TryParse(fullText, out val);
        }

19 View Source File : Response.cs
License : MIT License
Project Creator : alen-smajic

public static Response FromWebResponse(IAsyncRequest request, HttpWebResponse apiResponse, Exception apiEx) {

			Response response = new Response();
			response.Request = request;

			if (null != apiEx) {
				response.AddException(apiEx);
			}

			// timeout: API response is null
			if (null == apiResponse) {
				response.AddException(new Exception("No Reponse."));
			} else {
				// https://www.mapbox.com/api-doreplacedentation/#rate-limit-headers
				if (null != apiResponse.Headers) {
					response.Headers = new Dictionary<string, string>();
					for (int i = 0; i < apiResponse.Headers.Count; i++) {
						// TODO: implement .Net Core / UWP implementation
						string key = apiResponse.Headers.Keys[i];
						string val = apiResponse.Headers[i];
						response.Headers.Add(key, val);
						if (key.Equals("X-Rate-Limit-Interval", StringComparison.InvariantCultureIgnoreCase)) {
							int limitInterval;
							if (int.TryParse(val, out limitInterval)) { response.XRateLimitInterval = limitInterval; }
						} else if (key.Equals("X-Rate-Limit-Limit", StringComparison.InvariantCultureIgnoreCase)) {
							long limitLimit;
							if (long.TryParse(val, out limitLimit)) { response.XRateLimitLimit = limitLimit; }
						} else if (key.Equals("X-Rate-Limit-Reset", StringComparison.InvariantCultureIgnoreCase)) {
							double unixTimestamp;
							if (double.TryParse(val, out unixTimestamp)) {
								response.XRateLimitReset = UnixTimestampUtils.From(unixTimestamp);
							}
						} else if (key.Equals("Content-Type", StringComparison.InvariantCultureIgnoreCase)) {
							response.ContentType = val;
						}
					}
				}

				if (apiResponse.StatusCode != HttpStatusCode.OK) {
					response.AddException(new Exception(string.Format("{0}: {1}", apiResponse.StatusCode, apiResponse.StatusDescription)));
				}
				int statusCode = (int)apiResponse.StatusCode;
				response.StatusCode = statusCode;
				if (429 == statusCode) {
					response.AddException(new Exception("Rate limit hit"));
				}

				if (null != apiResponse) {
					using (Stream responseStream = apiResponse.GetResponseStream()) {
						byte[] buffer = new byte[0x1000];
						int bytesRead;
						using (MemoryStream ms = new MemoryStream()) {
							while (0 != (bytesRead = responseStream.Read(buffer, 0, buffer.Length))) {
								ms.Write(buffer, 0, bytesRead);
							}
							response.Data = ms.ToArray();
						}
					}
					apiResponse.Close();
				}
			}

			return response;
		}

19 View Source File : PointSizeComponent.xaml.cs
License : MIT License
Project Creator : ADeltaX

public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            if (double.TryParse((string)value, out _))
                return ValidationResult.ValidResult;
            else
                return new ValidationResult(false, "Not a valid double number");
        }

19 View Source File : ReaderHelper.cs
License : GNU General Public License v3.0
Project Creator : 9vult

public static Page[] SortPages(List<Page> aList)
        {
            Page[] items = aList.ToArray();

            // Get the numeric values of the items.
            int num_items = items.Length;
            const string float_pattern = @"-?\d+\.?\d*";
            double[] values = new double[num_items];
            for (int i = 0; i < num_items; i++)
            {
                string match = Regex.Match(items[i].GetID(), float_pattern).Value;
                if (!double.TryParse(match, out double value))
                    value = double.MinValue;
                values[i] = value;
            }

            // Sort the items array using the keys to determine order.
            Array.Sort(values, items);
            return items;
        }

19 View Source File : CommonExtensions.cs
License : MIT License
Project Creator : 17MKH

public static double ToDouble(this object s, int? digits = null)
    {
        if (s == null || s == DBNull.Value)
            return 0d;

        double.TryParse(s.ToString(), out double result);

        if (digits == null)
            return result;

        return Math.Round(result, digits.Value);
    }

19 View Source File : MainWindow.xaml.cs
License : GNU General Public License v3.0
Project Creator : 1RedOne

private void TextBox_OnStartingButtonTextInput(object sender, TextCompositionEventArgs e)
        {
            var textBox = sender as TextBox;
            // Use SelectionStart property to find the caret position.
            // Insert the previewed text into the existing text in the textbox.
            var fullText = textBox.Text.Insert(textBox.SelectionStart, e.Text);

            double val;
            // If parsing is successful, set Handled to false
            e.Handled = !double.TryParse(fullText, out val);
        }

19 View Source File : JSONParser.cs
License : MIT License
Project Creator : 5minlab

static object ParseAnonymousValue(string json) {
            if (json.Length == 0)
                return null;
            if (json[0] == '{' && json[json.Length - 1] == '}') {
                List<string> elems = Split(json);
                if (elems.Count % 2 != 0)
                    return null;
                var dict = new Dictionary<string, object>(elems.Count / 2);
                for (int i = 0; i < elems.Count; i += 2)
                    dict.Add(elems[i].Substring(1, elems[i].Length - 2), ParseAnonymousValue(elems[i + 1]));
                return dict;
            }
            if (json[0] == '[' && json[json.Length - 1] == ']') {
                List<string> items = Split(json);
                var finalList = new List<object>(items.Count);
                for (int i = 0; i < items.Count; i++)
                    finalList.Add(ParseAnonymousValue(items[i]));
                return finalList;
            }
            if (json[0] == '\"' && json[json.Length - 1] == '\"') {
                string str = json.Substring(1, json.Length - 2);
                return str.Replace("\\", string.Empty);
            }
            if (char.IsDigit(json[0]) || json[0] == '-') {
                if (json.Contains(".")) {
                    double result;
                    double.TryParse(json, out result);
                    return result;
                } else {
                    int result;
                    int.TryParse(json, out result);
                    return result;
                }
            }
            if (json == "true")
                return true;
            if (json == "false")
                return false;
            // handles json == "null" as well as invalid JSON
            return null;
        }

19 View Source File : SentinelCommands.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

[CommandHandler("ban", AccessLevel.Sentinel, CommandHandlerFlag.None, 4,
            "Bans the specified player account.",
            "[accountname] [days] [hours] [minutes] (reason)\n"
            + "This command bans the specified player account for the specified time. This player will not be able to enter the game with any character until the time expires.\n"
            + "Example: @ban AccountName 0 0 5\n"
            + "Example: @ban AccountName 1 0 0 banned 1 day because reasons\n")]
        public static void HandleBanAccount(Session session, params string[] parameters)
        {
            // usage: @ban < acct > < days > < hours > < minutes >
            // This command bans the specified player account for the specified time.This player will not be able to enter the game with any character until the time expires.
            // @ban - Bans the specified player account.

            var accountName = parameters[0];
            var banDays     = parameters[1];
            var banHours    = parameters[2];
            var banMinutes  = parameters[3];

            var banReason = string.Empty;
            if (parameters.Length > 4)
            {
                var parametersAfterBanParams = "";
                for (var i = 4; i < parameters.Length; i++)
                {
                    parametersAfterBanParams += parameters[i] + " ";
                }
                parametersAfterBanParams = parametersAfterBanParams.Trim();
                banReason = parametersAfterBanParams;
            }

            var account = DatabaseManager.Authentication.GetAccountByName(accountName);

            if (account == null)
            {
                CommandHandlerHelper.WriteOutputInfo(session, $"Cannot ban \"{accountName}\" because that account cannot be found in database. Check syntax/spelling and try again.", ChatMessageType.Broadcast);
                return;
            }

            if (!double.TryParse(banDays, out var days) || days < 0)
            {
                CommandHandlerHelper.WriteOutputInfo(session, $"Days must not be less than 0.", ChatMessageType.Broadcast);
                return;
            }
            if (!double.TryParse(banHours, out var hours) || hours < 0)
            {
                CommandHandlerHelper.WriteOutputInfo(session, $"Hours must not be less than 0.", ChatMessageType.Broadcast);
                return;
            }
            if (!double.TryParse(banMinutes, out var minutes) || minutes < 0)
            {
                CommandHandlerHelper.WriteOutputInfo(session, $"Minutes must not be less than 0.", ChatMessageType.Broadcast);
                return;
            }

            var bannedOn = DateTime.UtcNow;
            var banExpires = DateTime.UtcNow.AddDays(days).AddHours(hours).AddMinutes(minutes);

            var bannedBy = 0u;
            if (session != null)
            {
                bannedBy = session.AccountId;
            }

            account.BannedTime = bannedOn;
            account.BanExpireTime = banExpires;
            account.BannedByAccountId = bannedBy;
            if (!string.IsNullOrWhiteSpace(banReason))
                account.BanReason = banReason;

            DatabaseManager.Authentication.UpdateAccount(account);

            // Boot the player
            if (NetworkManager.Find(accountName) != null)
            {
                var bootArgs = new List<string> { "account" };
                if (!string.IsNullOrWhiteSpace(banReason))
                {
                    bootArgs.Add($"{accountName},");
                    bootArgs.Add(banReason);
                }
                else
                    bootArgs.Add(accountName);
                HandleBoot(session, bootArgs.ToArray());
            }

            var banText = $"Banned account {accountName} for {days} days, {hours} hours and {minutes} minutes.{(!string.IsNullOrWhiteSpace(banReason) ? $" Reason: {banReason}" : "")}";
            CommandHandlerHelper.WriteOutputInfo(session, banText, ChatMessageType.Broadcast);
            PlayerManager.BroadcastToAuditChannel(session?.Player, banText);
        }

19 View Source File : ModEntry.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn

public static void SpawnBossLoot(GameLocation location, float x, float y, float difficulty)
        {
            Vector2 playerPosition = new Vector2((float)Game1.player.GetBoundingBox().Center.X, (float)Game1.player.GetBoundingBox().Center.Y);

            foreach (string loot in BossLootList.loot)
            {
                string[] loota = loot.Split('/');
                if (!int.TryParse(loota[0], out int objectToAdd))
                {
                    try
                    {
                        objectToAdd = Game1.objectInformation.First(p => p.Value.StartsWith($"{loota[0]}/")).Key;
                    }
                    catch
                    {
                        PMonitor.Log($"loot object {loota[0]} is invalid", LogLevel.Error);
                        continue;
                    }
                }
                Object o = new Object(objectToAdd, 1);
                if (objectToAdd >= 0)
                {
                    if (o.Name == Game1.content.LoadString("Strings\\StringsFromCSFiles:CraftingRecipe.cs.575"))
                    {
                        PMonitor.Log($"object {objectToAdd} is error item");
                        continue;
                    }
                }

                if (!double.TryParse(loota[1], out double chance))
                {
                    PMonitor.Log($"loot chance {loota[1]} is invalid", LogLevel.Error);
                    continue;
                }

                while (chance > 1 || (chance > 0 && Game1.random.NextDouble() < chance))
                {
                    if (objectToAdd < 0)
                    {
                        Game1.createDebris(Math.Abs(objectToAdd), (int)x, (int)y, (int)Math.Round(Game1.random.Next(10, 40) * difficulty), location);
                    }
                    else
                    {
                        location.debris.Add(Game1.createItemDebris(o, new Vector2(x, y), Game1.random.Next(4)));
                    }

                    chance -= 1;
                }
            }
        }

See More Examples