public void TestGenerateLppl() { var options = new GeneratorOptions(); var generator = new Generator(options); var generated = generator.Generate(); Console.WriteLine(generated.ToListPlot()); }
public void ParseTracker() { var generator = new Generator(); generator.Settings.ContextNaming = ContextNaming.Preserve; generator.Settings.EntityNaming = EntityNaming.Singular; generator.Settings.RelationshipNaming = RelationshipNaming.ListSuffix; generator.Settings.TableNaming = TableNaming.Singular; var selector = GetDatabaseSchema("Tracker"); Assert.IsNotNull(selector); EntityContext entityContext = generator.Generate(selector); Assert.IsNotNull(entityContext); var settings = new XmlWriterSettings { Indent = true }; var serializer = new XmlSerializer(typeof(EntityContext)); using (var writer = XmlWriter.Create(@"..\..\Tracker.Generated.xml", settings)) serializer.Serialize(writer, entityContext); string contextDirectory = @"..\..\..\Tracker.Core"; string mappingDirectory = @"..\..\..\Tracker.Core\Mapping"; Synchronizer.UpdateFromSource(entityContext, contextDirectory, mappingDirectory); using (var writer = XmlWriter.Create(@"..\..\Tracker.Updated.xml", settings)) serializer.Serialize(writer, entityContext); }
public void Parse(string input, string[] args = null) { var xxr = new XamlXmlReader(new StringReader(input), new XamlSchemaContext()); var graphReader = new XamlObjectWriter(xxr.SchemaContext); while (xxr.Read()) graphReader.WriteNode(xxr); var page = (Page)graphReader.Result; // Map our generators var g = new Generator(); g.Map<Page, PageGeneratorBlock>(); g.Map<Button, ButtonGeneratorBlock>(); g.Map<StackPanel, StackPanelGeneratorBlock>(); var doc = new HtmlDocument(); var html = doc.CreateElement("html"); g.Generate(html, page); // HTML5 Doc type doc.DocumentNode.AppendChild(doc.CreateComment("<!DOCTYPE html>")); doc.DocumentNode.AppendChild(html); doc.Save("test.htm"); var cssContents = g.GenerateStyles(page); File.WriteAllText("XamlCore.css", cssContents); }
public IEnumerable<SetSong> Generate(int numSets, int numSongsPerSet, IEnumerable<Song> songs) { _masterSongList = songs.ToArray(); _generator = new Generator(_masterSongList); _setSongs = _generator.Generate(numSets, numSongsPerSet, GetNextSong); return _setSongs; }
public IEnumerable<SetSong> Generate(int numSets, int numSongsPerSet, IEnumerable<Song> songs) { _masterSongList = songs.ToArray(); _songMemberInstrumentList = _masterSongList.SelectMany(x => x.SongMemberInstruments).ToList(); _generator = new Generator(_masterSongList); _setSongs = _generator.Generate(numSets, numSongsPerSet, GetNextSong); return _setSongs; }
private WorkOrder CreateWorkOrder(Generator <WorkOrder> generator) { var expectedWorkOrder = generator?.Generate(); _repairsGatewayMock.Setup(r => r.GetWorkOrder(expectedWorkOrder.Id)) .ReturnsAsync(expectedWorkOrder); _repairsGatewayMock.Setup(r => r.GetWorkOrder(expectedWorkOrder.Id, It.IsAny <bool>())) .ReturnsAsync(expectedWorkOrder); return(expectedWorkOrder); }
public void TestGeneratePl() { var options = new GeneratorOptions { Function = x => new Pl().Evaluate(x) }; var generator = new Generator(options); var generated = generator.Generate(); Console.WriteLine(generated.ToListPlot()); }
public void CanGenerateClasses() { Assert.DoesNotThrow(() => { var outputPath = GetOutputPath("CanGenerateClasses"); var gen = new Generator { EnableDataBinding = true, IntegerDataType = typeof(int), UseXElementForAny = true, CollectionType = typeof(IList<>), CollectionImplementationType = typeof(List<>), GenerateDesignerCategoryAttribute = false, GenerateNullables = true, GenerateSerializableAttribute = false, OutputFolder = outputPath, NamingScheme = NamingScheme.Direct, DataAnnotationMode = DataAnnotationMode.None, EmitOrder = true, NamespaceProvider = new NamespaceProvider { GenerateNamespace = key => { switch (Path.GetFileName(key.Source.LocalPath)) { case "th000008_extern.xsd": case "ndh000010_extern.xsd": case "headerbasis000002.xsd": return "Elster.Basis"; case "datenabholung_5.xsd": case "elster0810_datenabholung_5.xsd": switch (key.XmlSchemaNamespace) { case "http://www.elster.de/2002/XMLSchema": return "Elster.Datenabholung5"; default: throw new NotSupportedException(string.Format("Namespace {0} for schema {1}", key.XmlSchemaNamespace, key.Source)); } default: throw new NotSupportedException(string.Format("Namespace {0} for schema {1}", key.XmlSchemaNamespace, key.Source)); } } } }; var xsdFiles = new[] { "headerbasis000002.xsd", "ndh000010_extern.xsd", "th000008_extern.xsd", "datenabholung_5.xsd", "elster0810_datenabholung_5.xsd", }.Select(x => Path.Combine(InputPath, x)).ToList(); gen.Generate(xsdFiles); }); }
public void GenerateTrackerDatabaseTest() { var selector = GetDatabaseSchema("Tracker"); Assert.IsNotNull(selector); var generator = new Generator(); EntityContext entityContext = generator.Generate(selector); Assert.IsNotNull(entityContext); var settings = new XmlWriterSettings { Indent = true }; var serializer = new XmlSerializer(typeof(EntityContext)); using (var writer = XmlWriter.Create(@"..\..\Tracker.xml", settings)) serializer.Serialize(writer, entityContext); }
public void TestLinearOptimizePl() { var pl = new Pl(); var options = new GeneratorOptions { Function = pl.Evaluate, ErrorRange = 0.25 }; var generator = new Generator(options); var generated = generator.Generate(); var optimizer = new LcFunctionLinearOptimizer(pl); optimizer.Optimize(generated); Console.WriteLine(pl.ToShow(generated)); }
public void RenameProperty() { var selector = GetDatabaseSchema("Tracker"); Assert.IsNotNull(selector); var generator = new Generator(); EntityContext entityContext = generator.Generate(selector); Assert.IsNotNull(entityContext); var settings = new XmlWriterSettings { Indent = true }; var serializer = new XmlSerializer(typeof(EntityContext)); using (var writer = XmlWriter.Create(@"..\..\Tracker.Before.xml", settings)) serializer.Serialize(writer, entityContext); entityContext.RenameProperty("Task", "PriorityId", "NewPriorityId"); using (var writer = XmlWriter.Create(@"..\..\Tracker.After.xml", settings)) serializer.Serialize(writer, entityContext); }
public void TestNonLinearOptimizePl() { var pl = new Pl(); Console.WriteLine(pl); var options = new GeneratorOptions { Function = pl.Evaluate, ErrorRange = 0,//.1, TimeRangeMax = 0.8 }; var generator = new Generator(options); var generated = generator.Generate(); pl.Tc += 0.5;// 5; pl.M += 0.3; var optimizer = new LcFunctionNonLinearOptimizer(pl); optimizer.Optimize(generated); Console.WriteLine(pl); Console.WriteLine(pl.ToShow(generated)); }
public void GenerateConnexInclusionModeTest() { var selector = GetDatabaseSchema("Connex"); Assert.IsNotNull(selector); selector.SelectMode = SelectMode.Include; selector.SelectedTables.Add("dbo.Agency"); selector.SelectedTables.Add("dbo.Client"); selector.SelectedTables.Add("dbo.Contact"); selector.SelectedTables.Add("dbo.Contract"); selector.SelectedTables.Add("dbo.MediaSupplier"); selector.SelectedTables.Add("dbo.Vendor"); selector.ColumnExpressions.Add(@"\.Id$"); selector.ColumnExpressions.Add(@"\.Name$"); selector.ColumnExpressions.Add(@"UniversalId$"); var generator = new Generator(); generator.Settings.TableNaming = TableNaming.Singular; generator.Settings.EntityNaming = EntityNaming.Singular; generator.Settings.RelationshipNaming = RelationshipNaming.Plural; generator.Settings.ContextNaming = ContextNaming.Plural; var cleanExpressions = new List<string> { "^(sp|tbl|udf|vw)_" }; foreach (string s in cleanExpressions) if (!string.IsNullOrEmpty(s)) generator.Settings.CleanExpressions.Add(s); EntityContext entityContext = generator.Generate(selector); Assert.IsNotNull(entityContext); string json = JsonConvert.SerializeObject(entityContext, Formatting.Indented); File.WriteAllText(@"..\..\Connex.json", json); }
private void GenerateCategory() { string template = Helper.ReadTextFile(categoryFileName); Generator gen = new Generator(template); gen.ParseTemplate(); //用起始标志,标志的4个区间 Region rgnTitle = gen.GetRegion("Title"); Region rgnCategory = gen.GetRegion("Category"); Region rgnProducts = gen.GetRegion("Products"); Region rgnNavigator = gen.GetRegion("Navigator"); if(rgnTitle == null || rgnCategory == null || rgnProducts == null || rgnNavigator == null) { Response.Write("Missing region."); return; } int categoryId; string outputFileName; DataView dvCategory = this.GetCategoryTable().DefaultView; Pager pgrCategory = new Pager(1, dvCategory.Count); for(int i = 0; i < pgrCategory.PageCount; i++) { rgnTitle.DataSource = (string)dvCategory[i]["CategoryName"]; //Use a string as data source rgnCategory.DataSource = dvCategory[i]; //Use a DataRowView object as data source categoryId = (int)dvCategory[i]["CategoryID"]; rgnProducts.DataSource = this.GetProductTable(categoryId); //Use a DataTable object as data souce //set pager pgrCategory.CurrentPage = i + 1; rgnNavigator.DataSource = pgrCategory; //Use a Pager object as data source outputFileName = string.Format(@"{0}\Html\Category{1}.html", outputPath, categoryId); Helper.WriteTextFile(outputFileName, gen.Generate()); } }
public void TestNonLinearOptimizeLppl() { var lppl = new Lppl(); var options = new GeneratorOptions { Function = lppl.Evaluate, TimeRangeMax = 0.9, ErrorRange = 0.1 }; var generator = new Generator(options); var generated = generator.Generate(); lppl.M += 0.0; lppl.Omega -= 0.5; lppl.Tc += 0.0; var optimizer = new LcFunctionNonLinearOptimizer(lppl); optimizer.Optimize(generated); Console.WriteLine(lppl); Console.WriteLine(lppl.ToShow(generated)); }
public override void TransformHtml(Generator generator, Drawable element, HtmlNode node) { // TODO: Flesh this out. Rather bare bones at the moment. var document = node.OwnerDocument; var newElement = document.CreateElement("div"); var style = element.Style; // TODO: Move this to GeneratorBlock, or not, at least not for this GeneratorBlock impl. // Reason being is that I do some ContentProperty voodoo, which isnt appropriate for us here. if (style != null) newElement.Attributes.Add(document.CreateAttribute("class", style)); // Add our created element to the parent. node.AppendChild(newElement); // This is where special handling of Content comes in. I simply loop through the StackPanel and call generate. // TODO: Try to generalize this and move it to GeneratorBlock. Will clean things up a bit. foreach (var child in ((StackPanel)element).Children) { generator.Generate(newElement, child); } }
public override void OnInspectorGUI() { targetGenerator = (Generator)target; base.OnInspectorGUI(); EditorGUILayout.Separator(); EditorGUILayout.BeginHorizontal(); partCount = EditorGUILayout.IntField("Steps", partCount); if (GUILayout.Button("Generate")) { targetGenerator.Clear(); targetGenerator.Generate(partCount); } EditorGUILayout.EndHorizontal(); var shapeBoxStyle = new GUIStyle { padding = new RectOffset(5, 5, 5, 5), normal = { background = MapUtility.GetColorTexture2D(Color.black) }, alignment = TextAnchor.MiddleCenter }; EditorGUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel("Shape"); GUILayout.Box(targetGenerator.ShapeTexture, shapeBoxStyle); EditorGUILayout.EndHorizontal(); EditorGUILayout.IntField("Seed", targetGenerator.Seed); if (GUILayout.Button("Clear")) { Debug.Log("CLEAR!"); targetGenerator.Clear(); } }
private static void OnOptionsSuccessful(Options options, TraceListener tracer) { if (options.Help) { string helpText = CommandLine.Text.HelpText.AutoBuild(options); tracer.WriteLine(helpText); } else { ILogger logger; if (options.Verbose) { logger = new DateTimeLogger(tracer); } else { logger = VoidLogger.Default; } var ioOperations = new IoOperations(new FileSystem(), options.OutputPath, logger); var generator = new Generator(options.StrictNullCheck); var result = generator.Generate(options.Files, ioOperations); ioOperations.Dump(result.Files); } }
/// <summary> /// Given a Pantheon Drawable, produces a node of HTML. /// </summary> /// <param name="generator">The current Generator.</param> /// <param name="element">The current Pantheon Drawable.</param> /// <param name="node">The current node. NOTE: If you're calling base.TransformHtml(..) be sure to call it /// with a child node you create using the HTMLAgility document. See: ButtonGeneratorBlock.</param> public virtual void TransformHtml(Generator generator, Drawable element, HtmlNode node) { // Do some reflection to get the [ContentProperty] from a Drawable and call Generator.Generate(..) on it. var axtt = element.GetType().CustomAttributes.Where(a => a.AttributeType == typeof(ContentPropertyAttribute)).SingleOrDefault(); if (axtt.ConstructorArguments.Count > 0) { // Get the Property name by scanning the Attribute for a Constuctor arg. var propName = (string)axtt.ConstructorArguments[0].Value; // Make sure our element actually contains the Property. // TODO: Does ContentPropertyAttribute make this check redundant? if (element.GetType().GetProperty(propName) != null) { // TODO: Cache to reduce the double check on GetProperty(..) var returnedType = element.GetType().GetProperty(propName).GetValue(element); // If the type is a Drawable call generate. // There will be cases where its an IList<...> but that's up to the implementer to deal with // See StackPanelGeneratorBlock if (returnedType is Drawable) generator.Generate(node, (Drawable)returnedType); } } }
//单击树节点选中对应的库 private void dbTree_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e) { var tag = e.Node.Tag as DbObject; if (tag != null) { if (e.Button == MouseButtons.Left) { if (tag.Type == DbObjectType.Database) { //选中当前库 tsDatabases.SelectedItem = _selectedDb = tag.Name; } } else { if (tag.Type == DbObjectType.Table) { var contextMenu = new ContextMenu(); var menuItem = new MenuItem("选择前100行"); menuItem.Click += delegate(object _sender, EventArgs _e) { var sql = String.Format(@"SELECT TOP 100 * FROM {0}", tag.Name); AppendSqlToEditor(sql); }; contextMenu.MenuItems.Add(menuItem); var menuItem2 = new MenuItem("生成代码"); menuItem2.Click += delegate(object _sender, EventArgs _e) { _generator.ConnectionString = _dbConnection.GetString(_selectedDb); _generator.Generate(new string[] { tag.Name }); }; contextMenu.MenuItems.Add(menuItem2); contextMenu.Show(dbTree, new Point(e.X, e.Y)); } else if (tag.Type == DbObjectType.Database) { var contextMenu = new ContextMenu(); var menuItem = new MenuItem("生成代码"); menuItem.Click += delegate(object _sender, EventArgs _e) { var tables = (from t in LoadTables(tag.Name) select t.Name ).ToArray(); _generator.ConnectionString = _dbConnection.GetString(tag.Name); _generator.Generate(tables); }; contextMenu.MenuItems.Add(menuItem); contextMenu.Show(dbTree, new Point(e.X, e.Y)); } else if (tag.Type == DbObjectType.Column) { var contextMenu = new ContextMenu(); var menuItem = new MenuItem("复制"); menuItem.Click += delegate(object _sender, EventArgs _e) { var name = tag.Name.Substring(0, tag.Name.IndexOf("(")).Trim(); Clipboard.SetDataObject(name); }; contextMenu.MenuItems.Add(menuItem); contextMenu.Show(dbTree, new Point(e.X, e.Y)); } } } }
protected void Generate() { Generator.Generate(ns, ContentType); Candidate = Type = ns.Types.Cast <CodeTypeDeclaration>().Single(); }
protected override DefinitionDto GenerateDefinitions(int parameter) { return(Generator.Generate(10, () => parameter, index => Random.Next(1, 100), index => 50)); }
public void Process(Expressions.CreateColumnExpression expression) { Process(Generator.Generate(expression)); }
public void Process(Expressions.DeleteSchemaExpression expression) { Process(Generator.Generate(expression)); }
public void Should_throw_formatter_exception_if_formatter_throws_exception_during_generation() { const string routeName = "test"; const string routeTemplate = "test"; SupurlativeOptions options = SupurlativeOptions.Defaults; options.AddFormatter<DummyFormatter>(); HttpRequestMessage request; request = TestHelper.CreateAHttpRequestMessage(_baseUrl, routeName, routeTemplate); var generator = new Generator(request, options); var exception = Assert.Throws<FormatterException>( () => generator.Generate("test", new { Id = 1 })); Assert.Equal( "There is a problem invoking the formatter: RimDev.Supurlative.Tests.DummyFormatter.", exception.Message); }
public void GeneratePetshopInclusionModeTest() { var selector = GetDatabaseSchema("Petshop"); Assert.IsNotNull(selector); selector.SelectMode = SelectMode.Include; selector.SelectedTables.Add("dbo.Account"); selector.SelectedTables.Add("dbo.Product"); selector.SelectedTables.Add("dbo.Category"); selector.SelectedColumns.Add("dbo.Product.Category"); selector.ColumnExpressions.Add(@"(ID|Id)$"); selector.ColumnExpressions.Add(@"Name$"); var generator = new Generator(); generator.Settings.TableNaming = TableNaming.Singular; generator.Settings.EntityNaming = EntityNaming.Singular; generator.Settings.RelationshipNaming = RelationshipNaming.Plural; generator.Settings.ContextNaming = ContextNaming.Plural; var cleanExpressions = new List<string> { "^(sp|tbl|udf|vw)_" }; foreach (string s in cleanExpressions) if (!string.IsNullOrEmpty(s)) generator.Settings.CleanExpressions.Add(s); EntityContext entityContext = generator.Generate(selector); Assert.IsNotNull(entityContext); string json = JsonConvert.SerializeObject(entityContext, Formatting.Indented); File.WriteAllText(@"..\..\PetshopInclusion.json", json); }
public override void Process(DeleteSequenceExpression expression) { truncator.Truncate(expression); RegisterExpression <DeleteSequenceExpression>(expression); InternalProcess(Generator.Generate(expression)); }
public static void TestGeneration() { int[,] numbs = new int[25, 25]; for (int i = 0; i < 25; i++) for (int j = 0; j < 25; j++) numbs[i, j] = 0; Sudoku sudoku9 = GetStandart9(numbs); Stopwatch time9 = new Stopwatch(); Generator generator9 = new Generator(sudoku9, fillness: 1); Console.WriteLine(generator9.AttemptsRemain); time9.Start(); Console.WriteLine(generator9.Generate()); time9.Stop(); ShowSudoku(sudoku9, 9); System.Xml.Linq.XElement Sudoku = sudoku9.UnloadXml(); Console.WriteLine(Sudoku); Sudoku sudoku0 = new Sudoku(); //(null, null, null, null, 0); sudoku0.LoadXml(Sudoku); Console.WriteLine("Go"); ShowSudoku(sudoku0, 9); PrintBlocks(sudoku0); Sudoku sudoku16 = GetStandart16(numbs); Stopwatch time16 = new Stopwatch(); Generator generator16 = new Generator(sudoku16, attemptsNumber: 0, fillness: 1); ///sudoku16.MixNumbers(); //Console.WriteLine("Sudoku. Разбор полетов и template: \n {0}", SudokuCoordinates(sudoku16)); Console.WriteLine(generator16.AttemptsRemain); time16.Start(); Console.WriteLine(generator16.Generate()); time16.Stop(); ShowSudoku(sudoku16, 16); Console.WriteLine("\n \n {0}x9x{2} against {1}x16x{3}", time9.Elapsed, time16.Elapsed, generator9.AttemptsRemain, generator16.AttemptsRemain); }
public static Sudoku SudokuEventTest(Sudoku sudoku) { Generator generator = new Generator(sudoku, fillness: 1); generator.Generate(); sudoku.onCompleted += SudokuEventTestSubscriber1; sudoku.onFilled += SudokuEventTestSubscriber2; sudoku.SetNumber(new Position(0, 0), sudoku.GetNumber(new Position(0, 0)).Value); return sudoku; }
public void SpecialTest() { JSONNode n = new JSONNode(); n["root"]["D"][0].asText = "1"; n["root"]["D"][1].asText = "1"; n["root"]["D"][2].asText = "1"; n["root"]["D"][3].asText = "1"; n["root"]["D"][4].asText = "1"; n["root"]["D"][5]["qwert"].asText = "hundred"; n["root"]["E"].asNumber = 1; n["root"]["G"].asNumber = 2; n["root"]["F"].asNumber = 3; n["root"]["myObjecy"]["test Array"][0].asText = "text"; //Console.WriteLine(n.data); string json = n.ToString(); Console.WriteLine(json); Tokenizer w = new Tokenizer(); w.ParseText(new StringReader(json)); //foreach (var s in result) // Console.WriteLine(s); Generator g = new Generator(); var newNode = g.Generate(json); Console.WriteLine("OUT" + newNode["root"]["D"][5]["qwert"].asText); }
public void GeneratorBasicTest() { Generator g = new Generator(); var node = g.Generate(BASIC_OBJECT); Assert.AreEqual(NodeType.DICTIONARY, node.nodeType); Assert.AreEqual(10, node.data.asNumber); }
public void FileIO() { JSONNode original = new JSONNode(); string[] values = { "a", "b", "c", "d", "e" }; original["root"]["D"][0].asText = values[0]; original["root"]["D"][1].asText = values[1]; original["root"]["D"][2].asText = values[2]; original["root"]["D"][3].asText = values[3]; original["root"]["D"][4].asText = values[4]; const string FILENAME = "tempFile.json"; File.Delete(FILENAME); //write to file JSONNodeWriter w = new JSONNodeWriter(); var fWrite = File.Open(FILENAME, FileMode.Create); w.WriteToStream(original, fWrite); fWrite.Close(); //read from file Generator g = new Generator(); var fRead = File.Open(FILENAME, FileMode.Open); JSONNode output = g.Generate(fRead); fRead.Close(); var enumrtr = values.GetEnumerator(); for (int i = 0; i < 5; i++) { enumrtr.MoveNext(); Assert.AreEqual(enumrtr.Current, output["root"]["D"][i].asText); } }
private Assembly Compile(string name, string pattern, Generator generatorPrototype = null) { if (Assemblies.ContainsKey(name)) return Assemblies[name]; var cs = new List<string>(); var outputFolder = Path.Combine("output", name); Directory.CreateDirectory(outputFolder); generatorPrototype = generatorPrototype ?? new Generator { GenerateNullables = true, IntegerDataType = typeof(int), DataAnnotationMode = DataAnnotationMode.All, GenerateDesignerCategoryAttribute = false, EntityFramework = false, GenerateInterfaces = true, NamespacePrefix = name, }; var gen = new Generator { OutputFolder = outputFolder, NamespaceProvider = generatorPrototype.NamespaceProvider, Log = f => cs.Add(f), GenerateNullables = generatorPrototype.GenerateNullables, IntegerDataType = generatorPrototype.IntegerDataType, DataAnnotationMode = generatorPrototype.DataAnnotationMode, GenerateDesignerCategoryAttribute = generatorPrototype.GenerateDesignerCategoryAttribute, EntityFramework = generatorPrototype.EntityFramework, GenerateInterfaces = generatorPrototype.GenerateInterfaces }; var files = Glob.Glob.ExpandNames(pattern); gen.Generate(files); var provider = CodeDomProvider.CreateProvider("CSharp"); var assemblies = new[] { "System.dll", "System.Core.dll", "System.Xml.dll", "System.Xml.Linq.dll", "System.Xml.Serialization.dll", "System.ServiceModel.dll", "System.ComponentModel.DataAnnotations.dll", }; var binFolder = Path.Combine(outputFolder, "bin"); Directory.CreateDirectory(binFolder); var results = provider.CompileAssemblyFromFile(new CompilerParameters(assemblies, Path.Combine(binFolder, name + ".dll")), cs.ToArray()); Assert.False(results.Errors.HasErrors, string.Join("\n", results.Output.Cast<string>())); Assert.False(results.Errors.HasWarnings, string.Join("\n", results.Output.Cast<string>())); Assert.NotNull(results.CompiledAssembly); var assembly = Assembly.Load(results.CompiledAssembly.GetName()); Assemblies[name] = assembly; return assembly; }
protected override DefinitionDto GenerateDefinition(int parameter) { return(Generator.Generate(10, () => 100, index => Weight.HasValue ? Weight.Value : Random.Next(0, 50), index => Random.Next(1, parameter))); }
private static async Task Generate(Generator generator) { await generator.Generate(Directory.GetCurrentDirectory(), Directory.GetCurrentDirectory()); }
public static void Main() { Console.Write("Enter the file you want to write to: "); string newpath = Console.ReadLine() + ".vmf"; if (File.Exists(newpath)) { Console.Write("File " + newpath + " already exists, overwrite? [y/n]: "); if (Console.ReadLine().ToLower() != "y") { return; } File.Delete(newpath); } ReAsk :; Console.Write("Box size: "); if (!int.TryParse(Console.ReadLine(), out int BoxSize)) { goto ReAsk; } Console.Write("Fill with displacements? [y/n]: "); bool UseDisplacement = Console.ReadLine().ToLower() == "y"; Console.WriteLine("\nAssembling map..."); Generator generator = new Generator(); Stopwatch watch = new Stopwatch(); watch.Start(); for (int i = 1; i <= MAX_MAP_SIZE / BoxSize - 1; i++) { if (UseDisplacement) { generator.MakeSolid(generator.MakeDisplacement(new Vector3((i * BoxSize) - (MAX_MAP_SIZE * 0.5f), 0, 0), new Vector3(BoxSize, BoxSize, 128))); } else { generator.MakeSolid(generator.MakeCube(new Vector3((i * BoxSize) - (MAX_MAP_SIZE * 0.5f), 0, 0), new Vector3(BoxSize, BoxSize, 128))); } for (int j = 1; j <= MAX_MAP_SIZE / BoxSize - 1; j++) { if (UseDisplacement) { generator.MakeSolid(generator.MakeDisplacement(new Vector3((i * BoxSize) - (MAX_MAP_SIZE * 0.5f), (j * BoxSize) - (MAX_MAP_SIZE * 0.5f), 128), new Vector3(BoxSize, BoxSize, 128))); } else { generator.MakeSolid(generator.MakeCube(new Vector3((i * BoxSize) - (MAX_MAP_SIZE * 0.5f), (j * BoxSize) - (MAX_MAP_SIZE * 0.5f), 128), new Vector3(BoxSize, BoxSize, 128))); } } } //generator.MakeSolid(generator.MakeCube(new Vector3(0, 0, 0), new Vector3(1024, 1024, 128))); Console.WriteLine("Generating..."); string MapToWrite = generator.Generate(); Console.WriteLine("Writing to file..."); File.WriteAllText(newpath, MapToWrite); Console.WriteLine("Created file " + newpath); watch.Stop(); TimeSpan time = watch.Elapsed; Console.WriteLine("Took: " + time.Seconds + " seconds"); Console.ReadLine(); }
public ActionResult Index() { var example = generator.Generate(); return(Content(example)); }
public override ScriptData GenerateTestObject(FileFormat format) { Faker faker = new Faker(); int varSpace = faker.Random.Int(4, 8000); int runningScripts = faker.Random.Int(1, 20); Faker <ScriptData> model = new Faker <ScriptData>() .RuleFor(x => x.ScriptSpace, f => Generator.Array(varSpace, g => f.Random.Byte())) .RuleFor(x => x.OnAMissionFlag, f => f.Random.Int()) .RuleFor(x => x.Contacts, f => Generator.Array(ScriptData.NumContacts, g => Generator.Generate <Contact, TestContact>())) .RuleFor(x => x.Collectives, f => Generator.Array(ScriptData.NumCollectives, g => Generator.Generate <Collective, TestCollective>())) .RuleFor(x => x.NextFreeCollectiveIndex, f => f.Random.Int()) .RuleFor(x => x.BuildingSwaps, f => Generator.Array(ScriptData.NumBuildingSwaps, g => Generator.Generate <BuildingSwap, TestBuildingSwap>())) .RuleFor(x => x.InvisibilitySettings, f => Generator.Array(ScriptData.NumInvisibilitySettings, g => Generator.Generate <InvisibleObject, TestInvisibleObject>())) .RuleFor(x => x.UsingAMultiScriptFile, f => f.Random.Bool()) .RuleFor(x => x.MainScriptSize, f => f.Random.Int()) .RuleFor(x => x.LargestMissionScriptSize, f => f.Random.Int()) .RuleFor(x => x.NumberOfMissionScripts, f => f.Random.Short()) .RuleFor(x => x.Threads, f => Generator.Array(runningScripts, g => Generator.Generate <RunningScript, TestRunningScript>(format))); return(model.Generate()); }
static int Main (string [] args) { Generator generator; try { foreach (string arg in args) { if (arg == "--log") Log.LogEnabled = true; else throw new Exception ("Invalid argument: " + arg); } InitializeCurrentDirectory (); generator = new Generator (); generator.Generate (); return 0; } catch (Exception ex) { Console.WriteLine (ex.ToString ()); return 1; } }
private void Button_Assembly_Click(object sender, EventArgs e) { Generator gen = new Generator(RichTextBox_ProgramCode.Text); gen.Generate(); }
public void Process(Expressions.CreateTableExpression expression) { Process(Generator.Generate(expression)); }
private Assembly Compile(string name, string pattern, Generator generatorPrototype = null) { var cs = new List<string>(); var outputFolder = Path.Combine("output", name); Directory.CreateDirectory(outputFolder); generatorPrototype = generatorPrototype ?? new Generator { GenerateNullables = true, IntegerDataType = typeof(int), DataAnnotationMode = DataAnnotationMode.Partial, GenerateDesignerCategoryAttribute = false, EntityFramework = false, GenerateInterfaces = true }; var gen = new Generator { OutputFolder = outputFolder, NamespaceProvider = new NamespaceProvider { GenerateNamespace = key => { var xn = key.XmlSchemaNamespace; var nm = string.Join(".", xn.Split('/').Where(p => Regex.IsMatch(p, @"^[A-Za-z]+$") && p != "schema") .Select(n => Generator.ToTitleCase(n, NamingScheme.PascalCase))); return name + (string.IsNullOrEmpty(nm) ? "" : ("." + nm)); } }, Log = f => cs.Add(f), GenerateNullables = generatorPrototype.GenerateNullables, IntegerDataType = generatorPrototype.IntegerDataType, DataAnnotationMode = generatorPrototype.DataAnnotationMode, GenerateDesignerCategoryAttribute = generatorPrototype.GenerateDesignerCategoryAttribute, EntityFramework = generatorPrototype.EntityFramework, GenerateInterfaces = generatorPrototype.GenerateInterfaces }; var files = Glob.Glob.ExpandNames(pattern); gen.Generate(files); var provider = CodeDomProvider.CreateProvider("CSharp"); var assemblies = new[] { "System.dll", "System.Core.dll", "System.Xml.dll", "System.Xml.Linq.dll", "System.Xml.Serialization.dll", "System.ServiceModel.dll", "System.ComponentModel.DataAnnotations.dll", }; var binFolder = Path.Combine(outputFolder, "bin"); Directory.CreateDirectory(binFolder); var results = provider.CompileAssemblyFromFile(new CompilerParameters(assemblies, Path.Combine(binFolder, name + ".dll")), cs.ToArray()); Assert.False(results.Errors.HasErrors); Assert.False(results.Errors.HasWarnings); Assert.NotNull(results.CompiledAssembly); var assembly = Assembly.Load(results.CompiledAssembly.GetName()); Assemblies[name] = assembly; return assembly; }
protected virtual void Generate() { Generator.Generate(attribute, property); }
public void Setup() { var generator = new Generator(); results = generator.Generate(); }
public static int Main(string[] args) { var input_paths = new List <string> (); string output_path = "-"; string generator_name = String.Empty; string source_root_path = null; string reduce_master_path = null; string reduce_retain_path = null; string android_input_strings_xml = null; string android_output_strings_xml = null; string analyer_config_path = null; LocalizationMetadata metadata = null; bool generate_pot = false; bool exclude_po_header = false; bool analyze = false; bool analyzer_warn_as_error = false; bool log = false; bool verbose = false; bool retain_order = false; bool show_help = false; bool count_words = false; int word_count = 0; Generator generator = null; var options = new OptionSet { { "i|input=", "Input directory, search pattern, or file to parse (non-recursive)", v => input_paths.Add(v) }, { "o|output=", "Output file for extracted string resources", v => output_path = v }, { "r|source-root=", "Root directory of source code", v => source_root_path = v }, { "g|generator=", String.Format("Generator to use ({0})", String.Join("|", Generator.GeneratorNames)), v => generator_name = v }, { "retain-order", "Retain the original input string order when generating. " + "Default behavior is to sort strings for better diff support.", v => retain_order = v != null }, { "a|analyze", "Run the string analyzer after generation", v => analyze = v != null }, { "analyzer-config=", "Path to a configuration file for the analyzer; use with --analyze", v => analyer_config_path = v }, { "analyzer-warnaserror", "Treat analyzer warnings as errors", v => analyzer_warn_as_error = v != null }, { "reduce-master=", "Reduce a master localized PO file, " + "keeping only strings defined by another unlocalized PO[T] file", v => reduce_master_path = v }, { "reduce-retain=", "An unlocalized PO[T] file used to " + "determine which strings from reduce-master should be retained", v => reduce_retain_path = v }, { "android-input-strings-xml=", "Input file of unlocalized Android Strings.xml " + "for preserving hand-maintained string resources", v => android_input_strings_xml = v }, { "android-output-strings-xml=", "Output file of localized Android Strings.xml " + "for preserving hand-maintained string resources", v => android_output_strings_xml = v }, { "pot", v => generate_pot = v != null }, { "exclude-po-header", v => exclude_po_header = v != null }, { "l|log", "Display logging", v => log = v != null }, { "m|meta=", "Add localization metadata (key=value)", v => { var parts = v.Split(new [] { '=' }, 2); if (parts != null && parts.Length == 2) { if (metadata == null) { metadata = new LocalizationMetadata(); } metadata.Add(parts[0].Trim(), parts[1].Trim()); } } }, { "wc", "Count words to translate, output goes in the po header and in the console (with -v)", v => count_words = v != null }, { "v|verbose", "Verbose logging", v => verbose = v != null }, { "h|help", "Show this help message and exit", v => show_help = v != null } }; try { options.Parse(args); if (show_help) { Console.WriteLine("Usage: vernacular [OPTIONS]+"); Console.WriteLine(); Console.WriteLine("Options:"); options.WriteOptionDescriptions(Console.Out); return(1); } if (source_root_path != null) { if (!Directory.Exists(source_root_path)) { throw new OptionException("invalid source-root", "source-root"); } source_root_path = new DirectoryInfo(source_root_path).FullName; } generator = Generator.GetGeneratorForName(generator_name.ToLower()); if (generator == null) { throw new OptionException("invalid generator", "generator"); } generator.RetainStringOrder = retain_order; if (generator is PoGenerator) { ((PoGenerator)generator).PotMode = generate_pot; ((PoGenerator)generator).ExcludeHeaderMetadata = exclude_po_header; } if (reduce_master_path != null && reduce_retain_path == null) { throw new OptionException("reduce-retain must be specified if reduce-master is", "reduce-retain"); } else if (reduce_master_path == null && reduce_retain_path != null) { throw new OptionException("reduce-master must be specified if reduce-retain is", "reduce-master"); } else if (reduce_master_path != null && reduce_retain_path != null) { var reduce_master = new PoParser { SourceRootPath = source_root_path }; var reduce_retain = new PoParser { SourceRootPath = source_root_path }; reduce_master.Add(reduce_master_path); reduce_retain.Add(reduce_retain_path); generator.Reduce(reduce_master, reduce_retain); generator.Generate(output_path); return(0); } } catch (OptionException e) { Console.WriteLine("vernacular: {0}", e.Message); Console.WriteLine("Try `vernacular --help` for more information."); return(1); } var parser = new AggregateParser { SourceRootPath = source_root_path }; if (verbose) { parser.LogLevel = 2; } else if (log) { parser.LogLevel = 1; } StringAnalyzer analyzer = null; if (analyze) { try { analyzer = new StringAnalyzer(analyer_config_path, analyzer_warn_as_error); } catch { return(1); } } foreach (var input_path in input_paths) { if (File.Exists(input_path)) { parser.Add(input_path); continue; } var search_pattern = "*"; var dir = input_path; if (!Directory.Exists(dir)) { search_pattern = Path.GetFileName(dir); dir = Path.GetDirectoryName(dir); if (!Directory.Exists(dir)) { continue; } } foreach (var path in Directory.EnumerateFiles(dir, search_pattern, SearchOption.TopDirectoryOnly)) { parser.Add(path); } } if (metadata != null) { generator.Add(metadata); } foreach (var localization_unit in parser.Parse()) { var localized_string = localization_unit as LocalizedString; if (count_words && localized_string != null) { var separators = new char[] { '.', '?', '!', ' ', ';', ':', ',' }; if (localized_string.UntranslatedSingularValue != null) { word_count += localized_string.UntranslatedSingularValue.Split(separators, StringSplitOptions.RemoveEmptyEntries). Count(); } if (localized_string.UntranslatedPluralValue != null) { word_count += localized_string.UntranslatedPluralValue.Split(separators, StringSplitOptions.RemoveEmptyEntries).Count(); } } generator.Add(localization_unit); if (analyzer != null) { analyzer.Add(localized_string); } } if (analyzer != null) { var error_count = analyzer.Analyze(); if (error_count > 0) { Console.WriteLine("The analyzer reported {0} errors. Generation skipped.", error_count); return(1); } } if (count_words) { var word_count_metadata = new LocalizationMetadata(); word_count_metadata.Add("Word-Count", word_count.ToString(CultureInfo.InvariantCulture)); generator.Add(word_count_metadata); } generator.Generate(output_path); if (generator is AndroidGenerator && android_input_strings_xml != null && android_output_strings_xml != null) { ((AndroidGenerator)generator).LocalizeManualStringsXml(android_input_strings_xml, android_output_strings_xml); } if (verbose && count_words) { Console.WriteLine("Total of words in untranslated messages: {0} words.", word_count); } return(0); }
static Dictionary <TAttr, object> ParseAttrs <TAttr>(Generator.Ctx ctx, IEnumerable <string> comments, params TAttr[] firstLineDefaultKeys ) where TAttr : struct { bool firstLine = true; var lstDescr = new List <string>(); Dictionary <TAttr, object> attrs = null; int iDefaultKey = (firstLineDefaultKeys.Length > 0) ? 0 : -1; foreach (var txt in comments) { bool isKeyValueComment; { int iEqualSign = txt.IndexOf('='); if (iEqualSign > 0) { isKeyValueComment = !Enumerable.Range(0, iEqualSign - 1).Any(i => char.IsWhiteSpace(txt[i])); } else { isKeyValueComment = false; } } if ((firstLineDefaultKeys.Length == 0 || !firstLine) && !isKeyValueComment) { if (txt.Trim().Length == 0) { lstDescr.Clear(); } else { lstDescr.Add(txt); } continue; // do not parse simple comment lines } foreach (Expr attr in Parser.ParseSequence(txt, comparison: StringComparison.InvariantCulture)) { string attrName; Expr attrValue; if (attr.nodeType == ExprType.Equal) { // named attribute var be = (BinaryExpr)attr; if (be.left.nodeType == ExprType.Reference) { attrName = Convert.ToString(be.left); } else { var name = Generator.Generate(be.left, ctx); if (OPs.KindOf(name) != ValueKind.Const) { ctx.Error("ParseAttrs: attribute name must be constant\t" + be.left.ToString()); } attrName = Convert.ToString(name); } attrValue = be.right; } else if (firstLine && iDefaultKey >= 0) { // unnamed attributes possible in first line attrs = attrs ?? new Dictionary <TAttr, object>(); attrs.Add(firstLineDefaultKeys[iDefaultKey], attr); if (++iDefaultKey >= firstLineDefaultKeys.Length) { iDefaultKey = -1; } continue; } else { break; // it is simple comment to the end of line? } if (attrValue.nodeType != ExprType.Constant) { attrValue = new CallExpr(FuncDefs_Core._block, attrValue); } var value = Generator.Generate(attrValue, ctx); if (OPs.KindOf(value) != ValueKind.Const) { ctx.Error(string.Format("ParseAttrs: attribute value must be constant\t{0}={1}", attrName, attrValue)); } if (attrName != null) { if (!Enum.TryParse <TAttr>(attrName, out var attrKey)) { throw new Generator.Exception($"Unrecognized attribute name, {attrName}={attrValue} // enum {typeof(TAttr)}"); } attrs = attrs ?? new Dictionary <TAttr, object>(); Attr.Add(attrs, attrKey, value, false); } } firstLine = false; } if (lstDescr.Count > 0) { attrs = attrs ?? new Dictionary <TAttr, object>(); if (!Enum.TryParse <TAttr>(nameof(Attr.Tbl.Description), out var attrDescription)) { throw new Generator.Exception($"ParseAttrs: enum '{typeof(TAttr)}' does not contains value named '{nameof(Attr.Tbl.Description)}'"); } attrs.Add(attrDescription, lstDescr); } return(attrs); }
public void Process(Expressions.DeleteForeignKeyExpression expression) { Process(Generator.Generate(expression)); }
public void Process(Expressions.DeleteIndexExpression expression) { Process(Generator.Generate(expression)); }
static void Main(string[] args) { var showHelp = false; var namespaces = new List <string>(); var outputFolder = ""; var integerType = typeof(string); var namespacePrefix = ""; var verbose = false; var nullables = false; var pclCompatible = false; var enableDataBinding = false; var emitOrder = false; var entityFramework = false; var interfaces = true; var pascal = true; var options = new OptionSet { { "h|help", "show this message and exit", v => showHelp = v != null }, { "n|namespace=", @"map an XML namespace to a C# namespace Separate XML namespace and C# namespace by '='. One option must be given for each namespace to be mapped. A file name may be given by appending a pipe sign (|) followed by a file name (like schema.xsd) to the XML namespace. If no mapping is found for an XML namespace, a name is generated automatically (may fail).", v => namespaces.Add(v) }, { "o|output=", "the {FOLDER} to write the resulting .cs files to", v => outputFolder = v }, { "i|integer=", @"map xs:integer and derived types to {TYPE} instead of string {TYPE} can be i[nt], l[ong], or d[ecimal].", v => { switch (v) { case "i": case "int": integerType = typeof(int); break; case "l": case "long": integerType = typeof(long); break; case "d": case "decimal": integerType = typeof(decimal); break; } } }, { "e|edb|enable-data-binding", "enable INotifyPropertyChanged data binding", v => enableDataBinding = v != null }, { "r|order", "emit order for all class members stored as XML element", v => emitOrder = v != null }, { "c|pcl", "PCL compatible output", v => pclCompatible = v != null }, { "p|prefix=", "the {PREFIX} to prepend to auto-generated namespace names", v => namespacePrefix = v }, { "v|verbose", "print generated file names on stdout", v => verbose = v != null }, { "0|nullable", "generate nullable adapter properties for optional elements/attributes w/o default values", v => nullables = v != null }, { "f|ef", "generate Entity Framework Code First compatible classes", v => entityFramework = v != null }, { "t|interface", "generate interfaces for groups and attribute groups (default is enabled)", v => interfaces = v != null }, { "a|pascal", "use Pascal case for class and property names (default is enabled)", v => pascal = v != null }, }; var files = options.Parse(args); if (showHelp) { ShowHelp(options); return; } files = files.SelectMany(f => Glob.Glob.ExpandNames(f)).ToList(); var namespaceMap = namespaces.Select(n => ParseNamespace(n, namespacePrefix)).ToNamespaceProvider(key => { var xn = key.XmlSchemaNamespace; var name = string.Join(".", xn.Split('/').Where(p => Regex.IsMatch(p, @"^[A-Za-z]+$") && p != "schema") .Select(n => Generator.ToTitleCase(n, NamingScheme.PascalCase))); if (!string.IsNullOrEmpty(namespacePrefix)) { name = namespacePrefix + (string.IsNullOrEmpty(name) ? "" : ("." + name)); } return(name); }); if (!string.IsNullOrEmpty(outputFolder)) { outputFolder = Path.GetFullPath(outputFolder); } var generator = new Generator { NamespaceProvider = namespaceMap, OutputFolder = outputFolder, GenerateNullables = nullables, EnableDataBinding = enableDataBinding, EmitOrder = emitOrder, IntegerDataType = integerType, EntityFramework = entityFramework, GenerateInterfaces = interfaces, NamingScheme = pascal ? NamingScheme.PascalCase : NamingScheme.Direct }; if (pclCompatible) { generator.UseXElementForAny = true; generator.GenerateDesignerCategoryAttribute = false; generator.GenerateSerializableAttribute = false; generator.DataAnnotationMode = DataAnnotationMode.None; } if (verbose) { generator.Log = s => System.Console.Out.WriteLine(s); } generator.Generate(files); }
public void Process(Expressions.InsertDataExpression expression) { Process(Generator.Generate(expression)); }
protected override DefinitionDto GenerateDefinition(int parameter) { return(Generator.Generate(10, () => 100, index => Weight ?? Random.Next(1, 50), index => Random.Next(1, 100) > parameter ? Random.Next(100, 200) : Random.Next(1, 100))); }
public void Process(Expressions.UpdateDataExpression expression) { Process(Generator.Generate(expression)); }
public static void Main(string[] args) { System.Diagnostics.Stopwatch testTime = new System.Diagnostics.Stopwatch(); testTime.Start(); LousySudoku.UnitTest.Common.Run(5); testTime.Stop(); Console.WriteLine("Time elapsed: {0}", testTime.Elapsed); Console.ReadKey(); return; int size = 9; List<Number> number = new List<Number> { }; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { number.Add (new Number(NumberType.Empty, new Position(i, j))); } } //Debug.Print.Position(new Position(17, 5)); //Debug.Print.Number(number); List<BlockType> blockType = new List<BlockType> { }; BlockType standart = new BlockType(); //standart.SetChecker(LousySudoku.Method.CheckMethod_Standart); //standart.SetGenerator // (LousySudoku.Method.GenerateMethod_Standart); blockType.Add(standart); List<Block> block = new List<Block> { }; Sudoku sudoku = new Sudoku(blockType, block, number, size); for (int col = 0; col < size; col++) { block.Add(new Block( sudoku, standart, number.FindAll(x => x.Coordinate.GetCoordinate(0) == col) )); block.Add(new Block( sudoku, standart, number.FindAll(x => x.Coordinate.GetCoordinate(1) == col) )); } for (int i = 0; i < size; i += 3) { for (int l = 0; l < size; l += 3) { Block b = new Block(sudoku, standart); for (int j = 0; j < 3; j++) { for (int k = 0; k < 3; k++) { b.AddChild(sudoku.GetNumber( new Position(i + j, k + l))); } } block.Add(b); } } //sudoku.Block.ForEach(new Action<Block>(Debug.Print.Block)); Alist.Xml.Transform.ElementToFile (sudoku.UnloadXml(), "standart_12x12.xml"); //LousySudoku.Constant.rand = new Random(); //foreach (Number numb in sudoku.Number) //{ // Console.Write("{0}; ", numb.parent.Count); //} //Console.WriteLine(); //sudoku.Block.ForEach(x => Console.Write("{0}, ", x.Child.Count)); Generator g = new Generator(sudoku, 1000000, 1); System.Diagnostics.Stopwatch s0 = new System.Diagnostics.Stopwatch(); s0.Start(); Console.WriteLine(g.Generate()); s0.Stop(); Console.WriteLine(s0.Elapsed); Console.WriteLine(g.AttemptsRemain); Debug.Print.Sudoku2D(sudoku); sudoku.Clear(); //bool isContinue = true; //for (int i = 0; isContinue; i++) //{ // bool success = true; //Block generate //for (int j = 0; (j < sudoku.Block.Count) && (success); j++) //{ // success = sudoku.Block[j].Generate(); //} //Number generate // for (int j = 0; (j < sudoku.Number.Count) && success; j++) // { // success // = LousySudoku.Method.Generate(sudoku.Number[j]); //#if DEBUG // if (!success) // ; //#endif // } // //List<int> digit = new List<int> // // { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; // //bool toDo = true; // //for (int k = 0; (k < 9) && toDo; k++) // //{ // // int index = rand.Next(digit.Count - 1); // // int newnumb = digit[index]; // // numb.Modify(newnumb); // // digit.Remove(newnumb); // // if (numb.IsBlockRight()) // // { // // toDo = false; // // } // //} // //if (toDo) // // success = false; // ///End of attempt // if (!sudoku.Block.All(x => x.IsRight())) // success = false; // //success = sudoku.IsRight(); // if (i % 1000 == 0) // { // Console.WriteLine("Attempt #{0}", i); // Debug.Print.Sudoku2D(sudoku); // //LousySudoku.Constant.rand = new Random(); // } // if (success) // { // Console.WriteLine("Stopped at {0}", i); // Debug.Print.Sudoku2D(sudoku); // isContinue = false; // } // else // { // //sudoku = new Sudoku(blockType, block, number, 9); // sudoku.Clear(); // } // } Debug.Common.ShowSudoku(sudoku, size); Console.ReadKey(); return; //Tmp; Console.Write("Enter secret code, to run debug. Or press enter: "); string s = Console.ReadLine(); if (s != "2713") { Run(); return; } //LousySudoku.Sudoku sudoku = Debug.TestSudoku1(); //Console.WriteLine("Change number"); //sudoku.ChangeNumber(new Position(2, 1), 9); //Console.WriteLine("Print sudoku"); //Debug.ShowSudoku(sudoku, 9); ///Debug.TryLoadDll(); //Console.ReadLine(); //Debug.TryLoadDll("Sudoku.dll"); //Console.ReadLine(); ///Debug.ShowSudoku(Debug.SudokuEventTest(Debug.GetStandart9(null)), 9); //Sudoku sudoku = Debug.GetStandart25(null); //(new Generator(sudoku, 10, 1)).Generate(); //Debug.ShowSudoku(sudoku, 25); ///Debug.TestGeneration(); Debug.Common.TestSudokuFiles(); Console.ReadLine(); }
public void Process(Expressions.AlterSchemaExpression expression) { Process(Generator.Generate(expression)); }
void LoadDataEx(int pointsCount) { chartSource = Generator.Generate(pointsCount); bindData(); DoEvents(); }
public void Process(Expressions.DeleteSequenceExpression expression) { Process(Generator.Generate(expression)); }
/// <summary>Generates a new puzzle and sets it to be the current puzzle in the grid.</summary> /// <param name="options">Options to use for the puzzle generation.</param> /// <remarks>Resets the undo states for the grid.</remarks> public void GenerateNewPuzzle(GeneratorOptions options) { LoadNewPuzzle(_puzzleGenerator.Generate(options)); }
public void Process(Expressions.DeleteDefaultConstraintExpression expression) { Process(Generator.Generate(expression)); }
private static void Generate(string projectFolder, string configPath) { // get config configPath = !string.IsNullOrEmpty(configPath) ? Path.Combine(projectFolder, configPath) : Path.Combine(projectFolder, "tgconfig.json"); TgConfig config = _configProvider.GetConfig(configPath, projectFolder); LogConfigWarnings(config); // register assembly resolver _assemblyResolver.Directories = config.ExternalAssemblyPaths; _assemblyResolver.Register(); IEnumerable <Assembly> assemblies = GetAssemblies(config.GetAssemblies()).ToArray(); // create generator GeneratorOptions generatorOptions = _generatorOptionsProvider.GetGeneratorOptions(config, assemblies, projectFolder); generatorOptions.BaseOutputDirectory = Path.Combine(projectFolder, config.OutputPath); var generator = new Generator(generatorOptions, _logger); // generate if (config.ClearOutputDirectory == true) { _fileSystem.ClearDirectory(generatorOptions.BaseOutputDirectory); } if (config.BuildProject == true) { _projectBuilder.Build(projectFolder); } _logger.Log($"Generating files for project \"{projectFolder}\"...", LogLevel.Info); var generatedFiles = new List <string>(); if (!config.GenerationSpecs.Any() || config.GenerateFromAssemblies == true) { generatedFiles.AddRange(generator.Generate(assemblies)); } if (config.GenerationSpecs.Any()) { var typeResolver = new TypeResolver(_logger, _fileSystem, projectFolder, assemblies); IEnumerable <GenerationSpec> generationSpecs = config.GenerationSpecs .Select(name => typeResolver.Resolve(name, "GenerationSpec")) .Where(t => t != null) .Select(t => (GenerationSpec)Activator.CreateInstance(t)) .ToArray(); generatedFiles.AddRange(generator.Generate(generationSpecs)); } foreach (string file in generatedFiles) { _logger.Log($"Generated {file}", LogLevel.Info); } if (config.AddFilesToProject ?? TgConfig.DefaultAddFilesToProject) { AddFilesToProject(projectFolder, generatedFiles); } // unregister assembly resolver _assemblyResolver.Unregister(); _logger.Log($"Files for project \"{projectFolder}\" generated successfully.{Environment.NewLine}", LogLevel.Info); }
public void Setup() { var connection = new MySqlConnection( "server=localhost;" + "port=3306;" + "uid=groupCJN;" + "password=abc123;" + "Sql Server Mode=true;" + "database=groupcjn;"); var creator = new DBCreator(connection); var generator = new Generator(DigitalVoterList.GetDefaultInstance()); generator.Generate(10, 100, 5000); }