public override void Init(Parsing.ParsingContext context, Parsing.ParseTreeNode treeNode) { base.Init(context, treeNode); _positionSetAstNode = (PositionSetAstNode)AddChild("PositionSetAstNode", treeNode.ChildNodes[0]); _expressionAstNode = (ExpressionAstNode)AddChild("ExpressionAstNode", treeNode.ChildNodes[1]); }
public override IAnalysisSet BinaryOperation(Node node, AnalysisUnit unit, Parsing.PythonOperator operation, IAnalysisSet rhs) { var res = AnalysisSet.Empty; switch (operation) { case PythonOperator.Add: foreach (var type in rhs) { if (type.IsOfType(ClassInfo)) { res = res.Union(ClassInfo.Instance); } else { res = res.Union(type.ReverseBinaryOperation(node, unit, operation, SelfSet)); } } break; case PythonOperator.Mod: if (_supportsMod) { res = SelfSet; } break; case PythonOperator.Multiply: foreach (var type in rhs) { if (type.IsOfType(ProjectState.ClassInfos[BuiltinTypeId.Int]) || type.IsOfType(ProjectState.ClassInfos[BuiltinTypeId.Long])) { res = res.Union(ClassInfo.Instance); } else { var partialRes = ConstantInfo.NumericOp(node, this, unit, operation, rhs); if (partialRes != null) { res = res.Union(partialRes); } } } break; } return res ?? base.BinaryOperation(node, unit, operation, rhs); }
internal void Parse(Parsing.Parser parser, VccCompilationPart compilationPart) { this.Parse(parser); this.compilationPart = compilationPart; this.SetContainingNodes(); this.isInitialized = true; }
public override IAnalysisSet BinaryOperation(Node node, AnalysisUnit unit, Parsing.PythonOperator operation, IAnalysisSet rhs) { if (_original == null) { return base.BinaryOperation(node, unit, operation, rhs); } return _original.BinaryOperation(node, unit, operation, rhs); }
public override bool AssignVariable(string name, Parsing.Ast.Node location, AnalysisUnit unit, IAnalysisSet values) { if (base.AssignVariable(name, location, unit, values)) { Module.ModuleDefinition.EnqueueDependents(); return true; } return false; }
private LambdaExpression _tracingLambda; // the transformed lambda used for tracing/debugging #endregion Fields #region Constructors /// <summary> /// Constructor used to create a FunctionCode for code that's been serialized to disk. /// /// Code constructed this way cannot be interpreted or debugged using sys.settrace/sys.setprofile. /// /// Function codes created this way do support recursion enforcement and are therefore registered in the global function code registry. /// </summary> internal FunctionCode(TotemContext context, Delegate code, Parsing.Ast.ScopeStatement scope, int localCount) { _normalDelegate = code; _lambda = scope; _argCount = CalculateArgumentCount(); // need to take this lock to ensure sys.settrace/sys.setprofile is not actively changing lock (_CodeCreateAndUpdateDelegateLock) { SetTarget(AddRecursionCheck(context, code)); } RegisterFunctionCode(context); }
public override INamespaceSet GetMember(Parsing.Ast.Node node, Interpreter.AnalysisUnit unit, string name) { if (name == "__new__") { if (_new == null) { var func = this._type.GetMember(unit.ProjectEntry.MyScope.InterpreterContext, name); if (func != null) { _new = new NewFunction((BuiltinFunctionInfo)unit.ProjectState.GetNamespaceFromObjects(func), ProjectState); } } if (_new != null) { return _new.SelfSet; } } return base.GetMember(node, unit, name); }
public override IAnalysisSet GetIndex(Parsing.Node node, AnalysisUnit unit, IAnalysisSet index) { var res = AnalysisSet.Empty; if (_function._curArgs != null) { foreach (var value in index) { var numIndex = value.Value.GetNumberValue(); if (numIndex != null && numIndex.Value >= 0 && (numIndex.Value % 1) == 0 && // integer number... ((int)numIndex.Value) < _function._curArgs.Args.Length) { res = res.Union(_function._curArgs.Args[(int)numIndex.Value]); } } } return res; }
public override void SetMember(Parsing.Node node, AnalysisUnit unit, string name, IAnalysisSet value) { foreach (var obj in value) { // function Class() { // this.abc = 42; // } // // Class.prototype.foo = function(fn) { // var x = this.abc; // } // this now includes us. UserFunctionValue userFunc = obj.Value as UserFunctionValue; if (userFunc != null) { var env = (FunctionEnvironmentRecord)(userFunc.AnalysisUnit._env); env._this.AddTypes(unit, _function._instance.SelfSet, declaringScope: DeclaringModule); } } base.SetMember(node, unit, name, value); }
public void NecessaryExecutableTest8() { var queryText = @"necessary executable load, shoot, shoot"; var query = Parsing.GetQuery(queryText); var text = @"initially alive and not loaded load causes loaded impossible shoot if not loaded when Bob shoot causes not alive and not loaded when John shoot causes not alive" ; var history = Parsing.GetHistory(text); var story = new Story(history); var graph = Graph.Graph.CreateGraph(story, query); if (query is ExecutableQueryStatement executableQuery) { var queryResult = executableQuery.Execute(graph, history); Assert.AreEqual(true, queryResult); } }
public void InputButton_Click(object sender, RoutedEventArgs e) { if (Parsing.SearchMistakes(InputBox.Text)) { Equation = Parsing.StartParsing(InputBox.Text); string equationStr = string.Empty; for (int i = 0; i < Equation.Count; i++) { equationStr += Equation[i]; } OutputResult.Text = equationStr; DeltaScroll = 1; DeltaX = 0; DeltaY = 0; DrawF(); } else { OutputResult.Text = "Вы допустили ошибку!"; } }
/// <inheritdoc /> public override async IAsyncEnumerable <string> Execute(string expr, Session session) { var voucherID = Parsing.Token(ref expr); var guids = new List <string>(); var guidT = Guid.Empty; // ReSharper disable once AccessToModifiedClosure while (Parsing.Token(ref expr, true, s => Guid.TryParse(s, out guidT)) != null) { guids.Add(guidT.ToString()); } Parsing.Eof(expr); var voucher = await session.Accountant.SelectVoucherAsync(voucherID); if (voucher == null) { throw new ApplicationException("找不到记账凭证"); } foreach (var detail in voucher.Details.Where(static vd => vd.Title is 1601 or 1701)
public void PossibllyExecutableTest9() { var queryText = @"possibly executable John load, shoot, John shoot"; var query = Parsing.GetQuery(queryText); var text = @"initially alive and not loaded load causes loaded impossible shoot if not loaded impossible Bob shoot observable not loaded and not alive after John shoot" ; var history = Parsing.GetHistory(text); var story = new Story(history); var graph = Graph.Graph.CreateGraph(story, query); if (query is ExecutableQueryStatement executableQuery) { var queryResult = executableQuery.Execute(graph, history); Assert.AreEqual(true, queryResult); } }
private static void CreateWorkbookForModule(string modulePath, string workbookPath) { var tables = Parsing.ParseTables(modulePath); File.Delete(workbookPath); var file = new FileInfo(workbookPath); using (var package = new ExcelPackage(file)) { foreach (var table in tables) { var worksheet = package.Workbook.Worksheets.Add(table.Code); var endCoordinate = table.WriteToWorksheet(worksheet, new ExcelCoordinate(1, 1)); worksheet.Pretty(); } package.Save(); } Console.WriteLine(file.FullName); }
public static void FillUserParamsFromString(string theString, string key, UnitOfMeasurementConverters converter, Enum theUnit) { var tbValue = double.NaN; var ucKey = key.ToUpper(); if (Parsing.TryParseDouble(theString, out tbValue)) { double fieldMinValue = double.NegativeInfinity, fieldMaxValue = double.PositiveInfinity; if (QraStateContainer.Instance.IsItemInDatabase(ucKey)) { fieldMinValue = QraStateContainer.Instance.GetStateDefinedValueObject(ucKey).MinValue; fieldMaxValue = QraStateContainer.Instance.GetStateDefinedValueObject(ucKey).MaxValue; } QraStateContainer.Instance.Parameters[ucKey] = new NdConvertibleValue(converter, theUnit, new double[1] { tbValue }, fieldMinValue, fieldMaxValue); } }
private void readCustomSampleBanks(string str, SampleBankInfo bankInfo) { if (string.IsNullOrEmpty(str)) { return; } string[] split = str.Split(':'); var bank = (LegacySampleBank)Parsing.ParseInt(split[0]); var addbank = (LegacySampleBank)Parsing.ParseInt(split[1]); string stringBank = bank.ToString().ToLowerInvariant(); if (stringBank == @"none") { stringBank = null; } string stringAddBank = addbank.ToString().ToLowerInvariant(); if (stringAddBank == @"none") { stringAddBank = null; } bankInfo.Normal = stringBank; bankInfo.Add = string.IsNullOrEmpty(stringAddBank) ? stringBank : stringAddBank; if (split.Length > 2) { bankInfo.CustomSampleBank = Parsing.ParseInt(split[2]); } if (split.Length > 3) { bankInfo.Volume = Math.Max(0, Parsing.ParseInt(split[3])); } bankInfo.Filename = split.Length > 4 ? split[4] : null; }
public void ImportModelFileSingleModelObject(string _, string modelFilePath, string expectedDtmi, bool strict) { 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}"); Assert.AreEqual(Handlers.ReturnCodes.Success, returnCode); Assert.False(standardError.Contains("Error:")); Assert.True(standardError.Contains(Outputs.StandardHeader)); Assert.True(standardOut.Contains("- Validating models conform to DTDL...")); Assert.True(standardOut.Contains($"- Importing model \"{expectedDtmi}\"...")); Parsing parsing = new Parsing(null); FileInfo modelFile = new FileInfo(Path.GetFullPath(testImportRepo.FullName + "/" + modelFilePath)); Assert.True(modelFile.Exists); DateTime lastWriteTimeUtc = modelFile.LastWriteTimeUtc; Assert.AreEqual(expectedDtmi, parsing.GetRootId(modelFile)); if (strict) { Assert.True(standardOut.Contains("- Ensuring DTMIs namespace conformance for model")); } // Import the same model to ensure its skipped. (returnCode, standardOut, _) = ClientInvokator.Invoke($"import --model-file \"{qualifiedModelFilePath}\" {targetRepo} {strictSwitch}"); Assert.AreEqual(Handlers.ReturnCodes.Success, returnCode); modelFile = new FileInfo(Path.GetFullPath(testImportRepo.FullName + "/" + modelFilePath)); Assert.AreEqual(lastWriteTimeUtc, modelFile.LastWriteTimeUtc); Assert.True(standardOut.Contains($"Skipping \"{expectedDtmi}\". Model file already exists in repository.")); }
public static void UnitlessTextBoxValueChanged(TextBox sender, ref NdConvertibleValue valueObj) { var testValue = double.NaN; if (Parsing.TryParseDouble(sender.Text, out testValue)) { var newValue = new double[1]; newValue[0] = testValue; valueObj.SetValue(UnitlessUnit.Unitless.ToString(), newValue); if (sender.ForeColor != Color.Black) { sender.ForeColor = Color.Black; } } else { if (sender.ForeColor != Color.Red) { sender.ForeColor = Color.Red; } } }
public void PossiblyExecutableTest12() { var queryText = @"possibly executable load, John shoot, shoot"; var query = Parsing.GetQuery(queryText); var text = @"initially alive and not loaded when Bob load causes loaded impossible shoot if not loaded impossible Eric shoot not loaded after Bob shoot when John shoot releases loaded" ; var history = Parsing.GetHistory(text); var story = new Story(history); var graph = Graph.Graph.CreateGraph(story, query); if (query is ExecutableQueryStatement executableQuery) { var queryResult = executableQuery.Execute(graph, history); Assert.AreEqual(true, queryResult); } }
/// <summary>Converts the string to a BIC. /// A return value indicates whether the conversion succeeded. /// </summary> /// <param name="s"> /// A string containing a BIC to convert. /// </param> /// <param name="formatProvider"> /// The specified format provider. /// </param> /// <param name="result"> /// The result of the parsing. /// </param> /// <returns> /// True if the string was converted successfully, otherwise false. /// </returns> public static bool TryParse(string s, IFormatProvider formatProvider, out BankIdentifierCode result) { result = BankIdentifierCode.Empty; if (string.IsNullOrEmpty(s)) { return(true); } if (Qowaiv.Unknown.IsUnknown(s, formatProvider as CultureInfo)) { result = BankIdentifierCode.Unknown; return(true); } if (IsValid(s, formatProvider)) { result = new BankIdentifierCode() { m_Value = Parsing.ClearSpacingAndMarkupToUpper(s) }; return(true); } return(false); }
private string FindCommonLetters(string input) { string boxId1 = string.Empty; string boxId2 = string.Empty; bool matchFound = false; List <string> boxIds = Parsing.SplitOnNewLine(input).ToList(); do { boxId1 = boxIds[0]; boxIds.RemoveAt(0); boxId2 = boxIds.FirstOrDefault(id2 => DoTwoBoxIdsDifferByOnlyOneChar(boxId1, id2) == true); if (boxId2 != null) { matchFound = true; } } while (!matchFound); return(RemoveUncommonLetterFromTwoBoxIds(boxId1, boxId2)); }
public void C_101_00_hypercubes() { var tableCode = "c_101.00"; var metFile = $"{MetricPath}/met.xsd"; var metrics = Parsing.ParseNames(metFile); var dimFile = $"{DimensionPath}/dim.xsd"; var dimensions = Parsing.ParseNames(dimFile); var expFile = $"{DomainPath}/exp.xsd"; var typFile = $"{DomainPath}/typ.xsd"; var domains = Parsing.ParseNames(expFile); var typDomains = Parsing.ParseNames(typFile); var typedDimensions = Parsing.ParseTypedDimensions(dimFile); typDomains.ToList().ForEach(x => domains[x.Key] = x.Value); var cubes = Parsing.ParseHypercubes(TaxonomyPath, tableCode, metrics, dimensions, domains, typedDimensions); Helper.DumpHypercubes(cubes); }
private double[] GetCdfInputValuesFromGrid(DataGridViewRow currentRow, out bool allValuesGood) { allValuesGood = true; var result = new double[currentRow.Cells.Count - 1]; for (var colIndex = 1; colIndex < currentRow.Cells.Count; colIndex++) { var thevalue = double.NaN; var strValue = currentRow.Cells[colIndex].Value.ToString(); if (Parsing.TryParseDouble(strValue, out thevalue)) { result[colIndex - 1] = thevalue; } else { allValuesGood = false; } } return(result); }
protected override void beforeEach() { _template = new Template("b/a.spark", "b", "c"); _template.Descriptor = _viewDescriptor = new SparkDescriptor(_template) { ViewModel = typeof(ProductModel) }; _parsing = new Parsing { Master = "application", ViewModelType = _viewDescriptor.ViewModel.FullName }; _request = new AttachRequest <ITemplate> { Template = _template, Logger = MockFor <ITemplateLogger>() }; MockFor <IParsingRegistrations <ITemplate> >().Expect(x => x.ParsingFor(_template)).Return(_parsing); }
public object Part1(string input) { var particles = input.Lines() .Select(Parsing.PatternParser <string, string, string, Particle>( @"p=<(-?\d+,-?\d+,-?\d+)>, v=<(-?\d+,-?\d+,-?\d+)>, a=<(-?\d+,-?\d+,-?\d+)>", static (p, v, a) => new Particle(vectorParser(p), vectorParser(v), vectorParser(a)) )) .ToArray(); for (int i = 0; i < 1000; i++) { for (int j = 0; j < particles.Length; j++) { var particle = particles[j]; particles[j] = particle with { pos = particle.pos + particle.vel, vel = particle.vel + particle.acc, }; } } return(particles.Select(static (p, i) => (p, i)).Aggregate(static (a, b) => Vector3.Zero.ManhattanDistance(a.p.pos) < Vector3.Zero.ManhattanDistance(b.p.pos) ? a : b).i);
public static double[] ExtractArrayFromTextbox(TextBox tb) { var sResult = tb.Text.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); var result = new double[sResult.Length]; for (var index = 0; index < result.Length; index++) { var parsedValue = double.NaN; var successfullyParsed = Parsing.TryParseDouble(sResult[index], out parsedValue); if (successfullyParsed) { result[index] = parsedValue; } else { result[index] = double.NaN; } } return(result); }
protected override List <IChapter> ParseChapterObjects(string html) { Log.Trace("Entering ParseChapterObjects"); if (IsChapter) { Log.Debug("The supplied URI is for a chapter."); var chapter = new List <IChapter>(); chapter.Add(new ChapterDistill(SeriesTitle, Address, HostData, Log)); return(chapter); } else { string path = HostData.Chapters.Path; string pathValue = HostData.Chapters.Value; var details = new ChapterParseDetails( path, pathValue, (element, parseDetails) => { return(GenericParseAction <IChapter> ( element, parseDetails, HostData.Chapters, (chapterUri) => ChapterParseActionUriSupplied(new DMR11.Core.Net.ValidatedUri(chapterUri), element, parseDetails, html) )); }, Log, HostVariables ); return(Parsing.ParseChapters(html, details)); } }
private double GetDoubleCellValue(object value) { var result = double.NaN; if (value == null) { result = 0D; } else { var valueType = value.GetType(); var doubleType = 0D.GetType(); var stringType = "".GetType(); if (valueType == stringType) { var strValue = (string)value; if (strValue == null) { result = 0D; } else { result = Parsing.ParseDouble(strValue); } } else if (valueType == doubleType) { result = (double)value; } else { throw new Exception("Type of " + value.GetType().Name + " is unrecognized."); } } return(result); }
public static string InputLoopNumber(string minimum, string maximum, string type, IEnumerable <Person> resultList) { var min = Parsing.StringToInt(minimum)[0]; var max = Parsing.StringToInt(maximum)[0]; var ok = false; while (true) { if (type.Equals("ID number") && ok == true) { PrintResultList(resultList); } Console.WriteLine("Enter with the " + type + ": "); var inputNumber = Console.ReadLine().Trim(); if (!String.IsNullOrEmpty(inputNumber)) { var converted = Parsing.StringToInt(inputNumber); if (converted != null && (converted[0] >= min && converted[0] <= max)) { return(converted[0].ToString()); } else { ok = true; Console.WriteLine("\nInvalid number.\n" + "It must be an interger number between " + (Parsing.StringToInt(minimum)[0]).ToString() + " and " + (Parsing.StringToInt(maximum)[0]).ToString() + ". \nTry again."); } } else { Console.WriteLine("\nError: Empty field.\nTry again."); } ClearScreen(false); } }
private void readLegacyReplay(Replay replay, StreamReader reader) { float lastTime = 0; ReplayFrame currentFrame = null; foreach (var l in reader.ReadToEnd().Split(',')) { var split = l.Split('|'); if (split.Length < 4) { continue; } if (split[0] == "-12345") { // Todo: The seed is provided in split[3], which we'll need to use at some point continue; } var diff = Parsing.ParseFloat(split[0]); lastTime += diff; // Todo: At some point we probably want to rewind and play back the negative-time frames // but for now we'll achieve equal playback to stable by skipping negative frames if (diff < 0) { continue; } currentFrame = convertFrame(new LegacyReplayFrame(lastTime, Parsing.ParseFloat(split[1], Parsing.MAX_COORDINATE_VALUE), Parsing.ParseFloat(split[2], Parsing.MAX_COORDINATE_VALUE), (ReplayButtonState)Parsing.ParseInt(split[3])), currentFrame); replay.Frames.Add(currentFrame); } }
// <viewdata model="FubuMVC.Diagnostics.DashboardModel" /> public Parsing Read() { var parsing = new Parsing(); using (var reader = new StreamReader(_file)) { string line; // Read and display lines from the file until the end of // the file is reached. while ((line = reader.ReadLine()) != null) { if (line.Contains("<viewdata")) { var document = new XmlDocument(); document.LoadXml(line.Trim()); parsing.ViewModelType = document.DocumentElement.GetAttribute("model"); } } } return parsing; }
/// <summary> /// Получить более менее команд /// </summary> /// <returns></returns> public async Task <MatchModels> GetPageCoefficient(bool fds = true, bool bm = true) { List <AllTotalModels> coeffBM = null, coeffFDS = null; var coeffPage = await new MatchInfomation().GetPageCoefficient(this); if (fds) { coeffFDS = Parsing.CoeffFDS(coeffPage); } if (bm) { coeffBM = Parsing.CoeffBM(coeffPage); } this.Coefficient = new CoefficientsModels() { BM = coeffBM, FDS = coeffFDS, }; return(this); }
/// <summary>Converts the string to a currency. /// A return value indicates whether the conversion succeeded. /// </summary> /// <param name="s"> /// A string containing a currency to convert. /// </param> /// <param name="formatProvider"> /// The specified format provider. /// </param> /// <param name="result"> /// The result of the parsing. /// </param> /// <returns> /// True if the string was converted successfully, otherwise false. /// </returns> public static bool TryParse(string s, IFormatProvider formatProvider, out Currency result) { result = Empty; if (string.IsNullOrEmpty(s)) { return(true); } var culture = formatProvider as CultureInfo ?? CultureInfo.InvariantCulture; if (Qowaiv.Unknown.IsUnknown(s, culture) || s == Unknown.Symbol) { result = Unknown; return(true); } AddCulture(culture); var str = Parsing.ToUnified(s); string val; if (Parsings[culture].TryGetValue(str, out val) || Parsings[CultureInfo.InvariantCulture].TryGetValue(str, out val)) { result = new Currency() { m_Value = val }; return(true); } foreach (var currency in AllCurrencies.Where(c => !string.IsNullOrEmpty(c.Symbol))) { if (currency.Symbol == str) { result = currency; return(true); } } return(false); }
/// <inheritdoc /> public override async IAsyncEnumerable<string> Execute(string expr, Session session) { var remark = Parsing.Token(ref expr); var rate = Parsing.DoubleF(ref expr) / 10000D; var all = Parsing.Optional(ref expr, "all"); var endDate = !all ? Parsing.UniqueTime(ref expr, session.Client) : null; Parsing.Eof(expr); var loans = (await session.Accountant.RunGroupedQueryAsync($"({MajorFilter()})-\"\" ``rtcC")).Items .Cast<ISubtotalRemark>() .ToList(); var rmkObj = loans.Single( b => b.Remark?.StartsWith(remark, StringComparison.InvariantCultureIgnoreCase) == true && !b.Remark.EndsWith("-利息", StringComparison.Ordinal)); var titleObj = rmkObj.Items.Cast<ISubtotalTitle>().Single(); var cntObj = titleObj.Items.Cast<ISubtotalContent>().Single(); var title = titleObj.Title!.Value; var content = cntObj.Content; var rmk = rmkObj.Remark; var currency = cntObj.Items.Cast<ISubtotalCurrency>().Single().Currency; var info = new LoanInfo { Currency = currency, Title = title, Content = content, Remark = rmk, Rate = rate, }; await using var vir = session.Accountant.Virtualize(); if (!all && !endDate.HasValue || endDate.HasValue) { var lastD = (await session.Accountant.RunVoucherQueryAsync(info.QueryInterest()) .OrderByDescending(static v => v.Date, new DateComparer())
public bool SaveData(Dictionary <string, List <StringDictionary> > data) { var parsing = new Parsing() { Date = DateTime.UtcNow }; // номер считать с лог файла var httpResponce = new HttpResponce(); T _tag; A _attr; List <StringDictionary> attrs; foreach (var tags in data) { _tag = new Tag { Name = tags.Key, Parsing = parsing } as T; _tags.Create(_tag); attrs = tags.Value; foreach (var attribute in attrs) { foreach (var attr in attribute.Keys) { _attr = new TagAttribute() { Name = attr.ToString(), Value = attribute[attr.ToString()], Tag = _tag } as A; _attrs.Create(_attr); } } } return(true); }
/// <summary> /// 解析记账凭证表达式 /// </summary> /// <param name="expr">表达式</param> /// <returns>记账凭证</returns> private Voucher GetVoucher(ref string expr) { Parsing.TrimStartComment(ref expr); var id = Parsing.Quoted(ref expr, '^'); Parsing.TrimStartComment(ref expr); DateTime? date = ClientDateTime.Today; try { date = ParsingF.UniqueTime(ref expr); } catch (Exception) { // ignore } Parsing.TrimStartComment(ref expr); var remark = Parsing.Quoted(ref expr, '%'); Parsing.TrimStartComment(ref expr); var typeT = VoucherType.Ordinary; var type = Parsing.Token(ref expr, false, t => TryParse(t, out typeT)) != null ? (VoucherType?)typeT : null; Parsing.TrimStartComment(ref expr); var lst = new List<VoucherDetail>(); VoucherDetail d; while ((d = ParseVoucherDetail(ref expr)) != null) lst.Add(d); return new Voucher { ID = id, Remark = remark, Type = type, Date = date, Details = lst }; }
/// <inheritdoc /> public Voucher ParseVoucher(string expr) { if (!expr.StartsWith(TheToken, StringComparison.Ordinal)) { throw new FormatException("格式错误"); } expr = expr.Substring(TheToken.Length); if (ParsingF.Token(ref expr, false, s => s == "!") == null) { throw new NotImplementedException(); } var v = GetVoucher(ref expr); Parsing.TrimStartComment(ref expr); if (Parsing.Token(ref expr, false) != "}") { throw new FormatException("格式错误"); } Parsing.Eof(expr); return(v); }
protected virtual void Watcher_Changed(object sender, FileSystemEventArgs e) { List <string> lines = new List <string>(); for (int i = 0; i != 3; ++i) { try { Thread.Sleep(100); var file = new FileInfo(FilePath); if (!file.Exists || file.Name != Defaults.ConfgFileName) { return; } lines = File.ReadAllLines(FilePath).ToList(); break; } catch (IOException) { } } if (lines.Count == 0) { return; } var triplets = Parsing.ParseLines(lines); if (!triplets.Equals(m_Triplets)) { m_Triplets = triplets; Changed?.Invoke(); } }
/// <summary> /// Try to add user to Online List, if already exists, find him and return /// </summary> /// <param name="chatLine">Full chat line</param> /// <returns>Sender user</returns> public User JoinUser(string chatLine) { string username = Parsing.ParseUsername(chatLine); long userId = Parsing.ParseUserId(chatLine); if (!OnlineUsers.Any(x => x.Username == username)) { // User is not in the list var newUser = new User(username) { ID = userId }; newUser = _botDataManager.LoadUserData(newUser); OnlineUsers.Add(newUser); OnUserJoined?.Invoke(this, new OnUserArgs { User = newUser }); _logger.LogInformation("[JOIN] {name} joined the broadcast!", username); return(newUser); } return(FindOnlineUser(username)); }
private async Task GetStationName() { Parsing parsing = new Parsing(); if (StationEntry.IsVisible == true) // Se al nome è associata una sola stazione { stationItem.StationName = await parsing.GetStationNameAsync("http://mobile.my-link.it/mylink/mobile/stazione", "stazione", StationEntry.Text.Trim()); if (stationItem.StationName != "Cerca Treno Per Stazione") { await Navigation.PushAsync(new StationPage(stationItem.StationName.Substring(13))); } else { await GetMultipleStations(); } } else // Se al nome sono associate più stazioni { stationItem.StationName = await parsing.GetStationNameAsync("http://mobile.my-link.it/mylink/mobile/stazione", "codiceStazione", stationId[StationPicker.SelectedIndex]); await Navigation.PushAsync(new StationPage(stationId[StationPicker.SelectedIndex], StationPicker.SelectedItem.ToString())); } }
private void ParserState_ModuleStateChanged(object sender, Parsing.ParseProgressEventArgs e) { // todo: figure out a way to handle error state. // the problem is that the _projects collection might not contain our failing module yet. }
//^ requires token == Token.Void || token == Token.Char || token == Token.Short || token == Token.Int || token == Token.Int8 || token == Token.Int16 || //^ token == Token.Int32 || token == Token.Int64 || token == Token.Long || token == Token.Float || token == Token.Double || //^ token == Token.Signed || token == Token.Unsigned || token == Token.Bool; public PrimitiveTypeSpecifier(Parsing.Token token, ISourceLocation sourceLocation) : base(sourceLocation) { this.Token = token; }
public override IAnalysisSet UnaryOperation(Node node, AnalysisUnit unit, Parsing.PythonOperator operation) { if (_original == null) { return AnalysisSet.Empty; } return _original.UnaryOperation(node, unit, operation); }
/// <summary> /// Calculate the duration of the selected title and chapters /// </summary> public TimeSpan calculateDuration(string chapter_start, string chapter_end, Parsing.Title selectedTitle) { TimeSpan Duration = TimeSpan.FromSeconds(0.0); // Get the durations between the 2 chapter points and add them together. if (chapter_start != "Auto" && chapter_end != "Auto") { int start_chapter, end_chapter = 0; int.TryParse(chapter_start, out start_chapter); int.TryParse(chapter_end, out end_chapter); int position = start_chapter - 1; if (start_chapter <= end_chapter) { if (end_chapter > selectedTitle.Chapters.Count) end_chapter = selectedTitle.Chapters.Count; while (position != end_chapter) { TimeSpan dur = selectedTitle.Chapters[position].Duration; Duration = Duration + dur; position++; } } } return Duration; }
/// <summary> /// Calculate the non-anamorphic resoltuion of the source /// </summary> /// <param name="width"></param> /// <returns></returns> public int cacluateNonAnamorphicHeight(int width, decimal top, decimal bottom, decimal left, decimal right, Parsing.Title selectedTitle) { float aspect = selectedTitle.AspectRatio; int aw = 0; int ah = 0; if (aspect.ToString() == "1.78") { aw = 16; ah = 9; } else if (aspect.ToString() == "1.33") { aw = 4; ah = 3; } if (aw != 0) { double a = width * selectedTitle.Resolution.Width * ah * (selectedTitle.Resolution.Height - (double)top - (double)bottom); double b = selectedTitle.Resolution.Height * aw * (selectedTitle.Resolution.Width - (double)left - (double)right); double y = a / b; // If it's not Mod 16, make it mod 16 if ((y % 16) != 0) { double mod16 = y % 16; if (mod16 >= 8) { mod16 = 16 - mod16; y = y + mod16; } else { y = y - mod16; } } //16 * (421 / 16) //double z = ( 16 * (( y + 8 ) / 16 ) ); int x = int.Parse(y.ToString()); return x; } return 0; }
public FunctionSpecifier(Parsing.Token token, ISourceLocation sourceLocation) : base(sourceLocation) { this.Token = token; }
public RunnableScriptCode(Parsing.Ast.TotemAst ast) : base(ast.SourceUnit) { _ast = ast; }
public IdentifierReference(Parsing.Symbols.IdentifierReference reference) { _reference = reference; }
public override INamespaceSet ReverseBinaryOperation(Node node, AnalysisUnit unit, Parsing.JOperator operation, INamespaceSet rhs) { return _original.ReverseBinaryOperation(node, unit, operation, rhs); }
/// <summary> /// Constructor to create a FunctionCode at runtime. /// /// Code constructed this way supports both being interpreted and debugged. When necessary the code will /// be re-compiled or re-interpreted for that specific purpose. /// /// Function codes created this way do support recursion enforcement and are therefore registered in the global function code registry. /// /// the initial delegate provided here should NOT be the actual code. It should always be a delegate which updates our Target lazily. /// </summary> internal FunctionCode(TotemContext context, Delegate initialDelegate, Parsing.Ast.ScopeStatement scope, bool? tracing, bool register) { _lambda = scope; Target = LightThrowTarget = initialDelegate; _localCount = scope.Variables == null ? 0 : scope.Variables.Count; _argCount = CalculateArgumentCount(); if (tracing.HasValue) { if (tracing.Value) { _tracingDelegate = initialDelegate; } else { _normalDelegate = initialDelegate; } } if (register) { RegisterFunctionCode(context); } }
public override void Init(Parsing.ParsingContext context, Parsing.ParseTreeNode treeNode) { base.Init(context, treeNode); _positionSetName = (IdentifierNode)treeNode.ChildNodes[0].AstNode; }
public StorageClassSpecifier(Parsing.Token token, ISourceLocation sourceLocation) : base(sourceLocation) { this.Token = token; }
public GruntfileAnalysisUnit(Parsing.JsAst tree, ModuleEnvironmentRecord environment) : base(tree, environment) { }
public override void Init(Parsing.ParsingContext context, Parsing.ParseTreeNode treeNode) { base.Init(context, treeNode); _name = (IdentifierNode) AddChild("name", treeNode.ChildNodes[0]); }
public override void Init(Parsing.ParsingContext context, Parsing.ParseTreeNode treeNode) { base.Init(context, treeNode); Variable = (ExpressionAstNode) AddChild("variable",treeNode.ChildNodes[0]); }
public override void Init(Parsing.ParsingContext context, Parsing.ParseTreeNode treeNode) { base.Init(context, treeNode); _setName = treeNode.ChildNodes[0].FindTokenAndGetText(); }
public override INamespaceSet UnaryOperation(Node node, AnalysisUnit unit, Parsing.JOperator operation) { return _original.UnaryOperation(node, unit, operation); }
//^ ensures this.members != null; //^ invariant isInitialized ==> this.members != null; private void Parse(Parsing.Parser parser) { List<INamespaceDeclarationMember> members = this.members = new List<INamespaceDeclarationMember>(); parser.ParseCompilationUnit(this.CompilationPart.GlobalDeclarationContainer, members); members.TrimExcess(); //^ assume this.members != null; }
public override void Init(Parsing.ParsingContext context, Parsing.ParseTreeNode treeNode) { base.Init(context, treeNode); _property = treeNode.ChildNodes[0].AstNode as IdentifierNode; _variable = treeNode.ChildNodes[1].AstNode as VariableAstNode; }
public TypeQualifier(Parsing.Token token, ISourceLocation sourceLocation) : base(sourceLocation) { this.Token = token; }