public static void Main() { using var outputFile = new StreamWriter("results.out"); ParsedFile inputFile = new ParsedFile("Inputs/testInput.txt"); var lines = inputFile.NextLine().NextElement <int>(); for (int i = 0; i < lines; ++i) { var line = inputFile.NextLine(); var player1 = (int)Enum.Parse(typeof(Item), line.NextElement <string>()); var player2 = (int)Enum.Parse(typeof(Item), line.NextElement <string>()); var players = new[] { player1, player2 }; var result = Math.Abs(player2 - player1) switch { 0 => "-", 1 => ((Item)players.Max()).ToString(), 2 => ((Item)players.Min()).ToString(), _ => throw new Exception(@"¯\_(ツ)_/¯") }; outputFile.WriteLine($"Case #{i + 1}: {result}"); } } }
public void WriteListString() { string path = "WriteListString.txt"; Writer.Clear(path); ICollection <string> vectorToWrite = new List <string>() { "string1", "string2", "string3", "string4" }; string textInFile = string.Empty; string separator = "$"; Writer.WriteLine <ICollection <string>, string>(path, vectorToWrite, separator); IParsedFile file = new ParsedFile(path, separator); while (!file.Empty) { IParsedLine line = file.NextLine(); while (!line.Empty) { textInFile += line.NextElement <string>(); if (!line.Empty) { textInFile += "@"; } } } List <string> vectorInFile = textInFile.Split('@').ToList(); Assert.Equal(vectorToWrite, vectorInFile); }
public void ParsingException() { IParsedFile file = new ParsedFile(_validPath + "Sample_file.txt"); IParsedLine line = file.NextLine(); while (!file.Empty) { line = file.NextLine(); } Assert.Throws <ParsingException>(() => file.NextLine()); while (!line.Empty) { line.NextElement <object>(); } Assert.Throws <ParsingException>(() => line.NextElement <object>()); Queue <string> testQueue = new(new string[] { string.Empty }); ParsedLine testLine = new(testQueue); Assert.Throws <ParsingException>(() => testLine.NextElement <char>()); }
public void ElementAt() { IParsedFile file = new ParsedFile(_sampleFolderPath + "Sample_file.txt"); IParsedLine firstLine = file.NextLine(); string lastElement = firstLine.ElementAt <string>(firstLine.Count - 1); Assert.Equal("food", lastElement); IParsedLine peekedSecondLine = file.PeekNextLine(); int number = peekedSecondLine.ElementAt <int>(1); Assert.Equal(100, number); const double modifiedNumber = 100 + Math.PI; peekedSecondLine.Append($" {modifiedNumber}"); IParsedLine secondLine = file.NextLine(); int numberAgain = secondLine.ElementAt <int>(1); Assert.Equal(number, numberAgain); double addedNumber = secondLine.ElementAt <double>(secondLine.Count - 1); Assert.Equal(modifiedNumber, addedNumber, 10); }
public void Test() { ParsedClass parsedClass = new ParsedClass(TestStringClassOnly, false); if (parsedClass.ParsedMethods.Count < 2) { throw new Exception("ParsedMethod count is too low"); } ParsedFile parsedFile = new ParsedFile(); parsedFile.SetFromContents(TestString, false, false); if (parsedFile.Namespaces.Count == 0) { throw new Exception("ParsedFile namespace is 0 when it shouldn't be"); } if (parsedFile.Namespaces[0].Classes.Count == 0) { throw new Exception("ParsedNamespace class count is 0 when it shouldn't be"); } if (parsedFile.Namespaces[0].Classes[0].ParsedMethods.Count < 2) { throw new Exception("ParsedMethod count is too low"); } }
public void ExtractChar() { const string fileName = "ExtractChar.txt"; const string line1 = "+-*/!?#$%&"; const string line2 = "@()[]{}\""; StringBuilder parsedFile = new(string.Empty); using (StreamWriter writer = new(fileName)) { writer.WriteLine(Math.PI.ToString()); writer.WriteLine(line1); writer.WriteLine(line2); } IParsedFile file = new ParsedFile(fileName); IParsedLine firstParsedLine = file.NextLine(); int nLines = Convert.ToInt32(Math.Floor(firstParsedLine.NextElement <double>())) - 1; for (int iLine = 0; iLine < nLines; ++iLine) { IParsedLine parsedLine = file.NextLine(); while (!parsedLine.Empty) { parsedFile.Append(parsedLine.NextElement <char>()); } parsedFile.Append('\\'); Assert.True(parsedLine.Empty); } Assert.True(file.Empty); Assert.Equal(line1 + '\\' + line2 + '\\', parsedFile.ToString()); }
public void CanFindScss() { var lines = ParsedFile.ReadScssLines("./Samples/Cards/Examples/CardSamples.razor"); var code = ParsedFile.ParseScss(lines); Assert.Equal(35, code.Count); }
private IEnumerable <Input> ParseInputPrivate(string level) { var file = new ParsedFile($"Inputs/{level}"); var numberOfLines = file.NextLine().NextElement <int>(); for (int i = 0; i < numberOfLines; ++i) { var line = file.NextLine().ToSingleString(); var elements = line.Split(","); if (elements.Length != 7) { throw new Exception("Error parsing file"); } yield return(new Input( double.Parse(elements[0]), double.Parse(elements[1]), double.Parse(elements[2]), double.Parse(elements[3]), elements[4], elements[5], double.Parse(elements[6]))); } if (!file.Empty) { throw new Exception("Error parsing file"); } }
public void CustomLineParse() { const string fileName = "CustomLineParse.txt"; const string sampleContent = " 3 1154 508 100 vegetable "; List <long> expectedList = new() { 1154, 508, 100 }; const string expectedString = "vegetable"; using (StreamWriter writer = new(fileName)) { writer.WriteLine(sampleContent); } IParsedLine line = new ParsedFile(fileName).NextLine(); int n_ints = line.NextElement <int>(); for (int i = 0; i < n_ints; ++i) { long data = line.NextElement <long>(); Assert.Equal(expectedList[i], data); } string rawString = line.PeekNextElement <string>(); // Raw string string lastString = line.NextElement <string>(); // Converted string => string Assert.Equal(rawString, lastString); Assert.Equal(expectedString, lastString); Assert.True(line.Empty); }
/// <summary> /// Generate local partial of a file /// </summary> /// <param name="file">File to generate for</param> protected void GenerateLocalPartial(ParsedFile file) { var model = file.Model as ClassModel; if (model == null) { return; } // Find all matching generators and collect their code fragments var fragments = (from gen in Generators.OfType <ILocalGenerator>() where gen.CanExtend(model) select new GeneratorPartial(gen, gen.Extend(model))).ToArray(); if (fragments.Length == 0) { return; } // Initialize and execute the class skeleton template var code = GenerateClass(model.Name, model.AccessModifier, model.Namespace, fragments); Console.WriteLine($"Generated {fragments.Length} fragments of code for {model.Name}."); // Write file var fileName = Path.GetFileNameWithoutExtension(file.Name) + ".Generated.cs"; fileName = Path.Combine(Path.GetDirectoryName(file.Name), fileName); File.WriteAllText(fileName, code); }
public void CanFindDescription() { var lines = ParsedFile.ReadLines(_testFilePath); var description = ParsedFile.ParseDescription(lines); Assert.StartsWith("Single option dropdown selector", description); }
public void CanFindTitle() { var lines = ParsedFile.ReadLines(_testFilePath); var title = ParsedFile.ParseTitle(lines); Assert.Equal("Basic Dropdowns", title); }
public void CanReadFile() { var lines = ParsedFile.ReadLines(_testFilePath); Assert.NotNull(lines); Assert.Equal(34, lines.Count()); }
static void Main(string[] args) { var cultureInfo = new CultureInfo("en-US"); CultureInfo.DefaultThreadCurrentCulture = cultureInfo; List <double> listDouble = new List <double>(); string str; // Input start IParsedFile file = new ParsedFile("SimpleInput.txt"); IParsedLine firstLine = file.NextLine(); int _integer = firstLine.NextElement <int>(); for (int i = 0; i < _integer; ++i) { listDouble.Add(firstLine.NextElement <double>()); } str = firstLine.NextElement <string>(); // Input end // Data Processing // Output start StreamWriter writer = new StreamWriter("..\\C#SimpleOutput.txt"); using (writer) { writer.WriteLine(_integer + " " + string.Join(null, listDouble)); } // Output end }
private ICollection <Event> ParseInput() { ICollection <Event> events = new List <Event>(); IParsedFile parsedFile = new ParsedFile(FilePath); while (!parsedFile.Empty) { IParsedLine parsedLine = parsedFile.NextLine(); string aux = string.Empty; while (!parsedLine.Empty) { aux += $"{parsedLine.NextElement<string>()} "; } string line = aux .Trim() .Replace(" ", " "); Event evnt = ParseEvent(line); evnt.DateTime = ParseDateTime(line); events.Add(evnt); } return(events); }
public void ParsedDoubleWithCommas() { IParsedFile parsedFile = new ParsedFile(Path.Combine(_sampleFolderPath, "DoubleWithCommas.txt")); ValidateSimpleFile(parsedFile.NextLine(), parsedFile.NextLine()); Assert.True(parsedFile.Empty); }
public ParsedFile ParseFileForPlot(FileInfo fileInfo) { var parsed = new ParsedFile { Name = fileInfo.Name, Points = ReadAllLines(fileInfo.FullName) }; return(parsed); }
public void ParsedDoubleWithPointsAndCommasAsThousandSeparators() { IParsedFile parsedFile = new ParsedFile(Path.Combine(_sampleFolderPath, "DoubleWithPointsAndCommasAsThousandsSeparators.txt")); ValidateFileWithPointsAndCommas(parsedFile.NextLine(), parsedFile.NextLine(), parsedFile.NextLine(), parsedFile.NextLine()); Assert.True(parsedFile.Empty); }
public void CanFindHtml() { var lines = ParsedFile.ReadLines(_testFilePath); var html = ParsedFile.ParseHtml(lines); Assert.Equal(7, html.Count); Assert.Contains(@"<AeTypography>", html.First()); Assert.Contains(@"/>", html.Last()); }
private void LoadData() { ParsedFile _file = new ParsedFile(_inputPath); IParsedLine firstLine = _file.NextLine(); /*long gridRow = */ firstLine.NextElement <long>(); /*long gridCol = */ firstLine.NextElement <long>(); //Grid = new Grid(gridRow, gridCol); long n_vehicles = firstLine.NextElement <long>(); for (int i = 0; i < n_vehicles; ++i) { VehicleList.Add(new Vehicle(i)); } long n_rides = firstLine.NextElement <long>(); long bonus = firstLine.NextElement <long>(); TotalSimulationSteps = firstLine.NextElement <long>(); long rideId = 0; while (!_file.Empty) { IParsedLine line = _file.NextLine(); long row = line.NextElement <long>(); long col = line.NextElement <long>(); long endrow = line.NextElement <long>(); long endcol = line.NextElement <long>(); long start = line.NextElement <long>(); long end = line.NextElement <long>(); RideList.Add(new Ride( rideId, bonus, new Position(row, col), new Position(endrow, endcol), start, end, TotalSimulationSteps)); ++rideId; } if (n_rides != RideList.Count) { throw new ParsingException(); } }
public void CanFindCode() { var lines = ParsedFile.ReadLines(_testFilePath); var code = ParsedFile.ParseCode(lines); Assert.Equal(15, code.Count); Assert.Equal("@code {", code.First()); Assert.Equal("}", code.Last()); }
private IEnumerable <string> ReadInputs() { IParsedFile inputFile = new ParsedFile(_inputFilePath); while (!inputFile.Empty) { yield return(inputFile.NextLine().ToSingleString()); } }
public void Parse(ParsedFile parsedFile) { foreach (var part in parsedFile.Parts) { if (part is ParagraphPart paragraph) { } } }
public void ToSingleStringWithEmptyWordSeparatorAndCustomLineSeparator() { IParsedFile parsedFile = new ParsedFile(Path.Combine(_sampleFolderPath, "ToSingleString.txt")); Assert.Equal( "0This1234isalinewithsomelinesoftext404\nSecondline1234\nend", parsedFile.ToSingleString(wordSeparator: string.Empty, lineSeparator: "\n")); Assert.True(parsedFile.Empty); }
public void ToSingleStringWithDefaultSeparators() { IParsedFile parsedFile = new ParsedFile(Path.Combine(_sampleFolderPath, "ToSingleString.txt")); Assert.Equal( "0 This 1234 is a line with some lines of text 404 Second line 1 2 34 end", parsedFile.ToSingleString()); Assert.True(parsedFile.Empty); }
private IEnumerable <ulong> ParseInput() { ParsedFile file = new ParsedFile(InputFilePath); var cases = file.NextLine().NextElement <int>(); for (int i = 0; i < cases; ++i) { yield return(ulong.Parse(file.NextLine().ToSingleString())); } }
public void DifferentFilesSameSeparators() { ICollection <string> sampleSlashes = new ParsedFile(_sampleFolderPath + "Sample_doubleslashes.txt", new char[] { '/', '/' }).ToList <string>(); ICollection <string> modififedSampleSlashes = new ParsedFile(_sampleFolderPath + "SlightlyModified_Sample_doubleslashes.txt", new char[] { '/', '/' }).ToList <string>(); ICollection <string> modififedSampleSlashes2 = new ParsedFile(_sampleFolderPath + "SlightlyModified_Sample_doubleslashes.txt", "//").ToList <string>(); Assert.True(sampleSlashes.Count > 1); Assert.NotEqual(sampleSlashes, modififedSampleSlashes); Assert.NotEqual(sampleSlashes, modififedSampleSlashes2); }
private static async Task <IParseInfo> ParseJson(Uri location, string appId) { try { // Get json object var doc = await GetInfoDoc(location.AbsoluteUri); ParseInfoObject parseInfo = null; await Task.Run(() => { var updateJson = JsonConvert.DeserializeObject <RootObject>(doc); var appUpdate = updateJson.eUpdate.update.FirstOrDefault(x => x.appID == appId); if (appUpdate == null) { return; } // Parse data // If Version is null, then we can't compare assembly versions for update var versionString = appUpdate.version; if (string.IsNullOrWhiteSpace(versionString)) { return; } var version = Version.Parse(versionString); var fileList = new List <IParsedFile>(); foreach (var file in appUpdate.files.file) { var parsedFile = new ParsedFile { FileName = file.fileName, Md5 = file.md5, Url = new Uri(file.url) }; fileList.Add(parsedFile); } var description = appUpdate.description; parseInfo = new ParseInfoObject(version, fileList, description, null); }); return(parseInfo); } catch (Exception) { return(null); } }
public void LineAt() { IParsedFile file = new ParsedFile(_sampleFolderPath + "Sample_file.txt"); IParsedLine lineAt0 = file.LineAt(0); int n = lineAt0.PeekNextElement <int>(); Assert.Equal(23, n); int nPlusOne = n + 1; lineAt0.Append($" {nPlusOne}"); file.Append(new ParsedLine(new[] { nPlusOne.ToString() })); int totalNumberOfLines = file.Count; IParsedLine firstLine = file.NextLine(); int nAgain = firstLine.NextElement <int>(); string str = firstLine.NextElement <string>(); int incrementedN = firstLine.NextElement <int>(); Assert.Equal(n, nAgain); Assert.Equal(nPlusOne, incrementedN); Assert.Equal("food", str); IParsedLine lastLine = file.LastLine(); Assert.Equal(incrementedN, lastLine.PeekNextElement <int>()); for (int lineIndex = 1; lineIndex < totalNumberOfLines - 1; ++lineIndex) { IParsedLine line = file.NextLine(); int counter = line.NextElement <int>(); for (int j = 0; j < counter; ++j) { line.NextElement <int>(); } while (!line.Empty) { line.NextElement <string>(); } } IParsedLine extraLine = file.NextLine(); Assert.Equal(incrementedN, extraLine.NextElement <int>()); Assert.True(extraLine.Empty); Assert.Throws <ArgumentOutOfRangeException>(() => extraLine.ElementAt <string>(1)); Assert.Throws <InvalidOperationException>(() => extraLine.LastElement <string>()); Assert.True(file.Empty); Assert.Throws <ArgumentOutOfRangeException>(() => file.LineAt(1)); Assert.Throws <InvalidOperationException>(() => file.LastLine()); }
private IEnumerable <Rectangle> ParseInput() { ICollection <Rectangle> rectangles = new List <Rectangle>(); IParsedFile parsedFile = new ParsedFile(FilePath); while (!parsedFile.Empty) { IParsedLine parsedLine = parsedFile.NextLine(); string idString = parsedLine.NextElement <string>(); if (!idString.StartsWith("#")) { throw new Exception($"{idString} is not #n"); } int.TryParse(idString.Trim('#'), out int id); if (parsedLine.NextElement <string>() != "@") { throw new Exception($"Exception parsing @"); } string[] x0y0 = parsedLine.NextElement <string>() .Trim(':') .Split(','); if (x0y0.Length != 2) { throw new Exception($"Length of {x0y0} isn't 2"); } int.TryParse(x0y0.First(), out int x0); int.TryParse(x0y0.Last(), out int y0); string[] xy = parsedLine.NextElement <string>() .Split('x'); if (xy.Length != 2) { throw new Exception($"Length of {xy} isn't 2"); } int.TryParse(xy.First(), out int x); int.TryParse(xy.Last(), out int y); if (!parsedLine.Empty) { throw new Exception($"Error parsing line, missing at least {parsedLine.PeekNextElement<string>()}"); } rectangles.Add(new Rectangle(x: x, y: y, x0: x0, y0: y0) { Id = id }); } return(rectangles); }
public static ParsedFile ParseDataFromFile(string rawPost) { var parsedFile = new ParsedFile(); //Get the Header info from a Post Markdown File //Find the first index of --- var startOfSettingsIndex = rawPost.IndexOf("---", StringComparison.InvariantCultureIgnoreCase); if (startOfSettingsIndex >= 0) { //Find the second index of --- after the first var endOfSettingsIndex = rawPost.IndexOf("---", startOfSettingsIndex + 3, StringComparison.InvariantCultureIgnoreCase); //If we find the 2nd index, parse the settings //Otherwise we assume there's no header or settings... if (endOfSettingsIndex >= 0) { parsedFile.Header = rawPost.Substring(startOfSettingsIndex, endOfSettingsIndex + 3); parsedFile.Body = rawPost.Substring(endOfSettingsIndex + 3, rawPost.Length - (endOfSettingsIndex + 3)); } } else { parsedFile.Body = rawPost; } //Everything that goes here will be defined as the excerpt of your blog post... //---end var startOfExcerpt = rawPost.IndexOf("---excerpt", StringComparison.InvariantCultureIgnoreCase); var endOfExcerpt = rawPost.IndexOf("---end", startOfExcerpt + 10, StringComparison.InvariantCultureIgnoreCase); if (startOfExcerpt >= 0 && endOfExcerpt > startOfExcerpt) { parsedFile.Excerpt = rawPost.Substring(startOfExcerpt + 10, endOfExcerpt - (startOfExcerpt + 10)); parsedFile.Body = rawPost.Substring(endOfExcerpt + 6, rawPost.Length - (endOfExcerpt + 6)); } return parsedFile; }