/// <summary> /// 解析任意视频源地址 /// </summary> public ParseResult Parse(ParseRequest request) { //返回值 ParseResult pr = new ParseResult(); //分辨率 string resolution = request.SpecificConfiguration.ContainsKey("resolution") ? request.SpecificConfiguration["resolution"] : ""; //修正url string url = "http://www.flvcd.com/parse.php?kw=" + Tools.UrlEncode(request.Id) + resolution; //取得网页源文件 string src = Network.GetHtmlSource(url, Encoding.GetEncoding("GB2312"), request.Proxy); //检查是否需要密码 if (src.Contains("请输入密码")) { url = url + "&passwd=" + request.Password; src = Network.GetHtmlSource(url, Encoding.GetEncoding("GB2312"), request.Proxy); } //取得内容 Regex rContent = new Regex("<input type=\"hidden\" name=\"inf\".+\">", RegexOptions.Singleline); Match mContent = rContent.Match(src); string content = mContent.Value; //取得各Part下载地址 List<string> partUrls = new List<string>(); Regex rPartUrls = new Regex(@"<U>(?<url>.+)"); MatchCollection mcPartUrls = rPartUrls.Matches(content); foreach (Match item in mcPartUrls) { pr.Items.Add(new ParseResultItem() { RealAddress = new Uri(item.Groups["url"].Value) }); } return pr; }
public ParseResult<Person> ParseFile(string filePath, char delimiter) { //Opens the file var parseResult = new ParseResult<Person>(); var reader = File.OpenText(filePath); var line = ""; //Reads each line while ((line = reader.ReadLine()) != null) { //Creates an array based on our delimiter var fieldArray = line.Split(delimiter); //Maps the array to a concrete object var personFromFile = new Person { LastName = fieldArray[0], FirstName = fieldArray[1], Birthday = DateTime.Parse(fieldArray[2]) }; //Perform some validation (method below) var validationResult = ValidatePerson(personFromFile, line); AddValidObjectOrParseErrorToResults(validationResult, parseResult, personFromFile, line); } return parseResult; }
public static IEnumerable<ITagSpan<IOutliningRegionTag>> GetTags(ParseResult parseResult, IOutliningRegionTagCreator tagCreator) { foreach (var taskDef in parseResult.SyntaxTree.GetRoot().DescendantNodes<TaskDefinitionSyntax>()) { var extent = taskDef.Extent; var nameToken = taskDef.Identifier; if (nameToken.IsMissing) { continue; } var rgnStartToken = nameToken.NextToken(); if (rgnStartToken.IsMissing) { continue; } var start = Math.Min(nameToken.End + 1, rgnStartToken.Start); int length = extent.End - start; if (length <= 0) { continue; } var regionSpan = new SnapshotSpan(new SnapshotPoint(parseResult.Snapshot, start), length); var hintSpan = new SnapshotSpan(new SnapshotPoint(parseResult.Snapshot, extent.Start), extent.Length); var tag = tagCreator.CreateTag("...", hintSpan); yield return new TagSpan<IOutliningRegionTag>(regionSpan, tag); } }
public static IEnumerable< ITagSpan<IOutliningRegionTag>> GetTags(ParseResult parseResult, IOutliningRegionTagCreator tagCreator) { var usingDirectives = parseResult.SyntaxTree.GetRoot().DescendantNodes<CodeUsingDeclarationSyntax>().ToList(); if (usingDirectives.Count<2) { yield break; } var firstUsing = usingDirectives[0]; var lastUsing = usingDirectives[usingDirectives.Count - 1]; var usingKeyword = firstUsing.UsingKeyword; if (usingKeyword.IsMissing) { yield break; } var extendStart = firstUsing.Extent; var extendEnd = lastUsing.Extent; var start = usingKeyword.End + 1; int length = extendEnd.End - start - 1; // Letzte ] noch mit anzeigen.. if (length <= 0) { yield break; } var regionSpan = new SnapshotSpan(new SnapshotPoint(parseResult.Snapshot, start), length); var hintSpan = new SnapshotSpan(new SnapshotPoint(parseResult.Snapshot, extendStart.Start), extendEnd.End- extendStart.Start); var tag = tagCreator.CreateTag("...", hintSpan); yield return new TagSpan<IOutliningRegionTag>(regionSpan, tag); }
/// <summary> /// /// </summary> /// <param name="task"></param> /// <param name="pr"></param> public void ProcessExecutedTask(Task task, ParseResult pr) { if (pr.Success) { if (StringHelper.Equal(task.Device.DeviceDefine.DeviceType, DeviceDefineConst.DDT_XD221Modbus)) { XD221ModbusProcessor.Default.ProcessExecutedTask(task, pr); } // xd221 // if (StringHelper.Equal(task.Device.DeviceDefine.DeviceType, DeviceDefineConst.DDT_XD221)) { XD221Processor.Defalut.ProcessExecutedTask(task, pr); } // xd202 // if (StringHelper.Equal(task.Device.DeviceDefine.DeviceType, DeviceDefineConst.DDT_XD202)) { XD202Processor.Default.ProcessExecutedTask(task, pr); } } // xd2300 // if (StringHelper.Equal(task.Device.DeviceType, DeviceDefineConst.DDT_XD2300)) { XD2300Processor.Default.ProcessExecutedTask(task, pr); } }
public static IEnumerable<ITagSpan<IOutliningRegionTag>> GetTags(ParseResult parseResult, IOutliningRegionTagCreator tagCreator) { var transitionBlocks = parseResult.SyntaxTree.GetRoot().DescendantNodes().OfType<TransitionDefinitionBlockSyntax>(); foreach (var transitionBlock in transitionBlocks) { var extent = transitionBlock.Extent; if (extent.IsEmptyOrMissing) { continue; } var startLine = parseResult.Snapshot.GetLineNumberFromPosition(extent.Start); var endLine = parseResult.Snapshot.GetLineNumberFromPosition(extent.End); if (startLine == endLine) { continue; } var collapsedForm = "Transitions"; var rgnSpan = new SnapshotSpan(new SnapshotPoint(parseResult.Snapshot, extent.Start), extent.Length); var hintSpan = new SnapshotSpan(new SnapshotPoint(parseResult.Snapshot, extent.Start), extent.Length); var rgnTag = tagCreator.CreateTag(collapsedForm, hintSpan); yield return new TagSpan<IOutliningRegionTag>(rgnSpan, rgnTag); } }
public override ParseResult Parse(List<Token> tokens, int startLocation) { // Head part var head = termParser.Parse(tokens, startLocation); if (!head.Succeed) head = termProductParser.Parse(tokens, startLocation); if (!head.Succeed) { head.ErrorMessage = "Expected reduction rule head term or term product: " + head.ErrorMessage; return head; } // Arrow if (head.NextParsePosition >= tokens.Count || tokens[head.NextParsePosition].TokenType != TokenType.Arrow) { var arrowError = new ParseResult(tokens, head.NextParsePosition); arrowError.ErrorMessage = "Expected reduction rule arrow symbol"; return arrowError; } // Tail part var tail = termParser.Parse(tokens, head.NextParsePosition + 1); if (!tail.Succeed) { tail.ErrorMessage = "Expected reduction rule tail term: " + tail.ErrorMessage; return tail; } var reductionRule = new ParseResult(tokens, startLocation); reductionRule.AstResult = new AstReductionRule((AstTermBase)head.AstResult, (AstTermBase)tail.AstResult); reductionRule.NextParsePosition = tail.NextParsePosition; return reductionRule; }
private void AssertDoubleTryParse(string s, ParseResult expectedResult, double? expectedValue) { double d; char[] c = s.ToCharArray(); ParseResult result = ConvertUtils.DoubleTryParse(c, 0, c.Length, out d); double d2; bool result2 = double.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out d2) && !s.StartsWith(".") && !s.EndsWith(".") && !(s.StartsWith("0") && s.Length > 1 && !s.StartsWith("0.") && !s.StartsWith("0e", StringComparison.OrdinalIgnoreCase)) && !(s.StartsWith("-0") && s.Length > 2 && !s.StartsWith("-0.") && !s.StartsWith("-0e", StringComparison.OrdinalIgnoreCase)) && s.IndexOf(".e", StringComparison.OrdinalIgnoreCase) == -1; Assert.AreEqual(expectedResult, result); Assert.AreEqual(expectedResult == ParseResult.Success, result2); if (result2) { Assert.IsTrue(expectedValue.HasValue); Assert.AreEqual(expectedValue.Value, d, "Input string: " + s); Assert.AreEqual(expectedValue.Value, d2, "DoubleTryParse result is not equal to double.Parse. Input string: " + s); } }
/// <summary> /// /// </summary> /// <param name="task"></param> /// <param name="pr"></param> public void ProcessExecutedTask(Task task, ParseResult pr) { int instantFlux = Convert.ToInt32(pr.NameObjects.GetObject("IF")); // remain amount out int32 range // int remainAmount = 0; object remainAmountObject = pr.NameObjects.GetObject("RemainAmount"); Debug.Assert(remainAmountObject != null, "remianAmountObject == null"); try { remainAmount = Convert.ToInt32(remainAmountObject); } catch (Exception ) { } //int remainAmount = 0; int beforeWL = Convert.ToInt32(pr.NameObjects.GetObject("WL1")); int behindWL = Convert.ToInt32(pr.NameObjects.GetObject("WL2")); int height = Convert.ToInt32(pr.NameObjects.GetObject("Height")); XD202Data data = new XD202Data(instantFlux, remainAmount, height, beforeWL, behindWL); XD202Device d = task.Device as XD202Device; d.XD202Data = data; // TODO: // DB.MeasureSluiceData.Insert(d, data); }
/// <summary> /// 解析新浪视频视频文件源地址 /// </summary> public ParseResult Parse(ParseRequest request) { ParseResult pr = new ParseResult(); //合并完整url string url = @"http://v.iask.com/v_play.php?vid=" + request.Id; string source = Network.GetHtmlSource(url, Encoding.UTF8, request.Proxy); //视频总长度 string totallength = Regex.Match(source, @"<timelength>(?<timelength>\d+)</timelength>").Groups["timelength"].Value; //Framecount string framecount = Regex.Match(source, @"<framecount>(?<framecount>\d+)</framecount>").Groups["framecount"].Value; //src string src = Regex.Match(source, @"<src>(?<src>\d+)</src>").Groups["src"].Value; pr.SpecificResult.Add("totallength", totallength); pr.SpecificResult.Add("framecount", framecount); pr.SpecificResult.Add("src", src); //vstr string vstr = Regex.Match(source, @"(?<=<vstr><!\[CDATA\[)\w+").Value; //视频信息 Regex r = new Regex(@"<durl>.+?<order>(?<order>\d+)</order>.+?<length>(?<length>\d+)</length>.+?<url><!\[CDATA\[(?<url>.+?)\]\]></url>.+?</durl>", RegexOptions.Singleline); MatchCollection matches = r.Matches(source); foreach (Match item in matches) { var pri = new ParseResultItem(); pri.RealAddress = new Uri(item.Groups["url"].Value + (string.IsNullOrEmpty(vstr) ? "" : "?vstr=" + vstr)); pri.Information.Add("order", item.Groups["order"].Value); pri.Information.Add("length", item.Groups["length"].Value); pr.Items.Add(pri); } //返回结果 return pr; }
/// <summary> /// /// </summary> /// <param name="task"></param> /// <param name="pr"></param> public void ProcessExecutedTask(Task task, ParseResult pr) { if (StringHelper.Equal(task.Opera.Name, OperaNames.ReadReal)) { // // 功能码: 0x10 // 数据数: 0位 // 成功后返回: 0x21+0x58+0x44+地址+0x80+功能码+0x12+日期+时间+已用水量+瞬时流量+闸前水位+闸后水位+CRC16 // 日期(3字节BCD码 年+月+日) // 时间(3字节BCD码 时+分+秒) // 已用水量(4字节)(无符号整型)带一位小数点 m3 <b> // 瞬时流量(4字节)(无符号整型)带一位小数点 m3/h <c> // 闸前水位(2字节)带两位小数点 m <a> // 闸后水位(2字节)带两位小数点 m // // 供电电压 (2Byte) 两位小数点 <d> // 水位, 单位CM, <a> // int wl1 = (Int16)pr.NameObjects.GetObject("WL1"); int wl2 = (Int16)pr.NameObjects.GetObject("WL2"); uint instantFlux = (UInt32)pr.NameObjects.GetObject("IF"); uint usedAmount = (uint)pr.NameObjects.GetObject("usedAmount"); object objTemp = pr.NameObjects.GetObject("voltage"); int voltage = Convert.ToInt32(objTemp); // <c> // instantFlux = (uint)(instantFlux / 10); // <b> // usedAmount = (uint)(usedAmount / 10); // <d> // voltage = voltage / 100; if (Config.Default.IsUseFluxFormula) { instantFlux = (uint)YeHeCommuniServerApp.Default.DevieFormaulCollectionMapCollection.CalcInstantFlux( task.Device.ID, DateTime.Now, wl1, wl2); } DitchDevice ditchDevice = task.Device as DitchDevice; ditchDevice.DitchData = new DitchData(wl1, wl2, instantFlux, usedAmount, voltage); DB.DitchDataDBI.Insert(ditchDevice, DateTime.Now, instantFlux, wl1, wl2, usedAmount, voltage); } //if (StringHelper.Equal(task.Opera.Name, OperaNames.ReadParams)) //{ // XD221Params p = ProcessParams(pr); // XD221Device xd221Device = task.Device as XD221Device; // xd221Device.Xd221Params = p; //} }
public override int Strategy(ParseResult parseResult) { _recoveryPerformanceData.Timer.Start(); var res = base.Strategy(parseResult); _recoveryPerformanceData.Timer.Stop(); return res; }
public void GetHashCode_WithEqualValuesAndCursors_ReturnsSameValue([Values(0, 1, 2)] int index) { var start = new Cursor("OK"); var end = start.Advance(index); var subjectA = new ParseResult<int>(start, end, 0); var subjectB = new ParseResult<int>(start, end, 0); Assert.That(subjectB.GetHashCode(), Is.EqualTo(subjectA.GetHashCode())); }
public void Equals_WithOtherObject_ReturnsFalse() { var start = new Cursor("OK", 0); var end = start.Advance(1); var subjectA = new ParseResult<int>(start, end, 0); var subjectB = new object(); Assert.That(subjectA.Equals(subjectB), Is.False); }
public void OpEquality_WithEqualValuesAndCursors_ReturnsTrue() { var start = new Cursor("OK", 0); var end = start.Advance(1); var subjectA = new ParseResult<int>(start, end, 0); var subjectB = new ParseResult<int>(start, end, 0); Assert.That(subjectA == subjectB, Is.True); }
public void OpEquality_WithNullReferenceOnRight_ReturnsFalse() { var start = new Cursor("OK", 0); var end = start.Advance(1); var subjectA = new ParseResult<int>(start, end, 0); var subjectB = (ParseResult<int>)null; Assert.That(subjectA == subjectB, Is.False); }
public override void Call(ParseResult parseResult, object values, string optionString) { var newValues = parseResult.Get<IEnumerable>(Destination, new object[] {}) .Cast<object>() .Concat(new[] {values}) .ToArray(); parseResult[Destination] = newValues; }
private static Member FindMember(Domain domain, ParseResult result) { var member = FindRootMember(domain, result[0]); for (var i = 1; i < result.ChildCount; ++i) { member = member.FindMember(domain, result[i]); } return member; }
public void OpEquality_WithUnequalEndCursors_ReturnsFalse() { var start = new Cursor("OK", 0); var one = start.Advance(1); var two = one.Advance(1); var subjectA = new ParseResult<int>(start, one, 0); var subjectB = new ParseResult<int>(start, two, 0); Assert.That(subjectA == subjectB, Is.False); }
void AddParseResultToList(ParseResult pr) { var item = listView1.Items.Add(pr.Text); item.SubItems.Add(pr.StartPos.ToString()); item.SubItems.Add(pr.Type.Description()); if (pr.Value != null) { item.SubItems.Add(pr.Value.GetType().Name); item.SubItems.Add(pr.Value.ToString()); } }
/// <summary> /// /// </summary> public static void ProduceExecutedTask( Task t , ParseResult pr ) { if (pr.Success) { ProcessSuccess(t, pr); } else { ProcessFail(t, pr); } }
/// <summary> /// /// </summary> /// <param name="task"></param> /// <param name="pr"></param> public void ProcessExecutedTask(Task task, ParseResult pr) { // xd221 modbus // //if (StringHelper.Equal(task.Device.DeviceDefine.DeviceType, // DeviceDefineConst.DDT_XD221Modbus) // && if (StringHelper.Equal(task.Opera.Name, OperaNames.ReadReal)) { object objTemp = pr.NameObjects.GetObject("WL1"); Int16 wl1 = Convert.ToInt16(objTemp); wl1 = MMToCM(wl1); objTemp = pr.NameObjects.GetObject("WL2"); Int16 wl2 = Convert.ToInt16(objTemp); wl2 = MMToCM(wl2); objTemp = pr.NameObjects.GetObject("IF"); uint instantFlux = Convert.ToUInt32(objTemp); objTemp = pr.NameObjects.GetObject("Voltage"); int voltage = Convert.ToInt32(objTemp); voltage = voltage / 100; DitchDevice ditchDevice = task.Device as DitchDevice; DitchDataCache cache = ditchDevice.DitchDataCache; cache.SetWLInstantFlux(wl1, wl2, instantFlux, voltage); if (cache.IsComplete()) { ditchDevice.DitchData = new DitchData(cache); DB.DitchDataDBI.Insert(ditchDevice, cache); cache.Clear(); } } if (StringHelper.Equal(task.Opera.Name, XD221ModbusOperaNames.ReadUsedAmount)) { object objTemp = pr.NameObjects.GetObject("usedAmount"); UInt32 usedAmount = Convert.ToUInt32(objTemp); DitchDevice ditchDevice = task.Device as DitchDevice; DitchDataCache cache = ditchDevice.DitchDataCache; cache.SetUsedAmount(usedAmount); if (cache.IsComplete()) { ditchDevice.DitchData = new DitchData(cache); DB.DitchDataDBI.Insert(ditchDevice, cache); cache.Clear(); } } }
/// <summary> /// /// </summary> /// <param name="t"></param> /// <param name="pr"></param> private static void ProcessFail(Task task, ParseResult pr) { XD2402Device xd2402 = task.Device as XD2402Device; if (StringHelper.Equal(task.Opera.Name, XD2402OperaNames.ReadRecord)) { int recordIndex = Convert.ToInt32(task.Opera.SendPart["RecordIndex"]); if (recordIndex >= xd2402.LastRecordIndex) { AddDownTask(xd2402); } } }
private static void AddValidObjectOrParseErrorToResults(ValidationResult validationResult, ParseResult<Person> parseResult, Person personToAdd, string line) { if (validationResult.IsValid) { parseResult.AddParsedRecordToCollection(personToAdd); } else { foreach (var errorMessage in validationResult.GetErrorMessages()) { parseResult.AddParsedErrorToCollection(errorMessage, line); } } }
/// <summary> /// /// </summary> /// <param name="task"></param> /// <param name="pr"></param> public void ProcessExecutedTask(Task task, ParseResult pr) { int instantFlux = Convert.ToInt32(pr.NameObjects.GetObject("IF")); int remainAmount = Convert.ToInt32(pr.NameObjects.GetObject("RemainAmount")); int beforeWL = Convert.ToInt32(pr.NameObjects.GetObject ("WL1")); int behindWL = Convert.ToInt32(pr.NameObjects.GetObject("WL2")); int height = Convert.ToInt32(pr.NameObjects.GetObject("Height")); XD202Data data = new XD202Data(instantFlux, remainAmount, height, beforeWL, behindWL); XD202Device d = task.Device as XD202Device; d.XD202Data = data; // TODO: // DB.MeasureSluiceData.Insert(d, data); }
public override void Call(ParseResult parseResult, object values, string optionString) { var valueStrings = (values as IEnumerable ?? new string[] {}).OfType<string>().ToList(); var parserName = valueStrings.FirstOrDefault(); var argStrings = valueStrings.Skip(1).ToList(); if (HasValidDestination) parseResult[Destination] = parserName; var parser = subParsers.SafeGetValue(parserName); if (parser == null) throw new UnknownParserException(this, parserName); // parse all the remaining options into the namespace // store any unrecognized options on the object, so that the top // level parser can decide what to do with them parser.ParseKnownArguments(argStrings, parseResult); }
public ParseResult Apply(ParseResult result) { if (result == null || !result.Success) return result; var dest = result.Index + result.Length; if (dest < Offset) { throw new ArgumentException("Cannot apply a match that occured earlier in the input.", "result"); } Offset = result.Index + result.Length; if (WhitespacePolicy == WhitespacePolicy.Ignore) { Offset = SkipWhitespace(Input, Offset); } return result; }
public ParseResult Parse(string sourceString) { Tokenizer tokenizer = new Tokenizer(); var tokensResult = tokenizer.Tokenize(sourceString); ParseResult retVal = new ParseResult(tokensResult.Tokens, 0); if (!tokensResult.Succeed) retVal.ErrorMessage = tokensResult.ErrorMessage; else { retVal = Parse(tokensResult.Tokens, 0); if (retVal.Succeed && retVal.NextParsePosition != tokensResult.Tokens.Count) { retVal.ErrorMessage = "Expected end of input at position " + tokensResult.Tokens[retVal.NextParsePosition].From; retVal.AstResult = null; } } return retVal; }
public ParseResultCollection Parse(int startIndex) { string _text = context.Text; ParseResultCollection prc = new ParseResultCollection(); string placeName = MatchPlaceName(_text, startIndex); if (placeName != null) { ParseResult pr = new ParseResult(); pr.Text = placeName; pr.StartPos = startIndex; pr.Type = POSType.A_NS; prc.Add(pr); return prc; } return prc; }
[Test] public void AddResults() { var parseResult = new ParseResult { {"res1", 1}, {"res2", 2}, {"res3", new[] {"a", "b", "c"}}, {"res4", "4"} }; Assert.That(parseResult.ToDictionary(), new BaseSmartEqualityConstraint(new Dictionary<string, object>(StringComparer.InvariantCultureIgnoreCase) { {"res1", 1}, {"res2", 2}, {"res3", new[] {"a", "b", "c"}}, {"res4", "4"} })); }
private FlattenSequences FlattenSubrule(FlattenSequences prevs, ParseResult parseResult, ParsedSequence seq, SubruleParses parses, ParsedSubrule subrule, int subruleInsertedTokens, Dictionary<ParsedSequenceKey, SubruleParsesAndEnd> memiozation) { Begin: //var txt = parseResult.Text.Substring(subrule.Begin, subrule.End - subrule.Begin); //var stateIndex = subrule.State; //var state = stateIndex < 0 ? null : seq.ParsingSequence.States[stateIndex]; if (subrule.End == 11) { } var currentNodes = new FlattenSequences(); //var subruledDesc = seq.GetSubruleDescription(subrule.State); if (subrule.IsEmpty) { //if (subruleInsertedTokens > 0) // Debug.WriteLine("Inserted = " + subruleInsertedTokens + " - " + subruledDesc + " Seq: " + seq); } else { var sequences = seq.GetSequencesForSubrule(subrule).ToArray(); if (sequences.Length > 1) { } foreach (var subSequences in sequences) { //Debug.WriteLine(subruledDesc); var result = FlattenSequence(prevs, parseResult, subSequences, subrule.End, subruleInsertedTokens, memiozation); currentNodes.AddRange(result); } } if (currentNodes.Count == 0) // если не было сабсиквенсов, надо создать продолжения из текущего сабруля { foreach (var prev in prevs) currentNodes.Add(new ParsedSequenceAndSubrules.Cons(new TokensInsertedForSubrule(subruleInsertedTokens, seq, subrule), prev)); } var nextSubrules = seq.GetNextSubrules(subrule, parses.Keys).ToArray(); switch (nextSubrules.Length) { case 0: return currentNodes; case 1: { var nextSubrule = nextSubrules[0]; if (nextSubrule.State == 9 && nextSubrule.Begin == 8 && nextSubrule.End == 15) { } subruleInsertedTokens = parses[nextSubrule]; if (subruleInsertedTokens == Fail) return currentNodes; // recursive self call... prevs = currentNodes; subrule = nextSubrule; goto Begin; return null; } default: { var resultNodes = new FlattenSequences(); foreach (var nextSubrule in nextSubrules) { var newSubruleInsertedTokens = parses[nextSubrule]; if (newSubruleInsertedTokens == Fail) continue; var result = FlattenSubrule(currentNodes, parseResult, seq, parses, nextSubrule, newSubruleInsertedTokens, memiozation); resultNodes.AddRange(result); } return resultNodes; } } }
public void NullOptions_HasOptions_ReturnsTrue() { var result = new ParseResult <TestOptions>(new TestOptions(), null); result.HasOptions.ShouldBeTrue(); }
public void FromOptions_HasOptions_ReturnsFalse() { var result = new ParseResult <TestOptions>(null, null); result.HasOptions.ShouldBeFalse(); }
internal static bool TryParseDollar(Buffer buffer, out ParseResult result) => TryParseSpecialCharacter(buffer, '$', Symbols.Dollar, out result);
internal static bool TryParseAt(Buffer buffer, out ParseResult result) => TryParseSpecialCharacter(buffer, '@', Symbols.At, out result);
public static void Main(string[] args) { var cmd = new RootCommand(); cmd.AddOption(new Option("-n", "Max number of requests to make concurrently.") { Argument = new Argument <int>("numWorkers", 1) }); cmd.AddOption(new Option("-maxContentLength", "Max content length for request and response bodies.") { Argument = new Argument <int>("numBytes", 1000) }); cmd.AddOption(new Option("-http", "HTTP version (1.1 or 2.0)") { Argument = new Argument <Version[]>("version", new[] { HttpVersion.Version20 }) }); cmd.AddOption(new Option("-connectionLifetime", "Max connection lifetime length (milliseconds).") { Argument = new Argument <int?>("connectionLifetime", null) }); cmd.AddOption(new Option("-ops", "Indices of the operations to use") { Argument = new Argument <int[]>("space-delimited indices", null) }); cmd.AddOption(new Option("-trace", "Enable Microsoft-System-Net-Http tracing.") { Argument = new Argument <string>("\"console\" or path") }); cmd.AddOption(new Option("-aspnetlog", "Enable ASP.NET warning and error logging.") { Argument = new Argument <bool>("enable", false) }); cmd.AddOption(new Option("-listOps", "List available options.") { Argument = new Argument <bool>("enable", false) }); cmd.AddOption(new Option("-seed", "Seed for generating pseudo-random parameters for a given -n argument.") { Argument = new Argument <int?>("seed", null) }); ParseResult cmdline = cmd.Parse(args); if (cmdline.Errors.Count > 0) { foreach (ParseError error in cmdline.Errors) { Console.WriteLine(error); } Console.WriteLine(); new HelpBuilder(new SystemConsole()).Write(cmd); return; } Run(concurrentRequests: cmdline.ValueForOption <int>("-n"), maxContentLength: cmdline.ValueForOption <int>("-maxContentLength"), httpVersions: cmdline.ValueForOption <Version[]>("-http"), connectionLifetime: cmdline.ValueForOption <int?>("-connectionLifetime"), opIndices: cmdline.ValueForOption <int[]>("-ops"), logPath: cmdline.HasOption("-trace") ? cmdline.ValueForOption <string>("-trace") : null, aspnetLog: cmdline.ValueForOption <bool>("-aspnetlog"), listOps: cmdline.ValueForOption <bool>("-listOps"), seed: cmdline.ValueForOption <int?>("-seed") ?? Random.Shared.Next()); }
protected virtual void ShowHelpOrErrorIfAppropriate(ParseResult parseResult) { parseResult.ShowHelpOrErrorIfAppropriate(); }
public void NullErrors_HasErrors_ReturnsFalse() { var result = new ParseResult <TestOptions>(new TestOptions(), null); result.HasErrors.ShouldBeFalse(); }
private static void DoParseAttributes( StudyLoaderArgs studyLoaderArgs, ParseResult result, string metaUri, XmlElement elem) { var collection = result.Attributes; collection.ValidateVrValues = false; collection.ValidateVrLengths = false; foreach (var node in elem) { var attrElem = node as XmlElement; if (attrElem == null) { continue; } if (!attrElem.Name.Equals("attr")) { continue; } var dcmTag = GetTagFromAttrElement(attrElem); DicomAttribute attr = collection[dcmTag]; DicomAttributeSQ sq = attr as DicomAttributeSQ; if (sq != null) { sq.ClearSequenceItems(); foreach (XmlNode itemNode in attrElem) { var itemElem = itemNode as XmlElement; if (itemElem != null) { if (itemElem.Name.Equals("item")) { var subResult = new ParseResult(); var subSequence = new DicomSequenceItem(); subResult.Attributes = subSequence; DoParseAttributes(studyLoaderArgs, subResult, metaUri, itemElem); sq.AddSequenceItem(subSequence); } } } } else { string val = null; if (attrElem.Attributes["val"] != null) { val = attrElem.Attributes["val"].Value; attr.SetStringValue(val); } else if (attrElem.Attributes["bid"] != null) { // TODO: This tag's value is binary. We're not interested in binary items other // than the pixel data so we ignore them -- they will be added to the // sequence but they will not have any value set. if (attr.Tag.TagValue == DicomTags.PixelData) { result.PixelDataBid = attrElem.Attributes["bid"].Value; } } else if (attrElem.Attributes["bytes"] != null) { // TODO: This tag's value is binary. We're not interested in binary items other // than the pixel data so we ignore them -- they will be added to the // sequence but they will not have any value set. ; } else if (attrElem.Attributes["bsize"] != null) { // TODO: Bulk binary loading can use this. } else { Platform.Log(LogLevel.Warn, "Attr element {0} missing ", attr.Tag, val); } } } }
internal static bool TryParseString(Buffer buffer, out ParseResult result) { var position = buffer.Cursor; var components = new List <ISymbol>(); var error = $"{Symbols.String} expected at position: {position + 1}"; //compulsory opening $" | @" | " if (TryParseInterpolationStringOpening(buffer, out var opening) || TryParseLiteralStringOpening(buffer, out opening) || TryParseStringOpening(buffer, out opening)) { components.Add(opening.Symbol); } else { return(Fail(error, buffer, position, out result)); } //the string body while (buffer.TryNext(out var @char)) { if (@char == '"') { if (opening.Symbol.Name == Symbols.LiteralStringOpening.ToString() && TryParseQuote(buffer, out var quote)) { components.Add(new NonTerminalSymbol( Symbols.LiteralStringEscape, quote.Symbol, new TerminalSymbol( Symbols.Quote, @char))); continue; } components.Add(new TerminalSymbol( Symbols.Quote, @char)); result = new ParseResult(new NonTerminalSymbol( Symbols.String, components)); return(true); } else if (@char == '\\') { if (opening.Symbol.Name != Symbols.LiteralStringOpening.ToString() && TryParseQuote(buffer, out var quote)) { components.Add(new NonTerminalSymbol( Symbols.LiteralStringEscape, new TerminalSymbol( Symbols.BSlash, @char), quote.Symbol)); continue; } } components.Add(new TerminalSymbol( Symbols.Character, @char)); } //end of input with no string termination. //terminate the string components.Add(new TerminalSymbol( Symbols.Quote, '"')); result = new ParseResult(new NonTerminalSymbol( Symbols.String, components, true)); return(true); }
public void Errors_HasErrors_ReturnsTrue() { var result = new ParseResult <TestOptions>(new TestOptions(), new[] { "Oops" }); result.HasErrors.ShouldBeTrue(); }
public virtual int Strategy(ParseResult parseResult) { #if DebugThreading if (ThreadId != System.Threading.Thread.CurrentThread.ManagedThreadId) Debug.Assert(false); Debug.WriteLine(">>>> Strategy " + _id + " ThreadId=" + System.Threading.Thread.CurrentThread.ManagedThreadId); #endif //Debug.Assert(parseResult.RecoveryStacks.Count > 0); _parseResult = parseResult; #if DebugOutput Debug.IndentSize = 1; var timer = Stopwatch.StartNew(); Debug.WriteLine(RecoveryDebug.CurrentTestName + " -----------------------------------------------------------"); #endif _deletedToken.Clear(); var textLen = parseResult.Text.Length; var rp = new RecoveryParser(parseResult); rp.StartParse(parseResult.RuleParser);//, parseResult.MaxFailPos); var startSeq = rp.Sequences.First().Value; UpdateEarleyParseTime(); #if DebugOutput timer.Stop(); Debug.WriteLine("Earley parse took: " + timer.Elapsed); timer.Restart(); #endif RecoverAllWays(rp); UpdateRecoverAllWaysTime(); #if DebugOutput timer.Stop(); Debug.WriteLine("RecoverAllWays took: " + timer.Elapsed); timer.Restart(); #endif if (parseResult.TerminateParsing) throw new OperationCanceledException(); var memiozation = new Dictionary<ParsedSequenceKey, SubruleParsesAndEnd>(); FindBestPath(startSeq, textLen, memiozation); UpdateFindBestPathTime(); #if DebugOutput timer.Stop(); Debug.WriteLine("FindBestPath took: " + timer.Elapsed); timer.Restart(); #endif if (parseResult.TerminateParsing) throw new OperationCanceledException(); var results = FlattenSequence(new FlattenSequences() { Nemerle.Collections.NList.ToList(new TokensInsertedForSubrule[0]) }, parseResult, startSeq, textLen, memiozation[new ParsedSequenceKey(startSeq, textLen)].End, memiozation); if (parseResult.TerminateParsing) throw new OperationCanceledException(); UpdateFlattenSequenceTime(); #if DebugOutput timer.Stop(); Debug.WriteLine("FlattenSequence took: " + timer.Elapsed); #endif CollectError(rp, results); #if DebugThreading Debug.WriteLine("<<<< Strategy " + _id + " ThreadId=" + System.Threading.Thread.CurrentThread.ManagedThreadId); #endif if (parseResult.TerminateParsing) throw new OperationCanceledException(); AstPatcher.Patch(startSeq, rp, memiozation); _parseResult = null; return parseResult.Text.Length; }
protected ParseResult ParseStatus(ParseResult res, String error) { Status = res; Error = error; return(Status); }
public async Task <ParseResult> Parse(MessageReader reader, ContentType type = ContentType.Text, ContentSubtype subtype = ContentSubtype.Plain, Boundary boundary = null) { if (type == ContentType.Multipart) { dataType = DataType.Multipart; while (true) { String line = await reader.ReadLineAsync(); if (line == null) { SetSize(); return(ParseResult.Eof); } else if (EmailParser.IsPostmark(line)) { // consumed too much, probably missing boundary? reader.PushCacheLine(line); SetSize(); return(ParseResult.Postmark); } WriteWithCrlf(line); // find open boundary if (boundary.IsOpen(line)) { Email email = null; ParseResult res; do { // consume all parts, consisting of header (optional) and content // the boundary token delimets the part // the close boundary completes multipart parsing // content in the multipart is responsible for consuming it's delimeter (end) // exception is the last part which is also multipart email = new Email(entity); Add(email); } while ((res = await email.Parse(reader, type, subtype, boundary)) == ParseResult.OkMultipart); // Ok // if the last part is a multipart or message? itself then it doesn't consume the close boundary // or more parts, continue parsing until all parts and close boundary are consumed /*if (Ok(res) && (data.Last<Email>().content.dataType == DataType.Multipart || * data.Last<Email>().content.dataType == DataType.Message))*/ if (res == ParseResult.Ok && boundary.NotClosed()) { continue; } if (res != ParseResult.Failed) { SetSize(); } return(res); } else if (boundary.IsClose(line, reader)) { SetSize(); return(ParseResult.Ok); // OkMultipart } } } else if (type == ContentType.Message) { dataType = DataType.Message; Email email = new Email(entity); Add(email); ParseResult res = await email.Parse(reader, type, subtype, boundary); if (res != ParseResult.Failed) { SetSize(); } return(res); } else { dataType = DataType.Data; while (true) { String line = await reader.ReadLineAsync(); if (line == null) { SetSize(); return(ParseResult.Eof); } else if (EmailParser.IsPostmark(line)) { // consumed too much, probably closing boundary is missing ? reader.PushCacheLine(line); SetSize(); return(ParseResult.Postmark); } else if (boundary != null && boundary.IsOpen(line)) { SetSize(); RewindLastCrlfSize(); WriteWithCrlf(line); return(ParseResult.OkMultipart); //Ok } else if (boundary != null && boundary.IsClose(line, reader)) { SetSize(); RewindLastCrlfSize(); WriteWithCrlf(line); return(ParseResult.Ok); //OkMultipart } else { WriteWithCrlf(line); } } } }
public override IEnumerable <string> NormalizeTokenSet(IEnumerable <string> tokens, ParseResult context) { var fracWords = new List <string>(); var tokenList = tokens.ToList(); var tokenLen = tokenList.Count; for (var i = 0; i < tokenLen; i++) { if ((i < tokenLen - 2) && tokenList[i + 1] == "-") { fracWords.Add(tokenList[i] + tokenList[i + 1] + tokenList[i + 2]); i += 2; } else { fracWords.Add(tokenList[i]); } } return(fracWords); }
/// <summary> /// Add the specified result, date and revision. /// </summary> /// <param name="result">Result.</param> /// <param name="date">Date.</param> /// <param name="revision">Revision.</param> public void Add(ParseResult result, DateTime date, long revision) { Add(result.Type, result.Namespace, date, result.Aggregations, result.Inheritance, revision); }
public void EmptyErrors_HasErrors_ReturnsFalse() { var result = new ParseResult <TestOptions>(new TestOptions(), new List <string>()); result.HasErrors.ShouldBeFalse(); }
private static string BestSplit(string sen, HashSet <string> dictionary) { ParseResult r = Split(sen, 0, dictionary); return(r == null ? null : r.Parsed); }
public static void AssertBirthNumberError <T>(this ParseResult <BirthNumber> parseResult) { Assert.False(parseResult.Success); Assert.Equal(typeof(T), parseResult.Exception.GetType()); }
public InvocationPipeline(ParseResult parseResult) { this.parseResult = parseResult ?? throw new ArgumentNullException(nameof(parseResult)); }
/// <summary> /// Parse the command line. /// </summary> /// <param name="commandLine">command line txt</param> /// <returns>exit code</returns> public Task <int> Parse(string commandLine) { ParseResult result = _parser.Parse(commandLine); return(_parser.InvokeAsync(result, _console)); }
protected CommandBase(ParseResult parseResult) { ShowHelpOrErrorIfAppropriate(parseResult); }
/// <summary> /// Entry method for the parser /// </summary> /// <param name="input">the input string</param> /// <param name="result">the result</param> /// <returns>indicating if the parse succeeded or failed</returns> public static bool TryParseCSharp(string input, out ParseResult result) { return(TryParseInternal(new Buffer(input.GetEnumerator()), out result)); }
public IEnumerable <string> NormalizeTokenSet(IEnumerable <string> tokens, ParseResult context) { return(tokens); }
public ParseResult Parse(ExtractResult extResult) { var ret = new ParseResult(extResult); ExtractResult numberResult; if (extResult.Data is ExtractResult unitResult) { numberResult = unitResult; } else if (extResult.Type.Equals(Constants.SYS_NUM)) { ret.Value = Config.InternalNumberParser.Parse(extResult).Value; return(ret); } else { // If there is no unitResult, means there is just unit numberResult = new ExtractResult { Start = -1, Length = 0 }; } // Key contains units var key = extResult.Text; var unitKeyBuild = new StringBuilder(); var unitKeys = new List <string>(); for (var i = 0; i <= key.Length; i++) { if (i == key.Length) { if (unitKeyBuild.Length != 0) { AddIfNotContained(unitKeys, unitKeyBuild.ToString().Trim()); } } else if (i == numberResult.Start) { // numberResult.start is a relative position if (unitKeyBuild.Length != 0) { AddIfNotContained(unitKeys, unitKeyBuild.ToString().Trim()); unitKeyBuild.Clear(); } var o = numberResult.Start + numberResult.Length - 1; if (o != null) { i = (int)o; } } else { unitKeyBuild.Append(key[i]); } } // Unit type depends on last unit in suffix var lastUnit = unitKeys.Last(); var normalizedLastUnit = lastUnit.ToLowerInvariant(); if (!string.IsNullOrEmpty(Config.ConnectorToken) && normalizedLastUnit.StartsWith(Config.ConnectorToken)) { normalizedLastUnit = normalizedLastUnit.Substring(Config.ConnectorToken.Length).Trim(); lastUnit = lastUnit.Substring(Config.ConnectorToken.Length).Trim(); } if (!string.IsNullOrWhiteSpace(key) && Config.UnitMap != null) { if (Config.UnitMap.TryGetValue(lastUnit, out var unitValue) || Config.UnitMap.TryGetValue(normalizedLastUnit, out unitValue)) { var numValue = string.IsNullOrEmpty(numberResult.Text) ? null : this.Config.InternalNumberParser.Parse(numberResult); ret.Value = new UnitValue { Number = numValue?.ResolutionStr, Unit = unitValue, }; ret.ResolutionStr = $"{numValue?.ResolutionStr} {unitValue}".Trim(); } } ret.Text = ret.Text.ToLowerInvariant(); return(ret); }
internal static bool TryParseQuote(Buffer buffer, out ParseResult result) => TryParseSpecialCharacter(buffer, '"', Symbols.Quote, out result);
public IEnumerable <string> NormalizeTokenSet(IEnumerable <string> tokens, ParseResult context) { throw new NotImplementedException(); }
public static IEnumerable <Bundle> GetFilteredBundles(IEnumerable <Bundle> bundles, ParseResult parseResult = null) { if (parseResult == null) { parseResult = CommandLineConfigs.CommandLineParseResult; } var option = parseResult.CommandResult.GetUninstallMainOption(); var typeSelection = parseResult.CommandResult.GetTypeSelection(); var archSelection = parseResult.CommandResult.GetArchSelection(); if (option == null) { if (parseResult.CommandResult.Tokens.Count == 0) { throw new RequiredArgMissingForUninstallCommandException(); } bundles = OptionFilterers.UninstallNoOptionFilterer.Filter( parseResult.CommandResult.Tokens.Select(t => t.Value), bundles, typeSelection, archSelection); } else { bundles = OptionFilterers.OptionFiltererDictionary[option].Filter( parseResult, option, bundles, typeSelection, archSelection); } if (parseResult.CommandResult.OptionResult(CommandLineConfigs.ForceOption.Name) == null) { bundles = FilterRequiredBundles(bundles, parseResult.CommandResult.Tokens); } if (bundles.Any(bundle => bundle.Version.SemVer >= VisualStudioSafeVersionsExtractor.UpperLimit)) { throw new UninstallationNotAllowedException(); } return(bundles); }
internal static bool TryParseBSlash(Buffer buffer, out ParseResult result) => TryParseSpecialCharacter(buffer, '\\', Symbols.BSlash, out result);
public static int Run(ParseResult parseResult) { return(RunWithReporter(parseResult, Reporter.Output)); }