public override List <ARewardFunction> getRewardFunctions(string CSVArgsStart, string CSVArgsEnd, string jump) { List <ARewardFunction> res = new List <ARewardFunction>(); if (CSVArgsEnd.Length == 0) { ConstantExponentialDecay r = new ConstantExponentialDecay(); r.setArgs(CSVArgsStart); res.Add(r); return(res); } try { var vals1 = ParsingUtils.separateCSV(CSVArgsStart); var vals2 = ParsingUtils.separateCSV(CSVArgsEnd); double eavesdroppingRadius = double.Parse(vals1[0]); double remainingRewardMin = double.Parse(vals1[1]); double remainingRewardMax = double.Parse(vals2[1]); double remainingRewardJump = double.Parse(jump); for (; remainingRewardMin < remainingRewardMax + remainingRewardJump; remainingRewardMin += remainingRewardJump) { remainingRewardMin = Math.Min(remainingRewardMin, remainingRewardMax); res.Add(new ConstantExponentialDecay(eavesdroppingRadius, remainingRewardMin)); } return(res); } catch (Exception) { throw new Exception("jump param should only contain jump value for remaining reward"); } }
public override bool ShowBatchModeStats() { string message = string.Format("تعداد اصلاحات انجام شده: {0}", ParsingUtils.ConvertNumber2Persian(m_bachModeStats.ToString())); PersianMessageBox.Show(ThisAddIn.GetWin32Window(), message, Constants.UIMessages.SuccessRefinementTitle); return(false); }
public void ImportModelFileExpandedModelArray(string modelFilePath, string expectedDeps, string expectedPaths, bool strict) { // TODO: Revisit. ResetTestRepoDir(); string qualifiedModelFilePath = Path.Combine(TestHelpers.TestLocalModelRepository, modelFilePath); string strictSwitch = strict ? "--strict" : ""; string targetRepo = $"--local-repo \"{testImportRepo.FullName}\""; (int returnCode, string standardOut, string standardError) = ClientInvokator.Invoke($"import --model-file \"{qualifiedModelFilePath}\" {targetRepo} {strictSwitch}"); string[] dtmis = expectedDeps.Split(",", StringSplitOptions.RemoveEmptyEntries); string[] paths = expectedPaths.Split(",", StringSplitOptions.RemoveEmptyEntries); Assert.AreEqual(Handlers.ReturnCodes.Success, returnCode); Assert.False(standardError.Contains(Outputs.DefaultErrorToken)); Assert.True(standardOut.Contains("- Validating models conform to DTDL...")); for (int i = 0; i < dtmis.Length; i++) { Assert.True(standardOut.Contains($"- Importing model \"{dtmis[i]}\"...")); FileInfo modelFile = new FileInfo(Path.GetFullPath(testImportRepo.FullName + "/" + paths[i])); Assert.True(modelFile.Exists); Assert.AreEqual(dtmis[i], ParsingUtils.GetRootId(modelFile)); } }
public override void setArgs(string CSVArgs) { var vals = ParsingUtils.separateCSV(CSVArgs); eavesdroppingRadius = double.Parse(vals[0]); remainingReward = double.Parse(vals[1]); }
/// <summary> /// Adds a new range to the list of ranges of the numeric setting. /// </summary> /// <param name="numberSetting">The XBee number setting to add the range to.</param> /// <param name="rangeMinValue">The minimum valid value of the range.</param> /// <param name="rangeMaxValue">The maximum valid value of the range.</param> private static void AddRange(XBeeSettingNumber numberSetting, string rangeMinValue, string rangeMaxValue) { Range range = new Range(rangeMinValue, rangeMaxValue); if (!range.RangeMin.ToLower().StartsWith("0x")) { // [XCTUNG-1180] Range may contain a reference to another AT command. if (ParsingUtils.IsHexadecimal(range.RangeMin)) { range.RangeMin = "0x" + range.RangeMin; } else { // The min range depends on another AT command, so add the dependency. numberSetting.OwnerFirmware.AddDependency(range.RangeMin, numberSetting.AtCommand); } } if (!range.RangeMax.ToLower().StartsWith("0x")) { // [XCTUNG-1180] Range may contain a reference to another AT command. if (ParsingUtils.IsHexadecimal(range.RangeMax)) { range.RangeMax = "0x" + range.RangeMax; } else { // The max range depends on another AT command, so add the dependency. numberSetting.OwnerFirmware.AddDependency(range.RangeMax, numberSetting.AtCommand); } } numberSetting.AddRange(range); }
/// <summary> /// Reads the text setting specific parameters from the XML element and fills /// the given text setting with them. /// </summary> /// <param name="settingElement">The XML element to read the specific parameters from.</param> /// <param name="textSetting">The text setting to be filled.</param> private static void FillTextSetting(XElement settingElement, XBeeSettingText textSetting) { if (settingElement.Element(XMLFirmwareConstants.ITEM_MIN_CHARS) != null && ParsingUtils.IsInteger(settingElement.Element(XMLFirmwareConstants.ITEM_MIN_CHARS).Value.Trim())) { textSetting.MinChars = int.Parse(settingElement.Element(XMLFirmwareConstants.ITEM_MIN_CHARS).Value.Trim()); } if (settingElement.Element(XMLFirmwareConstants.ITEM_MAX_CHARS) != null && ParsingUtils.IsInteger(settingElement.Element(XMLFirmwareConstants.ITEM_MAX_CHARS).Value.Trim())) { textSetting.MaxChars = int.Parse(settingElement.Element(XMLFirmwareConstants.ITEM_MAX_CHARS).Value.Trim()); } if (settingElement.Element(XMLFirmwareConstants.ITEM_FORMAT) != null) { string formatString = settingElement.Element(XMLFirmwareConstants.ITEM_FORMAT).Value.ToUpper(); Format format = Format.UNKNOWN.Get(formatString); if (format == Format.UNKNOWN) { format = Format.ASCII; } textSetting.Format = format; } if (settingElement.Element(XMLFirmwareConstants.ITEM_EXCEPTION) != null) { textSetting.ExceptionValue = settingElement.Element(XMLFirmwareConstants.ITEM_EXCEPTION).Value; } }
public override bool ShowBatchModeStats() { string message = string.Format("تعداد اصلاحات انجام شده: {0}", ParsingUtils.ConvertNumber2Persian(m_stats.ToString())); PersianMessageBox.Show(ThisAddIn.GetWin32Window(), message, Title); return(true); }
/// <summary> /// Returns the XBee value (value stored in the XBee module) of the stop bits setting of the /// firmware. /// </summary> /// <returns>The XBee value of the stop bits setting of the firmware.</returns> public int GetSerialStopBits() { AbstractXBeeSetting atSetting = GetAtSetting(SERIAL_SETTING_STOP_BITS); if (atSetting != null) { // Do not specify the network stack of the SB parameter by the moment (it's a common value). // TODO: [DUAL] When this setting is implemented individually for each network stack, update this code to // specify the network ID from which this parameter should be read. string settingValue = atSetting.GetXBeeValue(); if (!ParsingUtils.IsInteger(atSetting.GetXBeeValue())) { return(DEFAULT_SERIAL_STOP_BITS); } switch (int.Parse(settingValue)) { case 0: return(1); case 1: return(2); default: return(DEFAULT_SERIAL_STOP_BITS); } } return(DEFAULT_SERIAL_STOP_BITS); }
public void ExportInvocation(string dtmi, string expectedDeps, TestHelpers.ClientType clientType) { string targetRepo = string.Empty; if (clientType == TestHelpers.ClientType.Local) { targetRepo = $"--repo \"{TestHelpers.TestLocalModelRepository}\""; } (int returnCode, string standardOut, string standardError) = ClientInvokator.Invoke($"export --dtmi \"{dtmi}\" {targetRepo}"); Assert.AreEqual(Handlers.ReturnCodes.Success, returnCode); Assert.False(standardError.Contains(Outputs.DefaultErrorToken)); FileExtractResult extractResult = ParsingUtils.ExtractModels(standardOut); List <string> modelsResult = extractResult.Models; string[] expectedDtmis = $"{dtmi},{expectedDeps}".Split(",", StringSplitOptions.RemoveEmptyEntries); Assert.True(modelsResult.Count == expectedDtmis.Length); foreach (string model in modelsResult) { string targetId = ParsingUtils.GetRootId(model); Assert.True(expectedDtmis.Contains(targetId)); } }
public void ShowPageNumberProgress(int pageNo, int pageCount) { string msg = String.Format("صفحهٔ {0} از {1}", ParsingUtils.ConvertNumber2Persian(pageNo.ToString()), ParsingUtils.ConvertNumber2Persian(pageCount.ToString())); var act = new Action(delegate { lblProgress.Text = msg; if (!progressBar.Visible) { progressBar.Visible = true; } progressBar.Minimum = 0; progressBar.Maximum = pageCount; progressBar.Value = Math.Min(pageNo, pageCount); }); if (InvokeRequired) { Invoke(act); } else { act.Invoke(); } }
public override object InformationToProperty(IInformation information, Type propertyType) { var value = information as IInformationValue; if (value == null) { throw new OptionReaderException(information.Lines.First().Number, information.Lines.Last().Number, $"'{information.Name}' must be a value type."); } try { // Change .md or .markdown extensions to .html and change macros to an XML form. var menuString = MarkdownProcessor.Transform( ParsingUtils.ReplaceMacros( Regex.Replace( OtherUtils.ReadAllText(value.Value), @"\w+?\.(?:md|markdown)", match => PathUtils.ChangeExtension(match.Value, "html")))); return XmlUtils.WrapAndParse("Menu", menuString); } catch (Exception e) { throw new OptionReaderException(information.Lines.First().Number, information.Lines.Last().Number, e.Message); } }
private bool CheckIfParseable() { ScriptScope scope = _prefabPythonObject.ScriptScope; Type type = scope.GetVariable(_fieldName).GetType(); bool parseable = ParsingUtils.IsTextParseable(type); return(parseable); }
/// <summary> /// Reads the button setting specific parameters from the XML element and fills the given button /// setting with them. /// </summary> /// <param name="settingElement">The XML element to read the specific parameters from.</param> /// <param name="buttonSetting">The button setting to be filled.</param> private static void FillButtonSetting(XElement settingElement, XBeeSettingButton buttonSetting) { if (settingElement.Element(XMLFirmwareConstants.ITEM_FUNCTION_NUMBER) != null && ParsingUtils.IsInteger(settingElement.Element(XMLFirmwareConstants.ITEM_FUNCTION_NUMBER).Value.Trim())) { buttonSetting.FunctionNumber = int.Parse(settingElement.Element(XMLFirmwareConstants.ITEM_FUNCTION_NUMBER).Value.Trim()); } }
public void TestParenthesisPhone() { var phoneObject = ParsingUtils.ParsePhoneNumber("+55 (11) 997513126"); Assert.Equal(PhoneCountry.Brazil, phoneObject.CountryCode); Assert.Equal(PhoneRegion.SpCapital, phoneObject.StateCode); Assert.Equal(Convert.ToString(997513126L), Convert.ToString(phoneObject.Number)); }
/// <summary> /// Returns the default selected index. /// </summary> /// <returns>The default selected index.</returns> public int GetDefaultSelectedIndex() { if (!ParsingUtils.IsHexadecimal(DefaultValue)) { return(0); } return(ParsingUtils.HexStringToInt(DefaultValue)); }
public static AGameGraph loadGraph(string[] serialization) { string[] filteredSerialization = ParsingUtils.clearComments(serialization); string graphType = filteredSerialization[0]; AGameGraph graph = (AGameGraph)Activator.CreateInstance(null, graphType).Unwrap(); graph.deserialize(filteredSerialization); return(graph); }
/// <summary> /// Returns the XBee value (value stored in the XBee module) of the baud rate setting of the firmware. /// </summary> /// <returns>The XBee value of the baud rate setting of the firmware.</returns> public int GetSerialBaudRate() { AbstractXBeeSetting atSetting = GetAtSetting(SERIAL_SETTING_BAUD_RATE); if (atSetting != null) { // Do not specify the network stack of the BD parameter by the moment (it's a common value). // TODO: [DUAL] When this setting is implemented individually for each network stack, update this code to // specify the network ID from which this parameter should be read. string settingValue = atSetting.GetXBeeValue(); if (!ParsingUtils.IsHexadecimal(atSetting.GetXBeeValue())) { return(DEFAULT_SERIAL_BAUD_RATE); } switch (ParsingUtils.HexStringToInt(settingValue)) { case 0: return(1200); case 1: return(2400); case 2: return(4800); case 3: return(9600); case 4: return(19200); case 5: return(38400); case 6: return(57600); case 7: return(115200); case 8: return(230400); case 9: return(460800); case 10: return(921600); default: return(DEFAULT_SERIAL_BAUD_RATE); } } return(DEFAULT_SERIAL_BAUD_RATE); }
public override void ParseAndSet(object instance, string text) { if (!_isParseable) { throw new InvalidOperationException("Field does not support text input"); } object value = ParsingUtils.Parse(_fieldInfo.FieldType, text); SetValue(instance, value); }
public void ModifiedOutput(string source, string expected) { // Run the replacement on the string case and compare results. var actual = ParsingUtils.ReplaceMacros(source); Assert.AreEqual(expected, actual, "Lower-case case failed."); // Run the replacement on the string with random case and compare the lowercase results. var actualRandomCase = ParsingUtils.ReplaceMacros(source.ToRandomCase()).ToLower(); Assert.AreEqual(expected, actualRandomCase, "Randomized case failed."); }
private string StatsticsMessage() { var sb = new StringBuilder(); long sum = 0L; foreach (var pair in m_dicRefinementStats) { sum += pair.Value; sb.AppendLine(String.Format("{0}: {1}", GetRefinementTypeLabel(pair.Key), ParsingUtils.ConvertNumber2Persian(pair.Value.ToString()))); } return(String.Format("{0}: {1}{2}{2}", "تعداد کل نویسههای اصلاح شده", ParsingUtils.ConvertNumber2Persian(sum.ToString()), Environment.NewLine) + sb); }
public override void ParseAndSet(object instance, string text) { Type type = _prefabPythonObject.ScriptScope.GetVariable(_fieldName).GetType(); if (ParsingUtils.IsTextParseable(type)) { object value = ParsingUtils.Parse(type, text); SetValue(instance, value); } else { // TODO Throw exception } }
public float GetFloat(string key) { string val = dict[key]; try { return(ParsingUtils.ParseFloat(val)); } catch { AddErrorMsg("sbwrongfloatformat", key); return(float.NaN); } }
/// <summary> /// Returns whether or not the current value of the provided network index is valid. /// </summary> /// <returns><c>true</c> if the value is valid, <c>false</c> otherwise.</returns> public override bool ValidateSetting(int networkIndex) { if (GetCurrentValue(networkIndex) == null) { ValidationErrorMessage = "You must select one of the possible values."; return(false); } if (!ParsingUtils.IsHexadecimal(GetCurrentValue(networkIndex))) { ValidationErrorMessage = "Invalid selection value."; return(false); } ValidationErrorMessage = null; return(true); }
public bool CanParse(Type type) { if (!ParsingUtils.IsNullable(type)) { return(typeof(Enum).IsAssignableFrom(type)); } if (!_config.TypeParserOfClassIsNullables) { return(false); } var enumType = type.GetGenericArguments().FirstOrDefault(); return(typeof(Enum).IsAssignableFrom(enumType)); }
public void ExportOutFile(string dtmi, string outfilePath) { string qualifiedPath = Path.GetFullPath(outfilePath); (int returnCode, _, string standardError) = ClientInvokator.Invoke($"export -o \"{qualifiedPath}\" --dtmi \"{dtmi}\" --repo \"{TestHelpers.TestLocalModelRepository}\""); Assert.AreEqual(Handlers.ReturnCodes.Success, returnCode); Assert.False(standardError.Contains(Outputs.DefaultErrorToken)); FileExtractResult extractResult = ParsingUtils.ExtractModels(new FileInfo(qualifiedPath)); List <string> modelsResult = extractResult.Models; string targetId = ParsingUtils.GetRootId(modelsResult[0]); Assert.AreEqual(dtmi, targetId); }
private void AddPossibleYearNumbers(int yearNumber, DateCalendarType calendarType) { comboYearNumber.Items.Clear(); if (yearNumber <= 0) { return; } if (yearNumber < 100) { int newYear = yearNumber; switch (calendarType) { case DateCalendarType.Gregorian: if ((2000 - (1900 + yearNumber)) < ((2000 + yearNumber) - 2000)) { newYear += 1900; } else { newYear += 2000; } break; case DateCalendarType.HijriGhamari: newYear += 1400; break; case DateCalendarType.Jalali: newYear += 1300; break; default: break; } comboYearNumber.Items.Add(ParsingUtils.ConvertNumber2Persian(newYear.ToString())); comboYearNumber.Visible = true; comboYearNumber.Enabled = true; } comboYearNumber.Items.Add(ParsingUtils.ConvertNumber2Persian(yearNumber.ToString())); comboYearNumber.SelectedIndex = 0; }
public int GetSelectedYearNumber() { int yearNumber = -1; if (comboYearNumber.SelectedIndex >= 0 && comboYearNumber.Items.Count > 0) { string selectedYear = comboYearNumber.Items[comboYearNumber.SelectedIndex] as string; if (selectedYear != null) { if (Int32.TryParse(ParsingUtils.ConvertNumber2English(selectedYear), out yearNumber)) { return(yearNumber); } } } return(-1); }
/// <summary> /// Reads the combo setting specific parameters from the XML element and fills the given /// combo setting with them. /// </summary> /// <param name="settingElement">The XML element to read the specific parameters from.</param> /// <param name="comboSetting">The combo setting to be filled.</param> private static void FillComboSetting(XElement settingElement, XBeeSettingCombo comboSetting) { List <string> comboItems = new List <string>(); XElement comboItemsElement = settingElement.Element(XMLFirmwareConstants.ITEM_ITEMS); if (comboItemsElement == null) { return; } List <XElement> comboItemsList = new List <XElement>(); foreach (XElement element in comboItemsElement.Elements()) { if (element.Name.ToString().Equals(XMLFirmwareConstants.ITEM_ITEM)) { comboItemsList.Add(element); } } if (comboItemsList == null || comboItemsList.Count == 0) { return; } for (int i = 0; i < comboItemsList.Count; i++) { string index = ParsingUtils.IntegerToHexString(i, 1); while (index.StartsWith("0")) { if (index.Length == 1) { break; } index = index.Substring(1); } comboItems.Add(comboItemsList[i].Value + " [" + index + "]"); } comboSetting.Items = comboItems; }
protected override void OnOperationsCompletion() { base.OnOperationsCompletion(); string elapsedTime = ParsingUtils.GetElapsedTimeString(_stopwatch.Elapsed); _view.NotifyOperationsResult(LogMessagesUtils.GetReductionWorkCompletionText(_operationsStats.ProcessedFileCount, _operationsStats.SuccesfullyProcessedFileCount, _operationsStats.UnsuccessfullyProcessedFileCount, _operationsStats.TotalInputSize, _operationsStats.TotalOutputSize, elapsedTime)); string detailedWorkCompletionMessage = LogMessagesUtils.GetDetailedReductionWorkCompletionText(_operationsStats.ProcessedFileCount, _operationsStats.SuccesfullyProcessedFileCount, _operationsStats.UnsuccessfullyProcessedFileCount, _operationsStats.FileConvertedToPDFCount, _operationsStats.TotalInputSize, _operationsStats.TotalOutputSize, elapsedTime); if (!_appInfo.AutoRun) { _view.ShowInformationMessage(detailedWorkCompletionMessage, FrameworkGlobals.MessagesLocalizer.GetString("processTerminated", FrameworkGlobals.ApplicationLanguage)); _view.UnlockView(); } else { Console.Write(detailedWorkCompletionMessage); _view.ExitApplication(); } }
private LotDto ParseLot(IWebElement lotDiv) { try { var a = lotDiv.FindElement(By.CssSelector("a[class=\"goods-tile__picture\"]")); var imgElement = lotDiv.FindElement(By.CssSelector("img")); string title = imgElement.GetAttribute("title"); if (!keywordsRegex.IsMatch(title)) { return(null); } string link = new string(a.GetAttribute("href").TakeWhile(x => x != '?').ToArray()); string imgLink = imgElement.GetAttribute("src"); string priceStr = lotDiv.FindElement(By.CssSelector("span[class=\"goods-tile__price-value\"]")).Text; priceStr = new string(priceStr.Where(x => x != ' ').ToArray()); decimal price = decimal.Parse(new string(priceStr.TakeWhile(x => Char.IsDigit(x)).ToArray())); int grams = ParsingUtils.GetGrams(title); return(new LotDto() { Shop = this.shop, ImageLink = imgLink, Link = link, Manufacturer = null, Title = title, WeightInGrams = grams, Price = new PriceDto() { Date = DateTime.Now, Value = price } }); } catch (Exception ex) { return(null); } }