public void Should_cache_added_items() { var cache = new OutputWriter(new NullResponseWriter()); cache.WriteProject(new Project("")); var file = new FileRef("", null); cache.WriteFile(file); cache.WriteUsing(new Using(file, "", 0, 1)); cache.WriteNamespace(new Namespce(file, "", 0, 1)); cache.WriteClass(new Class(file, "", "", "", 0, 0)); cache.WriteInterface(new Interface(file, "", "", "", 0, 0)); cache.WriteStruct(new Struct(file, "", "", "", 0, 0)); cache.WriteEnum(new EnumType(file, "", "", "", 0, 0)); cache.WriteField(new Field(file, "", "", "", 0, 0, "")); cache.WriteMethod( new Method(file, "", "", "", 0, 0, "", new Parameter[] { new Parameter(file, "", "", "", 0, 0, "") })); cache.WriteVariable(new Variable(file, "", "", "", 0, 0, "")); Assert.That(cache.Projects.Count, Is.EqualTo(1)); Assert.That(cache.Files.Count, Is.EqualTo(1)); Assert.That(cache.Usings.Count, Is.EqualTo(1)); Assert.That(cache.Namespaces.Count, Is.EqualTo(1)); Assert.That(cache.Classes.Count, Is.EqualTo(1)); Assert.That(cache.Interfaces.Count, Is.EqualTo(1)); Assert.That(cache.Structs.Count, Is.EqualTo(1)); Assert.That(cache.Enums.Count, Is.EqualTo(1)); Assert.That(cache.Fields.Count, Is.EqualTo(1)); Assert.That(cache.Methods.Count, Is.EqualTo(1)); Assert.That(cache.Parameters.Count, Is.EqualTo(1)); Assert.That(cache.Variables.Count, Is.EqualTo(1)); }
public void Setup() { _globalCache = new OutputWriter(new NullResponseWriter()); _cache = new OutputWriter(new NullResponseWriter()); _resolver = new OutputWriterCacheReader(_cache, _globalCache); buildCache(); }
public OutputWriter Parse(string file) { var dirtyFile = _getDirtyFile(file); var usingDirtyFile = false; if (dirtyFile != null) { dirtyFile = parseDirtyFile(dirtyFile); if (dirtyFile.Trim() != "") { usingDirtyFile = true; file = dirtyFile.Trim(); } } var parser = new NRefactoryParser(); if (_parseLocalVariables) parser.ParseLocalVariables(); var cache = new OutputWriter(new NullResponseWriter()); parser.SetOutputWriter(cache); var fileRef = new FileRef(file, null); parser.ParseFile(fileRef, () => _fileReader(file)); if (usingDirtyFile) _fileRemover(file); cache.BuildTypeIndex(); new TypeResolver(new OutputWriterCacheReader(cache, _globalCache)) .ResolveAllUnresolved(cache); return cache; }
private void createGlobalCache() { _globalCache = new OutputWriter(new NullResponseWriter()); _globalCache .WriteClass(createSystemClass("String")); _globalCache .WriteClass(createSystemClass("Boolean")); }
public void Setup() { _cache = new OutputWriter(new NullResponseWriter()); _parser = new NRefactoryParser() //_parser = new CSharpFileParser() .SetOutputWriter(_cache); _parser.ParseFile(new FileRef("file1", null), () => { return getContent(); }); }
public static void Main(string[] args) { Stream inputStream = Console.OpenStandardInput(); InputReader inp = new InputReader(inputStream); Stream outputStream = Console.OpenStandardOutput(); OutputWriter outp = new OutputWriter(outputStream); Solver algorithm = new Solver(); algorithm.solve(inp, outp); outp.close(); }
public void When_merging_it_will_replace_info_for_the_entire_file() { var cache = new OutputWriter(new NullResponseWriter()); var file = new FileRef("file1", null); cache.WriteFile(file); cache.WriteUsing(new Using(file, "", 0, 1)); cache.WriteNamespace(new Namespce(file, "", 0, 1)); cache.WriteClass(new Class(file, "", "", "", 0, 0)); cache.WriteInterface(new Interface(file, "", "", "", 0, 0)); cache.WriteStruct(new Struct(file, "", "", "", 0, 0)); cache.WriteEnum(new EnumType(file, "", "", "", 0, 0)); cache.WriteField(new Field(file, "", "", "", 0, 0, "")); cache.WriteMethod( new Method(file, "", "", "", 0, 0, "", new Parameter[] { new Parameter(file, "", "", "", 0, 0, "") })); cache.WriteVariable(new Variable(file, "", "", "", 0, 0, "")); var cacheToMerge = new OutputWriter(new NullResponseWriter()); file = new FileRef("file1", null); cacheToMerge.WriteFile(file); cacheToMerge.WriteUsing(new Using(file, "", 0, 1)); cacheToMerge.WriteUsing(new Using(file, "", 0, 1)); cacheToMerge.WriteNamespace(new Namespce(file, "", 0, 1)); cacheToMerge.WriteNamespace(new Namespce(file, "", 0, 1)); cacheToMerge.WriteClass(new Class(file, "", "", "", 0, 0)); cacheToMerge.WriteClass(new Class(file, "", "", "", 0, 0)); cacheToMerge.WriteInterface(new Interface(file, "", "", "", 0, 0)); cacheToMerge.WriteInterface(new Interface(file, "", "", "", 0, 0)); cacheToMerge.WriteStruct(new Struct(file, "", "", "", 0, 0)); cacheToMerge.WriteStruct(new Struct(file, "", "", "", 0, 0)); cacheToMerge.WriteEnum(new EnumType(file, "", "", "", 0, 0)); cacheToMerge.WriteEnum(new EnumType(file, "", "", "", 0, 0)); cacheToMerge.WriteField(new Field(file, "", "", "", 0, 0, "")); cacheToMerge.WriteField(new Field(file, "", "", "", 0, 0, "")); cacheToMerge.WriteMethod( new Method(file, "", "", "", 0, 0, "", new Parameter[] { new Parameter(file, "", "", "", 0, 0, "") })); cacheToMerge.WriteMethod( new Method(file, "", "", "", 0, 0, "", new Parameter[] { new Parameter(file, "", "", "", 0, 0, "") })); cacheToMerge.WriteVariable(new Variable(file, "", "", "", 0, 0, "")); cacheToMerge.WriteVariable(new Variable(file, "", "", "", 0, 0, "")); cache.MergeWith(cacheToMerge); Assert.That(cache.Projects.Count, Is.EqualTo(0)); Assert.That(cache.Files.Count, Is.EqualTo(1)); Assert.That(cache.Usings.Count, Is.EqualTo(2)); Assert.That(cache.Namespaces.Count, Is.EqualTo(2)); Assert.That(cache.Classes.Count, Is.EqualTo(2)); Assert.That(cache.Interfaces.Count, Is.EqualTo(2)); Assert.That(cache.Structs.Count, Is.EqualTo(2)); Assert.That(cache.Enums.Count, Is.EqualTo(2)); Assert.That(cache.Fields.Count, Is.EqualTo(2)); Assert.That(cache.Methods.Count, Is.EqualTo(2)); Assert.That(cache.Parameters.Count, Is.EqualTo(2)); Assert.That(cache.Variables.Count, Is.EqualTo(2)); }
public void WriteResults_Should_WriteAnEntry_When_NoFileExists() { var streamFactory = new Mock<IStreamFactory>(); var memoryStream = new TestStreamContents(); streamFactory.Setup(s => s.GetStream("c:\\dir\\testname.json")).Returns(memoryStream); var target = new OutputWriter("c:\\dir", streamFactory.Object); target.WriteResults("testname", "label", 42); Assert.AreEqual(@"{ ""benchmarkname"": ""testname"", ""data"": [[""label"", 42]] }", memoryStream.Contents); }
static void Main(string[] args) { var reader = new InputReader(); var writer = new OutputWriter(); var playerId = reader.ReadPlayerId(); var player = new Player(playerId, reader, writer); while (true) { player.TakeALook(); player.Attack(); } }
protected ButtonBase(Frc_ExtensionPackage package, bool buttonNeedsQuery, Guid commandSetGuid, int pkgCmdIdOfButton) { Output =OutputWriter.Instance; Package = package; OleMenuCommandService mcs = Package.PublicGetService(typeof(IMenuCommandService)) as OleMenuCommandService; if (mcs != null) { CommandID commandId = new CommandID(commandSetGuid, pkgCmdIdOfButton); OleMenuItem = new OleMenuCommand(ButtonCallback, commandId); if (buttonNeedsQuery) { OleMenuItem.BeforeQueryStatus += QueryCallback; } mcs.AddCommand(OleMenuItem); } }
public void Should_find_basic_namespace() { var cache = new OutputWriter(new NullResponseWriter()); _parser = new NRefactoryParser() .SetOutputWriter(cache); _parser.ParseFile(new FileRef("TestFile", null), () => { return "namespace MyFirstNS {}"; }); var ns = cache.Namespaces.ElementAt(0); Assert.That(ns.File.File, Is.EqualTo("TestFile")); Assert.That(ns.Signature, Is.EqualTo("MyFirstNS")); Assert.That(ns.Name, Is.EqualTo("MyFirstNS")); Assert.That(ns.Line, Is.EqualTo(1)); Assert.That(ns.Column, Is.EqualTo(11)); Assert.That(ns.EndLine, Is.EqualTo(1)); Assert.That(ns.EndColumn, Is.EqualTo(23)); }
public void CompareContent(string userOutputPath, string expectedOutputPath) { try { OutputWriter.WriteMessageOnNewLine("Reading files..."); var mismatchPath = this.GetMismatchPath(expectedOutputPath); var actualOutputLines = File.ReadAllLines(userOutputPath); var expectedOutputLines = File.ReadAllLines(expectedOutputPath); bool hasMismatch; var mismatches = this.GetLinesWithPossibleMismatches(actualOutputLines, expectedOutputLines, out hasMismatch); this.PrintOutput(mismatches, hasMismatch, mismatchPath); OutputWriter.WriteMessageOnNewLine("Files read!"); } catch (IOException ioe) { OutputWriter.DisplayException(ioe.Message); } }
public static void Start(string s) { CounterEngine engine = new CounterEngine(s); Array AllRules = Enum.GetValues(enumType: typeof(CounterRules)); RuleOutput ouptutFile = new RuleOutput(); // string[] Rules = AllRules.Split('|'); Console.WriteLine("You can skip rule by entering -1 for input."); foreach (var rule in AllRules) { List <string> listOfInputs = new List <string>(); System.Diagnostics.Debug.Print(rule.ToString()); var operation = (CounterRules)Enum.Parse(typeof(CounterRules), Convert.ToString(rule)); var description = engine.GetRuleDescription(operation); Console.WriteLine(description); var pattern = @"{(.*?)}"; var matches = Regex.Matches(description, pattern); foreach (var input in matches) { string regExInput = CheckInput(Console.ReadLine()); if (regExInput.Equals(string.Empty)) { break; } listOfInputs.Add(regExInput); } if (listOfInputs.Count > 0) { var outputResult = engine.Process(operation, listOfInputs); string fileName = System.Environment.CurrentDirectory.ToString(); fileName = fileName + "\\" + ouptutFile.GetOutputFileName(operation); fileName = string.Format(fileName, listOfInputs.FirstOrDefault().Replace("|", ""), (listOfInputs.Count > 1)? listOfInputs.Skip(1).First().Replace("|", ""):""); OutputWriter.WriteToFile(outputResult, fileName); } } }
private static void FilterAndTake(Dictionary <string, List <int> > wantedData, Predicate <double> givenFilter, int studentsToTake) { int counterForPrinting = 0; foreach (var studentPoints in wantedData) { if (counterForPrinting == studentsToTake) { break; } var averageScores = studentPoints.Value.Average(); var pecentageOfFullfilment = averageScores / 100; var averageMark = pecentageOfFullfilment * 4 + 2; if (givenFilter(averageMark)) { OutputWriter.PrintStudent(studentPoints); counterForPrinting++; } } }
private void DisplayHelp() { OutputWriter.WriteMessageOnNewLine($"{new string('_', 100)}"); OutputWriter.WriteMessageOnNewLine(string.Format("|{0, -98}|", "make directory - mkdir: path ")); OutputWriter.WriteMessageOnNewLine(string.Format("|{0, -98}|", "traverse directory - ls: depth ")); OutputWriter.WriteMessageOnNewLine(string.Format("|{0, -98}|", "open file - open: file name ")); OutputWriter.WriteMessageOnNewLine(string.Format("|{0, -98}|", "comparing files - cmp: path1 path2")); OutputWriter.WriteMessageOnNewLine(string.Format("|{0, -98}|", "change directory - cdrel:relative path")); OutputWriter.WriteMessageOnNewLine(string.Format("|{0, -98}|", "change directory - cdabs:absolute path")); OutputWriter.WriteMessageOnNewLine(string.Format("|{0, -98}|", "read students data base - readDb: path")); OutputWriter.WriteMessageOnNewLine(string.Format("|{0, -98}|", "Help - help ")); OutputWriter.WriteMessageOnNewLine(string.Format("|{0, -98}|", "filter {courseName} excelent/average/poor take 2/5/all students - filterExcelent ")); OutputWriter.WriteMessageOnNewLine(string.Format("|{0, -98}|", "(the output is written on the console)")); OutputWriter.WriteMessageOnNewLine(string.Format("|{0, -98}|", "order increasing students - order {courseName} ascending/descending take 20/10/all ")); OutputWriter.WriteMessageOnNewLine(string.Format("|{0, -98}|", "(the output is written on the console)")); OutputWriter.WriteMessageOnNewLine(string.Format("|{0, -98}|", "download file - download: path of file (saved in current directory)")); OutputWriter.WriteMessageOnNewLine(string.Format("|{0, -98}|", "download file asinchronously - downloadAsynch: path of file (save in the current directory)")); OutputWriter.WriteMessageOnNewLine(string.Format("|{0, -98}|", "display data entities - displa students/cources ascending/descending")); OutputWriter.WriteMessageOnNewLine(string.Format("|{0, -98}|", "get help – help")); OutputWriter.WriteMessageOnNewLine($"{new string('_', 100)}"); OutputWriter.WriteEmptyLine(); }
private bool RunAllMutationTestsInAssembly() { var testAssembly = Assembly.LoadFrom(_testAssemblyLocation); int tests = 0; int failures = 0; foreach (var type in testAssembly.GetTypes()) { if (!type.IsPublic) { continue; } var mutationTests = type.GetMethods() .Where(m => m.GetCustomAttributes(true).Any(a => a.GetType() == typeof(MutationTestAttribute))); if (mutationTests.Any()) { var testFixtureInstance = Activator.CreateInstance(type); foreach (var mutationTest in mutationTests) { tests++; try { mutationTest.Invoke(testFixtureInstance, null); } catch (MutationTestFailureException) { failures++; } OutputWriter.Write("."); } } } OutputWriter.WriteLine(); _message = String.Format( @"Mutation test summary: {0} passed, {1} failed", tests - failures, failures); return(tests > 0 && failures == 0); }
public void CompareContent(string firstPath, string secondPath) { try { OutputWriter.WriteMessageOnNewLine("Reading files..."); string mismatchesPath = this.GetMismatchPath(secondPath); string[] actualOutputLines = File.ReadAllLines(firstPath); string[] expectedOutputLines = File.ReadAllLines(secondPath); bool hasMismatch; string[] mismatches = this.GetLineWithPossibleMismatches(actualOutputLines, expectedOutputLines, out hasMismatch); this.PrintOutput(mismatches, hasMismatch, mismatchesPath); OutputWriter.WriteMessageOnNewLine("Files read!"); } catch (IOException ioEx) { Console.WriteLine(ioEx.Message); } }
public void OrderAndTake(Dictionary <string, double> studentMarks, string comparison, int studentsToTake) { comparison = comparison.ToLower(); if (comparison == "ascending") { this.PrintStudents(studentMarks .OrderBy(x => x.Value) .Take(studentsToTake) .ToDictionary(pair => pair.Key, pair => pair.Value)); } else if (comparison == "descending") { this.PrintStudents(studentMarks .OrderByDescending(x => x.Value) .Take(studentsToTake) .ToDictionary(pair => pair.Key, pair => pair.Value)); } else { OutputWriter.DisplayException(ExceptionMessages.InvalidComparisonQuery); } }
public static void CompareContent(string userOutputPath, string expectedOutputPath) { try { OutputWriter.WriteMessageOnNewLine("Reading files..."); string mismatchPath = GetMismatchPath(expectedOutputPath); string[] actualOutputLines = File.ReadAllLines(userOutputPath); string[] expectedOutputLines = File.ReadAllLines(expectedOutputPath); bool hasMismatch; string[] mismatches = GetLinesWithPossibleMismatches(actualOutputLines, expectedOutputLines, out hasMismatch); PrintOutput(mismatches, hasMismatch, mismatchPath); OutputWriter.WriteMessageOnNewLine("Files read!"); } catch (FileNotFoundException) { OutputWriter.DisplayMessage(ExceptionMessages.InvalidPath); } }
private async void SolveAndOutput_Click(object sender, RoutedEventArgs e) { var instances = GetInstances().Skip(int.Parse(InstanceOffset.Text)) .Take(int.Parse(NumberOfInstances.Text)) .ToList(); var results = await SolveInstances(instances, false); var solutionInfoBuilder = new StringBuilder(); solutionInfoBuilder.AppendLine($"Min epsilon: {results.Select(r => r.Epsilon).Min()}"); solutionInfoBuilder.AppendLine($"Avg epsilon: {results.Select(r => r.Epsilon).Average()}"); solutionInfoBuilder.AppendLine($"Max epsilon: {results.Select(r => r.Epsilon).Max()}"); solutionInfoBuilder.AppendLine($"Min runtime: {results.Select(r => r.RunTimeMs).Min()}"); solutionInfoBuilder.AppendLine($"Avg runtime: {results.Select(r => r.RunTimeMs).Average()}"); solutionInfoBuilder.AppendLine($"Max runtime: {results.Select(r => r.RunTimeMs).Max()}"); solutionInfoBuilder.AppendLine($"Number of unsatisfied: {results.Aggregate(0, (acc, res) => res.Configuration.IsSatisfiable() ? acc : acc + 1)}"); SolutionInfo.Text = solutionInfoBuilder.ToString(); var outputLocation = System.IO.Path.Join(OutputFolder.Text, OutputFileName.Text); OutputWriter.WriteAllResults(results, outputLocation); }
public Sandbox(RantEngine engine, RantPattern pattern, RNG rng, int sizeLimit = 0, RantPatternArgs args = null) { _engine = engine; _format = engine.Format; _sizeLimit = new Limit(sizeLimit); _baseOutput = new OutputWriter(this); _outputs = new Stack <OutputWriter>(); _outputs.Push(_baseOutput); _rng = rng; _startingGen = rng.Generation; _pattern = pattern; _objects = new ObjectStack(engine.Objects); _blocks = new Stack <BlockState>(); _matches = new Stack <Match>(); _queryState = new QueryState(); _subroutineArgs = new Stack <Dictionary <string, RantAction> >(); _syncManager = new SyncManager(this); _blockManager = new BlockManager(); _scriptObjectStack = new Stack <object>(); _patternArgs = args; _stopwatch = new Stopwatch(); }
private string[] GetLineWithPossibleMismatches(string[] actualOutputLines, string[] expectedOutputLines, out bool hasMismatch) { hasMismatch = false; string output = string.Empty; OutputWriter.WriteMessageOnNewLine("Comparing files..."); int minOutputLines = actualOutputLines.Length; if (actualOutputLines.Length != expectedOutputLines.Length) { hasMismatch = true; minOutputLines = Math.Min(actualOutputLines.Length, expectedOutputLines.Length); OutputWriter.DisplayException(ExceptionMessages.ComparisonOfFilesWithDifferentSizes); } string[] mismatches = new string[minOutputLines]; for (int index = 0; index < minOutputLines; index++) { string actualLine = actualOutputLines[index]; string expectedLine = expectedOutputLines[index]; if (!actualLine.Equals(expectedLine)) { output = string.Format( $"Mismatch at line {index} -- expected: \"{expectedLine}\", actual: \"{actualLine}\""); output += Environment.NewLine; hasMismatch = true; } else { output = actualLine; output += Environment.NewLine; } mismatches[index] = output; } return(mismatches); }
private void FilterAndTake(Dictionary <string, List <int> > wantedData, Predicate <double> givenFilter, int studentsToTake) { int counter = 0; foreach (var username_score in wantedData) { if (counter == studentsToTake) { break; } var avrScore = username_score.Value.Average(); var percentageOfFullfillments = avrScore / 100; var mark = percentageOfFullfillments * 4 + 2; if (givenFilter(mark)) { OutputWriter.PrintStudent(username_score); counter++; } } }
private void DisplayHelp() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine($"{new string('_', 100)}"); stringBuilder.AppendLine(string.Format("|{0, -98}|", "make directory - mkdir nameOfFolder")); stringBuilder.AppendLine(string.Format("|{0, -98}|", "traverse directory - ls depth")); stringBuilder.AppendLine(string.Format("|{0, -98}|", "comparing files - cmp absolutePath1 absolutePath2")); stringBuilder.AppendLine(string.Format("|{0, -98}|", "change directory - cdRel relativePath or \"..\" for level up")); stringBuilder.AppendLine(string.Format("|{0, -98}|", "change directory - cdAbs absolutePath")); stringBuilder.AppendLine(string.Format("|{0, -98}|", "read students data base - readDb fileName")); stringBuilder.AppendLine(string.Format("|{0, -98}|", "filter {courseName} excelent/average/poor take 2/5/all students - filterExcelent (the output is written on the console)")); stringBuilder.AppendLine(string.Format("|{0, -98}|", "order increasing students - order {courseName} ascending/descending take 20/10/all (the output is written on the console)")); stringBuilder.AppendLine(string.Format("|{0, -98}|", "download file - download URL (saved in current directory)")); stringBuilder.AppendLine(string.Format("|{0, -98}|", "download file asinchronously - downloadAsynch URL (saved in the current directory)")); stringBuilder.AppendLine(string.Format("|{0, -98}|", "get help – help")); stringBuilder.AppendLine(string.Format("|{0, -98}|", "display data entities - display students/courses ascending/descending")); stringBuilder.AppendLine($"{new string('_', 100)}"); stringBuilder.AppendLine(); OutputWriter.WriteMessageOnNewLine(stringBuilder.ToString()); }
public void CompareContent(string userOutputPath, string expectedOutputPath) { OutputWriter.WriteMessageOnNewLine("Reading files..."); try { string mismatchPath = this.GetMismathPath(expectedOutputPath); string[] actualOutputLines = File.ReadAllLines(userOutputPath); string[] expectedOutputLines = File.ReadAllLines(expectedOutputPath); bool hasMismatch; string[] mismatches = this.GetLinesWithPossibleMismatches(actualOutputLines, expectedOutputLines, out hasMismatch); this.PrintOutput(mismatches, hasMismatch, mismatchPath); OutputWriter.WriteMessageOnNewLine("Files read!"); } catch (IOException) { throw new InvalidPathException(); } }
private static string[] GetLinesWithPossibleMismatches(string[] actualOutputLines, string[] expectedOutputLines, out bool hasMismatch) { hasMismatch = false; string output = string.Empty; string[] mismatches = new string[actualOutputLines.Length]; OutputWriter.WriteMessageOnNewLine("Comparing files..."); int minOutputLines = actualOutputLines.Length; if (actualOutputLines.Length != expectedOutputLines.Length) { hasMismatch = true; minOutputLines = Math.Min(actualOutputLines.Length, expectedOutputLines.Length); OutputWriter.DisplayMessage(ExceptionMessages.ComparisonOfFilesWithDifferentSizes); } for (int i = 0; i < minOutputLines; i++) { string actualLine = actualOutputLines[i]; string expectedLine = expectedOutputLines[i]; if (actualLine != expectedLine) { output = $"Mismatch at line {i} -- expected: \"{expectedLine}\", actual: \"{actualLine}\""; output += Environment.NewLine; hasMismatch = true; } else { output = actualLine; output += Environment.NewLine; } mismatches[i] = output; } return(mismatches); }
public void TakeConsoleInputAndWriteFieldsToConsoleOutput() { const string expectedFirstHeader = "Field #1:"; var expectedFirstField = "*100" + Environment.NewLine + "2210" + Environment.NewLine + "1*10" + Environment.NewLine + "1110"; const string expectedSecondHeader = "Field #2:"; var expectedSecondField = "**100" + Environment.NewLine + "33200" + Environment.NewLine + "1*100"; var mockInputStream = new Mock <TextReader>(); mockInputStream.SetupSequence(i => i.ReadLine()) .Returns("44") .Returns("*...") .Returns("....") .Returns(".*..") .Returns("....") .Returns("35") .Returns("**...") .Returns(".....") .Returns(".*...") .Returns("00"); var mockOutputStream = new Mock <TextWriter>(); var consoleReader = new InputReader(mockInputStream.Object); var consoleWriter = new OutputWriter(mockOutputStream.Object); var game = new Game(consoleReader, consoleWriter); game.Run(); mockOutputStream.Verify(m => m.WriteLine(expectedFirstHeader), Times.Once); mockOutputStream.Verify(m => m.WriteLine(expectedFirstField), Times.Once); mockOutputStream.Verify(m => m.WriteLine(expectedSecondHeader), Times.Once); mockOutputStream.Verify(m => m.WriteLine(expectedSecondField), Times.Once); }
public Sandbox(RantEngine engine, RantProgram pattern, RNG rng, int sizeLimit = 0, CarrierState carrierState = null, RantProgramArgs args = null) { // Public members RNG = rng; StartingGen = rng.Generation; Engine = engine; Format = engine.Format; SizeLimit = new Limit(sizeLimit); Pattern = pattern; PatternArgs = args; // Private members _blockManager = new BlockAttribManager(); _stopwatch = new Stopwatch(); _carrierState = carrierState; // Output initialization BaseOutput = new OutputWriter(this); _outputs = new Stack <OutputWriter>(); _outputs.Push(BaseOutput); }
private void ReportResult(bool result, MutationTestingReportSummary reportSummary = null) { var formatOption = Options.Options.OfType <Format>().FirstOrDefault(); if (_outputOption != null && formatOption != null && formatOption.OutputFormat == "HTML") { FormatOutput(_outputPath); } OutputWriter.WriteLine(); var statusColor = result ? ConsoleColor.Green : ConsoleColor.Red; using (new OutputWriterHighlight(statusColor)) { if (reportSummary != null) { OutputWriter.WriteLine(reportSummary.ToString()); } OutputWriter.WriteLine(_message); } }
public static void OrderAndTake(Dictionary <string, List <int> > wantedData, string comparison, int studentsToTake) { comparison = comparison.ToLower(); if (comparison == "ascending") { PrintStudents(wantedData .OrderBy(x => x.Value.Sum()) .Take(studentsToTake) .ToDictionary(pair => pair.Key, pair => pair.Value)); } else if (comparison == "descending") { PrintStudents(wantedData .OrderByDescending(x => x.Value.Sum()) .Take(studentsToTake) .ToDictionary(pair => pair.Key, pair => pair.Value)); } else { OutputWriter.DisplayException(ExceptionMessages.InvalidComparisonQuery); } }
protected void GetPricingTest(IPublicPricingProvider provider, List <AssetPair> pairs, bool firstPriceLessThan1, bool?firstVolumeBaseBiggerThanQuote = null) { OutputWriter.WriteLine("Pricing interface test\n\n"); if (provider.PricingFeatures.HasSingle) { OutputWriter.WriteLine("\nSingle features test\n"); var context = new PublicPriceContext(pairs.First()) { RequestStatistics = provider.PricingFeatures.Single.CanStatistics, RequestVolume = provider.PricingFeatures.Single.CanVolume }; InternalGetPriceAsync(provider, context, true, firstPriceLessThan1, firstVolumeBaseBiggerThanQuote); } if (provider.PricingFeatures.HasBulk) { OutputWriter.WriteLine("\nBulk features test with pairs selection\n"); var context = new PublicPricesContext(pairs) { RequestStatistics = provider.PricingFeatures.Bulk.CanStatistics, RequestVolume = provider.PricingFeatures.Bulk.CanVolume }; InternalGetPriceAsync(provider, context, false, firstPriceLessThan1, firstVolumeBaseBiggerThanQuote); if (provider.PricingFeatures.Bulk.CanReturnAll) { OutputWriter.WriteLine("\nBulk features test (provider can return all prices)\n"); context = new PublicPricesContext(); InternalGetPriceAsync(provider, context, false, firstPriceLessThan1, firstVolumeBaseBiggerThanQuote); } } TestVolumePricingSanity(provider, pairs); }
public Move Query(Board board, MoveOrganizer moveOrganizer) { int totalQuaryVal = 0; m_queryMoves.Clear(); foreach (Move move in moveOrganizer) { if (move.Execute(board)) { int currentQueryVal = 0; if (board.State.NonHitAndPawnMovesPlayed < 100 && board.BoardHistoryFrequency() < 3 && m_positionTable.TryGetValue(board.BoardHash(false), out currentQueryVal)) { totalQuaryVal += currentQueryVal; m_queryMoves.Add(new QueryEntry(move, currentQueryVal)); } move.UnExecute(board); } } //select a move using probabilety based on the quary value int selectValueCurrent = 0; int selectValueTarget = (int)Math.Round(m_moveSelector.NextDouble() * totalQuaryVal); for (int i = 0; i < m_queryMoves.Count; ++i) { selectValueCurrent += m_queryMoves[i].QueryScore; if (selectValueCurrent >= selectValueTarget) { OutputWriter.Write("Book moves: " + m_queryMoves.Count + ", Selecting: " + Math.Round((float)m_queryMoves[i].QueryScore / (float)totalQuaryVal, 6)); return(m_queryMoves[i].QueryMove); } } return(null); }
private static bool CopyConfigFile(string startPath, string resultPath) { var filesAreDifferent = false; if (startPath != resultPath) { filesAreDifferent = true; if (File.Exists(resultPath)) { filesAreDifferent = !FileEquals(startPath, resultPath); } if (filesAreDifferent) { try { if (File.Exists(resultPath)) { OutputWriter.Write($"Deleting existing temp config file at {resultPath}"); File.Delete(resultPath); } OutputWriter.Write($"Writing config {resultPath}"); File.Copy(startPath, resultPath); } catch (IOException io) { OutputWriter.Write($"An exception occured copying {startPath} to {resultPath}: {io}"); } catch (Exception e) { OutputWriter.Write(e, true); } } } return(filesAreDifferent); }
private void DisplayOrderStatusInfo(TradeOrderStatus tradeOrderStatus, AssetPair market) { OutputWriter.WriteLine($"Remote trade order id: {tradeOrderStatus.RemoteOrderId}"); var marketString = tradeOrderStatus.HasMarket ? tradeOrderStatus.Market: market; OutputWriter.WriteLine($"{(tradeOrderStatus.IsBuy ? "Buy" : "Sell")} {tradeOrderStatus.AmountInitial ?? Decimal.MinValue} for {tradeOrderStatus.Rate ?? Decimal.MinValue} on '{marketString}' market"); if (tradeOrderStatus.AmountFilled.HasValue) { OutputWriter.WriteLine($"Filled amount is {tradeOrderStatus.AmountFilled.Value}"); } if (tradeOrderStatus.AmountRemaining.HasValue) { OutputWriter.WriteLine($"Remaining amount is {tradeOrderStatus.AmountRemaining.Value}"); } if (tradeOrderStatus.IsOpen) { OutputWriter.WriteLine("Order is open"); } if (tradeOrderStatus.IsCanceled) { OutputWriter.WriteLine("Order is canceled"); } if (tradeOrderStatus.IsClosed) { OutputWriter.WriteLine("Order is closed"); } if (tradeOrderStatus.IsCancelRequested) { OutputWriter.WriteLine("Order is requested to be canceled"); } OutputWriter.WriteLine(""); }
public override bool TryParse() { if (!base.TryParse()) { return(false); } // iteration index Index = Node.Data.IndexSpecified ? Node.Data.Index : 0; if (Index <= 0) { OutputWriter.WriteLine(Properties.Resources.ErrMsg_Input_InvalidGUITestIterationIndex, Index.ToString()); return(false); } // actions Actions.Clear(); ReportNodeType[] childNodes = Node.ReportNode; if (childNodes != null) { foreach (ReportNodeType node in childNodes) { ActionReport action = Actions.TryParseAndAdd(node, this.Node); if (action != null) { AllStepsEnumerator.Merge(action.AllStepsEnumerator); continue; } } } if (Actions.Length == 0) { // no action node is parsed successfully under the iteration node, it is not a valid GUI test Xml report return(false); } return(true); }
private void DisplayHelp() { OutputWriter.WriteMessageOnNewLine($"{new string('_', 100)}"); OutputWriter.WriteMessageOnNewLine($"|{"make directory - mkdir: path ",-98}|"); OutputWriter.WriteMessageOnNewLine($"|{"traverse directory - ls: depth ",-98}|"); OutputWriter.WriteMessageOnNewLine($"|{"comparing files - cmp: path1 path2",-98}|"); OutputWriter.WriteMessageOnNewLine($"|{"change directory - changeDirREl:relative path",-98}|"); OutputWriter.WriteMessageOnNewLine($"|{"change directory - changeDir:absolute path",-98}|"); OutputWriter.WriteMessageOnNewLine($"|{"read students data base - readDb: path",-98}|"); OutputWriter.WriteMessageOnNewLine( $"|{"filter {courseName} excelent/average/poor take 2/5/all students - filterExcelent (the output is written on the console)",-98}|"); OutputWriter.WriteMessageOnNewLine( $"|{"order increasing students - order {courseName} ascending/descending take 20/10/all (the output is written on the console)",-98}|"); OutputWriter.WriteMessageOnNewLine( $"|{"download file - download: path of file (saved in current directory)",-98}|"); OutputWriter.WriteMessageOnNewLine( $"|{"download file asinchronously - downloadAsynch: path of file (save in the current directory)",-98}|"); OutputWriter.WriteMessageOnNewLine($"|{"get help – help",-98}|"); OutputWriter.WriteMessageOnNewLine($"{new string('_', 100)}"); OutputWriter.WriteMessageOnNewLine( $"|{"display data entities - display students/courses ascending/descending",-98}|"); OutputWriter.WriteEmptyLine(); }
public virtual Task Send(object value) { Context.Response.ContentType = IsJsonp ? Json.JsonpMimeType : Json.MimeType; return(EnqueueOperation(() => { if (IsJsonp) { OutputWriter.Write(JsonpCallback); OutputWriter.Write("("); } _jsonSerializer.Serialize(value, OutputWriter); if (IsJsonp) { OutputWriter.Write(");"); } OutputWriter.Flush(); return Context.Response.EndAsync(); })); }
private void TryParseParametersForFilterAndTake(string takeQuantity, string takeCommand, string filter, string courseName) { if (takeCommand == "take") { if (takeQuantity == "all") { this.Repository.FilterAndTake(courseName, filter); } else { int studenToTake; bool hasParsed = int.TryParse(takeQuantity, out studenToTake); if (hasParsed) { this.Repository.FilterAndTake(courseName, filter, studenToTake); } } } else { OutputWriter.DisplayException(ExceptionMessages.InvalidTakeQuantityParameter); } }
public void WritesNumericAcrossSpanBoundaries(int gapSize) { var writerBuffer = _pipe.Writer; var writer = OutputWriter.Create(writerBuffer); // almost fill up the first block var spacer = new byte[writer.Span.Length - gapSize]; writer.Write(spacer); var bufferLength = writer.Span.Length; writer.WriteNumeric(ulong.MaxValue); Assert.NotEqual(bufferLength, writer.Span.Length); writerBuffer.FlushAsync().GetAwaiter().GetResult(); var reader = _pipe.Reader.ReadAsync().GetAwaiter().GetResult(); var numAsString = ulong.MaxValue.ToString(); var written = reader.Buffer.Slice(spacer.Length, numAsString.Length); Assert.False(written.IsSingleSegment, "The buffer should cross spans"); AssertExtensions.Equal(Encoding.ASCII.GetBytes(numAsString), written.ToArray()); }
public override void Execute() { if (this.Data.Length < 2) { this.inputOutputIoManager.TraverseDirectory(0); } else if (this.Data.Length == 2) { int depth; if (int.TryParse(this.Data[1], out depth)) { this.inputOutputIoManager.TraverseDirectory(depth); } else { OutputWriter.DisplayException(ExceptionMessages.UnableToParseNumber); } } else { throw new InvalidCommandParametersCountException(this.Data[0]); } }
private static void FilterAndTake(Dictionary <string, List <int> > wantedData, Predicate <double> givenFilter, int studentsToTake) { int counterForPrinted = 0; foreach (var userName_Points in wantedData) { if (counterForPrinted == studentsToTake) { break; } double averageScore = userName_Points.Value.Average(); double percentageOfFullfilment = averageScore / 100; double averageMark = percentageOfFullfilment * 4 + 2; if (givenFilter(averageMark)) { OutputWriter.PrintStudent(userName_Points); counterForPrinted++; } } }
public void Execute(IResponseWriter writer, string[] args) { var output = new OutputWriter(writer); if (args.Length != 1) { output.WriteError("crawl-source requires one parameters which is path to the " + "file containing files/directories to crawl"); return; } var crawler = new CSharpCrawler(output, _mainCache); if (Directory.Exists(args[0])) { crawler.Crawl(new CrawlOptions(args[0])); } else { var lines = File .ReadAllText(args[0]) .Split(new string[] { Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries).ToList(); if (lines.Count > 0 && File.Exists(lines[0]) || Directory.Exists(lines[0])) { lines.ForEach(x => crawler.Crawl(new CrawlOptions(x))); } else { crawler.Crawl(new CrawlOptions(args[0])); } } System.Threading.ThreadPool.QueueUserWorkItem((m) => { lock (_mainCache) { Logger.Write("Merging crawl result into cache"); var cacheToMerge = (IOutputWriter)m; if (_mainCache == null) return; _mainCache.MergeWith(cacheToMerge); Logger.Write("Disposing and cleaning up"); cacheToMerge.Dispose(); GC.Collect(5); } }, output); }
internal Dictionary<string, string> GenerateSuper(Type type) { if (!IsApplicableForGeneration(type)) return null; var ret = new Dictionary<string, string>(); foreach (var method in GetApplicableControllerMethods(type)) { var outputWriter = new OutputWriter(); outputWriter.Write("namespace ") .Write(Utils.GetNamespace(type.Namespace, _options.NamespaceSubstitution)).EndLine() .Write("{").EndLine() .Indent(); outputWriter.Write("[DependencyDefinition]") .EndLine(); outputWriter.Write("public class ").Write(GetServiceTypeName(type.Name, method.Name)) .Write(" : ").Write(GetServiceBaseTypeName(type.Name, method.Name)).EndLine() .Write("{").EndLine() .Write("}").EndLine(); outputWriter .Unindent() .Write("}").EndLine().EndLine() .Unindent(); ret[Utils.GetNamespace(type.Namespace, _options.NamespaceSubstitution) + "." + GetServiceTypeName(type.Name, method.Name)] = outputWriter.ToString(); } return ret; }
public Player(int id, InputReader reader, OutputWriter writer) { this.id = id; this.entityFactory = EntityFactory.CreateChain(id); this.reader = reader; this.writer = writer; this.updateMethods = new Dictionary<Type, Action<Entity>> { { typeof(Droplet), e => UpdateDroplet(e as Droplet) }, { typeof(Chip), e => UpdateChip(e as Chip) } }; this.ownChips = new List<Chip>(); this.enemies = new List<Chip>(); this.powers = new List<Droplet>(); }
public OutputWriterTests() { outputWriter = new OutputWriter(); }
internal string GenerateBase(Type type) { if (!IsApplicableForGeneration(type)) return null; var outputWriter = new OutputWriter(); foreach (var method in GetApplicableControllerMethods(type)) { var clientServiceAttribute = (ClientServiceAttribute)method.GetCustomAttributes(typeof(ClientServiceAttribute), true)[0]; var returnType = clientServiceAttribute.ReturnType; var args = _argumentTypes[type.FullName + ":" + method.Name]; outputWriter.Write("namespace ") .Write(Utils.GetNamespace(type.Namespace, _options.NamespaceSubstitution)).EndLine() .Write("{").EndLine() .Indent(); outputWriter.Write("public class ").Write(GetServiceBaseTypeName(type.Name, method.Name)) .Write(" : Service") .Write("<"); if (args.Arguments.Count > 0) outputWriter.Write(args.GeneratedTypeName).Write(","); else outputWriter.Write("object,"); outputWriter.Write(Utils.GetViewModelTypeNameWithNamespace(returnType, _viewModelGeneratorOptions.NamespaceSubstitution)).Write(">") //outputWriter.Write(Utils.GetNamespace(returnType.Namespace, _options.NamespaceSubstitution) + "." + Utils.GetViewModelTypeName(returnType)).Write(">") .EndLine() .Write("{").EndLine() .Indent(); // Call method outputWriter.Write("public override void Call("); if (args.Arguments.Count > 0) outputWriter.Write(args.GeneratedTypeName).Write(" query"); else outputWriter.Write("object ignored = null"); outputWriter.Write(")").EndLine() .Write("{").EndLine() .Indent(); if (args.Arguments.Count > 0) outputWriter.Write("DoCall(query);").EndLine(); else outputWriter.Write("DoCall();").EndLine(); outputWriter .Unindent() .Write("}").EndLine(); // AddOnCompleteCallback method /* var returnType = clientServiceAttribute.ReturnType; outputWriter.Write("public void AddOnCompleteCallback(Action<Dictionary<string, object>> callback)").EndLine() .Write("{").EndLine() .Indent() .Write("DoAddOnSuccessCallback(callback);").EndLine() .Unindent() .Write("}").EndLine(); */ // overridable HttpMethod { get; } property var isPost = method.GetCustomAttributes(typeof(HttpPostAttribute), true).Length != 0; var acceptVerbsAttributes = (AcceptVerbsAttribute)method.GetCustomAttributes(typeof(AcceptVerbsAttribute), true).FirstOrDefault(); if (acceptVerbsAttributes != null && acceptVerbsAttributes.Verbs.Select(x => x.ToUpper()).Any(x => x == "POST")) isPost = true; if (isPost) { outputWriter.Write("public override string HttpMethod").EndLine() .Write("{").EndLine() .Indent() .Write("get { return \"").Write("POST").Write("\"; }").EndLine() .Unindent() .Write("}").EndLine(); } // overrideable InstantiateModel method // if using a model /* if (!Utils.PrimitiveTypes.Contains(returnType)) { outputWriter.Write("protected override object InstantiateModel(Dictionary<string, object> returnValue)").EndLine() .Write("{").EndLine() .Indent() .Write(GetReturnTypeForInstantiateMethod(returnType)).Write(" x = new ").Write(GetReturnTypeForInstantiateMethod(returnType)).Write("();").EndLine() .Write("x.Set(returnValue, null);").EndLine() .Write("return x;").EndLine() .Unindent() .Write("}").EndLine(); } */ outputWriter.Write("public override string GetUrl()").EndLine() .Write("{").EndLine() .Indent() .Write("return \"/") .Write(type.Name.Replace("Controller", "")) .Write("/") .Write(method.Name) .Write("\";").EndLine() .Unindent() .Write("}").EndLine(); // end class outputWriter .Unindent() .Write("}").EndLine(); // end namespace outputWriter .Unindent() .Write("}").EndLine().EndLine(); } return outputWriter.ToString(); }
internal string GenerateBase(Type type) { var outputWriter = new OutputWriter(); outputWriter.Write("namespace ") .Write(Utils.GetNamespace(type.Namespace, _options.NamespaceSubstitution)).EndLine() .Write("{").EndLine() .Indent() .Write("public class ").Write(GetViewModelBaseTypeName(type)); var isInheritsFromOtherViewModel = type.BaseType != typeof (Object); if (isInheritsFromOtherViewModel) { // assume this has already been validated outputWriter.Write(" : ").Write(Utils.GetViewModelTypeNameWithNamespace(type.BaseType, _options.NamespaceSubstitution)); _nestedPropertyTypes.Add(type.BaseType); } else { var idProperty = type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly). FirstOrDefault(p => p.Name == "Id"); var idPropertyType = typeof (int); if (idProperty != null) idPropertyType = idProperty.PropertyType; outputWriter.Write(" : ViewModel<").Write(idPropertyType.FullName).Write(">"); } outputWriter .EndLine() .Write("{").EndLine() .Indent(); // write getter/setters for individual properties foreach(var p in type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)) { if (p.GetCustomAttributes(typeof(ViewModelIgnoreAttribute), true).Any()) continue; if (p.Name == "Id") continue; var returnTypeName = GetPropertyTypeNameForMethodSignature(p.PropertyType, false); var implementationTypeName = GetPropertyTypeNameForMethodSignature(p.PropertyType); var jsPropertyName = GetJsPropertyName(p.Name); outputWriter.Write("public ").Write(returnTypeName).Write(" ").Write(p.Name) .EndLine() .Write("{").EndLine() .Indent() .Write("[InlineCode(\"{this}.get('").Write(jsPropertyName).Write("')\")]").EndLine() //.Write("get { return ").Write("GetProperty<").Write(propertyTypeName).Write(">(\"").Write(jsPropertyName).Write("\"); }").EndLine() .Write("get { return default(").Write(implementationTypeName).Write("); }").EndLine() .Write("[InlineCode(\"{this}.set({{'").Write(jsPropertyName).Write("': {value}}})\")]").EndLine() //.Write("set { SetProperty(\"").Write(jsPropertyName).Write("\", value); }").EndLine() .Write("set { }").EndLine() .Unindent() .Write("}").EndLine(); outputWriter.EndLine(); } // write 'Set' method to update object from JSON var settableProperties = 0; foreach (var p in type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)) { if (!ShouldHaveSpecialSetOverride(p)) continue; settableProperties++; } settableProperties = 1; // TODO NCU TMP if (settableProperties > 0) { //outputWriter.Write("[PreserveCase]").EndLine(); outputWriter.Write("public override bool SetFromJSON(JsDictionary<string, object> json, ViewSetOptions options)").EndLine() .Write("{").EndLine() .Indent() .Write("if (json == null)").EndLine() .Indent() .Write("return true;").EndLine() .Unindent(); foreach (var p in type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)) { if (!ShouldHaveSpecialSetOverride(p)) continue; var jsPropertyName = GetJsPropertyName(p.Name); outputWriter.Write("if (json.ContainsKey(\"").Write(jsPropertyName).Write("\"))").EndLine() .Write("{").EndLine() .Indent(); if (IsViewModelType(p.PropertyType)) { // ViewModel outputWriter.Write("if (this.").Write(p.Name).Write(" != null)").EndLine() .Write("{").EndLine() .Indent() .Write("if (this.").Write(p.Name).Write(".SetFromJSON((JsDictionary<string, object>)json[\"").Write(jsPropertyName).Write("\"], options))").EndLine() .Indent() .Write("json.Remove(\"").Write(jsPropertyName).Write("\");").EndLine() .Unindent() .Write("else").EndLine() .Indent() .Write("return false;").EndLine() .Unindent() .Unindent() .Write("}").EndLine() .Write("else").EndLine() .Write("{").EndLine() .Indent() .Write(GetPropertyTypeNameForMethodSignature(p.PropertyType, false)).Write(" x = new ").Write(GetPropertyTypeNameForMethodSignature(p.PropertyType)).Write("();").EndLine() .Write("if (!x.SetFromJSON((JsDictionary<string, object>)json[\"").Write(jsPropertyName).Write("\"], options))").EndLine() .Indent() .Write("return false;").EndLine() .Unindent() .Write("json[\"").Write(jsPropertyName).Write("\"] = x;").EndLine() //.Write("this.").Write(p.Name).Write(" = x;").EndLine() .Unindent() .Write("}").EndLine(); } else { // ViewModelCollection outputWriter .Write(GetPropertyTypeNameForMethodSignature(p.PropertyType, false)).Write(" l = new ").Write(GetPropertyTypeNameForMethodSignature(p.PropertyType)).Write("();").EndLine() .Write("if (this.").Write(p.Name).Write(" != null)").EndLine() .Indent() .Write("l = this.").Write(p.Name).Write(";").EndLine() .Unindent() .EndLine() .Write("l.Clear();").EndLine() .Write("var jsonList = (List<JsDictionary<string, object>>)json[\"").Write(jsPropertyName).Write("\"];").EndLine() .Write("if (jsonList != null)") .EndLine() .Write("{").EndLine().Indent() .Write("foreach(JsDictionary<string, object> itemJson in jsonList)").EndLine() .Write("{").EndLine() .Indent() .Write(GetPropertyTypeNameForMethodSignature(p.PropertyType.GetGenericArguments()[0])).Write(" x = new ").Write(GetPropertyTypeNameForMethodSignature(p.PropertyType.GetGenericArguments()[0])).Write("();").EndLine() .Write("if (!x.SetFromJSON(itemJson, options))").EndLine() .Indent() .Write("return false;").EndLine() .Unindent() .Write("l.Add(x);").EndLine() .Unindent() .Write("}").EndLine() .Unindent().Write("}").EndLine() .Write("json[\"").Write(jsPropertyName).Write("\"] = l;").EndLine(); } outputWriter .Unindent() .Write("}").EndLine(); } if (isInheritsFromOtherViewModel) outputWriter.Write("return base.SetFromJSON(json, options);").EndLine(); else outputWriter.Write("return base.Set(json, options);").EndLine(); outputWriter .Unindent() .Write("}").EndLine(); } // write 'SetXFromString' methods foreach (var p in type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)) { if (p.GetCustomAttributes(typeof(ViewModelIgnoreAttribute), true).Any()) continue; if (IsPrimitiveOrNullableProperty(p.PropertyType)) { var jsPropertyName = GetJsPropertyName(p.Name); outputWriter.Write("public void Set").Write(p.Name).Write("FromString(string value)") .EndLine() .Write("{").EndLine() .Indent() .Write("SetPropertyFromString(\"").Write(jsPropertyName).Write("\", value, typeof(").Write(GetPropertyTypeNameForJsTypeConversion(p.PropertyType)).Write("), ").Write(p.PropertyType.Name == "Nullable`1" ? "true" : "false").Write(");").EndLine() .Unindent() .Write("}").EndLine(); outputWriter.EndLine(); } foreach (var propertyTypeForGeneration in GetPropertyTypeForGeneration(p.PropertyType)) { //Console.WriteLine("Adding nested property type " + propertyTypeForGeneration + " for property " + p.Name + " in " + type.FullName); if (!_nestedPropertyTypes.Contains(propertyTypeForGeneration)) _nestedPropertyTypes.Add(propertyTypeForGeneration); } } // write 'Validate' method GenerateBaseValidateMethod(type, outputWriter); outputWriter.Unindent() .Write("}").EndLine() .Unindent() .Write("}").EndLine().EndLine(); return outputWriter.ToString(); }
internal string GenerateServiceArgs() { foreach (var serviceArguments in _argumentTypes) { KeyValuePair<string, ServiceArguments> arguments = serviceArguments; var hasOthers = _argumentTypes.Count(kvp => kvp.Value.HasArgumentsWithSameNameButDifferentTypes(arguments.Value)) > 1; if (arguments.Value.Arguments.Count == 0) serviceArguments.Value.GeneratedTypeName = null; else if (arguments.Value.Arguments.Count == 1 && arguments.Value.Arguments[0].Name.ToLower() == "id" && arguments.Value.Arguments[0].Type == typeof(int)) // special case for Id { serviceArguments.Value.GeneratedTypeName = "IdServiceParam"; var ns = serviceArguments.Key.Substring(0, serviceArguments.Key.IndexOf(':')); ns = ns.Substring(0, ns.LastIndexOf('.')); // TODO NCU this is incorrect - find the common base between Item1 and Item2 and use that. if (_options.NamespaceSubstitution != null && _options.NamespaceSubstitution.Item1 != null) ns = ns.Substring(0, _options.NamespaceSubstitution.Item1.Length); serviceArguments.Value.GeneratedTypeNamespace = ns; } else { serviceArguments.Value.GeneratedTypeName = serviceArguments.Key.Substring(serviceArguments.Key.LastIndexOf('.') + 1).Replace(":", "_") + "ServiceParam"; var ns = serviceArguments.Key.Substring(0, serviceArguments.Key.IndexOf(':')); ns = ns.Substring(0, ns.LastIndexOf('.')); serviceArguments.Value.GeneratedTypeNamespace = ns; } } var generated = new List<string>(); var outputWriter = new OutputWriter(); foreach (var serviceArguments in _argumentTypes) { if (serviceArguments.Value.Arguments.Count == 0) continue; if (generated.Contains(serviceArguments.Value.GeneratedTypeName)) continue; outputWriter.Write("namespace ") .Write(Utils.GetNamespace(serviceArguments.Value.GeneratedTypeNamespace, _options.NamespaceSubstitution)).EndLine() .Write("{").EndLine() .Indent(); outputWriter .Write("[IgnoreNamespace]") .Write("[Imported]") .Write("[ScriptName(\"Object\")]") .EndLine(); outputWriter.Write("public class ").Write(serviceArguments.Value.GeneratedTypeName).EndLine() .Write("{").EndLine() .Indent(); foreach(var param in serviceArguments.Value.Arguments) { outputWriter .Write("[IntrinsicProperty]") .EndLine(); outputWriter .Write("public ") .Write(GetParameterTypeForCallMethod(param.Type)) .Write(" ").Write(GetParameterName(param.Name)) .Write(" { get; set; }") .EndLine() .EndLine(); } outputWriter .Unindent() .Write("}").EndLine() .Unindent() .Write("}").EndLine(); generated.Add(serviceArguments.Value.GeneratedTypeName); } return outputWriter.ToString(); }
public SystemDependencyChecker(OutputWriter outputWriter) { _outputWriter = outputWriter; }
public void solve(InputReader inp, OutputWriter outp) { //hello-world outp.println("hello-world"); }
private void createLocalCache() { var sb = new StringBuilder(); Action<string> a = (s) => sb.AppendLine(s); a("using System;"); a(""); a("namespace MyNS"); a("{"); a(" public class MyClass"); a(" {"); a(" private void MyMethod(string word) {"); a(" var str = \"Hello World\";"); a(" Console.WriteLine(str + word);"); a(" var bleh = 15;"); a(" Console.WriteLine(bleh.ToString());"); a(" if (_isValid)"); a(" Console.WriteLine(\"meh\");"); a(" }"); a(" "); a(" private bool _isValid = false;"); a(" }"); a("}"); _fileContent = sb.ToString(); _cache = new OutputWriter(new NullResponseWriter()); _cache.SetTypeVisibility(true); var parser = new NRefactoryParser() .ParseLocalVariables(); parser.SetOutputWriter(_cache); parser.ParseFile(new FileRef("MyFile", null), () => _fileContent); _cache.BuildTypeIndex(); new TypeResolver(new OutputWriterCacheReader(_cache, _globalCache)) .ResolveAllUnresolved(_cache); }
// public static string SimpleBcl = File.ReadAllText(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "/Runtime/System/System.d") ; public static void Go(OutputWriter writer) { // writer.WriteLine(SimpleBcl); }
public FooterPanelContainerViewModel() { Strings = new StringLibrary(); Writer = new OutputWriter(); Output.Register(Writer); }
public void GenerateValidateMethod_WithOneAttributeOneProperty_ShouldGenerateCorrectValidation() { var generator = new ViewModelGenerator(new ViewModelGeneratorOptions()); var outputWriter = new OutputWriter(); generator.GenerateBaseValidateMethod(typeof(ModelWithOneValidationAttribute), outputWriter); Assert.AreEqual(@"public override bool Validate(Dictionary<string, object> attributes) { string res = null; res = new Southpaw.Runtime.Clientside.Validation.RequiredValidator().Validate(attributes[""Prop""], new Southpaw.Runtime.Clientside.Validation.RequiredValidatorOptions { Property = ""Prop"", AllowEmptyStrings = false, }); if (res != null) this.Errors.AddError(""Prop"", res); return this.Errors.IsError; } ", outputWriter.ToString()); }
public void GenerateValidateMethod_WithClassWithNoAttributes_ShouldNotGenerateAnything() { var generator = new ViewModelGenerator(new ViewModelGeneratorOptions()); var outputWriter = new OutputWriter(); generator.GenerateBaseValidateMethod(typeof(ModelWithArrayProperty), outputWriter); Assert.AreEqual("", outputWriter.ToString()); }
internal void GenerateBaseValidateMethod(Type type, OutputWriter outputWriter) { /* * TODO: * - Validate() to validate current object properties. Should use exact code below. * - below code should add type validation: Southpaw.Runtime.Clientside.Validation.Type.IntValidator.Validate(string, params); */ outputWriter.Write("public override bool Validate(JsDictionary<string, object> attributes)") .EndLine() .Write("{").EndLine() .Indent() .Write("this.Errors.Clear();") .EndLine(); var isResInitialised = false; Action maybeInitialiseRes; maybeInitialiseRes = () => { if (!isResInitialised) { outputWriter .Write("string res = null;") .EndLine(); isResInitialised = true; } }; foreach(var p in type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)) //.Where(p => p.GetCustomAttributes(true).Any(x => typeof (ValidationAttribute).IsAssignableFrom(x.GetType())))) { // validate type if (_typeValidatorMap.ContainsKey(p.PropertyType)) { maybeInitialiseRes(); outputWriter.Write("res = new " + _typeValidatorMap[p.PropertyType] + "().Validate(attributes[\"" + p.Name + "\"], new Southpaw.Runtime.Clientside.Validation.Type.TypeValidatorOptions { Property = \"" + p.Name + "\" });") .EndLine() .Write("if (res != null) this.Errors.AddError(\"" + p.Name + "\", res);") .EndLine(); } // validate attributes var attrs = p.GetCustomAttributes(true).Where(x => typeof (ValidationAttribute).IsAssignableFrom(x.GetType())); foreach (var attr in attrs) { if (attr.GetType().IsAbstract) continue; if (_validatorMap.ContainsKey(attr.GetType().FullName)) { maybeInitialiseRes(); outputWriter.Write("res = new " + _validatorMap[attr.GetType().FullName] + "().Validate(attributes[\"" + p.Name + "\"], new " + _validatorMap[attr.GetType().FullName] + "Options { Property = \"" + p.Name + "\", "); foreach (var ap in attr.GetType().GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance)) { if (ap.PropertyType == typeof (Type)) continue; // Type doesn't exist in Saltarelle outputWriter.Write(ap.Name + " = "); if (ap.PropertyType == typeof(string)) outputWriter.Write("\"" + ap.GetValue(attr, null).ToString().Replace("\\", "\\\\") + "\""); else // TODO: will fail with datetime, char. Not used in any of the standard // validators. Need to implement for custom validators. outputWriter.Write(ap.GetValue(attr, null).ToString().ToLower()); outputWriter.Write(", "); } outputWriter.Write("});") .EndLine(); outputWriter.Write("if (res != null) this.Errors.AddError(\"" + p.Name + "\", res);") .EndLine(); } else { throw new ArgumentException(string.Format( "Property '{0}' in type '{1}' has a validator of type '{2}', which isn't mapped", p.Name, type.FullName, attr.GetType().FullName)); } } } outputWriter .Write("return !this.Errors.IsError;") .EndLine() .Unindent() .Write("}").EndLine(); }
internal string GenerateSuper(Type type) { var outputWriter = new OutputWriter(); outputWriter.Write("namespace ") .Write(Utils.GetNamespace(type.Namespace, _options.NamespaceSubstitution)).EndLine() .Write("{").EndLine() .Indent() .Write("public class ").Write(Utils.GetViewModelTypeName(type)).Write(" : ").Write(GetViewModelBaseTypeName(type)).EndLine() .Write("{") .EndLine(); outputWriter.Write("}").EndLine() .Unindent() .Write("}").EndLine().EndLine() .Unindent(); return outputWriter.ToString(); }
internal string GenerateEnum(Type type) { var outputWriter = new OutputWriter(); outputWriter.Write("namespace ") .Write(Utils.GetNamespace(type.Namespace, _options.NamespaceSubstitution)).EndLine() .Write("{").EndLine() .Indent() .Write("public enum ").Write(type.Name).EndLine() .Write("{").EndLine() .Indent(); var values = Enum.GetValues(type); for(var i = 0; i < values.Length; i++) { var name = Enum.GetName(type, values.GetValue(i)); var value = Convert.ChangeType(values.GetValue(i), Enum.GetUnderlyingType(type)); if (name.ToString() == value.ToString()) outputWriter.Write(name); else outputWriter.Write(name).Write(" = ") .Write(value.ToString()); if (i < values.Length - 1) outputWriter.Write(","); outputWriter.EndLine(); } outputWriter .Unindent() .Write("}").EndLine() .Unindent() .Write("}").EndLine().EndLine() .Unindent(); return outputWriter.ToString(); }
///////////////////////////////////////////////////////////////////////////// // Overridden Package Implementation #region Package Members /// <summary> /// Initialization of the package; this method is called right after the package is sited, so this is the place /// where you can put all the initialization code that rely on services provided by VisualStudio. /// </summary> protected override void Initialize() { Instance = this; Debug.WriteLine (string.Format(CultureInfo.CurrentCulture, "Entering Initialize() of: {0}", this.ToString())); base.Initialize(); m_writer = OutputWriter.Instance; m_deployButton = new DeployDebugButton(this, (int)PkgCmdIDList.cmdidDeployCode, false); m_debugButton = new DeployDebugButton(this, (int)PkgCmdIDList.cmdidDebugCode, true); m_killButton = new KillButton(this); string monoFolder = WPILibFolderStructure.CreateMonoFolder(); string monoFile = monoFolder + Path.DirectorySeparatorChar + DeployProperties.MonoVersion; m_monoFile = new MonoFile(monoFile); m_installMonoButton = new InstallMonoButton(this, m_monoFile); m_downloadMonoButton = new DownloadMonoButton(this, m_monoFile, m_installMonoButton); m_saveMonoButton = new SaveMonoButton(this, m_monoFile); m_aboutButton = new AboutButton(this); m_netConsoleButton = new NetConsoleButton(this); m_settingsButton = new SettingsButton(this); m_setMainRobotButton = new SetMainRobotButton(this); }