public void Functions() { var parser = new Parser(new Scanner("../../sources/for_unit_tests/functions.exs")); parser.DoPostParseProcessing = true; parser.Parse(); var ast = parser.TopmostAst; var options = new ExpressoCompilerOptions{ LibraryPaths = new List<string>{""}, OutputPath = "../../test_executable", BuildType = BuildType.Debug | BuildType.Executable }; var emitter = new CSharpEmitter(parser, options); ast.AcceptWalker(emitter, null); var asm = emitter.AssemblyBuilder; var main_method = asm.GetModule("main.exe") .GetType("ExsMain") .GetMethod("Main", BindingFlags.NonPublic | BindingFlags.Static); Assert.AreEqual(main_method.Name, "Main"); Assert.IsTrue(main_method.IsStatic); Assert.AreEqual(typeof(int), main_method.ReturnType); Assert.AreEqual(0, main_method.GetParameters().Length); //Assert.IsTrue(main_method.GetParameters().SequenceEqual(new []{typeof(string[])})); Console.Out.WriteLine("テスト実行"); Console.Out.WriteLine(main_method.ToString()); //main_method.Invoke(null, new object[]{}); }
public static void Register() { Suite suite = new Suite(); suite.Name = "parse/e-info"; suite.SetSetup(delegate() { p = Init.init_parse_e(); }); suite.SetTeardown(delegate() { p.Destroy(); }); suite.AddTest("order", test_order); suite.AddTest("n0", test_n0); suite.AddTest("w0", test_w0); suite.AddTest("x0", test_x0); suite.AddTest("t0", test_t0); suite.AddTest("t1", test_t1); suite.AddTest("c0", test_c0); suite.AddTest("m0", test_m0); suite.AddTest("f0", test_f0); suite.AddTest("d0", test_d0); suite.AddTest("l0", test_l0); UnitTest_Main.AddSuite(suite); }
public static void SetModel(this Parser parser, string definition, Parser subParser) { // clean the models from old parsers var model = parser.GetModel(); model.Definition = definition; model.SubParsers = new[] { subParser }; }
private static void Main(string[] args) { /* if (args.Length != 1) exit("Usage: Simplecalc.exe filename"); */ using (StreamReader sr = new StreamReader(File.Open("test", FileMode.Open))) { // Read source Lexer lexer = new Lexer(sr); // Parse source Parser parser = new Parser(lexer); Start ast = null; try { ast = parser.Parse(); } catch (Exception ex) { exit(ex.ToString()); } // Print tree SimplePrinter printer = new SimplePrinter(true, ConsoleColor.White, ConsoleColor.Gray, ConsoleColor.Red, ConsoleColor.Blue); ast.Apply(printer); } exit("Done"); }
public void Errors_of_type_MutuallyExclusiveSetError_are_properly_formatted() { // Fixture setup var help = new StringWriter(); var sut = new Parser(config => config.HelpWriter = help); // Exercize system sut.ParseArguments<FakeOptionsWithTwoRequiredAndSets>( new[] { "--weburl=value.com", "--ftpurl=value.org" }); var result = help.ToString(); // Verify outcome result.Length.Should().BeGreaterThan(0); var lines = result.ToNotEmptyLines().TrimStringArray(); lines[0].Should().StartWithEquivalent("CommandLine"); lines[1].ShouldBeEquivalentTo("Copyright (c) 2005 - 2015 Giacomo Stelluti Scala"); lines[2].ShouldBeEquivalentTo("ERROR(S):"); lines[3].ShouldBeEquivalentTo("Option: 'weburl' is not compatible with: 'ftpurl'."); lines[4].ShouldBeEquivalentTo("Option: 'ftpurl' is not compatible with: 'weburl'."); lines[5].ShouldBeEquivalentTo("--weburl Required."); lines[6].ShouldBeEquivalentTo("--ftpurl Required."); lines[7].ShouldBeEquivalentTo("-a"); lines[8].ShouldBeEquivalentTo("--help Display this help screen."); lines[9].ShouldBeEquivalentTo("--version Display version information."); // Teardown }
public void AddItemFromParser(Parser theParser, int index) { object obj = Token(theParser, index); if (obj is ASTNode) Pipeline.Add(obj as ASTNode); }
public void Process(BundleContext context, BundleResponse bundle) { if (bundle == null) { throw new ArgumentNullException("bundle"); } context.HttpContext.Response.Cache.SetLastModifiedFromFileDependencies(); var lessParser = new Parser(); ILessEngine lessEngine = CreateLessEngine(lessParser); var content = new StringBuilder(bundle.Content.Length); foreach (FileInfo file in bundle.Files) { SetCurrentFilePath(lessParser, file.FullName); string source = File.ReadAllText(file.FullName); content.Append(lessEngine.TransformToCss(source, file.FullName)); content.AppendLine(); AddFileDependencies(lessParser); } bundle.ContentType = "text/css"; bundle.Content = content.ToString(); }
public IExpression Parse(Parser parser, Token<TokenType> token) { var name = parser.TakeExpression<CallExpression>(Predecence.Prefix); if (!name.GetArguments().All(a => a is NameExpression)) // TODO: should this constraint be handled by the parser? throw new ParseException(token.GetLocation(), "All arguments in function's name must be NameExpressions"); List<IExpression> inner = new List<IExpression>(); while (true) { var innerToken = parser.PeekToken(); if (innerToken.Identifier == TokenType.End) { parser.TakeToken(); // consume the token we peeked break; } if (innerToken.Identifier == TokenType.EOF) throw new ParseException(innerToken.GetLocation(), "EOF token reached before End was found"); inner.Add(parser.TakeExpression(Predecence.Prefix)); } return new FunctionExpression(name, inner, token); }
public static PipelineNode GetPipeline(Parser theParser) { PipelineNode pipeline = null; if (theParser != null) { object objLeft = theParser.GetReductionSyntaxNode(0); object objRight = theParser.GetReductionSyntaxNode(2); if (objLeft is PipelineNode) { pipeline = (PipelineNode)objLeft; pipeline.AddItem(objRight as ASTNode); } else if (objRight is PipelineNode) { pipeline = (PipelineNode)objRight; pipeline.Insert(0, objLeft as ASTNode); } } if (pipeline == null) { pipeline = new PipelineNode(theParser); if (theParser != null) { pipeline.AddItemFromParser(theParser, 0); pipeline.AddItemFromParser(theParser, 2); } } return pipeline; }
protected GroupParser(GroupParser other, ParserCloneArgs chain) : base(other, chain) { this.Line = chain.Clone(other.Line); this.Start = chain.Clone(other.Start); this.End = chain.Clone(other.End); }
public void Failed_verb_parsing_prints_particular_help_screen() { string invokedVerb = null; object invokedVerbInstance = null; var options = new OptionsWithVerbsHelp(); var testWriter = new StringWriter(); ReflectionUtil.AssemblyFromWhichToPullInformation = Assembly.GetExecutingAssembly(); var parser = new Parser(with => with.UseHelpWriter(testWriter)); var result = parser.ParseArguments(new string[] { "clone", "--no_hardlinks" }, options, (verb, subOptions) => { invokedVerb = verb; invokedVerbInstance = subOptions; }); result.Should().BeFalse(); var helpText = testWriter.ToString(); Console.WriteLine(helpText); var lines = helpText.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); // Verify just significant output lines[5].Trim().Should().Be("--no-hardlinks Optimize the cloning process from a repository on a local"); lines[6].Trim().Should().Be("filesystem by copying files."); lines[7].Trim().Should().Be("-q, --quiet Suppress summary message."); invokedVerb.Should().Be("clone"); invokedVerbInstance.Should().Be(null); }
public void GenerateTest() { Assert.Inconclusive("TBA"); // # Arrange. var sut = new Parser(); sut.Generate(); }
public ElasticsearchOutput(TimberWinR.Manager manager, Parser.ElasticsearchOutputParameters parameters, CancellationToken cancelToken) : base(cancelToken, "Elasticsearch") { _sentMessages = 0; _errorCount = 0; _parameters = parameters; _flushSize = parameters.FlushSize; _idleFlushTimeSeconds = parameters.IdleFlushTimeInSeconds; _protocol = parameters.Protocol; _timeout = parameters.Timeout; _manager = manager; _port = parameters.Port; _ssl = parameters.Ssl; _username = parameters.Username; _password = parameters.Password; _interval = parameters.Interval; _hosts = parameters.Host; _jsonQueue = new List<JObject>(); _numThreads = parameters.NumThreads; _maxQueueSize = parameters.MaxQueueSize; _queueOverflowDiscardOldest = parameters.QueueOverflowDiscardOldest; _disablePing = !parameters.EnablePing; _pingTimeout = parameters.PingTimeout; for (int i = 0; i < parameters.NumThreads; i++) { Task.Factory.StartNew(ElasticsearchSender, cancelToken, TaskCreationOptions.LongRunning, TaskScheduler.Current); } }
public void HandleInitialSpells(Parser packet) { ReadByte("Talent Spec"); var spellsCount = Reader.ReadUInt16(); AppendFormatLine("Spells count: {0}", spellsCount); for (var i = 0; i < spellsCount; ++i) { UInt32("SpellID"); UInt16("slot"); } var cooldownsCount = Reader.ReadUInt16(); AppendFormatLine("Cooldowns count: {0}", cooldownsCount); for (var i = 0; i < cooldownsCount; ++i) { UInt32("spellId"); UInt16("itemId"); UInt32("category"); UInt32("time1"); UInt32("time2"); } }
public Rule(Parser parser, RuleType ruleType, Predicate<Parser> lookAhead, RuleDelegate evaluate) { _parser = parser; _ruleType = ruleType; _lookAhead = lookAhead; _evaluate = evaluate; }
internal override Expression Resolve(Parser parser) { string className = this.NameToken.Value; if (parser.IsTranslateMode) { StructDefinition structDefinition = parser.GetStructDefinition(className); if (structDefinition != null) { if (this.Args.Length != structDefinition.Fields.Length) { throw new ParserException(this.FirstToken, "Args length did not match struct field count for '" + structDefinition.Name.Value + "'."); } StructInstance si = new StructInstance(this.FirstToken, this.NameToken, this.Args, this.FunctionOrClassOwner); si = (StructInstance)si.Resolve(parser); return si; } } for (int i = 0; i < this.Args.Length; ++i) { this.Args[i] = this.Args[i].Resolve(parser); } ConstructorDefinition cons = this.Class.Constructor; if (this.Args.Length < cons.MinArgCount || this.Args.Length > cons.MaxArgCount) { // TODO: show the correct arg count. throw new ParserException(this.FirstToken, "This constructor has the wrong number of arguments."); } return this; }
public static ParamsListNode GetParamsList(Parser theParser) { ParamsListNode paramsList = null; if (theParser != null) { object objLeft = theParser.GetReductionSyntaxNode(0); object objRight = theParser.GetReductionSyntaxNode(1); if (objLeft is ParamsListNode) { paramsList = (ParamsListNode)objLeft; paramsList.AddParam(objRight); } else if (objRight is ParamsListNode) { paramsList = (ParamsListNode)objRight; paramsList.Insert(0, objLeft); } } if (paramsList == null) { paramsList = new ParamsListNode(theParser); if (theParser != null) { paramsList.AddParamFromParser(theParser, 0); paramsList.AddParamFromParser(theParser, 1); } } return paramsList; }
// Main method and Inizialisation of the Threadpool static void Main(string[] args) { string[] exp = System.IO.File.ReadAllLines("C:/expressions1.txt"); int Expressions = exp.Length; // Every event is for each Parserobject ManualResetEvent[] doneEvents = new ManualResetEvent[Expressions]; Parser[] parsArray = new Parser[Expressions]; // Starting the Threads with a Threadpool Console.WriteLine("launching {0} tasks...",Expressions); for (int i = 0; i < Expressions; i++) { doneEvents[i] = new ManualResetEvent(false); Parser pars = new Parser(exp[i], doneEvents[i]); parsArray[i] = pars; ThreadPool.QueueUserWorkItem(pars.ThreadPoolCallback, i); } // Wait until all ParserEvents are done WaitHandle.WaitAll(doneEvents); Console.WriteLine("All Expressions are parsed"); // Output of the results for (int i = 0; i < Expressions; i++) { Parser p = parsArray[i]; Console.WriteLine("Expression({0}) = {1}", p.getText, p.getResult); } Console.ReadKey(); }
public UriTemplate(string uriTemplate) { this.uriTemplate = uriTemplate; Parser parser = new Parser(uriTemplate); this.variableNames = parser.GetVariableNames(); this.matchRegex = parser.GetMatchRegex(); }
/// <summary> /// Reads a directive node. /// </summary> /// <param name="parser">The parser to read the directive node from.</param> /// <returns>The directive node.</returns> /// <exception cref="BadDataException">Read an invalid directive.</exception> /// <exception cref="MissingDataException">Closing directive node was missing.</exception> public static DirectiveNode Create(Parser parser) { var startLocation = parser.InputReader.Location.Clone(); string line = parser.InputReader.ReadLine(); foreach(var type in GetDirectiveTypes()) { foreach(var attr in type.GetCustomAttributes(typeof(DirectiveAttribute), true).OfType<DirectiveAttribute>()) { var info = ParseDirectiveLine(parser, attr.NameExpression, line, startLocation); if(info == null) { continue; } using(info.ParametersReader) { var node = CreateInstance(type, info); if(node == null) { continue; } node.ReadSubNodes(parser); return node; } } } throw new BadDataException("Unknown directive " + line, startLocation); }
public void HandleGuildBankUpdateTab(Parser packet) { UInt64("Guid)"); CString("TabID"); CString("Name"); CString("Icon"); }
public void Module() { ModuleDeclaration moduleDeclaration = new Parser().Module(new Lexer("module Something 1.2.3 { }")); Assert.IsNotNull(moduleDeclaration); Assert.AreEqual("Something", moduleDeclaration.Name.ToString()); Assert.IsNotNull(moduleDeclaration.Members); Assert.IsFalse(moduleDeclaration.Members.Any()); Assert.AreEqual(moduleDeclaration.Version, Version.Parse("1.2.3")); moduleDeclaration = new Parser().Module(new Lexer("module Something 1.2.0 { a: Int32 }")); Assert.IsNotNull(moduleDeclaration); Assert.AreEqual("Something", moduleDeclaration.Name.ToString()); Assert.AreEqual(moduleDeclaration.Version, Version.Parse("1.2.0")); Assert.IsNotNull(moduleDeclaration.Members); Assert.AreEqual(1, moduleDeclaration.Members.Count); Assert.AreEqual("a", moduleDeclaration.Members[0].Name.Components[0]); moduleDeclaration = new Parser().Module(new Lexer(@" module Something 1.0.0 { a: Int32 b: const 5 }")); Assert.IsNotNull(moduleDeclaration); Assert.AreEqual("Something", moduleDeclaration.Name.ToString()); Assert.AreEqual(moduleDeclaration.Version, Version.Parse("1.0.0")); Assert.IsNotNull(moduleDeclaration.Members); Assert.AreEqual(2, moduleDeclaration.Members.Count); Assert.AreEqual("a", moduleDeclaration.Members[0].Name.ToString()); Assert.AreEqual("b", moduleDeclaration.Members[1].Name.ToString()); }
/// <summary> /// Parser for identifier starting with <paramref name="firstLetterParser"/> and continuing with <paramref name="tailLetterParser"/> /// </summary> public static Parser<string> Identifier(Parser<char> firstLetterParser, Parser<char> tailLetterParser) { return from firstLetter in firstLetterParser from tail in tailLetterParser.Many().Text() select firstLetter + tail; }
private async void btnStart_Click(object sender, EventArgs e) { pbMain.Value = 0; var parser = new Parser(txtThread.Text); if (!parser.IsValid()) return; ToggleGroupBoxes(false); TitleBuilder.Build(this, "Initializing"); var threadData = await parser.BuildThreadData(); var scraper = new Scraper(threadData, UpdateProgress); var files = await scraper.CollectFileURLs(cbWEBM.Checked, cbDuplicates.Checked); if (files == null) return; pbMain.Maximum = files.Count; await Task.WhenAll(files.Select(p => scraper.DownloadFileAsync(this, p, rbUID.Checked, txtPath.Text))); ToggleGroupBoxes(true); TitleBuilder.Build(this, "Completed", false); }
public static CombatLog CreateCombatLog(string combatLog) { string hash = ComputeHash(combatLog); var logParser = new Parser(); var log = logParser.Parse(new StringReader(combatLog)); return CreateCombatLog(hash, log); }
private static void DoGenerate(string pegFile) { // Parse the file. if (Program.Verbosity >= 1) Console.WriteLine("parsing '{0}'", pegFile); var parser = new Parser(); string input = File.ReadAllText(pegFile, System.Text.Encoding.UTF8); parser.Parse(input, pegFile); // Check for errors. parser.Grammar.Validate(); // Delete the old parser. if (File.Exists(ms_outFile)) File.Delete(ms_outFile); // Write the new parser. if (Program.Verbosity >= 1) Console.WriteLine("writing '{0}'", ms_outFile); using (var stream = new StreamWriter(ms_outFile, false, System.Text.Encoding.UTF8)) { using (var writer = new Writer(stream, parser.Grammar)) { writer.Write(pegFile); stream.Flush(); } } }
public void HandleFriendStatus(Parser packet) { var result = (ContactResult)packet.ReadByte(); WriteLine("Result: " + result); var guid = packet.ReadGuid(); WriteLine("GUID: " + guid); switch (result) { case ContactResult.FriendAddedOnline: case ContactResult.FriendAddedOffline: case ContactResult.Online: { if (result != ContactResult.Online) { var note = packet.ReadCString(); WriteLine("Note: " + note); } ReadSingleContactBlock(packet, false); break; } } }
public ParseContext(ParseContext parent, Parser parser) : this(parent.Input, -1) { Parent = parent; Parser = parser; WhitespacePolicy = parent.WhitespacePolicy; var wsRule = parser as WhitespaceRuleParser; if (wsRule != null) { _whitespaceParsers = new HashSet<Parser>(parent._whitespaceParsers ?? Enumerable.Empty<Parser>()) { wsRule.WhitespaceParser }; } else { _whitespaceParsers = parent._whitespaceParsers; } var policy = parser as WhitespacePolicyParser; if (policy != null) WhitespacePolicy = policy.Policy; InitialOffset = Offset = parent.WhitespacePolicy == WhitespacePolicy.Ignore ? SkipWhitespace(parent.Input, parent.Offset) : parent.Offset; }
public void HandleContactList(Parser packet) { var flags = (ContactListFlag)packet.ReadInt32(); WriteLine("List Flags: " + flags); var count = packet.ReadInt32(); WriteLine("Count: " + count); for (var i = 0; i < count; i++) { var guid = packet.ReadGuid(); WriteLine("GUID: " + guid); var cflags = (ContactEntryFlag)packet.ReadInt32(); WriteLine("Flags: " + cflags); var note = packet.ReadCString(); WriteLine("Note: " + note); if (!cflags.HasFlag(ContactEntryFlag.Friend)) continue; ReadSingleContactBlock(packet, true); } }
public void Should_Parse_Simple_Name_And_Array_Value() { var simpleTemplatStream = File.OpenRead(AppDomain.CurrentDomain.BaseDirectory + "/templates/simple template.xls"); IParser parser = new Parser(); try { var parserResult = parser.Parse(simpleTemplatStream, ExcelExtension.XLS); Assert.AreEqual(3, parserResult.Count); Assert.AreEqual("Name", parserResult[0].Name); Assert.AreEqual(0, parserResult[0].RowIndex); Assert.AreEqual(1, parserResult[0].ColumnIndex); Assert.IsFalse(parserResult[0].IsArray); Assert.AreEqual("Owner", parserResult[1].Name); Assert.AreEqual(3, parserResult[1].RowIndex); Assert.AreEqual(0, parserResult[1].ColumnIndex); Assert.IsTrue(parserResult[1].IsArray); Assert.AreEqual("Price", parserResult[2].Name); Assert.AreEqual(3, parserResult[2].RowIndex); Assert.AreEqual(1, parserResult[2].ColumnIndex); Assert.IsTrue(parserResult[2].IsArray); } finally { simpleTemplatStream.Close(); } }
public Expression Parse(Parser parser, Expression left, Token <RMathToken> token) { return(new PostfixOperatorExpression(token, left)); }
private void ProcessInput(string input, bool executeQuery) { // Ignore empty input. // if (input == null) { return; } input = input.Trim(); if (string.IsNullOrEmpty(input)) { return; } AppState.Transcript.Entries.AddTranscriptEntry(TranscriptEntryTypes.Request, input); Clause selectedClause = ctrlProgram.SelectedClause; CodeSentence[] codeSentences = Parser.Parse(input); if (codeSentences == null || codeSentences.Length == 0) { AppState.Transcript.Entries.AddTranscriptEntry(TranscriptEntryTypes.Response, Properties.Resources.MessageUnrecognizedInput); } else { foreach (CodeSentence codeSentence in codeSentences) { if (codeSentence.Head == null) // query { Query query = new Query(codeSentence); AppState.Machine = PrologMachine.Create(AppState.Program, query); if (executeQuery) { AppState.Machine.RunToSuccess(); } } else // fact or rule { if (selectedClause != null && selectedClause.Container.Procedure.Functor == Functor.Create(codeSentence.Head.Functor)) { selectedClause.CodeSentence = codeSentence; AppState.Transcript.Entries.AddTranscriptEntry(TranscriptEntryTypes.Response, Properties.Resources.ResponseSuccess); } else { if (AppState.Program.Contains(codeSentence)) { AppState.Transcript.Entries.AddTranscriptEntry(TranscriptEntryTypes.Response, Properties.Resources.MessageDuplicateClause); } else { AppState.Program.Add(codeSentence); AppState.Transcript.Entries.AddTranscriptEntry(TranscriptEntryTypes.Response, Properties.Resources.ResponseSuccess); } } } } } }
/// <summary> /// Uses the Parser to parse a Sentence from a string. /// </summary> /// <param name="str">A string to parse.</param> /// <returns>The result from the Parser parsing the given string.</returns> public static Sentence parseFromString(string str) { return(Parser.parseString(str)); }
/// <summary> /// Inspects a global constant declaration even during parsing /// </summary> /// <param name="parser">Parser currently analyzing the source code</param> /// <param name="decl">Current global constant declaration</param> public void GlobalConstantDeclarationReduced(Parser /*!*/ parser, GlobalConstantDecl /*!*/ decl) { compilationUnit.GlobalConstantDeclarationReduced(parser, decl); }
/// <summary> /// Inspects a inclusion statement even during parsing /// </summary> /// <param name="parser">Parser currently analyzing the source code</param> /// <param name="decl">Current inclusion</param> public void InclusionReduced(Parser /*!*/ parser, IncludingEx /*!*/ decl) { compilationUnit.InclusionReduced(parser, decl); }
static int Main(string[] args) { #if !DEBUG try #endif { var options = new Options(); var parser = new Parser( s => { s.IgnoreUnknownArguments = false; s.MutuallyExclusive = true; s.CaseSensitive = true; s.HelpWriter = Console.Error; } ); var isValid = parser.ParseArgumentsStrict(args, options); if (!isValid) { return(1); } if (options.Version) { PrintVersion(); return(0); } if (string.IsNullOrEmpty(options.Input) || (!File.Exists(options.Input) && !Directory.Exists(options.Input))) { Console.WriteLine(options.GetUsage()); return(1); } if (string.IsNullOrEmpty(options.PackageFormat)) { options.PackageFormat = "nuget"; } if (string.IsNullOrEmpty(options.PackageName)) { options.PackageName = Path.GetFileName(options.Input); } if (string.IsNullOrEmpty(options.PackageVersion)) { options.PackageVersion = "1.0.0"; } if (options.PackageFormat != "nuget" && options.PackageFormat != "zip") { Console.WriteLine(options.GetUsage()); return(1); } string outputDir = "Deployer." + options.PackageName + "-" + options.PackageVersion; if (Directory.Exists(outputDir)) { Directory.Delete(outputDir, true); } Directory.CreateDirectory(outputDir); string outputToolDir = outputDir; if (options.PackageFormat == "nuget") { outputToolDir = Path.Combine(outputDir, "tools"); Directory.CreateDirectory(outputToolDir); } if (Directory.Exists(options.Input)) { string inputDir = SimplifyDirectory(options.Input); DirectoryCopy(inputDir, outputToolDir, true); } else if (Path.GetExtension(options.Input) == ".zip") { string zipFileName = Path.GetFileName(options.Input); string uncompressedLocation = Path.GetFileNameWithoutExtension(zipFileName); ZipFile.ExtractToDirectory(zipFileName, uncompressedLocation); string inputDir = SimplifyDirectory(uncompressedLocation); DirectoryCopy(inputDir, outputToolDir, true); Directory.Delete(uncompressedLocation, true); } else if (Path.GetExtension(options.Input) == ".exe") { string exeFileName = Path.GetFileName(options.Input); File.Copy(options.Input, Path.Combine(outputToolDir, exeFileName), true); } switch (options.PackageFormat) { case "nuget": Package pkg = new Package(options.PackageName, options.PackageVersion); string nuspecFilePath = Path.Combine(outputDir, options.PackageName + ".nuspec"); pkg.Serialize(nuspecFilePath); Console.WriteLine("You need to run now:"); Console.WriteLine("> nuget pack" + nuspecFilePath); Console.WriteLine("> nuget push .\\Pakcate.nupkg -source \"nugetServerUrl\\path\""); break; case "zip": ZipFile.CreateFromDirectory(outputDir, outputDir + ".zip"); Directory.Delete(outputDir, true); Console.WriteLine("You need to run now:"); Console.WriteLine("> curl -u<USERNAME>:<PASSWORD> -T filePath \"serverUrl\\path\""); break; default: return(1); } return(0); } #if !DEBUG catch (Exception e) { Console.WriteLine("Fatal error -> " + e.Message); return(-1); } #endif }
private static bool ParseAttributes(XElement elt, VisualElementAsset res, StyleSheetBuilder ssb, VisualTreeAsset vta, VisualElementAsset parent) { bool startedRule = false; foreach (XAttribute xattr in elt.Attributes()) { string attrName = xattr.Name.LocalName; // start with special cases switch (attrName) { case "class": res.classes = xattr.Value.Split(' '); continue; case "contentContainer": if (vta.contentContainerId != 0) { logger.LogError(ImportErrorType.Semantic, ImportErrorCode.DuplicateContentContainer, null, Error.Level.Fatal, elt); continue; } vta.contentContainerId = res.id; continue; case k_SlotDefinitionAttr: if (String.IsNullOrEmpty(xattr.Value)) logger.LogError(ImportErrorType.Semantic, ImportErrorCode.SlotDefinitionHasEmptyName, null, Error.Level.Fatal, elt); else if (!vta.AddSlotDefinition(xattr.Value, res.id)) logger.LogError(ImportErrorType.Semantic, ImportErrorCode.DuplicateSlotDefinition, xattr.Value, Error.Level.Fatal, elt); continue; case k_SlotUsageAttr: var templateAsset = parent as TemplateAsset; if (templateAsset == null) { logger.LogError(ImportErrorType.Semantic, ImportErrorCode.SlotUsageInNonTemplate, parent, Error.Level.Fatal, elt); continue; } if (string.IsNullOrEmpty(xattr.Value)) { logger.LogError(ImportErrorType.Semantic, ImportErrorCode.SlotUsageHasEmptyName, null, Error.Level.Fatal, elt); continue; } templateAsset.AddSlotUsage(xattr.Value, res.id); continue; case "style": ExCSS.StyleSheet parsed = new Parser().Parse("* { " + xattr.Value + " }"); if (parsed.Errors.Count != 0) { logger.LogError( ImportErrorType.Semantic, ImportErrorCode.InvalidCssInStyleAttribute, parsed.Errors.Aggregate("", (s, error) => s + error.ToString() + "\n"), Error.Level.Warning, xattr); continue; } if (parsed.StyleRules.Count != 1) { logger.LogError( ImportErrorType.Semantic, ImportErrorCode.InvalidCssInStyleAttribute, "Expected one style rule, found " + parsed.StyleRules.Count, Error.Level.Warning, xattr); continue; } ssb.BeginRule(-1); startedRule = true; StyleSheetImportErrors errors = new StyleSheetImportErrors(); foreach (Property prop in parsed.StyleRules[0].Declarations) { ssb.BeginProperty(prop.Name); StyleSheetImporterImpl.VisitValue(errors, ssb, prop.Term); ssb.EndProperty(); } // Don't call ssb.EndRule() here, it's done in LoadXml to get the rule index at the same time ! continue; } res.AddProperty(xattr.Name.LocalName, xattr.Value); } return startedRule; }
/// <summary> /// Inspects a function declaration even during parsing /// </summary> /// <param name="parser">Parser currently analyzing the source code</param> /// <param name="decl">Current function declaration</param> public void FunctionDeclarationReduced(Parser /*!*/ parser, FunctionDecl /*!*/ decl) { functions[decl] = this.Ast; compilationUnit.FunctionDeclarationReduced(parser, decl); }
Value ParseExpression(string e) { var p = new Parser(Current, new StringReader(e)); return p.ParseExpression().Eval(); }
// Note that we don't filter out rows with parsing issues since it's not acceptable to // produce a different set of rows when subsetting columns. Any parsing errors need to be // translated to NaN, not result in skipping the row. We should produce some diagnostics // to alert the user to the issues. private Cursor(TextLoader parent, ParseStats stats, bool[] active, LineReader reader, int srcNeeded, int cthd) : base(parent._host) { Ch.Assert(active == null || active.Length == parent._bindings.Infos.Length); Ch.AssertValue(reader); Ch.AssertValue(stats); Ch.Assert(srcNeeded >= 0); Ch.Assert(cthd > 0); _total = -1; _batch = -1; _bindings = parent._bindings; _parser = parent._parser; _active = active; _reader = reader; _stats = stats; _srcNeeded = srcNeeded; ParallelState state = null; if (cthd > 1) { state = new ParallelState(this, out _rows, cthd); } else { _rows = _parser.CreateRowSet(_stats, 1, _active); } try { _getters = new Delegate[_bindings.Infos.Length]; for (int i = 0; i < _getters.Length; i++) { if (_active != null && !_active[i]) { continue; } ColumnPipe v = _rows.Pipes[i]; Ch.Assert(v != null); _getters[i] = v.GetGetter(); Ch.Assert(_getters[i] != null); } if (state != null) { _ator = ParseParallel(state).GetEnumerator(); state = null; } else { _ator = ParseSequential().GetEnumerator(); } } finally { if (state != null) { state.Dispose(); } } }
public void When_string_for_parsing_is_null_or_empty_it_should_throw_an_argument_null_exception() { var parser = new Parser(); parser.Parse(""); }
public override void ExecuteCommand(EvtChatCommandArgs args) { List <string> arguments = args.Command.ArgumentsAsList; if (arguments.Count < 2) { QueueMessage(UsageMessage); return; } string macroName = arguments[0].ToLowerInvariant(); //Make sure the first argument has at least a minimum number of characters if (macroName.Length < MIN_MACRO_NAME_LENGTH) { QueueMessage($"Input macros need to be at least {MIN_MACRO_NAME_LENGTH} characters long."); return; } if (macroName.StartsWith(Parser.DEFAULT_PARSER_REGEX_MACRO_INPUT) == false) { QueueMessage($"Input macros must start with \"{Parser.DEFAULT_PARSER_REGEX_MACRO_INPUT}\"."); return; } //For simplicity with wait inputs, force the first character in the macro name to be alphanumeric if (char.IsLetterOrDigit(arguments[0][1]) == false) { QueueMessage("The first character in input macro names must be alphanumeric."); return; } //Check for max macro name if (macroName.Length > MAX_MACRO_NAME_LENGTH) { QueueMessage($"Input macros may have up to a max of {MAX_MACRO_NAME_LENGTH} characters in their name."); return; } int curConsoleID = (int)DataHelper.GetSettingInt(SettingsConstants.LAST_CONSOLE, 1L); GameConsole consoleInstance = null; using (BotDBContext context = DatabaseManager.OpenContext()) { GameConsole curConsole = context.Consoles.FirstOrDefault(c => c.ID == curConsoleID); if (curConsole == null) { QueueMessage("Cannot validate input macro, as the current console is invalid. Fix this by setting another console."); return; } consoleInstance = new GameConsole(curConsole.Name, curConsole.InputList); } Parser parser = new Parser(); //Trim the macro name from the input sequence string macroVal = args.Command.ArgumentsAsString.Remove(0, macroName.Length + 1).ToLowerInvariant(); //Console.WriteLine(macroVal); bool isDynamic = false; //Check for a dynamic macro int openParenIndex = macroName.IndexOf('(', 0); if (openParenIndex >= 0) { //If we found the open parenthesis, check for the asterisk //This is not comprehensive, but it should smooth out a few issues if (openParenIndex == (macroName.Length - 1) || macroName[openParenIndex + 1] != '*') { QueueMessage("Invalid input macro. Dynamic macro arguments must be specified with \"*\"."); return; } if (macroName[macroName.Length - 1] != ')') { QueueMessage("Invalid input macro. Dynamic macros must end with \")\"."); return; } isDynamic = true; } //Validate input if not dynamic if (isDynamic == false) { ParsedInputSequence inputSequence = default; try { string userName = args.Command.ChatMessage.Username; //Get default and max input durations //Use user overrides if they exist, otherwise use the global values int defaultDur = (int)DataHelper.GetUserOrGlobalDefaultInputDur(userName); int maxDur = (int)DataHelper.GetUserOrGlobalMaxInputDur(userName); string regexStr = consoleInstance.InputRegex; string readyMessage = string.Empty; using (BotDBContext context = DatabaseManager.OpenContext()) { IQueryable <InputSynonym> synonyms = context.InputSynonyms.Where(syn => syn.ConsoleID == curConsoleID); readyMessage = parser.PrepParse(macroVal, context.Macros, synonyms); } inputSequence = parser.ParseInputs(readyMessage, regexStr, new ParserOptions(0, defaultDur, true, maxDur)); TRBotLogger.Logger.Debug(inputSequence.ToString()); if (inputSequence.ParsedInputResult != ParsedInputResults.Valid) { if (string.IsNullOrEmpty(inputSequence.Error) == true) { QueueMessage("Invalid input macro."); } else { QueueMessage($"Invalid input macro: {inputSequence.Error}"); } return; } } catch (Exception e) { QueueMessage($"Invalid input macro: {e.Message}"); return; } } string message = string.Empty; using (BotDBContext context = DatabaseManager.OpenContext()) { InputMacro inputMacro = context.Macros.FirstOrDefault(m => m.MacroName == macroName); //Not an existing macro, so add it if (inputMacro == null) { InputMacro newMacro = new InputMacro(macroName, macroVal); context.Macros.Add(newMacro); if (isDynamic == false) { message = $"Added input macro \"{macroName}\"!"; } else { message = $"Added dynamic input macro \"{macroName}\"! Dynamic input macros can't be validated beforehand, so verify it works manually."; } } //Update the macro value else { inputMacro.MacroValue = macroVal; if (isDynamic == false) { message = $"Updated input macro \"{macroName}\"!"; } else { message = $"Updated dynamic input macro \"{macroName}\"! Dynamic input macros can't be validated beforehand, so verify it works manually."; } } context.SaveChanges(); } QueueMessage(message); }
public void HandleChildStyleChanged(EditStyling.Style style, IEditableUIControl childControl) { switch (style) { case EditStyling.Style.RevealBox: { // first, find the target in our list int targetIndex = 0; foreach (IUIControl child in ChildControls) { // when we find it if (child.Equals(childControl) == true) { // take its index, and remove it from the renderer and our list of children targetIndex = ChildControls.IndexOf(child); child.RemoveFromView(ParentEditingCanvas); ChildControls.RemoveAt(targetIndex); break; } } // if we received RevealBox, we're either upgrading a NoteText to BE a RevealBox, // or downgrading a RevealBox to be a normal NoteText. EditableNoteText editableNoteText = childControl as EditableNoteText; if (editableNoteText != null) { // create a new revealBox, but force the text to uppper-case and add the bold font (since this is typically what the Mobile App does) Style controlStyle = childControl.GetControlStyle( ); controlStyle.mFont = new FontParams( ); controlStyle.mFont.mName = sDefaultBoldFontName; RevealBox newRevealBox = Parser.CreateRevealBox(new CreateParams(this, Frame.Width, Frame.Height, ref controlStyle), editableNoteText.GetText( ).ToUpper( ).Trim( )); newRevealBox.AddToView(ParentEditingCanvas); // add the new revealBox into the same spot as what it's replacing ChildControls.Insert(targetIndex, newRevealBox); // make sure we add a space after the reveal box, as that's required. NoteText textLabel = Parser.CreateNoteText(new CreateParams(this, Frame.Width, Frame.Height, ref mStyle), " "); textLabel.AddToView(ParentEditingCanvas); ChildControls.Insert(targetIndex + 1, textLabel); } EditableRevealBox editableRevealBox = childControl as EditableRevealBox; if (editableRevealBox != null) { // create a new revealBox that has the styling and text of the noteText it's replacing. Style controlStyle = childControl.GetControlStyle( ); NoteText newNoteText = Parser.CreateNoteText(new CreateParams(this, Frame.Width, Frame.Height, ref controlStyle), editableRevealBox.GetText( ).Trim( )); newNoteText.AddToView(ParentEditingCanvas); // add the new revealBox into the same spot as what it's replacing ChildControls.Insert(targetIndex, newNoteText); } break; } } // for now, lets just redo our layout. SetPosition(Frame.Left, Frame.Top); }
public void Test() { var parser = new Parser(); var result = parser.Parse(@"MSH|^~\&|SUBx||PAT||20040328112408||ADT^A01^ADT_A01|47|P|2.5|||AL|NE|DEU|8859/1|DEU^^HL70296||2.16.840.1.113883.2.6.9.1^^2.16.840.1.113883.2.6^ISO|<cr>"); Assert.IsNotNull(result); }
public void SetPosition(float xPos, float yPos) { // we're not moving if we're in edit mode if (EditMode_Enabled == false) { // clamp the yPos to the vertical bounds of our parent yPos = Math.Max(yPos, ParentNote.Padding.Top); // now left, which is easy xPos = Math.Max(xPos, ParentNote.Padding.Left); // Now do the right edge. This is tricky because we will allow this control to move forward // until it can't wrap any more. Then, we'll clamp its movement to the parent's edge. // Get the width of the widest child. This is the minimum width // required for the paragraph, since it's wrapping will stop at the widest child. float minRequiredWidth = 0; foreach (IUIControl control in ChildControls) { RectangleF controlFrame = control.GetFrame( ); if (controlFrame.Width > minRequiredWidth) { minRequiredWidth = controlFrame.Width; } } // now, if the control cannot wrap any further, we want to clamp its movement // to the parent's right edge // Right Edge Check xPos = Math.Min(xPos, ParentSize.Width - ParentNote.Padding.Right - minRequiredWidth); float currX = Frame.Left; float currY = Frame.Top; Frame = new RectangleF(xPos, yPos, Frame.Width, Frame.Height); float xOffset = Frame.Left - currX; float yOffset = Frame.Top - currY; // position each interactive label relative to ourselves foreach (IUIControl control in ChildControls) { control.AddOffset(xOffset, yOffset); } BorderView.Position = new PointF(BorderView.Position.X + xOffset, BorderView.Position.Y + yOffset); float xPosInParent = Frame.Left; float yPosInParent = Frame.Top; // given this new position, see how much space we actually have now. UpdateLayout((ParentSize.Width - ParentNote.Padding.Right) - xPosInParent, ParentSize.Height - yPosInParent); // Build our final frame that determines our dimensions RectangleF frame = new RectangleF(65000, 65000, -65000, -65000); // for each child control foreach (IUIControl control in ChildControls) { // enlarge our frame by the current frame and the next child frame = Parser.CalcBoundingFrame(frame, control.GetFrame( )); } // now set the new width / height int borderPaddingPx = 0; if (mStyle.mBorderWidth.HasValue) { borderPaddingPx = (int)Rock.Mobile.Graphics.Util.UnitToPx(mStyle.mBorderWidth.Value + PrivateNoteConfig.BorderPadding); } Frame = new RectangleF(Frame.Left, Frame.Top, frame.Width + Padding.Width + Padding.Left + (borderPaddingPx * 2), frame.Height + Padding.Height + Padding.Top + (borderPaddingPx * 2) //add in padding ); // and store that as our bounds BorderView.Frame = Frame; SetDebugFrame(Frame); } }
protected override IList ExecuteCrawl(bool crawlAll) { IList list = new ArrayList(); //取得页码 int pageInt = 1; string html = string.Empty; try { html = this.ToolWebSite.GetHtmlByUrl(this.ToolWebSite.UrlEncode(SiteUrl), Encoding.UTF8); } catch (Exception ex) { return(list); } Parser parser = new Parser(new Lexer(html)); NodeList sNode = parser.ExtractAllNodesThatMatch(new AndFilter(new HasParentFilter(new TagNameFilter("div")), new HasAttributeFilter("id", "page_div"))); if (sNode != null && sNode.Count > 0) { string page = ToolHtml.GetRegexString(sNode.AsString(), "共", "页"); try { pageInt = int.Parse(page); } catch { pageInt = 7; } } parser.Reset(); for (int i = 1; i <= pageInt; i++) { if (i > 1) { try { html = this.ToolWebSite.GetHtmlByUrl("http://www.conghua.gov.cn/zgch/zbzb/list_" + i.ToString() + ".shtml", Encoding.Default); } catch (Exception ex) { continue; } } parser = new Parser(new Lexer(html)); sNode = parser.ExtractAllNodesThatMatch(new AndFilter(new HasParentFilter(new AndFilter(new TagNameFilter("div"), new HasAttributeFilter("class", "list_list"))), new TagNameFilter("table"))); if (sNode != null && sNode.Count > 0) { TableTag table = sNode[0] as TableTag; for (int j = 0; j < table.RowCount; j++) { TableRow tr = table.Rows[j]; string projectName = ToolHtml.GetHtmlAtagValue("title", tr.ToHtml()); if (!projectName.Contains("中标") && !projectName.Contains("结果") && !projectName.Contains("候选单位公示")) { string code = string.Empty, buildUnit = string.Empty, prjName = string.Empty, prjAddress = string.Empty, inviteCtx = string.Empty, inviteType = string.Empty, specType = string.Empty, beginDate = string.Empty, endDate = string.Empty, remark = string.Empty, inviteCon = string.Empty, InfoUrl = string.Empty, CreateTime = string.Empty, msgType = string.Empty, otherType = string.Empty, HtmlTxt = string.Empty; prjName = projectName; inviteType = ToolHtml.GetInviteTypes(projectName); beginDate = ToolHtml.GetRegexDateTime(tr.Columns[1].ToPlainTextString()); InfoUrl = "http://www.conghua.gov.cn" + ToolHtml.GetHtmlAtagValue("href", tr.ToHtml()).Replace("..", ""); string htmlDtl = string.Empty; try { htmlDtl = this.ToolWebSite.GetHtmlByUrl(InfoUrl, Encoding.UTF8); htmlDtl = ToolHtml.GetRegexHtlTxt(htmlDtl); } catch { continue; } parser = new Parser(new Lexer(htmlDtl)); NodeList dtlList = parser.ExtractAllNodesThatMatch(new AndFilter(new TagNameFilter("div"), new HasAttributeFilter("id", "zoomcon"))); if (dtlList != null && dtlList.Count > 0) { HtmlTxt = dtlList.ToHtml(); inviteCtx = dtlList.AsString().Replace(" ", ""); buildUnit = ToolHtml.GetRegexString(inviteCtx, ToolHtml.BuildRegex, true); if (!string.IsNullOrEmpty(buildUnit) && buildUnit.Contains(" ")) { buildUnit = buildUnit.Remove(buildUnit.IndexOf(" ")); } buildUnit = ToolHtml.GetSubString(buildUnit, 150); msgType = "广州建设工程交易中心"; specType = "建设工程"; inviteType = inviteType == "" ? "小型工程" : inviteType; if (string.IsNullOrEmpty(buildUnit)) { buildUnit = "广州建设工程交易中心"; } InviteInfo info = ToolDb.GenInviteInfo("广东省", "广州市区", "从化市", string.Empty, code, prjName, prjAddress, buildUnit, beginDate, endDate, inviteCtx, remark, msgType, inviteType, specType, otherType, InfoUrl, HtmlTxt); list.Add(info); if (!crawlAll && list.Count >= this.MaxCount) { return(list); } } } else { string prjName = string.Empty, buildUnit = string.Empty, bidUnit = string.Empty, bidMoney = string.Empty, code = string.Empty, bidDate = string.Empty, beginDate = string.Empty, endDate = string.Empty, bidType = string.Empty, specType = string.Empty, InfoUrl = string.Empty, msgType = string.Empty, bidCtx = string.Empty, prjAddress = string.Empty, remark = string.Empty, prjMgr = string.Empty, otherType = string.Empty, HtmlTxt = string.Empty; prjName = projectName; bidType = ToolHtml.GetInviteTypes(projectName); beginDate = ToolHtml.GetRegexDateTime(tr.Columns[1].ToPlainTextString()); InfoUrl = "http://www.conghua.gov.cn" + ToolHtml.GetHtmlAtagValue("href", tr.ToHtml()).Replace("..", ""); string htmlDtl = string.Empty; try { htmlDtl = this.ToolWebSite.GetHtmlByUrl(InfoUrl, Encoding.UTF8); htmlDtl = ToolHtml.GetRegexHtlTxt(htmlDtl); } catch { continue; } parser = new Parser(new Lexer(htmlDtl)); NodeList dtlList = parser.ExtractAllNodesThatMatch(new AndFilter(new TagNameFilter("div"), new HasAttributeFilter("id", "zoomcon"))); if (dtlList != null && dtlList.Count > 0) { HtmlTxt = dtlList.ToHtml(); bidCtx = dtlList.AsString(); buildUnit = ToolHtml.GetRegexString(bidCtx, ToolHtml.BuildRegex, true); buildUnit = ToolHtml.GetSubString(buildUnit, 150); msgType = "广州建设工程交易中心"; specType = "建设工程"; bidType = bidType == "" ? bidType : "小型工程"; parser = new Parser(new Lexer(HtmlTxt)); NodeList bidNode = parser.ExtractAllNodesThatMatch(new TagNameFilter("table")); if (bidNode != null && bidNode.Count > 0) { string ctx = string.Empty; TableTag bidTable = bidNode[0] as TableTag; try { for (int r = 0; r < bidTable.RowCount; r++) { ctx += bidTable.Rows[r].Columns[0].ToNodePlainString() + ":"; ctx += bidTable.Rows[r].Columns[1].ToNodePlainString() + "\r\n"; } } catch { } bidUnit = ctx.GetRegex("单位名称,承包意向人名称"); bidMoney = ctx.GetMoneyRegex(); prjMgr = ctx.GetMgrRegex(); if (prjMgr.Contains("/")) { prjMgr = prjMgr.Remove(prjMgr.IndexOf("/")); } } if (string.IsNullOrEmpty(buildUnit)) { buildUnit = "广州建设工程交易中心"; } BidInfo info = ToolDb.GenBidInfo("广东省", "广州市区", "从化市", string.Empty, code, prjName, buildUnit, beginDate, bidUnit, beginDate, endDate, bidCtx, string.Empty, msgType, bidType, specType, otherType, bidMoney, InfoUrl, prjMgr, HtmlTxt); list.Add(info); if (!crawlAll && list.Count >= this.MaxCount) { return(list); } } } } } } return(list); }
public static void FreeParserMemory() { Program temp; Parser.Parse("", "emptyFile", out temp); }
public void SetStyleValue(EditStyling.Style style, object value) { switch (style) { case EditStyling.Style.BoldParagraph: { // force all children to bold foreach (IUIControl child in ChildControls) { IEditableUIControl editableChild = child as IEditableUIControl; if (editableChild != null) { editableChild.SetStyleValue(EditStyling.Style.FontName, EditableParagraph.sDefaultBoldFontName); } } break; } case EditStyling.Style.BoldItalicizeParagraph: { // force all children to bold foreach (IUIControl child in ChildControls) { IEditableUIControl editableChild = child as IEditableUIControl; if (editableChild != null) { editableChild.SetStyleValue(EditStyling.Style.FontName, EditableParagraph.sDefaultBoldItalicFontName); } } break; } case EditStyling.Style.ItalicizeParagraph: { // force all children to bold foreach (IUIControl child in ChildControls) { IEditableUIControl editableChild = child as IEditableUIControl; if (editableChild != null) { editableChild.SetStyleValue(EditStyling.Style.FontName, EditableParagraph.sDefaultItalicFontName); } } break; } case EditStyling.Style.BulletParagraph: { // create a noteText with the bullet, and then insert it XmlTextReader reader = new XmlTextReader(new StringReader("<NT>" + sBulletChar + "</NT>")); reader.Read( ); IUIControl bulletText = Parser.TryParseControl(new CreateParams(this, ParentSize.Width, ParentSize.Height, ref mStyle), reader); ChildControls.Insert(0, bulletText); SetPosition(Frame.Left, Frame.Top); bulletText.AddToView(ParentEditingCanvas); break; } case EditStyling.Style.UnderlineParagraph: { // to underline the whole thing, we need to make it one big NoteText. // we'll gather all the text, convert it to a single NoteText with Underlined Attribute, // remove the existing children, and replace them with the new single underlined one. // get the full text. we can use the build HTML stream code to do this. string htmlStream = string.Empty; string textStream = string.Empty; BuildHTMLContent(ref htmlStream, ref textStream, new List <IUIControl>( )); // if the last character is a URL glyph, remove it textStream = textStream.Trim(new char[] { ' ', PrivateNoteConfig.CitationUrl_Icon[0] }); XmlTextReader reader = new XmlTextReader(new StringReader("<NT Underlined=\"True\">" + textStream + "</NT>")); reader.Read( ); IUIControl noteText = Parser.TryParseControl(new CreateParams(this, ParentSize.Width, ParentSize.Height, ref mStyle), reader); foreach (IUIControl control in ChildControls) { control.RemoveFromView(ParentEditingCanvas); } ChildControls.Clear( ); ChildControls.Add(noteText); SetPosition(Frame.Left, Frame.Top); noteText.AddToView(ParentEditingCanvas); break; } } }
public ASTAddNode(Parser p, int id) : base(p, id) { }
protected override IList ExecuteCrawl(bool crawlAll) { IList list = new ArrayList(); int pageInt = 1; string html = string.Empty; string viewState = string.Empty; string eventValidation = string.Empty; string cookiestr = string.Empty; try { html = this.ToolWebSite.GetHtmlByUrl(this.SiteUrl).GetJsString().ToNodeString(); } catch { return(list); } Parser parser = new Parser(new Lexer(html)); NodeList pageNode = parser.ExtractAllNodesThatMatch(new AndFilter(new TagNameFilter("div"), new HasAttributeFilter("class", "c3"))); if (pageNode != null && pageNode.Count > 1) { try { string temp = pageNode.AsString().GetRegexBegEnd("共", "页"); pageInt = int.Parse(temp); } catch { } } else { pageInt = 33; } for (int i = 1; i <= pageInt; i++) { if (i > 1) { try { html = this.ToolWebSite.GetHtmlByUrl(this.SiteUrl + "&num=" + i).GetJsString().ToNodeString(); } catch { continue; } } parser = new Parser(new Lexer(html)); NodeList listNode = parser.ExtractAllNodesThatMatch(new TagNameFilter("li")); if (listNode != null && listNode.Count > 0) { for (int j = 0; j < listNode.Count; j++) { ATag aTag = listNode[j].GetATag(); if (aTag == null) { continue; } string prjName = string.Empty, beginDate = string.Empty, InfoUrl = string.Empty; beginDate = listNode[j].ToPlainTextString().GetDateRegex(); InfoUrl = "http://cs.caac.net" + aTag.Link.GetReplace("&", "&"); prjName = aTag.LinkText.ToNodeString(); if (string.IsNullOrWhiteSpace(prjName) || string.IsNullOrWhiteSpace(beginDate)) { continue; } string htmldtl = string.Empty; try { htmldtl = this.ToolWebSite.GetHtmlByUrl(InfoUrl, Encoding.UTF8).GetJsString(); } catch { continue; } parser = new Parser(new Lexer(htmldtl)); NodeList dtlNode = parser.ExtractAllNodesThatMatch(new AndFilter(new TagNameFilter("div"), new HasAttributeFilter("class", "news_content"))); if (dtlNode == null || dtlNode.Count < 1) { parser.Reset(); dtlNode = parser.ExtractAllNodesThatMatch(new AndFilter(new TagNameFilter("table"), new HasAttributeFilter("class", "vT_detail_content w900c"))); } if (dtlNode != null && dtlNode.Count > 0) { if (prjName.Contains("成交") || prjName.Contains("中标") || prjName.Contains("结果")) { string buildUnit = string.Empty, bidUnit = string.Empty, bidMoney = string.Empty, code = string.Empty, bidDate = string.Empty, endDate = string.Empty, bidType = string.Empty, specType = string.Empty, msgType = string.Empty, bidCtx = string.Empty, prjAddress = string.Empty, remark = string.Empty, prjMgr = string.Empty, otherType = string.Empty, HtmlTxt = string.Empty; HtmlTxt = dtlNode.AsHtml(); bidCtx = HtmlTxt.ToLower().GetReplace("</span>,</p>,<br/>", "\r\n").ToCtxString(); bidUnit = bidCtx.GetBidRegex(); bidMoney = bidCtx.GetMoneyRegex(null, false, "万元"); prjMgr = bidCtx.GetMgrRegex(); buildUnit = bidCtx.GetBuildRegex(); code = bidCtx.GetCodeRegex().GetCodeDel(); if (bidUnit.Contains("公司")) { bidUnit = bidUnit.Remove(bidUnit.IndexOf("公司")) + "公司"; } if (bidUnit.Contains("中标价")) { bidUnit = ""; } if (buildUnit.Contains("公司")) { buildUnit = buildUnit.Remove(buildUnit.IndexOf("公司")) + "公司"; } if (buildUnit.Contains("地址")) { buildUnit = buildUnit.Remove(buildUnit.IndexOf("地址")); } msgType = "广州民航职业技术学院"; specType = "社会招标"; bidType = prjName.GetInviteBidType(); BidInfo info = ToolDb.GenBidInfo("广东省", "广州市区", "", string.Empty, code, prjName, buildUnit, beginDate, bidUnit, beginDate, endDate, bidCtx, string.Empty, msgType, bidType, specType, otherType, bidMoney, InfoUrl, prjMgr, HtmlTxt); list.Add(info); parser = new Parser(new Lexer(HtmlTxt)); NodeList aNode = parser.ExtractAllNodesThatMatch(new TagNameFilter("a")); if (aNode != null && aNode.Count > 0) { for (int k = 0; k < aNode.Count; k++) { ATag a = aNode[k] as ATag; if (a.IsAtagAttach() || a.Link.Contains("File_C")) { string link = string.Empty; if (a.Link.ToLower().Contains("http")) { link = a.Link.GetReplace("&", "&"); } else { link = "http://cs.caac.net/" + a.Link.GetReplace("&", "&"); } if (Encoding.Default.GetByteCount(link) > 500) { continue; } BaseAttach attach = ToolDb.GenBaseAttach(a.LinkText, info.Id, link); base.AttachList.Add(attach); } } } if (!crawlAll && list.Count >= this.MaxCount) { return(list); } } else { string code = string.Empty, buildUnit = string.Empty, prjAddress = string.Empty, inviteCtx = string.Empty, inviteType = string.Empty, specType = string.Empty, endDate = string.Empty, remark = string.Empty, inviteCon = string.Empty, CreateTime = string.Empty, msgType = string.Empty, otherType = string.Empty, HtmlTxt = string.Empty, area = string.Empty; HtmlTxt = dtlNode.AsHtml(); inviteCtx = HtmlTxt.ToCtxString(); prjAddress = inviteCtx.GetAddressRegex(); buildUnit = inviteCtx.GetBuildRegex(); if (buildUnit.Contains("公司")) { buildUnit = buildUnit.Remove(buildUnit.IndexOf("公司")) + "公司"; } if (buildUnit.Contains("地址")) { buildUnit = buildUnit.Remove(buildUnit.IndexOf("地址")); } if (buildUnit.Contains("工程地点") || buildUnit.Contains("武警")) { buildUnit = ""; } code = inviteCtx.GetCodeRegex().GetCodeDel(); msgType = "广州民航职业技术学院"; specType = "社会招标"; inviteType = prjName.GetInviteBidType(); InviteInfo info = ToolDb.GenInviteInfo("广东省", "广州市区", area, string.Empty, code, prjName, prjAddress, buildUnit, beginDate, endDate, inviteCtx, remark, msgType, inviteType, specType, otherType, InfoUrl, HtmlTxt); list.Add(info); parser = new Parser(new Lexer(HtmlTxt)); NodeList aNode = parser.ExtractAllNodesThatMatch(new TagNameFilter("a")); if (aNode != null && aNode.Count > 0) { for (int k = 0; k < aNode.Count; k++) { ATag a = aNode[k] as ATag; if (a.IsAtagAttach() || a.Link.Contains("File_C")) { string link = string.Empty; if (a.Link.ToLower().Contains("http")) { link = a.Link.GetReplace("&", "&"); } else { link = "http://cs.caac.net/" + a.Link.GetReplace("&", "&"); } if (Encoding.Default.GetByteCount(link) > 500) { continue; } BaseAttach attach = ToolDb.GenBaseAttach(a.LinkText, info.Id, link); base.AttachList.Add(attach); } } } if (!crawlAll && list.Count >= this.MaxCount) { return(list); } } } } } } return(list); }
protected override int GetNextAutoIndentSize(string text) { return(Parser.GetNextAutoIndentSize(text, Options.AutoIndentSize)); }
public Module(string name, Store store, byte[] bytes) { Name = name; Store = store; parser = new Parser(bytes, this); if (parser.GetByte() != 0x00 || parser.GetByte() != 0x61 || parser.GetByte() != 0x73 || parser.GetByte() != 0x6D) { throw new Exception("Invalid magic number."); } UInt32 version = parser.GetVersion(); while (!parser.Done()) { byte section = parser.GetByte(); switch (section) { case 0x00: UInt32 sectionSize = parser.GetUInt32(); parser.Skip(sectionSize); break; case 0x01: loadTypes(); continue; case 0x02: loadImports(); continue; case 0x03: loadFunctions(); continue; case 0x04: loadTables(); continue; case 0x05: loadMemory(); continue; case 0x06: loadGlobals(); continue; case 0x07: loadExports(); continue; case 0x08: loadStart(); continue; case 0x09: loadElements(); continue; case 0x0A: loadCode(); continue; case 0x0B: loadData(); continue; default: throw new Exception("Invalid module section ID: 0x" + section.ToString("X")); } } functions = Functions.ToArray(); memory = Memory.ToArray(); globals = Globals.ToArray(); if (startFunction != null) { Store.runtime.Call(startFunction.GlobalIndex); while (Store.Step(1000)) { } } }