double.Parse(string)

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

1259 Examples 7

19 View Source File : AnalogyFilePlotting.cs
License : MIT License
Project Creator : Analogy-LogViewer

[MethodImpl(MethodImplOptions.AggressiveInlining)]
        private void ProcessLine(string line)
        {
            try
            {
                var items = line.Split(seperators);
                if (CustomXAxis)
                {
                    switch (_xAxisType)
                    {
                        case replacedogyCustomXAxisPlot.Numerical:
                            var x = double.Parse(items[0]);
                            for (int i = 1; i < items.Length; i++)
                            {
                                var str = items[i];
                                double val = double.Parse(str);
                                string series = headers[i];
                                var data = new replacedogyPlottingPointData(series, val, x);
                                OnNewPointData?.Invoke(this, data);
                            }
                            break;
                        case replacedogyCustomXAxisPlot.DateTimeUnixMillisecond:
                            DateTime timeMili = DateTimeOffset.FromUnixTimeMilliseconds(long.Parse(items[0])).DateTime;
                            for (int i = 1; i < items.Length; i++)
                            {
                                var str = items[i];
                                double val = double.Parse(str);
                                string series = headers[i];
                                var data = new replacedogyPlottingPointData(series, val, timeMili);
                                OnNewPointData?.Invoke(this, data);
                            }
                            break;
                        case replacedogyCustomXAxisPlot.DateTimeUnixSecond:
                            DateTime timeSecond = DateTimeOffset.FromUnixTimeSeconds(long.Parse(items[0])).DateTime;
                            for (int i = 1; i < items.Length; i++)
                            {
                                var str = items[i];
                                double val = double.Parse(str);
                                string series = headers[i];
                                var data = new replacedogyPlottingPointData(series, val, timeSecond);
                                OnNewPointData?.Invoke(this, data);
                            }
                            break;
                        default:
                            throw new ArgumentOutOfRangeException();
                    }
                }
                else
                {
                    for (int i = 0; i < items.Length; i++)
                    {
                        var str = items[i];
                        double val = double.Parse(str);
                        string series = headers[i];
                        var data = new replacedogyPlottingPointData(series, val, processed);
                        OnNewPointData?.Invoke(this, data);
                    }
                }
                processed++;
            }
            catch (Exception e)
            {
                replacedogyLogManager.Instance.LogError(e.ToString(), nameof(replacedogyFilePlotting));
            }

        }

19 View Source File : EgsDoseLoader.cs
License : Apache License 2.0
Project Creator : anmcgrath

public EgsDoseObject Load(string fileName)
        {
            EgsDoseObject dose = new EgsDoseObject();
            GridBasedVoxelDataStructure grid = new GridBasedVoxelDataStructure();
            dose.Name = Path.GetFileName(fileName);
            string text = File.ReadAllText(fileName);
            string[] numbers = text.Split(new char[] { '\n', ' ', '\t', '\r' }, StringSplitOptions.RemoveEmptyEntries);
            int SizeX = Int32.Parse(numbers[0]);
            int SizeY = Int32.Parse(numbers[1]);
            int SizeZ = Int32.Parse(numbers[2]);
            grid.XCoords = new double[SizeX];
            grid.YCoords = new double[SizeY];
            grid.ZCoords = new double[SizeZ];
            grid.Data = new float[SizeX, SizeY, SizeZ];

            int offset = 3;

            for (int i = 0; i < SizeX; i++)
            {
                grid.XCoords[i] = 10 * (Double.Parse(numbers[offset + i]) + Double.Parse(numbers[offset + i + 1])) / 2;
            }
            offset += SizeX + 1;
            for (int i = 0; i < SizeY; i++)
            {
                grid.YCoords[i] = 10 * (Double.Parse(numbers[offset + i]) + Double.Parse(numbers[offset + i + 1])) / 2;
            }
            offset += SizeY + 1;
            for (int i = 0; i < SizeZ; i++)
            {
                grid.ZCoords[i] = 10 * (Double.Parse(numbers[offset + i]) + Double.Parse(numbers[offset + i + 1])) / 2;
            }
            offset += SizeZ + 1;

            for (int i = 0; i < SizeX * SizeY * SizeZ; i++)
            {
                int indexX = i % SizeX;
                int indexZ = (int)(i / (SizeX * SizeY));
                int indexY = (int)(i / SizeX) - indexZ * (SizeY);
                grid.Data[indexX, indexY, indexZ] = float.Parse(numbers[offset + i]);
            }

            foreach(Voxel voxel in grid.Voxels)
            {
                if (voxel.Value > grid.GlobalMax.Value)
                    grid.GlobalMax = voxel;
            }
            return dose;
        }

19 View Source File : Util.cs
License : MIT License
Project Creator : ajayyy

public static float GetCommandLineArgValue( string argumentName, float flDefaultValue )
		{
			string[] args = System.Environment.GetCommandLineArgs();
			for ( int i = 0; i < args.Length; i++ )
			{
				if ( args[i].Equals( argumentName ) )
				{
					if ( i == ( args.Length - 1 ) ) // Last arg, return default
					{
						return flDefaultValue;
					}

					return (float)Double.Parse( args[i + 1] );
				}
			}

			return flDefaultValue;
		}

19 View Source File : TestAnalogAudioOutput.cs
License : GNU General Public License v3.0
Project Creator : alvaroyurrita

static double GetFirstParameterDouble(string value, string MessageHelp)
        {
            var commands = value.Split(' ');
            double Result;
            try
            {
                Result = double.Parse(commands[0]);
                Result = Math.Round(Result, 1);
            }
            catch (Exception)
            {
                CrestronConsole.ConsoleCommandResponse(MessageHelp);
                return 0xffff;
            }
            return Result;
        }

19 View Source File : PriceExternalList.cs
License : GNU Affero General Public License v3.0
Project Creator : alexander-pick

private void importRun(string filePath, string defaultFoil, string defaultPlayset, string defaultSigned, string defaultAltered,
        string defaultCondition, string defaultExpansion, string defaultLanguageID)
    {
      DataTable dt;
      try
      {
        dt = MKMCsvUtils.ConvertCSVtoDataTable(filePath);
      }
      catch (Exception eError)
      {
        LogError("importing file " + filePath, eError.Message, true);
        return;
      }
      importedColumns = dt.Columns;
      MainView.Instance.LogMainWindow("Loaded file with " + dt.Rows.Count + " articles, processing...");

      importedAll.Clear();
      importedValidOnly.Clear();
      int counter = 0, failed = 0, hasPriceGuide = 0;
      // if we search for products based on their locName, we have to make a product query for each of them - store the result to reuse in case there are more of those cards later in the list
      Dictionary<string, string> locNameProducts = new Dictionary<string, string>();
      foreach (DataRow row in dt.Rows)
      {
        MKMMetaCard mc = new MKMMetaCard(row);
        importedAll.Add(mc); // add it no matter if it can be correctly processed or not so that we can export it
        counter++;
        string productID = mc.GetAttribute(MCAttribute.ProductID);
        string name = mc.GetAttribute(MCAttribute.Name);
        string languageID = mc.GetAttribute(MCAttribute.LanguageID);
        if (languageID == "" && defaultLanguageID != "")
        {
          languageID = defaultLanguageID;
          mc.SetLanguageID(languageID);
        }
        if (name == "" && productID == "") // we have neither name or productID - we have to hope we have locName and language
        {
          string locName = mc.GetAttribute(MCAttribute.LocName).ToLower();
          if (locName == "" || languageID == "")
          {
            LogError("importing line #" + (counter + 1) + ", article will be ignored",
                "Neither product ID, English name, or localized name + language was found, cannot identify the card.", false);
            failed++;
            continue;
          }
          // have to use search on MKM to get the English name
          string hash = "" + locName + languageID; // technically it is unlikely that two different languages would have the same name, but could happen
          if (!locNameProducts.TryGetValue(hash, out name)) // we haven't had a product like this in the list yet, use MKM API to find it
          {
            int start = 0;
            List<XmlNode> found = new List<XmlNode>();
            try
            {
              XmlNodeList products;
              do
              {
                XmlDoreplacedent doc = MKMInteract.RequestHelper.FindProducts(locName, languageID, start);
                products = doc.GetElementsByTagName("product");
                // we still want to insert empty string in the hash table - this way we know in the future that this name is invalid
                locNameProducts[hash] = "";
                foreach (XmlNode product in products)
                {
                  // only take exact matches, otherwise we get all kinds of garbage like sleeves etc. that use the name of the card
                  if (product["locName"].InnerText.ToLower() == locName)
                    found.Add(product);
                }
                start += products.Count;
              } while (products.Count == 100);

            }
            catch (Exception eError)
            {
              LogError("importing line #" + (counter + 1) + ", trying to find product by its localized name "
                  + locName + ", article will be ignored", eError.Message, false);
              failed++;
              continue;
            }
            if (found.Count < 1)
            {
              LogError("importing line #" + (counter + 1) + ", trying to find product by its localized name "
                  + locName + ", article will be ignored", "No article called " + locName + " in "
                  + mc.GetAttribute(MCAttribute.Language) + " language found on MKM.", false);
              failed++;
              continue;
            }
            locNameProducts[hash] = name = found[0]["enName"].InnerText;
            mc.SetAttribute(MCAttribute.Name, name);
          }
          else if (name != "")
            mc.SetAttribute(MCAttribute.Name, name);
          else
          {
            LogError("importing line #" + (counter + 1) + ", trying to find product by its localized name "
                + locName + ", article will be ignored", "" + locName + " is not a valid name", false);
            failed++;
            continue;
          }
        }
        // process foil and condition now as it can be useful in determining expansion
        string temp = mc.GetAttribute(MCAttribute.Foil);
        Bool3 isFoil;
        if (temp == "")
        {
          mc.SetBoolAttribute(MCAttribute.Foil, defaultFoil);
          isFoil = ParseBool3(mc.GetAttribute(MCAttribute.Foil));
        }
        else
          isFoil = ParseBool3(temp);

        string condition = mc.GetAttribute(MCAttribute.Condition);
        if (condition == "")
        {
          condition = defaultCondition;
          mc.SetCondition(condition);
        }

        if (productID == "") // we now know we have the name, but we have to find out which expansion it is from to get the productID
        {
          string expID = mc.GetAttribute(MCAttribute.ExpansionID); // if the Expansion would be set, ExpansionID would be set as well in constructor of MKMMetaCard
          if (expID == "") // we have to determine the expansion
          {
            var all = MKMDbManager.Instance.GetCardByName(name);
            // options are: Latest, Oldest, Cheapest, Median Price, Most Expensive                        
            if (all.GetEnumerator().MoveNext())
            {
              // used for prices based on price guide (cheapest, median, most expensive):
              // for non-foil, compare the LOWEX+ for EX+ items, LOW for worse conditions, for foil compare the LOWFOIL, for "any foil" compare SELL
              string priceGuidePrice;
              if (isFoil == Bool3.True)
                priceGuidePrice = "LOWFOIL";
              else if (isFoil == Bool3.Any)
                priceGuidePrice = "SELL";
              else
              {
                if (IsBetterOrSameCondition(condition, "EX"))
                  priceGuidePrice = "LOWEX+";
                else
                  priceGuidePrice = "LOW";
              }
              switch (defaultExpansion)
              {
                // for latest and oldest, we can just check local database
                case "Latest":
                  DateTime latestTime = new DateTime(0);
                  foreach (DataRow dr in all)
                  {
                    string tempExpID = dr[MKMDbManager.InventoryFields.ExpansionID].ToString();
                    string releaseDate = MKMDbManager.Instance.GetExpansionByID(
                        tempExpID)[MKMDbManager.ExpansionsFields.ReleaseDate].ToString();
                    DateTime rel = DateTime.Parse(releaseDate, CultureInfo.InvariantCulture);
                    if (latestTime < rel)
                    {
                      latestTime = rel;
                      expID = tempExpID;
                    }
                  }
                  mc.SetAttribute(MCAttribute.ExpansionID, expID);
                  mc.SetAttribute(MCAttribute.Expansion,
                      MKMDbManager.Instance.GetExpansionByID(expID)[MKMDbManager.ExpansionsFields.Name].ToString());
                  break;
                case "Oldest":
                  DateTime oldestTime = DateTime.Now;
                  foreach (DataRow dr in all)
                  {
                    string tempExpID = dr[MKMDbManager.InventoryFields.ExpansionID].ToString();
                    string releaseDate = MKMDbManager.Instance.GetExpansionByID(
                        tempExpID)[MKMDbManager.ExpansionsFields.ReleaseDate].ToString();
                    DateTime rel = DateTime.Parse(releaseDate, CultureInfo.InvariantCulture);
                    if (oldestTime > rel)
                    {
                      latestTime = rel;
                      expID = tempExpID;
                    }
                  }
                  mc.SetAttribute(MCAttribute.ExpansionID, expID);
                  mc.SetAttribute(MCAttribute.Expansion,
                      MKMDbManager.Instance.GetExpansionByID(expID)[MKMDbManager.ExpansionsFields.Name].ToString());
                  break;
                // for the others we have to do product queries for each possibility
                case "Cheapest":
                  XmlNode cheapestProduct = null; // we know all has at least one item so this will either get replacedigned or an exception is thrown and caught inside the foreach cycle
                  double cheapestPrice = double.MaxValue;
                  foreach (DataRow dr in all)
                  {
                    try
                    {
                      // there should always be exactly one product in the list
                      XmlNode product = MKMInteract.RequestHelper.GetProduct(
                          dr[MKMDbManager.InventoryFields.ProductID].ToString()).GetElementsByTagName("product")[0];
                      double price = double.Parse(product["priceGuide"][priceGuidePrice].InnerText);
                      if (price < cheapestPrice)
                      {
                        cheapestPrice = price;
                        cheapestProduct = product;
                      }
                    }
                    catch (Exception eError)
                    {
                      LogError("importing line #" + (counter + 1) + ", could not identify cheapest expansion for " + name + ", article will be ignored",
                          eError.Message, false);
                      failed++;
                      continue;
                    }
                  }
                  mc.FillProductInfo(cheapestProduct);
                  hasPriceGuide++;
                  break;
                case "Median Price":
                  SortedList<double, XmlNode> prices = new SortedList<double, XmlNode>();
                  foreach (DataRow dr in all)
                  {
                    try
                    {
                      // there should always be exactly one product in the list
                      XmlNode product = MKMInteract.RequestHelper.GetProduct(
                          dr[MKMDbManager.InventoryFields.ProductID].ToString()).GetElementsByTagName("product")[0];
                      double price = double.Parse(product["priceGuide"][priceGuidePrice].InnerText);
                      prices.Add(price, product);
                    }
                    catch (Exception eError)
                    {
                      LogError("importing line #" + (counter + 1) + ", could not identify median price expansion for " + name + ", article will be ignored",
                          eError.Message, false);
                      failed++;
                      continue;
                    }
                  }
                  mc.FillProductInfo(prices.Values[prices.Count / 2]);
                  hasPriceGuide++;
                  break;
                case "Most Expensive":
                  XmlNode mostExpProduct = null; // we know all has at least one item so this will either get replacedigned or an exception is thrown and caught inside the foreach cycle
                  double highestPrice = double.MinValue;
                  foreach (DataRow dr in all)
                  {
                    try
                    {
                      // there should always be exactly one product in the list
                      XmlNode product = MKMInteract.RequestHelper.GetProduct(
                          dr[MKMDbManager.InventoryFields.ProductID].ToString()).GetElementsByTagName("product")[0];
                      double price = double.Parse(product["priceGuide"][priceGuidePrice].InnerText);
                      if (price > highestPrice)
                      {
                        highestPrice = price;
                        mostExpProduct = product;
                      }
                    }
                    catch (Exception eError)
                    {
                      LogError("importing line #" + (counter + 1) + ", could not identify cheapest expansion for " + name + ", article will be ignored",
                          eError.Message, false);
                      failed++;
                      continue;
                    }
                  }
                  mc.FillProductInfo(mostExpProduct);
                  hasPriceGuide++;
                  break;
              }
            }
            else
            {
              LogError("importing line #" + (counter + 1) + ", identifying expansion for " + name + ", article will be ignored",
                  "No card with this name found.", false);
              failed++;
              continue;
            }
            // TODO - determine whether the expansion is foil only / cannot be foil and based on the isFoil flag of the current article choose the correct set
          }
          // now we have expID and English name -> we can determine the product ID
          string[] ids = MKMDbManager.Instance.GetCardProductID(name, mc.GetAttribute(MCAttribute.ExpansionID));
          if (ids.Length == 0)
          {
            LogError("importing line #" + (counter + 1) + ", article will be ignored",
                "The specified " + name + " and expansion ID " + expID + " do not match - product cannot be identified.", false);
            failed++;
            continue;
          }
          else if (ids.Length > 1)
          {
            string cardNumber = mc.GetAttribute(MCAttribute.CardNumber);
            if (cardNumber == "")
            {
              LogError("importing line #" + (counter + 1) + ", article will be ignored", "The specified " + name +
                  " and expansion ID " + expID + " match multiple products - please provide Card Number to identify which one it is.", false);
              failed++;
              continue;
            }
            // search for the matching item
            int start = 0;
            try
            {
              XmlNodeList products;
              do
              {
                XmlDoreplacedent doc = MKMInteract.RequestHelper.FindProducts(name, "1", start);
                products = doc.GetElementsByTagName("product");
                string expansion = mc.GetAttribute(MCAttribute.Expansion);
                foreach (XmlNode product in products)
                {
                  if (product["number"].InnerText == cardNumber && product["expansionName"].InnerText == expansion)
                  {
                    productID = product["idProduct"].InnerText;
                    // since we already have it, why not fill the product info in the MetaCard
                    mc.FillProductInfo(product);
                    break;
                  }
                }
                start += products.Count;
              } while (products.Count == 100 && productID == "");

            }
            catch (Exception eError)
            {
              LogError("importing line #" + (counter + 1) + ", trying to find product ID for "
                  + name + " based on its card number and expansion, article will be ignored", eError.Message, false);
              failed++;
              continue;
            }
            if (productID == "")
            {
              LogError("importing line #" + (counter + 1) + ", article will be ignored", "The specified " + name +
                  " and expansion ID " + expID
                  + " match multiple products, Card Number was used to find the correct article, but no match was found, verify the data is correct.", false);
              failed++;
              continue;
            }
          }
          else
            productID = ids[0];
          mc.SetAttribute(MCAttribute.ProductID, productID);
        }

        // if the defaults are "Any", there is not point in checking whether that attribute has been set or not
        if (defaultPlayset != "")
        {
          temp = mc.GetAttribute(MCAttribute.Playset);
          if (temp == "")
            mc.SetBoolAttribute(MCAttribute.Playset, defaultPlayset);
        }
        if (defaultSigned != "")
        {
          temp = mc.GetAttribute(MCAttribute.Signed);
          if (temp == "")
            mc.SetBoolAttribute(MCAttribute.Signed, defaultSigned);
        }
        if (defaultAltered != "")
        {
          temp = mc.GetAttribute(MCAttribute.Altered);
          if (temp == "")
            mc.SetBoolAttribute(MCAttribute.Altered, defaultAltered);
        }
        // rarity might not be present in some cases, check it and get it from database, or worst case from MKM
        var rarity = mc.GetAttribute(MCAttribute.Rarity);
        if (rarity == "")
        {
          var dataRow = MKMDbManager.Instance.GetSingleCard(productID);
          rarity = dataRow[MKMDbManager.InventoryFields.Rarity].ToString();
          if (rarity == "")
          {
            try
            {
              var productDoc = MKMInteract.RequestHelper.GetProduct(productID);
              rarity = productDoc["response"]["product"]["rarity"].InnerText;
              dataRow[MKMDbManager.InventoryFields.Rarity] = rarity;
            }
            catch (Exception eError)
            {
              LogError("getting rarity for product " + productID, eError.Message, false);
            }
          }
          mc.SetAttribute(MCAttribute.Rarity, rarity);
        }

        importedValidOnly.Add(mc);
        if (checkBoxImportLog.Checked)
          MainView.Instance.LogMainWindow("Imported line #" + (counter + 1) + ", " + name);
      }

      MainView.Instance.LogMainWindow("Card list " + filePath + " imported. Successfully imported " + importedValidOnly.Count +
          " articles, failed to import: " + failed + ", articles that include MKM Price Guide: " + hasPriceGuide);
      if (hasPriceGuide > 0)
        priceGuidesGenerated = true;
    }

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

public void AddOdds(string odds, string npcClreplaced)
		{
			switch (NpcSpawnHelper.GetClreplacedFromName(npcClreplaced))
			{
				case "Main":
					oddsMain += double.Parse(odds);
					return;
				case "Sub":
					oddsSub += double.Parse(odds);
					return;
				default:
					return; // Do nothing - we're only interested in Main and Sub
			}
		}

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

public void position(string lat, string lng, string b_0)
        {
            if (_Right == false)
            {
                if (cbGet.Checked == false)
                {
                    Location1.Longitude = double.Parse(lng) + Convert.ToDouble(nudLon.Value);
                    Location1.Lareplacedude = double.Parse(lat) + Convert.ToDouble(nudLat.Value);

                    txtLocation.Text = "经度:" + Location1.Longitude + "\r\n纬度:" + Location1.Lareplacedude + "\r\n位置:" + b_0;
                    if (cbAuto.Checked)
                    {
                        service.UpdateLocation(Location1);
                    }
                }
                else//精准模式 需调用经纬转换API
                {
                    Location1.Longitude = double.Parse(lng);
                    Location1.Lareplacedude = double.Parse(lat);
                    Debug.WriteLine("经度:" + Location1.Longitude + "纬度:" + Location1.Lareplacedude);
                    Location2 = getLocation("http://api.gpsspg.com/convert/coord/?oid=[oid]&key=[key]&from=3&to=0&latlng=" + Location1.Lareplacedude + "," + Location1.Longitude);
                    txtLocation.Text = "经度:" + Location2.Longitude + "\r\n纬度:" + Location2.Lareplacedude + "\r\n位置:" + b_0;
                    if (cbAuto.Checked)
                    {
                        service.UpdateLocation(Location2);
                    }
                }
            }
            else//偏移校正 需调用经纬转换API
            {
                Location1.Longitude = double.Parse(lng);
                Location1.Lareplacedude = double.Parse(lat);
                Location2 = getLocation("http://api.gpsspg.com/convert/coord/?oid=[oid]&key=[key]&from=3&to=0&latlng=" + Location1.Lareplacedude + "," + Location1.Longitude);
                nudLon.Value = Convert.ToDecimal(Location2.Longitude - Location1.Longitude);
                nudLat.Value = Convert.ToDecimal(Location2.Lareplacedude - Location1.Lareplacedude);
                MessageBox.Show("位置偏移已校准。");
                _Right = false;
            }
        }

19 View Source File : ThrottlingReportHandler.cs
License : MIT License
Project Creator : actions

protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            // Call the inner handler.
            var response = await base.SendAsync(request, cancellationToken).ConfigureAwait(false);

            // Inspect whether response has throttling information
            IEnumerable<string> vssRequestDelayed = null;
            IEnumerable<string> vssRequestQuotaReset = null;

            if (response.Headers.TryGetValues(HttpHeaders.VssRateLimitDelay, out vssRequestDelayed) &&
                response.Headers.TryGetValues(HttpHeaders.VssRateLimitReset, out vssRequestQuotaReset) &&
                !string.IsNullOrEmpty(vssRequestDelayed.FirstOrDefault()) &&
                !string.IsNullOrEmpty(vssRequestQuotaReset.FirstOrDefault()))
            {
                TimeSpan delay = TimeSpan.FromSeconds(double.Parse(vssRequestDelayed.First()));
                int expirationEpoch = int.Parse(vssRequestQuotaReset.First());
                DateTime expiration = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(expirationEpoch);

                _throttlingReporter.ReportThrottling(delay, expiration);
            }

            return response;
        }

19 View Source File : StringConverter.cs
License : MIT License
Project Creator : ansel86castro

public static object GetValue(Type type, string value)
        {
            if (string.IsNullOrEmpty(value))
                return null;
            if (type == typeof(float))
                return float.Parse(value);
            else if (type == typeof(int))
                return int.Parse(value);
            else if (type == typeof(bool))
                return bool.Parse(value);
            else if (type == typeof(short))
                return short.Parse(value);
            else if (type == typeof(double))
                return double.Parse(value);
            else if (type == typeof(byte))
                return byte.Parse(value);
            else if (type == typeof(string))
                return value;
            else if (type == typeof(Vector3))
            {
                //var match = Regex.Match(value, @"(?<X>\d+(\.\d+)?)\s?,\s?(?<Y>\d+(\.\d+)?)\s?,\s?(?<Z>\d+(\.\d+)?)");
                var match = Regex.Match(value, @"\((?<X>-?\d+(\.\d+)?)\s?,\s?(?<Y>-?\d+(\.\d+)?)\s?,\s?(?<Z>-?\d+(\.\d+)?)\)");
                //var match = Regex.Matches(value, @"(-?\d+(\.\d+)?)");
                return new Vector3(float.Parse(match.Groups["X"].Value), float.Parse(match.Groups["Y"].Value), float.Parse(match.Groups["Z"].Value));
            }
            else if (type == typeof(Vector2))
            {
                //var match = Regex.Matches(value, @"(-?\d+(\.\d+)?)");                
                var match = Regex.Match(value, @"\((?<X>-?\d+(\.\d+)?)\s?,\s?(?<Y>-?\d+(\.\d+)?)\)");
                return new Vector2(float.Parse(match.Groups["X"].Value), float.Parse(match.Groups["Y"].Value));
            }
            else if (type == typeof(Vector4))
            {
                //var match = Regex.Matches(value, @"(-?\d+(\.\d+)?)");
                var match = Regex.Match(value, @"\((?<X>-?\d+(\.\d+)?)\s?,\s?(?<Y>-?\d+(\.\d+)?)\s?,\s?(?<Z>-?\d+(\.\d+)?)\s?,\s?(?<W>-?\d+(\.\d+)?)\)");
                return new Vector4(float.Parse(match.Groups["X"].Value), float.Parse(match.Groups["Y"].Value), float.Parse(match.Groups["Z"].Value), float.Parse(match.Groups["W"].Value));
            }
            else if (type == typeof(Euler))
            {
                //var match = Regex.Matches(value, @"(-?\d+(\.\d+)?)");
                var match = Regex.Match(value, @"<(?<X>-?\d+(\.\d+)?)\s?,\s?(?<Y>-?\d+(\.\d+)?)\s?,\s?(?<Z>-?\d+(\.\d+)?)>");
                return new Euler(ToRadians(float.Parse(match.Groups["X"].Value)), ToRadians(float.Parse(match.Groups["Y"].Value)), ToRadians(float.Parse(match.Groups["Z"].Value)));
            }
            else if (type == typeof(SizeF))
            {
                var match = Regex.Match(value, @"<(?<W>-?\d+(\.\d+)?)\s?x\s?(?<H>-?\d+(\.\d+)?)>F");
                //var match = Regex.Matches(value, @"(-?\d+(\.\d+)?)");
                return new SizeF(float.Parse(match.Groups["W"].Value), float.Parse(match.Groups["H"].Value));
            }
            else if (type == typeof(Size))
            {
                var match = Regex.Match(value, @"<(?<W>-?\d+(\.\d+)?)\s?x\s?(?<H>-?\d+(\.\d+)?)>");
                //var match = Regex.Matches(value, @"(-?\d+(\.\d+)?)");
                return new SizeF(float.Parse(match.Groups["W"].Value), float.Parse(match.Groups["H"].Value));
            }
            else if (type == typeof(Spherical))
            {
                var match = Regex.Match(value, @"<(?<THETA>-?\d+(\.\d+)?)\s?,\s?(?<PITCH>-?\d+(\.\d+)?)>");
                //var match = Regex.Matches(value, @"(-?\d+(\.\d+)?)");
                return new SizeF(float.Parse(match.Groups["THETA"].Value), float.Parse(match.Groups["PITCH"].Value));
            }        
            else if (type == typeof(Plane))
            {
                //var match = Regex.Matches(value, @"(-?\d+(\.\d+)?)");
                var match = Regex.Match(value, @"< \((?<X>-?\d+(\.\d+)?)\s?,\s?(?<Y>-?\d+(\.\d+)?)\s?,\s?(?<Z>-?\d+(\.\d+)?)\) \s?,\s? (?<D>-?\d+(\.\d+)?)>", RegexOptions.IgnorePatternWhitespace);
                return new Plane(float.Parse(match.Groups["X"].Value), float.Parse(match.Groups["Y"].Value), float.Parse(match.Groups["Z"].Value), float.Parse(match.Groups["D"].Value));
            }          
            else if (type == typeof(Spherical))
            {
                var match = Regex.Match(value, @"\((?<Theta>-?\d+(\.\d+)?)\s?,\s?(?<Phi>-?\d+(\.\d+)?)\)");
                return new Spherical(ToRadians(float.Parse(match.Groups["Theta"].Value)), ToRadians(float.Parse(match.Groups["Phi"].Value)));
            }
            throw new ArgumentException("Unable to Converto to " + type + " from " + value);
        }

19 View Source File : AdColonyUtils.cs
License : Apache License 2.0
Project Creator : AdColony

double ParseNumber(char[] json, ref int index)
        {
            EatWhitespace(json, ref index);

            int lastIndex = GetLastIndexOfNumber(json, index);
            int charLength = (lastIndex - index) + 1;
            char[] numberCharArray = new char[charLength];

            Array.Copy(json, index, numberCharArray, 0, charLength);
            index = lastIndex + 1;
            return double.Parse(new string(numberCharArray));
        }

19 View Source File : Style.cs
License : MIT License
Project Creator : AliFlux

private Color parseColor(object iColor)
        {
            if (iColor.GetType() == typeof(Color))
            {
                return (Color)iColor;
            }

            if (iColor.GetType() != typeof(string))
            {

            }

            var colorString = (string)iColor;

            if (colorString[0] == '#')
            {
                return (Color)ColorConverter.ConvertFromString(colorString);
            }

            if (colorString.StartsWith("hsl("))
            {
                var segments = colorString.Replace('%', '\0').Split(',', '(', ')');
                double h = double.Parse(segments[1]);
                double s = double.Parse(segments[2]);
                double l = double.Parse(segments[3]);

                var color = (new ColorMine.ColorSpaces.Hsl()
                {
                    H = h,
                    S = s,
                    L = l,
                }).ToRgb();

                return Color.FromRgb((byte)color.R, (byte)color.G, (byte)color.B);
            }

            if (colorString.StartsWith("hsla("))
            {
                var segments = colorString.Replace('%', '\0').Split(',', '(', ')');
                double h = double.Parse(segments[1]);
                double s = double.Parse(segments[2]);
                double l = double.Parse(segments[3]);
                double a = double.Parse(segments[4]) * 255;

                var color = (new ColorMine.ColorSpaces.Hsl()
                {
                    H = h,
                    S = s,
                    L = l,
                }).ToRgb();

                return Color.FromArgb((byte)(a), (byte)color.R, (byte)color.G, (byte)color.B);
            }

            if (colorString.StartsWith("rgba("))
            {
                var segments = colorString.Replace('%', '\0').Split(',', '(', ')');
                double r = double.Parse(segments[1]);
                double g = double.Parse(segments[2]);
                double b = double.Parse(segments[3]);
                double a = double.Parse(segments[4]) * 255;

                return Color.FromArgb((byte)a, (byte)r, (byte)g, (byte)b);
            }

            if (colorString.StartsWith("rgb("))
            {
                var segments = colorString.Replace('%', '\0').Split(',', '(', ')');
                double r = double.Parse(segments[1]);
                double g = double.Parse(segments[2]);
                double b = double.Parse(segments[3]);

                return Color.FromRgb((byte)r, (byte)g, (byte)b);
            }

            try
            {
                return (Color)ColorConverter.ConvertFromString(colorString);
            }
            catch (Exception e)
            {
                throw new NotImplementedException("Not implemented color format: " + colorString);
            }
            //return Colors.Violet;
        }

19 View Source File : DoubleExtensions.cs
License : MIT License
Project Creator : AlexGyver

public static double RemoveNoise(this double value, int maxDigits = 8)
        {
            return double.Parse(value.ToString("e" + maxDigits));
        }

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

private Color ColorizeGrey(string[] baseColour, Color greyMap)
        {
            if (greyMap.R != greyMap.G || greyMap.R != greyMap.B || greyMap.G != greyMap.B) // not greyscale
            {
                return greyMap;
            }
            //base.Monitor.Log(string.Join("", baseColour), LogLevel.Alert);
            Color outColour = new Color
            {
                R = (byte)(greyMap.R - Math.Round((255 - double.Parse(baseColour[0])) * greyMap.R / 255)),
                G = (byte)(greyMap.G - Math.Round((255 - double.Parse(baseColour[1])) * greyMap.G / 255)),
                B = (byte)(greyMap.B - Math.Round((255 - double.Parse(baseColour[2])) * greyMap.B / 255)),
                A = greyMap.A
            };
            return outColour;
        }

19 View Source File : TestVGAInput.cs
License : GNU General Public License v3.0
Project Creator : alvaroyurrita

double GetFirstParameterDouble(string value, string MessageHelp)
        {
            var commands = value.Split(' ');
            double Result;
            try
            {
                Result = double.Parse(commands[0]);
            }
            catch (Exception)
            {
                CrestronConsole.ConsoleCommandResponse(MessageHelp);
                return 0xffff;
            }
            return Result;
        }

19 View Source File : MinusConverter.cs
License : MIT License
Project Creator : Accelerider

public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            var left = double.Parse(values[0].ToString());
            var right = double.Parse(values[1].ToString());
            return left - right;
        }

19 View Source File : TransformingAutoEncoders.cs
License : MIT License
Project Creator : anastasios-stamoulis

double extractLoss(string filename) {
      var prefix = "val_metric_";
      var pos = filename.LastIndexOf(prefix);
      if ( pos<0 ) { return 0; }
      var dotPos = filename.LastIndexOf(".model");
      if ( dotPos<0 ) { return 0; }
      var startPos = pos + prefix.Length;
      var lossMetricreplacedtring = filename.Substring(startPos, dotPos - startPos);
      var lossMetric = double.Parse(lossMetricreplacedtring);
      return lossMetric;
    }

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

public override void FromString(string value) {
			Value = double.Parse(value.TrimEnd('D'));
		}

19 View Source File : Dialog.cs
License : MIT License
Project Creator : AngeloCresta

private void YValue_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
		{
			if((e.KeyChar >= '0' && e.KeyChar <= '9') || e.KeyChar == 8 || e.KeyChar == 46  || e.KeyChar == '.')
			{
				string editText = ((TextBox)(sender)).Text;
				if(e.KeyChar != 8)
				{
					TextBox textBox = (TextBox)sender;
					int selStart = textBox.SelectionStart;
					int selLength = textBox.SelectionLength;
	
					if(selLength > 0)
					{
						editText = editText.Remove(selStart, selLength);
						textBox.Text = editText;
						textBox.SelectionLength = 0;
						textBox.SelectionStart = selStart;
					}


					editText = editText.Insert(selStart,e.KeyChar.ToString());

					try
					{
						double newValue = double.Parse(editText);
						if(newValue <= 10 && newValue >= 0)
						{
							e.Handled = false;
						}
						else
							e.Handled = true;
					}
					catch(Exception )
					{
						e.Handled = true;
					}
				}
				else
					e.Handled = false;
			}
			else
			{
				e.Handled = true;
			}
		
		}

19 View Source File : TestAmf3Reader.cs
License : MIT License
Project Creator : a1q123456

[TestMethod]
        public void TestReadNumber()
        {
            var reader = new Amf3Reader();

            var files = Directory.GetFiles("../../../../samples/amf3/number");

            foreach (var file in files)
            {
                var value = double.Parse(Path.GetFileNameWithoutExtension(file));
                using (var f = new FileStream(file, FileMode.Open))
                {
                    var data = new byte[f.Length];
                    f.Read(data);
                    replacedert.IsTrue(reader.TryGetDouble(data, out var dataRead, out var consumed));
                    replacedert.AreEqual(dataRead, value);
                    replacedert.AreEqual(consumed, f.Length);
                }
            }
        }

19 View Source File : LiteralExpression.cs
License : MIT License
Project Creator : ansel86castro

public override System.Linq.Expressions.Expression GenerateLinqExpression(IASTContext context)
        {
            if (type == ExpressionType.String)
            {
                return System.Linq.Expressions.Expression.Constant(value, typeof(string));
            }
            else if (type == ExpressionType.Null)
            {
                return System.Linq.Expressions.Expression.Constant(null);
            }
            else if (type == ExpressionType.Bool)
            {
                return System.Linq.Expressions.Expression.Constant(bool.Parse(value));
            }
            else if (type == ExpressionType.Integer)
            {
                return System.Linq.Expressions.Expression.Constant(int.Parse(value));
            }
            else if (type == ExpressionType.Double)
            {
                return System.Linq.Expressions.Expression.Constant(double.Parse(value));
            }
            throw new InvalidOperationException();
        }

19 View Source File : UpdateProgress.cs
License : MIT License
Project Creator : AlbertMN

public void SetProgress(DownloadProgressChangedEventArgs e) {
            this.BeginInvoke((MethodInvoker)delegate {
                double bytesIn = double.Parse(e.BytesReceived.ToString());
                double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
                double percentage = bytesIn / totalBytes * 100;
                progressText.Text = int.Parse(Math.Truncate(percentage).ToString()) + "%";

                var transString = Translator.__("downloaded_bytes", "update_downloading");
                transString = transString.Replace("{x}", e.BytesReceived.ToString());
                transString = transString.Replace("{y}", e.TotalBytesToReceive.ToString());

                //byteText.Text = "Downloaded " + e.BytesReceived + " of " + e.TotalBytesToReceive + " bytes";
                byteText.Text = transString;

                progressBar.Value = int.Parse(Math.Truncate(percentage).ToString());
            });
        }

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

void Awake()
		{
			_searchLocation.OnGeocoderResponse += SearchLocation_OnGeocoderResponse;
			_stylesDropdown.ClearOptions();
			_stylesDropdown.AddOptions(_mapboxStyles.ToList());
			_stylesDropdown.onValueChanged.AddListener(ToggleDropdownStyles);
			_zoomSlider.onValueChanged.AddListener(AdjustZoom);

			var parsed = _latLon.Split(',');
			_startLoc.x = double.Parse(parsed[0]);
			_startLoc.y = double.Parse(parsed[1]);
		}

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

public static void ReadIndexFromFile()
        {
            var location = replacedembly.GetExecutingreplacedembly().Location;

            var index = location.IndexOf(@"\bin", StringComparison.InvariantCulture);

            var filePath = location.Substring(0, index) + InvertedIndexRelativePath;

            string[] lines = File.ReadAllLines(filePath);

            _invertedIndex.Clear();
            foreach (var line in lines)
            {
                var splittedLine = line.Split('|');

                string term = splittedLine[0];
                var postings = splittedLine[1].Split(';');
                var termFrequencies = splittedLine[2].Split(',');
                var invertedDocFrequency = double.Parse(splittedLine[3]);

                var termInfos = new List<TermInfo>();

                for (int i = 0; i < postings.Length; i++)
                {
                    var posting = postings[i];
                    var tf = double.Parse(termFrequencies[i]);

                    var post = posting.Split(':');
                    var termEntries = post[1].Split(',').Select(ushort.Parse).ToArray();
                    
                    termInfos.Add(new TermInfo(new Guid(post[0]), termEntries, (float) tf));
                }

                _invertedIndex[term] = new Posting(termInfos) {InvertedDoreplacedentFrequency = invertedDocFrequency};
            }
        }

19 View Source File : MainForm.cs
License : GNU General Public License v3.0
Project Creator : alexgracianoarj

private void mnuCheckForUpdates_Click(object sender, EventArgs e)
        {
            System.Threading.Tasks.Task<IReadOnlyList<Octokit.Release>> releases;
            Octokit.Release latest = null;

            ProgressDialog progressDownload = new ProgressDialog();

            Thread thread = new Thread(() =>
            {
                Octokit.GitHubClient client = new Octokit.GitHubClient(new Octokit.ProductHeaderValue("alexgracianoarj"));
                releases = client.Repository.Release.GetAll("alexgracianoarj", "nclreplaced");
                latest = releases.Result[0];

                if (progressDownload.InvokeRequired)
                    progressDownload.BeginInvoke(new Action(() => progressDownload.Close()));
            });

            thread.Start();

            progressDownload.Text = "Update";
            progressDownload.lblPleaseWait.Text = "Checking...";
            progressDownload.SetIndeterminate(true);

            progressDownload.ShowDialog();

            double latestVersion = Convert.ToDouble(latest.TagName.Replace("v", ""), System.Globalization.CultureInfo.InvariantCulture);
            double programVersion = Convert.ToDouble(Program.CurrentVersion.ToString(2), System.Globalization.CultureInfo.InvariantCulture);

            if (latestVersion > programVersion)
            {
                if (MessageBox.Show("There is a new version of NClreplaced.\n\nDo you want download the new version and install it now?", "NClreplaced", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == System.Windows.Forms.DialogResult.Yes)
                {
                    thread = new Thread(() =>
                    {
                        WebClient wc = new WebClient();

                        wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler((sen, env) =>
                        {
                            double bytesIn = double.Parse(env.BytesReceived.ToString());
                            double totalBytes = double.Parse(env.TotalBytesToReceive.ToString());
                            double percentage = bytesIn / totalBytes * 100;

                            if (progressDownload.InvokeRequired)
                                progressDownload.BeginInvoke(new Action(() => progressDownload.SetIndeterminate(false)));

                            if (progressDownload.InvokeRequired)
                                progressDownload.BeginInvoke(new Action(() => progressDownload.lblPleaseWait.Text = "Downloaded " + Convert.ToInt32(percentage) + "% - " + (env.BytesReceived / 1024) + " KB of " + (env.TotalBytesToReceive / 1024) + " KB"));

                            if (progressDownload.InvokeRequired)
                                progressDownload.BeginInvoke(new Action(() => progressDownload.progressBar1.Value = Convert.ToInt32(percentage)));

                        });

                        wc.DownloadFileCompleted += new AsyncCompletedEventHandler((sen, env) =>
                        {
                            // Close the dialog if it hasn't been already
                            if (progressDownload.InvokeRequired)
                                progressDownload.BeginInvoke(new Action(() => progressDownload.Close()));

                            System.Diagnostics.Process.Start(Path.GetTempPath() + "NClreplaced_Update.exe");

                            Application.Exit();
                        });

                        wc.DownloadFileAsync(new Uri(latest.replacedets[0].BrowserDownloadUrl), Path.GetTempPath() + "NClreplaced_Update.exe");
                    });

                    thread.Start();

                    progressDownload.lblPleaseWait.Text = "Downloading...";

                    progressDownload.ShowDialog();
                }
            }
            else
            {
                MessageBox.Show("NClreplaced is already updated.", "NClreplaced", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

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

public byte[] GetValueData()
        {
            if (_dataType == DataTypeEnum.RegUwpPoint)
            {
                return FromPoint(new Point(double.Parse(_firstDouble), double.Parse(_secondDouble)), _timestamp);
            }
            else
            {
                return FromSize(new Size(double.Parse(_firstDouble), double.Parse(_secondDouble)), _timestamp);
            }
        }

19 View Source File : FunctionExtensions.cs
License : MIT License
Project Creator : alfa-laboratory

public static object parseDouble(string str)
        {
            try
            {
                return double.Parse(str);
            }
            catch (FormatException ex)
            {
                Log.Logger().LogWarning($"Parsing string to double return an error {ex.Message}.");
                return str;
            }
        }

19 View Source File : ArgumentParseHelper.cs
License : Apache License 2.0
Project Creator : alexyakunin

public static double ParseRelativeValue(string value, double defaultValue, bool negativeSubtractsFromDefault = false)
        {
            value = value?.Trim();
            if (string.IsNullOrEmpty(value))
                return defaultValue;

            var offset = 0.0;
            var unit = 1.0;
            if (value.EndsWith('%')) {
                value = value.Substring(0, value.Length - 1).Trim();
                unit = defaultValue / 100;
            }
            else if (value.EndsWith("pct")) {
                value = value.Substring(0, value.Length - 3).Trim();
                unit = defaultValue / 100;
            }
            else if (value.EndsWith("pts")) {
                value = value.Substring(0, value.Length - 3).Trim();
                unit = defaultValue / 1000;
            }
            if (value.StartsWith('-') && negativeSubtractsFromDefault) {
                offset = defaultValue;
            }
            return offset + double.Parse(value) * unit;
        }

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

public string MakeString()
        {
            string str = "";
            int mHour;
            int mH;
            int mM;
            if(morningEarliest != "any")
            {
                mHour = int.Parse(morningEarliest.Substring(0,morningEarliest.Length == 4?2:1));
                mM = (int.Parse(morningEarliest) % 100) / 10;
                mH = Game1.random.Next(mHour, Math.Max(7, Math.Min(mHour,9)));
                mM = Game1.random.Next(mH == mHour?mM:0, 5);
            }
            else
            {
                mH = Game1.random.Next(7, 9);
                mM = Game1.random.Next(0, 5);
            }
            this.mTime = mH.ToString() + mM.ToString() + "0";

            int aH;
            int aHour;
            int aM;
            if(afternoonEarliest != "any" && int.Parse(afternoonEarliest) > 1200)
            {
                aHour = (int)Math.Round((double)(double.Parse(afternoonEarliest)/100));
                aM = (int.Parse(afternoonEarliest) % 100) / 10;
                aH = Game1.random.Next(aHour, Math.Min(aHour, 16));
                aM = Game1.random.Next((aH == aHour?aM:0), 5);
            }
            else
            {
                aH = Game1.random.Next(12, 16);
                aM = Game1.random.Next(0, 5);
            }
            this.aTime = aH.ToString() + aM.ToString() + "0";

            // create starting location to go to

            int startX = Game1.random.Next(25, 35);
            int startY = Game1.random.Next(63, 72);
            int startFace = 0;
            if(startY < 66)
            {
                startFace = 2;
            }
            else if (startY < 68)
            {
                if (startX < 30)
                {
                    startFace = 1;
                }
                else
                {
                    startFace = 3;
                }
            }

            startM = Game1.random.Next(1, 5);

            str += "6"+startM+"0 Town "+startX+" "+startY+" "+startFace+"/"+ mTime + " " + morningLoc + "/" + aTime + " " + afternoonLoc+ "/"+ModEntry.Config.LeaveTime+ " BusStop 12 9 0";
            return str;
        }

19 View Source File : JemBenchmark.cs
License : MIT License
Project Creator : allisterb

public static Tuple<double, string> PrintBytesToTuple(double bytes, string suffix = "")
        {
            string[] s = PrintBytes(bytes, suffix).Split(' ');
            return new Tuple<double, string>(Double.Parse(s[0]), s[1]);
        }

19 View Source File : CompareConverters.cs
License : MIT License
Project Creator : Accelerider

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var left = double.Parse(value.ToString());
            var right = double.Parse(parameter.ToString());
            return left > right;
        }

19 View Source File : TestDMInput.cs
License : GNU General Public License v3.0
Project Creator : alvaroyurrita

double GetFirstParameterDouble(string value, string MessageHelp)
        {
            var commands = value.Split(' ');
            double Result;
            try
            {
                Result = double.Parse(commands[0]);
                Result = Math.Round(Result, 1);
            }
            catch (Exception)
            {
                CrestronConsole.ConsoleCommandResponse(MessageHelp);
                return 0xffff;
            }
            return Result;
        }

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

public void ReduceDecimals()
		{
			if (Validation.decimalHeaders.Contains(columnName))
			{
				if (data != string.Empty)
				{
					try
					{
						// Parse the string as a double, round it, cast it to an int, then cast it back to a string.
						data = ((int)Math.Round(double.Parse(data))).ToString();
					}
					catch (Exception)
					{
						ReportValidationError();
					}
				}
			}
		}

19 View Source File : NumericTextBox.cs
License : Apache License 2.0
Project Creator : AmpScm

public bool Validate()
        {
            try
            {
                m_dValue = double.Parse(base.Text);
                return ValidateValue();
            }
            catch (Exception)
            {
                SetText(m_dValue);
                return false;
            }
        }

19 View Source File : TestAmf0Reader.cs
License : MIT License
Project Creator : a1q123456

[TestMethod]
        public void TestReadNumber()
        {
            var reader = new Amf0Reader();

            var files = Directory.GetFiles("../../../../samples/amf0/number");

            foreach (var file in files)
            {
                var value = double.Parse(Path.GetFileNameWithoutExtension(file));
                using (var f = new FileStream(file, FileMode.Open))
                {
                    var data = new byte[f.Length];
                    f.Read(data);
                    replacedert.IsTrue(reader.TryGetNumber(data, out var dataRead, out var consumed));
                    replacedert.AreEqual(dataRead, value);
                    replacedert.AreEqual(consumed, f.Length);
                }
            }
        }

19 View Source File : CliParser.cs
License : Apache License 2.0
Project Creator : anadventureisu

public void ParseLine(string line)
        {
            Match m = null;
            if ((m = StatusLine.Match(line)).Success)
            {
                try
                {
                    string timestamp = m.Groups[1].Captures[0].Value;
                    int gpuIndex = int.Parse(m.Groups[2].Captures[0].Value);
                    int gpuTemp = int.Parse(m.Groups[3].Captures[0].Value);
                    int gpuRpm = int.Parse(m.Groups[4].Captures[0].Value);
                    double gpuHashrate = double.Parse(m.Groups[5].Captures[0].Value);

                    GpuSample samp = new GpuSample(DateTime.Now, (long)gpuHashrate, gpuRpm, gpuTemp);

                    // Get GPU.
                    GpuState gpu = App.GetGpu(gpuIndex);

                    gpu.AddSample(samp);
                } catch(FormatException e)
                {
                    Debug.WriteLine("Could not parse line: " + line + ": " + e);
                }
            }
            else if ((m = StatisticLine.Match(line)).Success)
            {
                try
                {
                    int stat = int.Parse(m.Groups[1].Captures[0].Value);
                    string msg = m.Groups[3].Captures[0].Value;

                    if(ACCEPTED.Equals(msg))
                    {
                        App.SharesAccepted = stat;
                    }
                    else if (REJECTED.Equals(msg))
                    {
                        App.SharesRejected = stat;
                    }
                    else if (INVALID.Equals(msg))
                    {
                        App.SharesInvalid = stat;
                    }
                    else if (NETWORK.Equals(msg))
                    {
                        App.SharesNetworkError = stat;
                    }
                    else if (OUTDATED.Equals(msg))
                    {
                        App.SharesOutdated = stat;
                    }

                    App.TotalShares = App.SharesAccepted + App.SharesInvalid + App.SharesNetworkError + App.SharesOutdated + App.SharesRejected;
                }
                catch (FormatException e)
                {
                    Debug.WriteLine("Could not parse line: " + line + ": " + e);
                }
            }
        }

19 View Source File : DrawingParser.cs
License : MIT License
Project Creator : ahopper

private static GradientStop ParseGradientStop(XmlReader reader)
        {
            GradientStop gradientStop = new GradientStop();
            while (reader.MoveToNextAttribute())
            {
                switch (reader.Name)
                {
                    case "Color": gradientStop.Color = Color.Parse(reader.Value); break;
                    case "Offset": gradientStop.Offset = Double.Parse(reader.Value); break;
                }
            }
            return gradientStop;
        }

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

public void position(string a_0, string a_1, string b_0)
        {
            this.label3.Text = (double.Parse( a_1) - 0.0125).ToString();
            this.label4.Text = (double.Parse(a_0) - 0.00736).ToString();
            this.label5.Text = b_0;
        }

19 View Source File : PlusConverter.cs
License : MIT License
Project Creator : Accelerider

public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            double? result = values.Select(value => double.Parse(value.ToString())).Aggregate((sum, value) => sum + value);
            return result <= 0 ? null : result;
        }

19 View Source File : MenuFitWidthConverter.cs
License : MIT License
Project Creator : AndreiMisiukevich

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
            => ((double)value) - double.Parse(parameter.ToString());

19 View Source File : DefaultParamValueProcessors.cs
License : MIT License
Project Creator : aillieo

public double Load(string serializedValue)
        {
            return double.Parse(serializedValue);
        }

19 View Source File : Multiple.cs
License : The Unlicense
Project Creator : Anirban166

static void Main()
    {
        double Num1, Num2;
        double Result = 0.00;
        char op;
        try
            {
                Console.Write("Enter your First Number :  ");
                Num1 = double.Parse(Console.ReadLine());
                Console.Write("Enter an Operator  (+, -, * or /): ");
                op = char.Parse(Console.ReadLine());
                if (op != '+' && op != '-' &&
                        op != '*' && op != '/')
                    throw new Exception(op.ToString());
                Console.Write("Enter your Second Number :");
                Num2 = double.Parse(Console.ReadLine());
                if (op == '/')
                    if (Num2 == 0)
                        throw new DivideByZeroException("Division by zero is not allowed");
                Result = Calculator(Num1, Num2, op);
                Console.WriteLine("\n{0} {1} {2} = {3}", Num1, op, Num2, Result);
            }
        catch (FormatException)
            {
                Console.WriteLine("The number you typed is not valid");
            }
        catch (DivideByZeroException ex)
            {
                Console.WriteLine(ex.Message);
            }
        catch (Exception ex)
            {
                Console.WriteLine("Operation Error: {0} is not a valid op", ex.Message);
            }
        Console.Read();
    }

19 View Source File : TypeConverterHelper.cs
License : MIT License
Project Creator : 1iveowl

public static object Convert(string value, string destinationTypeFullName)
        {
            if (string.IsNullOrWhiteSpace(destinationTypeFullName))
            {
                throw new ArgumentNullException(destinationTypeFullName);
            }

            var scope = GetScope(destinationTypeFullName);

            if (string.Equals(scope, "System", StringComparison.Ordinal))
            {
                if (string.Equals(destinationTypeFullName, typeof(string).FullName, StringComparison.Ordinal))
                {
                    return value;
                }
                else if (string.Equals(destinationTypeFullName, typeof(bool).FullName, StringComparison.Ordinal))
                {
                    return bool.Parse(value);
                }
                else if (string.Equals(destinationTypeFullName, typeof(int).FullName, StringComparison.Ordinal))
                {
                    return int.Parse(value);
                }
                else if (string.Equals(destinationTypeFullName, typeof(double).FullName, StringComparison.Ordinal))
                {
                    return double.Parse(value);
                }
            }

            return null;
        }

19 View Source File : LiteralExpression.cs
License : MIT License
Project Creator : ansel86castro

public object GetValue()
        {
            if (type == ExpressionType.String)
            {
                return value;
            }
            else if (type == ExpressionType.Null)
            {
                return null;
            }
            else if (type == ExpressionType.Bool)
            {
                return bool.Parse(value);
            }
            else if (type == ExpressionType.Integer)
            {
               return int.Parse(value);
            }
            else if (type == ExpressionType.Double)
            {
              return double.Parse(value);
            }

            throw new InvalidOperationException();
        }

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

async Task OnCommand(string command, string args)
    {
        var argStrings = args.ToLowerInvariant().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).ToList();
        PluginLog.Debug($"command: {command}, {string.Join('|', argStrings)}");
        if (argStrings.Any())
        {
            switch (argStrings[0])
            {
                case "cancel":
                    PerformActions.DoPerformAction(0);
                    break;
                case "perform":
                    try
                    {
                        var instrumentInput = argStrings[1];
                        if (instrumentInput == "cancel")
                        {
                            PerformActions.DoPerformAction(0);
                        }
                        else if (uint.TryParse(instrumentInput, out var id1) && id1 < InstrumentStrings.Length)
                        {
                            SwitchInstrument.SwitchToContinue(id1);
                        }
                        else if (SwitchInstrument.TryParseInstrumentName(instrumentInput, out var id2))
                        {
                            SwitchInstrument.SwitchToContinue(id2);
                        }
                    }
                    catch (Exception e)
                    {
                        PluginLog.Warning(e, "error when parsing or finding instrument strings");
                        ChatGui.PrintError($"failed parsing command argument \"{args}\"");
                    }

                    break;
                case "playpause":
                    MidiPlayerControl.PlayPause();
                    break;
                case "play":
                    MidiPlayerControl.Play();
                    break;
                case "pause":
                    MidiPlayerControl.Pause();
                    break;
                case "stop":
                    MidiPlayerControl.Stop();
                    break;
                case "next":
                    MidiPlayerControl.Next();
                    break;
                case "prev":
                    MidiPlayerControl.Prev();
                    break;
                case "visual":
                    try
                    {
                        config.PlotTracks = argStrings[1] switch
                        {
                            "on" => true,
                            "off" => false,
                            _ => !config.PlotTracks
                        };
                    }
                    catch (Exception e)
                    {
                        config.PlotTracks ^= true;
                    }
                    break;
                case "rewind":
                {
                    double timeInSeconds = -5;
                    try
                    {
                        timeInSeconds = -double.Parse(argStrings[1]);
                    }
                    catch (Exception e)
                    {
                    }

                    MidiPlayerControl.MoveTime(timeInSeconds);
                }
                    break;
                case "fastforward":
                {
                    double timeInSeconds = 5;
                    try
                    {
                        timeInSeconds = double.Parse(argStrings[1]);
                    }
                    catch (Exception e)
                    {
                    }

                    MidiPlayerControl.MoveTime(timeInSeconds);
                }
                    break;
            }
        }

19 View Source File : BigDecimal.cs
License : MIT License
Project Creator : AdamWhiteHat

public static BigDecimal Divide(BigDecimal dividend, BigDecimal divisor)
		{
			if (divisor == BigDecimal.Zero) throw new DivideByZeroException();

			dividend.Normalize();
			divisor.Normalize();

			//	if (dividend > divisor) { return Divide_Positive(dividend, divisor); }

			if (BigDecimal.Abs(dividend) == 1)
			{
				double doubleDivisor = double.Parse(divisor.ToString());
				doubleDivisor = (1d / doubleDivisor);

				return BigDecimal.Parse(doubleDivisor.ToString());
			}

			string remString = "";
			string mantissaString = "";
			string dividendMantissaString = dividend.Mantissa.ToString();
			string divisorMantissaString = divisor.Mantissa.ToString();

			int dividendMantissaLength = dividend.DecimalPlaces;
			int divisorMantissaLength = divisor.DecimalPlaces;
			var exponentChange = dividend.Exponent - divisor.Exponent; //(dividendMantissaLength - divisorMantissaLength);

			int counter = 0;
			BigDecimal result = 0;
			BigInteger remainder = 0;
			result.Mantissa = BigInteger.DivRem(dividend.Mantissa, divisor.Mantissa, out remainder);
			while (remainder != 0 && result.SignifigantDigits < divisor.SignifigantDigits)
			{
				while (BigInteger.Abs(remainder) < BigInteger.Abs(divisor.Mantissa))
				{
					remainder *= 10;
					result.Mantissa *= 10;
					counter++;
					remString = remainder.ToString();
					mantissaString = result.Mantissa.ToString();
				}
				result.Mantissa = result.Mantissa + BigInteger.DivRem(remainder, divisor.Mantissa, out remainder);

				remString = remainder.ToString();
				mantissaString = result.Mantissa.ToString();
			}

			result.Exponent = exponentChange - counter;
			return result;
		}

19 View Source File : Program.cs
License : MIT License
Project Creator : 0x727

public static void CreateTask(string randomname, string destinationFile, string min)
        {
            TaskDefinition td = TaskService.Instance.NewTask();
            td.RegistrationInfo.Author = "Microsoft"; //创建者
            td.RegistrationInfo.Description = "UPnPHost Service Settings"; //描述
            //计划任务运行时间 Min/Day
            double time = double.Parse(min);
            TimeTrigger tt = new TimeTrigger();
            tt.StartBoundary = DateTime.Now;
            tt.Repereplacedion.Interval = TimeSpan.FromMinutes(time);

            td.Triggers.Add(tt);
            td.Actions.Add(destinationFile, null, null);
            string taskpath = @"\Microsoft\Windows\UPnP\" + randomname;
            TaskService.Instance.RootFolder.RegisterTaskDefinition(taskpath, definition: td, TaskCreation.CreateOrUpdate, null, null, 0);
            HidXml(taskpath);
            RegistryKeyRule(randomname);
        }

19 View Source File : MainWindow.xaml.cs
License : MIT License
Project Creator : 3RD-Dimension

private void ButtonRestoreViewport_Click(object sender, RoutedEventArgs e)
		{
			string[] scoords = Properties.Settings.Default.ViewPortPos.Split(';');

			try
			{
				IEnumerable<double> coords = scoords.Select(s => double.Parse(s));

				viewport.Camera.Position = new Vector3(coords.Take(3).ToArray()).ToPoint3D();
				viewport.Camera.LookDirection = new Vector3(coords.Skip(3).ToArray()).ToVector3D();
				viewport.Camera.UpDirection = new System.Windows.Media.Media3D.Vector3D(0, 0, 1);
			}
			catch
			{
				ButtonResetViewport_Click(null, null);
			}
		}

19 View Source File : CompareConverters.cs
License : MIT License
Project Creator : Accelerider

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var left = double.Parse(value.ToString());
            var right = double.Parse(parameter.ToString());
            return left < right;
        }

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

public byte[] GetValueData() 
            => FromRect(new Rect(double.Parse(_xDouble), double.Parse(_yDouble), double.Parse(_widthDouble), double.Parse(_heightDouble)), _timestamp);

19 View Source File : HardwareInfo.cs
License : Apache License 2.0
Project Creator : alexyakunin

public static int? GetRamSize()
        {
            try {
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) {
                    var cmd = Command.Run("wmic", "computersystem", "get", "TotalPhysicalMemory");
                    var stringValue = cmd.StandardOutput.GetLines().SkipEmpty().Last().Trim();
                    return (int) Math.Round(long.Parse(stringValue) / Sizes.GB);
                }
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) {
                    var cmd = Command.Run("cat", "/proc/meminfo");
                    var stringValue = cmd.StandardOutput.GetLines().SkipEmpty()
                        .ToPairs().Single(p => p.Name == "MemTotal")
                        .Value.Split(' ', StringSplitOptions.RemoveEmptyEntries).First();
                    return (int) Math.Round(long.Parse(stringValue) * Sizes.KB / Sizes.GB);
                }
                if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) {
                    var cmd = Command.Run("system_profiler", "SPHardwareDataType");
                    var stringValue = cmd.StandardOutput.GetLines().SkipEmpty()
                        .ToPairs().Single(p => p.Name == "Memory")
                        .Value.Split(' ', StringSplitOptions.RemoveEmptyEntries).First();
                    return (int) Math.Round(double.Parse(stringValue));
                }
                return null;
            }
            catch {
                return null;
            }
        }

See More Examples