Esempio n. 1
0
 public void TestThatGraphCanBeCreatedWithTwoConnectedNodes()
 {
     var root = new SimpleNode("root");
     root.AddChild(new SimpleNode("child"));
     var graph = new GraphBuilder<SimpleNode>(GetChildren).Build(root);
     Assert.AreEqual(2, graph.Order);
 }
        public void Configure_a_family_that_does_not_exist_and_log_an_error_with_PluginGraph()
        {
            var builder = new GraphBuilder(new PluginGraph());
            builder.ConfigureFamily(new TypePath("a,a"), delegate { });

            builder.PluginGraph.Log.AssertHasError(103);
        }
        public void AddAssembly_SadPath()
        {
            var builder = new GraphBuilder(new PluginGraph());
            builder.AddAssembly("something");

            builder.PluginGraph.Log.AssertHasError(101);
        }
Esempio n. 4
0
 /// <summary>
 /// Creates an instance of this class based on a method. The method is assumed to be a test method.
 /// </summary>
 /// <param name="method">The method that contains/defines the test case.</param>
 /// <param name="testCaseOrigin">Contains origin information about the test case. Not
 /// mandatory.</param>
 /// <param name="frameworks">Test and mock frameworks for this test case.</param>
 public TestCase(MethodDefinition method, RelatedFrameworks frameworks, TestCaseOrigin testCaseOrigin = null)
 {
     TestMethod = method;
     _origin = testCaseOrigin;
     CallGraph = new GraphBuilder<MethodCall>(CalledMethodsFinder).Build(new MethodCall(null, method));
     Framework = frameworks != null ? frameworks.TestFramework : null;
     _mockFrameworks = frameworks != null ? frameworks.MockFrameworks : new IMockFramework[0];
 }
Esempio n. 5
0
 public void TestThatNodeTailsAreReachableThroughEnumeration()
 {
     var root = new SimpleNode("root");
     var child = new SimpleNode("child");
     root.AddChild(child);
     var graph = new GraphBuilder<SimpleNode>(GetChildren).Build(root);
     CollectionAssert.Contains(new List<SimpleNode>(graph.TailsFor(child)), root);
 }
Esempio n. 6
0
 public void TestThatBuilderHandlesCycle()
 {
     var root = new SimpleNode("root");
     var child = new SimpleNode("child");
     root.AddChild(child);
     child.AddChild(root);
     var graph = new GraphBuilder<SimpleNode>(GetChildren).Build(root);
     Assert.AreEqual(2, graph.Order);
 }
        public void handles_failures_gracefully_if_the_registry_cannot_be_loaded()
        {
            //290
            var graph = new PluginGraph();
            var builder = new GraphBuilder(graph);
            builder.AddRegistry("an invalid type name");

            graph.Log.ErrorCount.ShouldEqual(1);
            graph.Log.AssertHasError(290);
        }
Esempio n. 8
0
        public void TestThatGraphCanBeWalkedFromRoot()
        {
            var root = new SimpleNode("root");
            var child = new SimpleNode("child");
            root.AddChild(child);
            var graph = new GraphBuilder<SimpleNode>(GetChildren).Build(root);

            var result = graph.Walk().Aggregate("", (str, node) => str + node.ToString());
            Assert.AreEqual("rootchild", result);
        }
Esempio n. 9
0
        public void TestThatHeadsForRootWithTwoEdgesToChildIncludesChildTwice()
        {
            var root = new SimpleNode("root");
            var child = new SimpleNode("child");
            root.AddChild(child);
            root.AddChild(child);
            var graph = new GraphBuilder<SimpleNode>(GetChildren).Build(root);

            Assert.AreEqual(2, graph.HeadsFor(root).Count());
        }
Esempio n. 10
0
        public void TestThatHeadsAreOrderedBasedOnInput()
        {
            var root = new SimpleNode("root");
            var child1 = new SimpleNode("child1");
            var child2 = new SimpleNode("child2");
            root.AddChild(child1);
            root.AddChild(child2);
            var graph = new GraphBuilder<SimpleNode>(GetChildren).Build(root);

            Assert.AreSame(child1, graph.HeadByIndex(root, 0));
        }
        public void Call_the_action_on_configure_family_if_the_pluginType_is_found()
        {
            var typePath = new TypePath(typeof (IGateway));

            bool iWasCalled = false;
            var builder = new GraphBuilder(new PluginGraph());
            builder.ConfigureFamily(typePath, f =>
            {
                Assert.AreEqual(typeof (IGateway), f.PluginType);
                iWasCalled = true;
            });

            Assert.IsTrue(iWasCalled);
        }
Esempio n. 12
0
 public void TestThatGraphExposesRootNode()
 {
     var root = new SimpleNode("root");
     var graph = new GraphBuilder<SimpleNode>(GetChildren).Build(root);
     Assert.AreSame(root, graph.Root);
 }
Esempio n. 13
0
        public void ThatThatPathBetweenNodeAndChildContainsNodeAndChild()
        {
            var root = new SimpleNode("root");
            var child = new SimpleNode("child");
            root.AddChild(child);
            var graph = new GraphBuilder<SimpleNode>(GetChildren).Build(root);

            var paths = graph.FindPaths(root, child);
            Assert.AreEqual("root child", DescribePaths(paths));
        }
        public static void Init()
        {
            GraphBuilder builder = new GraphBuilder();

            builder.AddNode("63000011").AddNode("63000006").AddNode("63000012").AddNode("2000487").AddNode("2000496").AddNode("2000062")
            .AddNode("2000114").AddNode("2000115").AddNode("2000116").AddNode("2000117").AddNode("2000118").AddNode("2000001").AddNode("2000107")
            .AddNode("2000119").AddNode("2000083").AddNode("2000092").AddNode("2000084").AddNode("2000134").AddNode("2000136").AddNode("2000043")
            .AddNode("2000017").AddNode("2000014").AddNode("2000064").AddNode("2000137").AddNode("2000041").AddNode("2000135").AddNode("2000145")
            .AddNode("2000146").AddNode("2000402").AddNode("2000266").AddNode("2000265").AddNode("2000279").AddNode("2000162").AddNode("2000269")
            .AddNode("2000271").AddNode("2000272").AddNode("2000270").AddNode("2000273").AddNode("2000274").AddNode("2000275").AddNode("2000276")
            .AddNode("2000187").AddNode("2000277").AddNode("2000163").AddNode("2000167").AddNode("2000148").AddNode("2000216").AddNode("2000100")
            .AddNode("2000164").AddNode("2000147").AddNode("2000139").AddNode("2000110").AddNode("2000086").AddNode("2000111").AddNode("2000085")
            .AddNode("2000059").AddNode("2000003").AddNode("2000130").AddNode("2000002").AddNode("2000087").AddNode("2000088").AddNode("2000006")
            .AddNode("2000089").AddNode("2000101").AddNode("2000023").AddNode("2000005").AddNode("2000112").AddNode("2000129").AddNode("2000113")
            .AddNode("2000042").AddNode("2000182").AddNode("2000183").AddNode("2000063").AddNode("2000067").AddNode("2000102").AddNode("2000181")
            .AddNode("2000180").AddNode("2000131").AddNode("2000132").AddNode("2000108").AddNode("2000278").AddNode("2000214").AddNode("2000172")
            .AddNode("2000053").AddNode("2000090").AddNode("2000103").AddNode("2000060").AddNode("2000004").AddNode("2000024").AddNode("2000215")
            .AddNode("2000022").AddNode("2000048").AddNode("2000010").AddNode("2000267").AddNode("2000051").AddNode("2000050").AddNode("2000046")
            .AddNode("2000095").AddNode("2000096").AddNode("2000128").AddNode("2000045").AddNode("2000039").AddNode("2000056").AddNode("2000054")
            .AddNode("2000217").AddNode("2000168").AddNode("2000049").AddNode("2000169").AddNode("2000170").AddNode("2000094").AddNode("2000133")
            .AddNode("2000061").AddNode("2000097").AddNode("2000093").AddNode("2000044").AddNode("2000076").AddNode("2000104").AddNode("2000058")
            .AddNode("2000173").AddNode("2000174").AddNode("2000256").AddNode("2000175").AddNode("2000040").AddNode("2000011").AddNode("2000268")
            .AddNode("2000200").AddNode("2000192").AddNode("2000105").AddNode("2000203").AddNode("2000143").AddNode("2000057").AddNode("2000091")
            .AddNode("2000186").AddNode("2000185").AddNode("2000007").AddNode("2000009").AddNode("2000021").AddNode("2000038").AddNode("2000015")
            .AddNode("2000013").AddNode("2000166").AddNode("2000184").AddNode("2000231").AddNode("2000018").AddNode("2000255").AddNode("2000280")
            .AddNode("2000262").AddNode("2000259").AddNode("2000258").AddNode("2000257").AddNode("2000142").AddNode("2000165").AddNode("2000008")
            .AddNode("2000124").AddNode("2000138").AddNode("2000036").AddNode("2000377").AddNode("3000134").AddNode("3000146").AddNode("3000014")
            .AddNode("3000135").AddNode("3000136").AddNode("3000145").AddNode("3000059").AddNode("3000022").AddNode("3000130").AddNode("3000003")
            .AddNode("3000057").AddNode("3000143").AddNode("3000118").AddNode("3000117").AddNode("3000115").AddNode("3000165").AddNode("3000185")
            .AddNode("3000007").AddNode("3000009").AddNode("3000089").AddNode("3000006").AddNode("3000101").AddNode("3000024").AddNode("3000060")
            .AddNode("3000103").AddNode("3000090").AddNode("3000004").AddNode("3000043").AddNode("3000064").AddNode("3000092").AddNode("2010002")
            .AddNode("2010084").AddNode("2010043").AddNode("2010083").AddNode("2010020").AddNode("2010016").AddNode("2010009").AddNode("2010039")
            .AddNode("2010038").AddNode("2010036").AddNode("2010063").AddNode("2010023").AddNode("2010033").AddNode("2010047").AddNode("2010027")
            .AddNode("2010028").AddNode("2010030").AddNode("2010034").AddNode("2010029").AddNode("2010026").AddNode("2010062").AddNode("2010010")
            .AddNode("2010014").AddNode("2010019").AddNode("2010012").AddNode("2010022").AddNode("2010011").AddNode("2000176").AddNode("2000263")
            .AddNode("2000264").AddNode("2000261").AddNode("2000260").AddNode("2000411").AddNode("2000412").AddNode("2000413").AddNode("2000414")
            .AddNode("2000415").AddNode("2000171").AddNode("2000235").AddNode("2000236").AddNode("2000416").AddNode("2000417").AddNode("2000418")
            .AddNode("2020029").AddNode("2020041").AddNode("2020030").AddNode("2020031").AddNode("2020006").AddNode("2020004").AddNode("2020001")
            .AddNode("2020013").AddNode("2020032").AddNode("2020010").AddNode("2020034").AddNode("2020051").AddNode("2020016").AddNode("2020017")
            .AddNode("2020033").AddNode("2020003").AddNode("2020014").AddNode("2020009").AddNode("2020008").AddNode("2020018").AddNode("2020035")
            .AddNode("2020036").AddNode("2020037").AddNode("2000424").AddNode("2000425").AddNode("2000423");

            // Victoria island
            builder.AddBidirectionalLink("2000062", "2000114", 1);
            builder.AddBidirectionalLink("2000114", "2000115", 1);
            builder.AddBidirectionalLink("2000115", "2000116", 1);
            builder.AddBidirectionalLink("2000116", "2000117", 1);
            builder.AddBidirectionalLink("2000117", "2000118", 1);
            builder.AddBidirectionalLink("2000118", "2000001", 1);

            builder.AddBidirectionalLink("2000001", "2000487", 1);
            builder.AddBidirectionalLink("2000001", "2000002", 1);
            builder.AddBidirectionalLink("2000001", "2000064", 1);
            builder.AddBidirectionalLink("2000001", "2000119", 1);
            builder.AddBidirectionalLink("2000001", "2000107", 1);
            builder.AddBidirectionalLink("2020004", "2020001", 1);

            builder.AddBidirectionalLink("2000107", "2000119", 1);

            builder.AddBidirectionalLink("2000014", "2000119", 1);
            builder.AddBidirectionalLink("2000014", "2000134", 1);
            builder.AddBidirectionalLink("2000014", "2000092", 1);

            builder.AddBidirectionalLink("2000134", "2000092", 1);

            builder.AddBidirectionalLink("2000092", "2000135", 1);
            builder.AddBidirectionalLink("2000092", "2000084", 1);
            builder.AddBidirectionalLink("2000092", "2000083", 1);
            builder.AddBidirectionalLink("2000092", "2000119", 1);

            builder.AddBidirectionalLink("2000135", "2000136", 1);

            builder.AddBidirectionalLink("2000136", "2000145", 1);
            builder.AddBidirectionalLink("2000136", "2000266", 1);
            builder.AddBidirectionalLink("2000136", "2000137", 1);

            builder.AddBidirectionalLink("2000146", "2000145", 1);
            builder.AddBidirectionalLink("2000146", "2000136", 1);
            builder.AddBidirectionalLink("2000146", "2000402", 1);

            builder.AddBidirectionalLink("2000402", "2000496", 1);

            builder.AddBidirectionalLink("2000266", "2000137", 1);
            builder.AddBidirectionalLink("2000266", "2000265", 1);
            builder.AddBidirectionalLink("2000266", "2000279", 1);

            builder.AddBidirectionalLink("2000279", "2000265", 1);
            builder.AddBidirectionalLink("2000279", "2000162", 1);

            builder.AddBidirectionalLink("2000162", "2000269", 1);
            builder.AddBidirectionalLink("2000162", "2000271", 1);
            builder.AddBidirectionalLink("2000162", "2000265", 1);

            builder.AddBidirectionalLink("2000271", "2000272", 1);
            builder.AddBidirectionalLink("2000271", "2000269", 1);
            builder.AddBidirectionalLink("2000271", "2000270", 1);
            builder.AddBidirectionalLink("2000271", "2000163", 1);

            builder.AddBidirectionalLink("2000270", "2000273", 1);

            builder.AddBidirectionalLink("2000273", "2000274", 1);

            builder.AddBidirectionalLink("2000274", "2000275", 1);
            builder.AddBidirectionalLink("2000274", "2000276", 1);

            builder.AddBidirectionalLink("2000276", "2000187", 1);
            builder.AddBidirectionalLink("2000276", "2000163", 1);

            builder.AddBidirectionalLink("2000187", "2000277", 1);
            builder.AddBidirectionalLink("2000187", "2000163", 1);
            builder.AddBidirectionalLink("2000277", "2000163", 1);

            builder.AddBidirectionalLink("2000269", "2000163", 1);

            builder.AddBidirectionalLink("2000265", "2000148", 1);
            builder.AddBidirectionalLink("2000265", "2000167", 1);

            builder.AddBidirectionalLink("2000138", "2000137", 1);
            builder.AddBidirectionalLink("2000138", "2000139", 1);

            builder.AddBidirectionalLink("2000139", "2000148", 1);
            builder.AddBidirectionalLink("2000139", "2000147", 1);
            builder.AddBidirectionalLink("2000139", "2000110", 1);

            builder.AddBidirectionalLink("2000110", "2000084", 1);
            builder.AddBidirectionalLink("2000110", "2000086", 1);

            builder.AddBidirectionalLink("2000083", "2000041", 1);
            builder.AddBidirectionalLink("2000083", "2000084", 1);

            builder.AddBidirectionalLink("2000017", "2000064", 1);
            builder.AddBidirectionalLink("2000017", "2000041", 1);
            builder.AddBidirectionalLink("2000017", "2000043", 1);

            builder.AddBidirectionalLink("2000111", "2000086", 1);
            builder.AddBidirectionalLink("2000111", "2000085", 1);

            builder.AddBidirectionalLink("2000085", "2000043", 1);
            builder.AddBidirectionalLink("2000085", "2000059", 1);
            builder.AddBidirectionalLink("2000085", "2000054", 1);

            builder.AddBidirectionalLink("2000059", "2000043", 1);
            builder.AddBidirectionalLink("2000059", "2000054", 1);
            builder.AddBidirectionalLink("2000059", "2000003", 1);

            builder.AddBidirectionalLink("2000100", "2000148", 1);
            builder.AddBidirectionalLink("2000100", "2000167", 1);
            builder.AddBidirectionalLink("2000100", "2000164", 1);
            builder.AddBidirectionalLink("2000100", "2000216", 1);
            builder.AddBidirectionalLink("2000100", "2000166", 1);
            builder.AddBidirectionalLink("2000100", "2000147", 1);
            builder.AddBidirectionalLink("2000100", "2000165", 1);

            builder.AddBidirectionalLink("2000216", "2000164", 1);
            builder.AddBidirectionalLink("2000216", "2000167", 1);

            builder.AddBidirectionalLink("2000147", "2000091", 1);
            builder.AddBidirectionalLink("2000147", "2000165", 1);

            builder.AddBidirectionalLink("2000166", "2000165", 1);
            builder.AddBidirectionalLink("2000166", "2000142", 1);
            builder.AddBidirectionalLink("2000166", "2000184", 1);
            builder.AddBidirectionalLink("2000166", "2000231", 1);

            builder.AddBidirectionalLink("2000231", "2000184", 1);
            builder.AddBidirectionalLink("2000231", "2000255", 1);
            builder.AddBidirectionalLink("2000231", "2000280", 1);
            builder.AddBidirectionalLink("2000231", "2000018", 1);

            builder.AddBidirectionalLink("2000262", "2000018", 1);
            builder.AddBidirectionalLink("2000262", "2000280", 1);

            builder.AddBidirectionalLink("2000280", "2000255", 1);
            builder.AddBidirectionalLink("2000280", "2000257", 1);

            builder.AddBidirectionalLink("2000258", "2000259", 1);
            builder.AddBidirectionalLink("2000258", "2000257", 1);

            builder.AddBidirectionalLink("2000255", "2000184", 1);
            builder.AddBidirectionalLink("2000255", "2000257", 1);
            builder.AddBidirectionalLink("2000255", "2000142", 1);

            builder.AddBidirectionalLink("2000142", "2000184", 1);
            builder.AddBidirectionalLink("2000142", "2000165", 1);
            builder.AddBidirectionalLink("2000142", "2000008", 1);

            builder.AddBidirectionalLink("2000185", "2000165", 1);
            builder.AddBidirectionalLink("2000185", "2000186", 1);
            builder.AddBidirectionalLink("2000185", "2000007", 1);

            builder.AddBidirectionalLink("2000007", "2000008", 1);
            builder.AddBidirectionalLink("2000007", "2000009", 1);
            builder.AddBidirectionalLink("2000007", "2000021", 1);

            builder.AddBidirectionalLink("2000038", "2000021", 1);
            builder.AddBidirectionalLink("2000038", "2000009", 1);
            builder.AddBidirectionalLink("2000009", "2000021", 1);

            builder.AddBidirectionalLink("2000015", "2000021", 1);
            builder.AddBidirectionalLink("2000015", "2000013", 1);

            builder.AddBidirectionalLink("2000105", "2000013", 1);

            builder.AddBidirectionalLink("2000076", "2000054", 1);
            builder.AddBidirectionalLink("2000076", "2000104", 1);
            builder.AddBidirectionalLink("2000076", "2000105", 1);
            builder.AddBidirectionalLink("2000076", "2000203", 1);
            builder.AddBidirectionalLink("2000076", "2000143", 1);

            builder.AddBidirectionalLink("2000143", "2000203", 1);
            builder.AddBidirectionalLink("2000143", "2000057", 1);

            builder.AddBidirectionalLink("2000057", "2000186", 1);
            builder.AddBidirectionalLink("2000057", "2000091", 1);

            builder.AddBidirectionalLink("2000002", "2000087", 1);
            builder.AddBidirectionalLink("2000002", "2000088", 1);

            builder.AddBidirectionalLink("2000088", "2000087", 1);
            builder.AddBidirectionalLink("2000088", "2000006", 1);

            builder.AddBidirectionalLink("2000006", "2000089", 1);
            builder.AddBidirectionalLink("2000006", "2000036", 1);
            builder.AddBidirectionalLink("2000006", "2000101", 1);

            builder.AddBidirectionalLink("2000023", "2000129", 1);
            builder.AddBidirectionalLink("2000023", "2000005", 1);
            builder.AddBidirectionalLink("2000023", "2000036", 1);
            builder.AddBidirectionalLink("2000023", "2000101", 1);
            builder.AddBidirectionalLink("2000023", "2000102", 1);
            builder.AddBidirectionalLink("2000023", "2000112", 1);

            builder.AddBidirectionalLink("2000036", "2000101", 1);
            builder.AddBidirectionalLink("2000036", "2000005", 1);

            builder.AddBidirectionalLink("2000005", "2000129", 1);
            builder.AddBidirectionalLink("2000005", "2000113", 1);
            builder.AddBidirectionalLink("2000005", "2000042", 1);

            builder.AddBidirectionalLink("2000042", "2000113", 1);
            builder.AddBidirectionalLink("2000042", "2000063", 1);
            builder.AddBidirectionalLink("2000042", "2000182", 1);
            builder.AddBidirectionalLink("2000042", "2000183", 1);
            builder.AddBidirectionalLink("2000182", "2000183", 1);

            builder.AddBidirectionalLink("2000113", "2000129", 1);
            builder.AddBidirectionalLink("2000113", "2000063", 1);

            builder.AddBidirectionalLink("2000067", "2000063", 1);
            builder.AddBidirectionalLink("2000067", "2000377", 1);

            builder.AddBidirectionalLink("2000129", "2000112", 1);
            builder.AddBidirectionalLink("2000181", "2000180", 1);
            builder.AddBidirectionalLink("2000181", "2000129", 1);

            builder.AddBidirectionalLink("2000131", "2000180", 1);
            builder.AddBidirectionalLink("2000131", "2000132", 1);

            builder.AddBidirectionalLink("2000132", "2000108", 1);
            builder.AddBidirectionalLink("2000132", "2000278", 1);

            builder.AddBidirectionalLink("2000214", "2000172", 1);
            builder.AddBidirectionalLink("2000214", "2000278", 1);

            builder.AddBidirectionalLink("2000172", "2000053", 1);
            builder.AddBidirectionalLink("2000172", "2000102", 1);
            builder.AddBidirectionalLink("2000172", "2000090", 1);

            builder.AddBidirectionalLink("2000053", "2000090", 1);
            builder.AddBidirectionalLink("2000053", "2000102", 1);
            builder.AddBidirectionalLink("2000102", "2000112", 1);

            builder.AddBidirectionalLink("2000103", "2000090", 1);
            builder.AddBidirectionalLink("2000103", "2000060", 1);
            builder.AddBidirectionalLink("2000103", "2000048", 1);

            builder.AddBidirectionalLink("2000060", "2000048", 1);
            builder.AddBidirectionalLink("2000060", "2000004", 1);

            builder.AddBidirectionalLink("2000024", "2000004", 1);
            builder.AddBidirectionalLink("2000024", "2000101", 1);
            builder.AddBidirectionalLink("2000024", "2000215", 1);

            builder.AddBidirectionalLink("2000022", "2000215", 1);
            builder.AddBidirectionalLink("2000022", "2000130", 1);
            builder.AddBidirectionalLink("2000022", "2000128", 1);

            builder.AddBidirectionalLink("2000130", "2000003", 1);

            builder.AddBidirectionalLink("2000128", "2000096", 1);

            builder.AddBidirectionalLink("2000095", "2000096", 1);
            builder.AddBidirectionalLink("2000095", "2000046", 1);

            builder.AddBidirectionalLink("2000046", "2000050", 1);
            builder.AddBidirectionalLink("2000046", "2000045", 1);

            builder.AddBidirectionalLink("2000039", "2000045", 1);
            builder.AddBidirectionalLink("2000039", "2000056", 1);

            builder.AddBidirectionalLink("2000056", "2000054", 1);
            builder.AddBidirectionalLink("2000056", "2000104", 1);

            builder.AddBidirectionalLink("2000104", "2000058", 1);

            builder.AddBidirectionalLink("2000173", "2000058", 1);
            builder.AddBidirectionalLink("2000173", "2000174", 1);
            builder.AddBidirectionalLink("2000174", "2000256", 1);

            builder.AddBidirectionalLink("2000175", "2000256", 1);
            builder.AddBidirectionalLink("2000175", "2000040", 1);
            builder.AddBidirectionalLink("2000175", "2000192", 1);

            builder.AddBidirectionalLink("2000011", "2000040", 1);
            builder.AddBidirectionalLink("2000011", "2000268", 1);

            builder.AddBidirectionalLink("2000268", "2000200", 1);
            builder.AddBidirectionalLink("2000268", "2000235", 1);

            builder.AddBidirectionalLink("2000236", "2000235", 1);
            builder.AddBidirectionalLink("2000236", "2000416", 1);

            builder.AddBidirectionalLink("2000417", "2000416", 1);
            builder.AddBidirectionalLink("2000417", "2000418", 1);


            builder.AddBidirectionalLink("2000176", "2000192", 1);
            builder.AddBidirectionalLink("2000176", "2000261", 1);

            builder.AddBidirectionalLink("2000260", "2000261", 1);
            builder.AddBidirectionalLink("2000260", "2000263", 1);
            builder.AddBidirectionalLink("2000260", "2000264", 1);

            builder.AddBidirectionalLink("2000264", "2000263", 1);
            builder.AddBidirectionalLink("2000264", "2000415", 1);

            builder.AddBidirectionalLink("2000414", "2000415", 1);
            builder.AddBidirectionalLink("2000414", "2000413", 1);

            builder.AddBidirectionalLink("2000412", "2000413", 1);
            builder.AddBidirectionalLink("2000412", "2000411", 1);

            builder.AddBidirectionalLink("2000044", "2000411", 1);
            builder.AddBidirectionalLink("2000044", "2000171", 1);
            builder.AddBidirectionalLink("2000044", "2000093", 1);

            builder.AddBidirectionalLink("2000170", "2000171", 1);
            builder.AddBidirectionalLink("2000170", "2000169", 1);

            builder.AddBidirectionalLink("2000097", "2000093", 1);
            builder.AddBidirectionalLink("2000097", "2000061", 1);

            builder.AddBidirectionalLink("2000061", "2000133", 1);
            builder.AddBidirectionalLink("2000061", "2000094", 1);

            builder.AddBidirectionalLink("2000094", "2000168", 1);
            builder.AddBidirectionalLink("2000094", "2000049", 1);
            builder.AddBidirectionalLink("2000049", "2000169", 1);

            builder.AddBidirectionalLink("2000051", "2000049", 1);
            builder.AddBidirectionalLink("2000051", "2000168", 1);
            builder.AddBidirectionalLink("2000051", "2000217", 1);
            builder.AddBidirectionalLink("2000051", "2000267", 1);
            builder.AddBidirectionalLink("2000051", "2000010", 1);
            builder.AddBidirectionalLink("2000051", "2000050", 1);

            builder.AddBidirectionalLink("2000010", "2000050", 1);
            builder.AddBidirectionalLink("2000010", "2000048", 1);
            builder.AddBidirectionalLink("2000048", "2000267", 1);

            // Karkar island
            builder.AddBidirectionalLink("2010002", "2010010", 1);
            builder.AddBidirectionalLink("2010002", "2010084", 1);
            builder.AddBidirectionalLink("2010002", "2010009", 1);

            builder.AddBidirectionalLink("2010014", "2010019", 1);
            builder.AddBidirectionalLink("2010014", "2010010", 1);

            builder.AddBidirectionalLink("2010043", "2010084", 1);

            builder.AddBidirectionalLink("2010012", "2010009", 1);
            builder.AddBidirectionalLink("2010012", "2010039", 1);

            builder.AddBidirectionalLink("2010038", "2010039", 1);
            builder.AddBidirectionalLink("2010038", "2010036", 1);
            builder.AddBidirectionalLink("2010063", "2010036", 1);
            builder.AddBidirectionalLink("2010063", "2010023", 1);
            builder.AddBidirectionalLink("2010023", "2010033", 1);
            builder.AddBidirectionalLink("2010023", "2010036", 1);

            // Kritias
            builder.AddBidirectionalLink("2020041", "2020004", 1);
            builder.AddBidirectionalLink("2020041", "2020031", 1);
            builder.AddBidirectionalLink("2020041", "2020032", 1);
            builder.AddBidirectionalLink("2020041", "2020013", 1);

            builder.AddBidirectionalLink("2020031", "2020030", 1);
            builder.AddBidirectionalLink("2020030", "2020029", 1);
            builder.AddBidirectionalLink("2020032", "2020010", 1);

            builder.AddBidirectionalLink("2020051", "2020013", 1);
            builder.AddBidirectionalLink("2020051", "2020032", 1);
            builder.AddBidirectionalLink("2020051", "2020003", 1);

            builder.AddBidirectionalLink("2020008", "2020003", 1);
            builder.AddBidirectionalLink("2020008", "2020018", 1);
            builder.AddBidirectionalLink("2020008", "2020035", 1);

            builder.AddBidirectionalLink("2020033", "2020018", 1);
            builder.AddBidirectionalLink("2020033", "2020017", 1);
            builder.AddBidirectionalLink("2020016", "2020017", 1);
            builder.AddBidirectionalLink("2020016", "2020013", 1);

            WorldMapGraph = builder.Build();
        }
Esempio n. 15
0
        public void TestThatTwoPathsAreFoundForTwoEdgesBetweenVertices()
        {
            var root = new SimpleNode("root");
            var child = new SimpleNode("child");
            root.AddChild(child);
            root.AddChild(child);
            var graph = new GraphBuilder<SimpleNode>(GetChildren).Build(root);

            var paths = graph.FindPaths(root, child);
            Assert.AreEqual("root child\nroot child", DescribePaths(paths));
        }
Esempio n. 16
0
        public string WriteGraph(RootModel model, string file = null)
        {
            var regionNodes = new Node("record", "filled", "yellow");
            var envNodes    = new Node("doublecircle", "filled", "lightblue");
            var zoneNodes   = new Node("doublecircle", "filled", "lightgreen");

            var edgesTo = new Edge("bold", null, null);
            //var edgesFrom = new Edge("bold", null, null);
            var edgesBoth = new Edge("bold", null, "both");

            foreach (var region in model.Regions)
            {
                regionNodes.Elements.Add(region.Id);

                foreach (var env in region.Environments)
                {
                    envNodes.Elements.Add(env.Id);
                    edgesTo.Connections.Add(new Connection(region.Id, env.Id, ""));

                    foreach (var zone in env.Zones)
                    {
                        edgesTo.Connections.Add(new Connection(env.Id, zone.Id, ""));
                        zoneNodes.Elements.Add(zone.Id);
                    }

                    foreach (var rule in env.Rules)
                    {
                        if (rule.IsBidirectional)
                        {
                            edgesBoth.Connections.Add(new Connection(rule.From, rule.To, rule.Description));
                            //need a bidirectional edge
                        }
                        else
                        {
                            edgesTo.Connections.Add(new Connection(rule.From, rule.To, rule.Description));
                        }
                    }
                }
            }

            var graphBuilder = new GraphBuilder();

            var nodes = new List <Node>
            {
                regionNodes, envNodes, zoneNodes
            };

            var edges = new List <Edge>
            {
                edgesTo, edgesBoth
            };

            var dotGraph = graphBuilder.Build(nodes, edges, model.ZoneGroup);

            if (!string.IsNullOrWhiteSpace(file))
            {
                File.WriteAllText(file, dotGraph);
            }


            return(dotGraph);
        }
Esempio n. 17
0
 public Form1()
 {
     InitializeComponent();
     GraphBuilder.DrawPlots(plotExact, plotApprox);
 }
Esempio n. 18
0
        public List<TestEntry> GetTestsFor(List<string> assemblies)
        {
            var ret = new List<TestEntry>();
            var param = from a in assemblies select new BuildFullMapParams(a, a);
            BuildFullMap(param);
            toDispose.Clear();
            changes = GetChanges(assemblies);
            if (changes != null)
            {
                foreach (var change in changes)
                {
                    InvokeMinimizerMessage(MessageType.Debug, change.ChangeType + " " + change.ItemChanged.GetCacheName());
                }
                ReIndex(changes);
            }

            toDispose.ForEach(x => x.Dispose());
            ModuleDefinition.KillAllReadModules();
            var strategy = new GraphBuilder(_cache, _testStrategies, new IfInTestAssemblyContinueInterfaceFollowingStrategy(_cache), _debug, _numThreads);
            strategy.DebugMessage += (x,y) => InvokeMinimizerMessage(y.MessageType, y.Message);
            _lastAffectedGraph = strategy.GetAffectedGraphForChangeSet(changes);
            var entries = BuildEntriesFor(_lastAffectedGraph).ToList();
            foreach(var file in assemblies) WriteHistoryFile(file);
            return entries;
        }
 public static MathGenericNode AddMath(this GraphBuilder b, MathGeneratedFunction function)
 {
     return(b.AddNode(new MathGenericNode().WithFunction(function)));
 }
Esempio n. 20
0
        private GraphInfo GetGraph(GraphType type, ExposureDataAdaptor expData, GraphBuildCache GraphCache)
        {
            GraphBuilder builder = new GraphBuilder(GraphCache);

            return(builder.MakeGraph(type, expData));
        }
Esempio n. 21
0
        public void Do_not_call_the_action_on_ConfigureFamily_if_the_type_path_blows_up()
        {
            var builder = new GraphBuilder(new PluginGraph());

            builder.ConfigureFamily(new TypePath("a,a"), obj => Assert.Fail("Should not be called"));
        }
Esempio n. 22
0
        public void Should_have_false_value_for_all_adjacencies()
        {
            var graph = GraphBuilder.ValidUndirected();

            GraphTraversal.TraverseGraph(graph, graph.MyGraph[8], graph.MyGraph[2]);
        }
Esempio n. 23
0
        protected KahnTopologicalSortTests(Func <ISetGraphDensity <int>, IBuildGraph <int> > graphFactory)
        {
            var partialBuilder = new GraphBuilder <int>().Directed();

            Graph = graphFactory(partialBuilder).Build();
        }
Esempio n. 24
0
        public void DenyInvalidComplexCycle()
        {
            var builder = new GraphBuilder();

            Assert.Throws <InvalidOperationException>(() => builder.GenerateGraph("a-b-c\nb-d-e\nd-f-g\ng-b"));
        }
Esempio n. 25
0
        public void DenyInvalidDag()
        {
            var builder = new GraphBuilder();

            Assert.Throws <InvalidOperationException>(() => builder.GenerateGraph("a-b-a"));
        }
        static void HandleConstants(GraphBuilder builder, out INode node, out Dictionary <string, uint> portToOffsetMapping,
                                    IConstantNodeModel constantNodeModel)
        {
            portToOffsetMapping = new Dictionary <string, uint>();
            var outputPortId = constantNodeModel.OutputPort?.UniqueId ?? "";

            switch (constantNodeModel)
            {
            case StringConstantModel stringConstantModel:
            {
                var index = builder.StoreStringConstant(stringConstantModel.value);
                var cf    = new ConstantString {
                    Value = new StringReference(index)
                };
                node = MapPort(portToOffsetMapping, outputPortId, ref cf.ValuePort.Port, cf);
                return;
            }

            case BooleanConstantNodeModel booleanConstantNodeModel:
            {
                var cf = new ConstantBool {
                    Value = booleanConstantNodeModel.value
                };
                node = MapPort(portToOffsetMapping, outputPortId, ref cf.ValuePort.Port, cf);
                return;
            }

            case IntConstantModel intConstantModel:
            {
                var cf = new ConstantInt {
                    Value = intConstantModel.value
                };
                node = MapPort(portToOffsetMapping, outputPortId, ref cf.ValuePort.Port, cf);
                return;
            }

            case FloatConstantModel floatConstantModel:
            {
                var cf = new ConstantFloat {
                    Value = floatConstantModel.value
                };
                node = MapPort(portToOffsetMapping, outputPortId, ref cf.ValuePort.Port, cf);
                return;
            }

            case Vector2ConstantModel vector2ConstantModel:
            {
                var cf = new ConstantFloat2 {
                    Value = vector2ConstantModel.value
                };
                node = MapPort(portToOffsetMapping, outputPortId, ref cf.ValuePort.Port, cf);
                return;
            }

            case Vector3ConstantModel vector3ConstantModel:
            {
                var cf = new ConstantFloat3 {
                    Value = vector3ConstantModel.value
                };
                node = MapPort(portToOffsetMapping, outputPortId, ref cf.ValuePort.Port, cf);
                return;
            }

            case Vector4ConstantModel vector4ConstantModel:
            {
                var cf = new ConstantFloat4 {
                    Value = vector4ConstantModel.value
                };
                node = MapPort(portToOffsetMapping, outputPortId, ref cf.ValuePort.Port, cf);
                return;
            }

            case QuaternionConstantModel quaternionConstantModel:
            {
                var cf = new ConstantQuaternion {
                    Value = quaternionConstantModel.value
                };
                node = MapPort(portToOffsetMapping, outputPortId, ref cf.ValuePort.Port, cf);
                return;
            }

            case ObjectConstantModel _:
            {
                throw new NotImplementedException(
                          "Conversion and all - either a prefab (might live in a graph) or a scene object (must be injected during runtime bootstrap)");

                // portToOffsetMapping = new Dictionary<IPortModel, uint>();
                // var cf = new ConstantEntity {Value = objectConstantModel.value};
                // MapPort(portToOffsetMapping, objectConstantModel.OutputPort, ref cf.ValuePort.Port, nodeId);
                // node = cf;
                // return;
            }

            default:
                throw new NotImplementedException();
            }
        }
 public static GraphBuilder.VariableHandle BindVariableToDataIndex(this GraphBuilder b, string variableName)
 {
     return(b.BindVariableToDataIndex(variableName.ToBidingId()));
 }
Esempio n. 28
0
 public GreedyBot(BotBoard board)
 {
     _graph = GraphBuilder.Build(board);
 }
Esempio n. 29
0
        public void SetupGraph()
        {
            GraphBuilder = (IGraphBuilder) new FilterGraph();

            // Get ICaptureGraphBuilder2 to build the graph
            CaptureGraphBuilder2 = new CaptureGraphBuilder2() as ICaptureGraphBuilder2;

            try
            {
                ReturnHR = CaptureGraphBuilder2.SetFiltergraph(GraphBuilder);

                IBaseFilter source_filter = null;

                ReturnHR = GraphBuilder.AddSourceFilter(InputFile, "Source Filter", out source_filter);

                IBaseFilter       wmv_video_decoder_dmo = (IBaseFilter) new DMOWrapperFilter();
                IDMOWrapperFilter dmo_wrapper_filter_v  = (IDMOWrapperFilter)wmv_video_decoder_dmo;

                ReturnHR = dmo_wrapper_filter_v.Init(new Guid("{82D353DF-90BD-4382-8BC2-3F6192B76E34}"), DMOCategory.VideoDecoder);
                ReturnHR = GraphBuilder.AddFilter(wmv_video_decoder_dmo, "Wmv Video Decoder DMO");

                IBaseFilter       wmv_audio_decoder_dmo = (IBaseFilter) new DMOWrapperFilter();
                IDMOWrapperFilter dmo_wrapper_filter_a  = (IDMOWrapperFilter)wmv_audio_decoder_dmo;

                ReturnHR = dmo_wrapper_filter_a.Init(new Guid("{2EEB4ADF-4578-4D10-BCA7-BB955F56320A}"), DMOCategory.AudioDecoder);
                ReturnHR = GraphBuilder.AddFilter(wmv_audio_decoder_dmo, "Wmv Audio Decoder DMO");

                IBaseFilter vp8_encoder = (IBaseFilter) new VP8Encoder();
                ReturnHR = GraphBuilder.AddFilter(vp8_encoder, "VP8 Encoder");

                IVP8Encoder vp8_encoder_interface = (IVP8Encoder)vp8_encoder;
                if (target_bitrate != 0)
                {
                    vp8_encoder_interface.SetTargetBitrate(target_bitrate);
                }

                IBaseFilter webm_muxer = (IBaseFilter) new WebMMuxer();
                ReturnHR = GraphBuilder.AddFilter(webm_muxer, "WebM Muxer");

                IBaseFilter vorbis_encoder = (IBaseFilter) new VorbisEncoder();
                ReturnHR = GraphBuilder.AddFilter(vorbis_encoder, "Vorbis Encoder");

                IBaseFilter file_writer = (IBaseFilter) new FileWriter();
                ReturnHR = GraphBuilder.AddFilter(file_writer, "file writer");
                IFileSinkFilter filewriter_sink = file_writer as IFileSinkFilter;
                ReturnHR = filewriter_sink.SetFileName(OutputFile, null);

                ReturnHR = GraphBuilder.ConnectDirect(FindPin("Raw Video 1", source_filter), FindPin("in0", wmv_video_decoder_dmo), null);
                ReturnHR = GraphBuilder.ConnectDirect(FindPin("Raw Audio 0", source_filter), FindPin("in0", wmv_audio_decoder_dmo), null);
                ReturnHR = GraphBuilder.ConnectDirect(FindPin("out0", wmv_audio_decoder_dmo), FindPin("PCM In", vorbis_encoder), null);
                ReturnHR = GraphBuilder.ConnectDirect(FindPin("out0", wmv_video_decoder_dmo), FindPin("YUV", vp8_encoder), null);
                ReturnHR = GraphBuilder.ConnectDirect(FindPin("Vorbis Out", vorbis_encoder), FindPin("audio", webm_muxer), null);
                ReturnHR = GraphBuilder.ConnectDirect(FindPin("VP80", vp8_encoder), FindPin("video", webm_muxer), null);
                ReturnHR = GraphBuilder.ConnectDirect(FindPin("outpin", webm_muxer), FindPin("in", file_writer), null);
            }
            catch (Exception)
            {
                LogError("Failed to initialize FilterGraph.");
            }
            finally
            {
                if (CaptureGraphBuilder2 != null)
                {
                    Marshal.ReleaseComObject(CaptureGraphBuilder2);
                    CaptureGraphBuilder2 = null;
                }
            }
        }
Esempio n. 30
0
        void RenderOpaqueGBuffer(Camera RenderCamera, CullingResults CullingData, NativeArray <FVisibleMeshBatch> VisibleMeshBatchList)
        {
            //Request Resource
            RendererList  RenderList   = RendererList.Create(CreateRendererListDesc(CullingData, RenderCamera, InfinityPassIDs.OpaqueGBuffer));
            RDGTextureRef DepthTexture = GraphBuilder.ScopeTexture(InfinityShaderIDs.RT_DepthBuffer);

            RDGTextureDesc GBufferDescA = new RDGTextureDesc(RenderCamera.pixelWidth, RenderCamera.pixelHeight)
            {
                clearBuffer = true, clearColor = Color.clear, dimension = TextureDimension.Tex2D, enableMSAA = false, bindTextureMS = false, name = "GBufferATexture", colorFormat = GraphicsFormat.R16G16B16A16_UNorm
            };
            RDGTextureDesc GBufferDescB = new RDGTextureDesc(RenderCamera.pixelWidth, RenderCamera.pixelHeight)
            {
                clearBuffer = true, clearColor = Color.clear, dimension = TextureDimension.Tex2D, enableMSAA = false, bindTextureMS = false, name = "GBufferBTexture", colorFormat = GraphicsFormat.A2B10G10R10_UIntPack32
            };
            RDGTextureRef GBufferTextureA = GraphBuilder.CreateTexture(GBufferDescA, InfinityShaderIDs.RT_ThinGBufferA);
            RDGTextureRef GBufferTextureB = GraphBuilder.CreateTexture(GBufferDescB, InfinityShaderIDs.RT_ThinGBufferB);

            GraphBuilder.ScopeTexture(InfinityShaderIDs.RT_ThinGBufferA, GBufferTextureA);
            GraphBuilder.ScopeTexture(InfinityShaderIDs.RT_ThinGBufferB, GBufferTextureB);

            //Add RenderPass
            GraphBuilder.AddRenderPass <FOpaqueGBufferData>("OpaqueGBuffer", ProfilingSampler.Get(CustomSamplerId.OpaqueGBuffer),
                                                            (ref FOpaqueGBufferData PassData, ref RDGPassBuilder PassBuilder) =>
            {
                PassData.RendererList = RenderList;
                PassData.GBufferA     = PassBuilder.UseColorBuffer(GBufferTextureA, 0);
                PassData.GBufferB     = PassBuilder.UseColorBuffer(GBufferTextureB, 1);
                PassData.DepthBuffer  = PassBuilder.UseDepthBuffer(DepthTexture, EDepthAccess.ReadWrite);
            },
                                                            (ref FOpaqueGBufferData PassData, RDGContext GraphContext) =>
            {
                //Draw UnityRenderer
                RendererList GBufferRenderList = PassData.RendererList;
                GBufferRenderList.drawSettings.perObjectData         = PerObjectData.Lightmaps;
                GBufferRenderList.drawSettings.enableInstancing      = RenderPipelineAsset.EnableInstanceBatch;
                GBufferRenderList.drawSettings.enableDynamicBatching = RenderPipelineAsset.EnableDynamicBatch;
                GBufferRenderList.filteringSettings.renderQueueRange = new RenderQueueRange(0, 2450);
                GraphContext.RenderContext.DrawRenderers(GBufferRenderList.cullingResult, ref GBufferRenderList.drawSettings, ref GBufferRenderList.filteringSettings);

                //Draw CustomRenderer
                RenderWorld World = GraphContext.World;
                NativeList <FMeshBatch> MeshBatchList = World.GetMeshBatchColloctor().GetMeshBatchList();

                if (VisibleMeshBatchList.Length == 0)
                {
                    return;
                }

                for (int i = 0; i < VisibleMeshBatchList.Length; i++)
                {
                    FVisibleMeshBatch VisibleMeshBatch = VisibleMeshBatchList[i];
                    if (VisibleMeshBatch.visible)
                    {
                        FMeshBatch MeshBatch = MeshBatchList[VisibleMeshBatch.index];
                        Mesh mesh            = World.WorldMeshList.Get(MeshBatch.Mesh);
                        Material material    = World.WorldMaterialList.Get(MeshBatch.Material);

                        if (mesh && material)
                        {
                            GraphContext.CmdBuffer.DrawMesh(mesh, MeshBatch.Matrix_LocalToWorld, material, MeshBatch.SubmeshIndex, 2);
                        }
                    }
                }
            });
        }
Esempio n. 31
0
 public QueryTests()
 {
     graph      = GraphBuilder.WaltDisneyGraphBuild();
     donaldduck = new RDFResource("http://www.waltdisney.com/donald_duck");
 }
Esempio n. 32
0
        public void TestThatPathsCanBeFoundWhenThereIsACycle()
        {
            var root = new SimpleNode("root");
            var child = new SimpleNode("child");
            var target = new SimpleNode("target");
            var back = new SimpleNode("back");

            root.AddChild(child);
            child.AddChild(target);
            child.AddChild(back);
            back.AddChild(root);

            var graph = new GraphBuilder<SimpleNode>(GetChildren).Build(root);

            var paths = graph.FindPaths(root, target);

            var result = string.Join("|", paths.Select(path => string.Join(",", path)));
            Assert.AreEqual("root,child,target|root,child,back,root,child,target", result);
        }
Esempio n. 33
0
        public void TestThatTailsForChildWithTwoEdgesToRootIncludesRootTwice()
        {
            var root = new SimpleNode("root");
            var child = new SimpleNode("child");
            root.AddChild(child);
            root.AddChild(child);
            var graph = new GraphBuilder<SimpleNode>(GetChildren).Build(root);

            Assert.AreEqual(2, graph.TailsFor(child).Count());
        }
Esempio n. 34
0
 public Deserializer()
 {
     builder = new GraphBuilder();
 }
Esempio n. 35
0
        public void TestThatTwoPathsAreFoundInDiamondGraph()
        {
            var root = new SimpleNode("root");
            var child1 = new SimpleNode("child1");
            var child2 = new SimpleNode("child2");
            var end = new SimpleNode("end");
            root.AddChild(child1);
            root.AddChild(child2);
            child1.AddChild(end);
            child2.AddChild(end);
            var graph = new GraphBuilder<SimpleNode>(GetChildren).Build(root);

            var paths = graph.FindPaths(root, end);
            Assert.AreEqual("root child1 end\nroot child2 end", DescribePaths(paths));
        }
Esempio n. 36
0
        //
        // Main Dryad LINQ execution stuff
        //
        public int ExecLinqToDryad(string[] args)
        {
            //
            // must be at least two arguments (program name and query XML file name)
            //
            if (args.Length < 2)
            {
                DryadLogger.LogCritical(0, null, "Must provide at least query XML file name.");
                return -1;
            }

            //
            // break if --break is included in arguments (and eliminate it, as it is not known downstream)
            //
            if (ConsumeSingleArgument("--break", ref args))
            {
                DebugHelper.WaitForDebugger();
            }

            //
            // parse the XML input, producing a DryadLINQ Query
            //
            Query query = new Query();
            QueryPlanParser parser = new QueryPlanParser();
            if (!parser.ParseQueryXml(args[1], query))
            {
                DryadLogger.LogCritical(0, null, "Invalid query plan");
                return -1;
            }

            //
            // build internal app arguments
            //
            List<string> internalArgs = new List<string>();

            //
            // add the XmlExecHost args to the internal app arguments
            //
            foreach (string xmlExecHostArg in query.xmlExecHostArgs)

            {
                if (xmlExecHostArg == "--break")
                {
                    DebugHelper.WaitForDebugger();
                }
                else
                {
                    internalArgs.Add(xmlExecHostArg);
                }
            }

            //
            // combine internal arguments with any additional arguments received on the command line
            // don't include argv[0] and argv[1] (program name and query XML file name)
            //

            int internalArgc = (int)internalArgs.Count;
            int externalArgc = args.Length - 2;          // don't include argv[0] and argv[1]
            int combinedArgc = internalArgc + externalArgc;
            string[] combinedArgv = new string[combinedArgc];

            string msg = "";
            // internal arguments first
            for (int i=0; i<internalArgc; i++)
            {
                combinedArgv[i] = internalArgs[i];
                msg += String.Format("{0} ", combinedArgv[i]);
            }

            // then external arguments
            for (int i = 0; i<externalArgc; i++)
            {
                combinedArgv[i+internalArgc] = args[i+2]; // don't include argv[0] and argv[1]

                msg += String.Format("{0} ", combinedArgv[i+internalArgc]);
            }
            DryadLogger.LogInformation(null, "Arguments: {0}", msg);

            string jobClass = "DryadLINQ";
            string dryadBinDir = Environment.GetEnvironmentVariable("DRYAD_HOME");
            if (String.IsNullOrEmpty(dryadBinDir))
            {
                throw new ApplicationException("DryadLINQ requires the DRYAD_HOME environment variable to be set to the Dryad binary folder.");
            }
            string exeName = Path.Combine(dryadBinDir, "VertexHost.exe");

            // create app and run it
            //
            DrGraphParameters p = DrDefaultParameters.Make(exeName, jobClass, query.enableSpeculativeDuplication);

            DrArtemisLegacyReporter reporter = new DrArtemisLegacyReporter();
            p.m_defaultProcessTemplate.GetListenerList().Add(reporter);
            p.m_defaultVertexTemplate.GetListenerList().Add(reporter);
            p.m_topologyReporter = reporter;
            p.m_intermediateCompressionMode = query.intermediateDataCompression;
            DrGraphExecutor graphExecutor = new DrGraphExecutor();
            DrGraph graph = graphExecutor.Initialize(p);
            if (graph == null)
            {
                DryadLogger.LogCritical(0, null, "Failed to initialize Graph Executor");
                return -1;
            }
            DryadLINQApp app = new DryadLINQApp(graph);

            // Initialize with arguments
            app.SetXmlFileName(args[1]);
            if (!app.ParseCommandLineFlags(combinedArgv))
            {
                DryadLogger.LogCritical(0, null, "Bad command-line options");
                return -1;
            }
            // Build graph from query plan
            GraphBuilder builder = new GraphBuilder();
            builder.BuildGraphFromQuery(app, query);

            // Run the app
            DryadLogger.LogInformation(null, "Running the app");

            graphExecutor.Run();
            DrError exitStatus = graphExecutor.Join();

            DryadLogger.LogInformation(null, "Finished running the app");

            if (exitStatus == null || exitStatus.m_code == 0)
            {
                FinalizeExecution(query, graph);
                DryadLogger.LogInformation(null, "Application completed successfully.");
                return 0;
            }
            else
            {
                DryadLogger.LogCritical(exitStatus.m_code, null, "Application failed with error code 0x{0:X8}.\n", exitStatus.m_code);
                return exitStatus.m_code;
            }
        }
Esempio n. 37
0
        public void TestThatWalkingIsDepthFirst()
        {
            var root = new SimpleNode("root");
            var child11 = new SimpleNode("child11");
            var child12 = new SimpleNode("child12");
            var child111 = new SimpleNode("child111");
            root.AddChild(child11);
            root.AddChild(child12);
            child11.AddChild(child111);
            var graph = new GraphBuilder<SimpleNode>(GetChildren).Build(root);

            var result = graph.Walk().Aggregate("", (str, node) => str + node.ToString());
            Assert.AreEqual("rootchild11child111child12", result);
        }
Esempio n. 38
0
 private static Graph<Instruction> CreateInstructionGraph(MethodDefinition method)
 {
     var builder = new GraphBuilder<Instruction>(NextInstructions);
     return builder.Build(method.Body.Instructions[0]);
 }
Esempio n. 39
0
        public void ThatThatThereIsSinglePathBetweenNodeAndItself()
        {
            var root = new SimpleNode("root");
            var graph = new GraphBuilder<SimpleNode>(GetChildren).Build(root);

            var paths = graph.FindPaths(root, root);
            Assert.AreEqual("root", DescribePaths(paths));
        }
Esempio n. 40
0
        public IEnumerable<AssemblyScanner> GetScanners(PluginGraphBuilder builder)
        {
            ConfigurationParser[] parsers = GetParsers(builder.Log);
            var graphBuilder = new GraphBuilder(builder.Graph);

            foreach (var p in parsers)
            {
                builder.Log.StartSource(p.Description);
                p.ParseRegistries(graphBuilder);
                p.ParseAssemblies(graphBuilder);
            }

            yield return graphBuilder.AssemblyScanner;
        }
Esempio n. 41
0
        public object Write(
            object data, 
            string masterPassphrase,
            params KeyValuePair<string, string>[] parameters)
        {
            if (data.GetType() != typeof(Vault)) throw new ArgumentException("Data must be of type 'Vault'.", "data");

            DLoggerManager.Instance.Logger.Log(DFramework.Logging.Interfaces.LoggerMessageType.VerboseHigh | DFramework.Logging.Interfaces.LoggerMessageType.Information, "Writing Vault to AES encrypted byte array.");

            Dictionary<string, string> parametersDict = parameters.ToDictionary(x => x.Key, x => x.Value);

            Vault dataVault = (Vault)data;

            JSONVaultSerialiser jsonSerialiser = new JSONVaultSerialiser();
            JObject json = (JObject)jsonSerialiser.Write(dataVault, String.Empty, parameters);

            String jsonString = json.ToString(Newtonsoft.Json.Formatting.None, null);
            Byte[] salt = SimpleRandomGenerator.QuickGetRandomBytes(16);

            GraphBuilder decryptGraph = new GraphBuilder("AESEncryptedVaultSerialiser.Read");
            GraphIO<String> unencryptedInput = new GraphIO<String>(jsonString);
            GraphIO<Byte[]> saltInput = new GraphIO<Byte[]>(salt);

            //create derive node here
            IGraphNode keyDerivationNode = null;

            if (parametersDict.ContainsKey("KeyDerivationFunction"))
            {
                string keyDerivationFunction = parametersDict["KeyDerivationFunction"];
                switch (keyDerivationFunction)
                {
                    case "PBKDF2":
                        {
                            int iterationCount = int.Parse(parametersDict["IterationCount"]);
                            keyDerivationNode = new Rfc2898DeriveBytesNode(new GraphIO<String>(String.Empty), new GraphIO<Int32>(32), saltInput, new GraphIO<int>(iterationCount));
                            decryptGraph.AddNode("deriveNode", keyDerivationNode);
                            break;
                        }
                    case "SCRYPT":
                        {
                            int iterationCount = int.Parse(parametersDict["IterationCount"]);
                            int blockSize = int.Parse(parametersDict["BlockSize"]);
                            int threadCount = int.Parse(parametersDict["ThreadCount"]);
                            keyDerivationNode = new SCryptDeriveBytesNode(new GraphIO<String>(String.Empty), new GraphIO<Int32>(32), saltInput, new GraphIO<int>(iterationCount), new GraphIO<int>(blockSize), new GraphIO<int>(threadCount));
                            decryptGraph.AddNode("deriveNode", keyDerivationNode);
                            break;
                        }
                    default:
                        {
                            throw new InvalidOperationException(String.Format("Unknown key derivation function '{0}'.", keyDerivationFunction));
                        }
                }
            }
            else
            {
                //default setup
                keyDerivationNode = new Rfc2898DeriveBytesNode(new GraphIO<String>(String.Empty), new GraphIO<Int32>(32), saltInput, new GraphIO<int>(10000));
                decryptGraph.AddNode("deriveNode", keyDerivationNode);
            }

            AESEncryptNode encryptNode = new AESEncryptNode(unencryptedInput, new GraphIO<Byte[]>(null), keyDerivationNode.GetBytesIO("DerivedKey"));

            decryptGraph.AddNode("encryptNode", encryptNode);
            decryptGraph.CreateRoute("encrypt",
                keyDerivationNode.GetStringIO("Password"),
                encryptNode.EncryptedData,
                "deriveNode",
                new String[] { "deriveNode", "encryptNode" });

            Object output = null;
            if (decryptGraph.Process(true, "encrypt", masterPassphrase, out output))
            {
                byte[] encrypted = (byte[])output;
                byte[] encryptedWithSalt = encrypted.AppendBytes(salt);
                return (encryptedWithSalt);
            }
            else
            {
                throw new Exception("Failed to encrypt Vault.");
            }

            throw new NotImplementedException();
        }
 public void SetUp() => _graphDict = GraphBuilder.GetGraphs();
Esempio n. 43
0
        public object Read(
            object data, 
            string masterPassphrase,
            params KeyValuePair<string, string>[] parameters)
        {
            if (data.GetType() != typeof(Byte[])) throw new ArgumentException("Data must be of type 'Byte[]'.", "data");

            DLoggerManager.Instance.Logger.Log(DFramework.Logging.Interfaces.LoggerMessageType.VerboseHigh | DFramework.Logging.Interfaces.LoggerMessageType.Information, "Reading Vault from AES encrypted byte array.");

            Dictionary<string, string> parametersDict = parameters.ToDictionary(x => x.Key, x => x.Value);

            byte[] dataBytesWithSalt = (Byte[])data;
            byte[] dataBytes;
            byte[] salt;
            dataBytesWithSalt.RemoveFromEnd(16, out dataBytes, out salt);

            GraphBuilder decryptGraph = new GraphBuilder("AESEncryptedVaultSerialiser.Read");
            GraphIO<Byte[]> encryptedInput = new GraphIO<Byte[]>(dataBytes);
            GraphIO<Byte[]> saltInput = new GraphIO<Byte[]>(salt);

            IGraphNode keyDerivationNode = null;

            if(parametersDict.ContainsKey("KeyDerivationFunction"))
            {
                string keyDerivationFunction = parametersDict["KeyDerivationFunction"];
                switch (keyDerivationFunction)
                {
                    case "PBKDF2":
                        {
                            int iterationCount = int.Parse(parametersDict["IterationCount"]);
                            keyDerivationNode = new Rfc2898DeriveBytesNode(new GraphIO<String>(String.Empty), new GraphIO<Int32>(32), saltInput, new GraphIO<int>(iterationCount));
                            decryptGraph.AddNode("deriveNode", keyDerivationNode);
                            break;
                        }
                    case "SCRYPT":
                        {
                            int iterationCount = int.Parse(parametersDict["IterationCount"]);
                            int blockSize = int.Parse(parametersDict["BlockSize"]);
                            int threadCount = int.Parse(parametersDict["ThreadCount"]);
                            keyDerivationNode = new SCryptDeriveBytesNode(new GraphIO<String>(String.Empty), new GraphIO<Int32>(32), saltInput, new GraphIO<int>(iterationCount), new GraphIO<int>(blockSize), new GraphIO<int>(threadCount));
                            decryptGraph.AddNode("deriveNode", keyDerivationNode);
                            break;
                        }
                    default:
                        {
                            throw new InvalidOperationException(String.Format("Unknown key derivation function '{0}'.", keyDerivationFunction));
                        }
                }
            }
            else
            {
                keyDerivationNode = new Rfc2898DeriveBytesNode(new GraphIO<String>(String.Empty), new GraphIO<Int32>(32), saltInput, new GraphIO<Int32>(10000));
                decryptGraph.AddNode("deriveNode", keyDerivationNode);
            }

            AESDecryptNode decryptNode = new AESDecryptNode(encryptedInput, new GraphIO<Byte[]>(null), keyDerivationNode.GetBytesIO("DerivedKey"));

            decryptGraph.AddNode("decryptNode", decryptNode);
            decryptGraph.CreateRoute("decrypt",
                keyDerivationNode.GetStringIO("Password"),
                decryptNode.UnencryptedData,
                "deriveNode",
                new String[] { "deriveNode", "decryptNode" });

            Object output = null;
            if (decryptGraph.Process(true, "decrypt", masterPassphrase, out output))
            {
                String decryptedJSON = (String)output;
                JObject json = JObject.Parse(decryptedJSON);

                JSONVaultSerialiser jsonSerialiser = new JSONVaultSerialiser();
                Vault vault = (Vault)jsonSerialiser.Read(json, String.Empty);
                return (vault);
            }
            else
            {
                throw new Exception("Failed to decrypt Vault.");
            }
        }
Esempio n. 44
0
        public override void OnInspectorGUI()
        {
            bool dirty = false;
            ScriptingGraphAuthoring authoring  = target as ScriptingGraphAuthoring;
            VSGraphAssetModel       assetModel = null;

            if (authoring.ScriptingGraph)
            {
                var path = AssetDatabase.GetAssetPath(authoring.ScriptingGraph);
                assetModel = AssetDatabase.LoadAssetAtPath <VSGraphAssetModel>(path);
            }

            var newAssetModel =
                EditorGUILayout.ObjectField("Scripting Graph", assetModel, typeof(VSGraphAssetModel)) as
                VSGraphAssetModel;

            if (assetModel != newAssetModel)
            {
                dirty = true;
                if (newAssetModel)
                {
                    authoring.ScriptingGraph = ((DotsStencil)newAssetModel.GraphModel.Stencil).CompiledScriptingGraphAsset;
                }
                else
                {
                    authoring.ScriptingGraph = null;
                }
            }

            // I/O
            if (!(newAssetModel?.GraphModel is VSGraphModel graph))
            {
                return;
            }
            if (m_ProcessedBindings == null)
            {
                m_ProcessedBindings = new HashSet <BindingId>();
            }
            else
            {
                m_ProcessedBindings.Clear();
            }

            foreach (var graphVariableModel in graph.GraphVariableModels)
            {
                var variableType = GraphBuilder.GetVariableType(graphVariableModel);
                switch (variableType)
                {
                case GraphBuilder.VariableType.SmartObject:
                case GraphBuilder.VariableType.ObjectReference:
                    BindingId id = GetExistingBinding(graphVariableModel, authoring, out var binding);
                    m_ProcessedBindings.Add(id);
                    if (binding == null)
                    {
                        dirty = true;
                        authoring.Values.Add(binding = new ScriptingGraphAuthoring.InputBindingAuthoring(id));
                    }

                    var valueType = graphVariableModel.DataType.TypeHandleToValueType();
                    EditorGUI.BeginChangeCheck();
                    switch (valueType)
                    {
                    case ValueType.Entity:
                        binding.Object = EditorGUILayout.ObjectField(graphVariableModel.Name, binding.Object,
                                                                     typeof(GameObject), true);
                        break;

                    default:
                        EditorGUILayout.LabelField(graphVariableModel.Name, valueType.ToString());
                        break;
                    }

                    if (EditorGUI.EndChangeCheck())
                    {
                        dirty = true;
                    }
                    break;

                case GraphBuilder.VariableType.InputOutput:
                case GraphBuilder.VariableType.Variable:
                    continue;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }

            if (authoring.Values != null)
            {
                for (var index = authoring.Values.Count - 1; index >= 0; index--)
                {
                    var binding = authoring.Values[index];
                    if (!m_ProcessedBindings.Contains(binding.Id))
                    {
                        authoring.Values.RemoveAt(index);
                        dirty = true;
                    }
                }
            }

            if (dirty)
            {
                EditorUtility.SetDirty(authoring);
            }
        }
Esempio n. 45
0
        private ITaskItem[] GetRepositoryBuildOrder(IEnumerable <ArtifactInfo.Package> artifacts, IEnumerable <SolutionInfo> solutions)
        {
            var repositories = solutions.Select(s =>
            {
                var repoName = Path.GetFileName(Path.GetDirectoryName(s.FullPath));
                var repo     = new Repository(repoName)
                {
                    RootDir = Path.GetDirectoryName(s.FullPath)
                };

                var packages = artifacts
                               .Where(a => string.Equals(a.RepoName, repoName, StringComparison.OrdinalIgnoreCase))
                               .ToDictionary(p => p.PackageInfo.Id, p => p, StringComparer.OrdinalIgnoreCase);

                foreach (var proj in s.Projects)
                {
                    IList <Project> projectGroup;
                    if (packages.ContainsKey(proj.PackageId))
                    {
                        // this project is a package producer and consumer
                        packages.Remove(proj.PackageId);
                        projectGroup = repo.Projects;
                    }
                    else
                    {
                        // this project is a package consumer
                        projectGroup = repo.SupportProjects;
                    }


                    projectGroup.Add(new Project(proj.PackageId)
                    {
                        Repository        = repo,
                        PackageReferences = new HashSet <string>(proj
                                                                 .Frameworks
                                                                 .SelectMany(f => f.Dependencies.Keys)
                                                                 .Concat(proj.Tools.Select(t => t.Id)), StringComparer.OrdinalIgnoreCase),
                    });
                }

                foreach (var packageId in packages.Keys)
                {
                    // these packages are produced from something besides a csproj. e.g. .Sources packages
                    repo.Projects.Add(new Project(packageId)
                    {
                        Repository = repo
                    });
                }

                return(repo);
            }).ToList();

            var graph = GraphBuilder.Generate(repositories, StartGraphAt, Log);
            var repositoriesWithOrder = new List <(ITaskItem repository, int order)>();

            foreach (var repository in repositories)
            {
                var graphNodeRepository = graph.FirstOrDefault(g => g.Repository.Name == repository.Name);
                if (graphNodeRepository == null)
                {
                    // StartGraphAt was specified so the graph is incomplete.
                    continue;
                }

                var order = TopologicalSort.GetOrder(graphNodeRepository);
                var repositoryTaskItem = new TaskItem(repository.Name);
                repositoryTaskItem.SetMetadata("Order", order.ToString());
                repositoryTaskItem.SetMetadata("RootPath", repository.RootDir);
                repositoriesWithOrder.Add((repositoryTaskItem, order));
            }

            Log.LogMessage(MessageImportance.High, "Repository build order:");
            foreach (var buildGroup in repositoriesWithOrder.GroupBy(r => r.order).OrderBy(g => g.Key))
            {
                var buildGroupRepos = buildGroup.Select(b => b.repository.ItemSpec);
                Log.LogMessage(MessageImportance.High, $"{buildGroup.Key.ToString().PadLeft(2, ' ')}: {string.Join(", ", buildGroupRepos)}");
            }

            return(repositoriesWithOrder
                   .OrderBy(r => r.order)
                   .Select(r => r.repository)
                   .ToArray());
        }
Esempio n. 46
0
        /// <summary>
        /// Builds the minimum spanning tree of a given graph.
        /// </summary>
        /// <typeparam name="TV">Type of the graph vertex values.</typeparam>
        /// <typeparam name="TW">Type of the graph edge weights.</typeparam>
        /// <param name="graph">The graph got which to build the minimum spanning tree.</param>
        /// <returns>Returns the minimum spanning tree of the given graph.</returns>
        public static IWeightedGraph <TV, TW> FindMinimumSpanningTree <TV, TW>(IWeightedGraph <TV, TW> graph, TW min, TW max)
            where TV : IEquatable <TV>
            where TW : IComparable
        {
            // Builder used to incrementally build the target minimum spanning tree
            GraphBuilder <TV, TW> builder = new GraphBuilder <TV, TW>();

            // Get all verteces and edges of graph
            IEnumerable <IVertex <TV> >           verteces = graph.GetAllVerteces();
            IEnumerable <IWeightedEdge <TV, TW> > edges    = graph.GetAllEdges();

            // TODO: replace with more performant priority queue implementation
            // Track minimum known cost to connect to target vertex
            IPriorityQueue <TV, TW> vertexCosts = new NaivePriorityQueue <TV, TW>();

            // Track target vertex and edge connecting to target vertex with minimum known cost
            Dictionary <TV, IVertex <TV> >           vertexValue = new Dictionary <TV, IVertex <TV> >();
            Dictionary <TV, IWeightedEdge <TV, TW> > vertexEdges = new Dictionary <TV, IWeightedEdge <TV, TW> >();

            // Initialize vertex costs with all costs set to max
            foreach (IVertex <TV> vertex in verteces)
            {
                vertexCosts.Enqueue(vertex.Value, max);
                vertexValue.Add(vertex.Value, vertex);
                vertexEdges.Add(vertex.Value, null);
            }

            // Set starting vertex
            vertexCosts.UpdatePriority(verteces.First().Value, min);

            // While there are verteces left to add, select vertex with smallest cost
            while (!vertexCosts.Empty)
            {
                // Get and remove vertex with smallest cost
                TV minCost = vertexCosts.Dequeue().Item1;

                // For easier handling, get vertex and edge
                IVertex <TV>           vertex = vertexValue[minCost];
                IWeightedEdge <TV, TW> edge   = vertexEdges[minCost];

                // Add vertex and edge to target MST
                builder.AddVertex(vertex.Value);
                if (edge != null)
                {
                    builder.AddEdge(vertex.Value, edge.ConnectedVertex(vertex.Value).Value, edge.Weight);
                }

                // Update vertex cost for adjacent verteces and store edges
                foreach (IWeightedEdge <TV, TW> connectedEdge in graph.GetEdgesOfVertex(vertex))
                {
                    // Ignore edges leading to verteces already added to the MST
                    IVertex <TV> targetVertex = connectedEdge.ConnectedVertex(vertex);
                    if (vertexCosts.Contains(targetVertex.Value) &&
                        connectedEdge.Weight.CompareTo(vertexCosts.GetPriorityOf(targetVertex.Value)) < 0)
                    {
                        vertexCosts.UpdatePriority(targetVertex.Value, connectedEdge.Weight);
                        vertexEdges[targetVertex.Value] = connectedEdge;
                    }
                }
            }

            // All verteces added to MST - done!
            return(builder.Build());
        }
Esempio n. 47
0
            public string BuildDeleteCommandText(GraphBuilder graph)
            {
                var deleteSql = string.Join("\n", BuildCommands(graph));

                return($"BEGIN\n{deleteSql}\nEND;");
            }
Esempio n. 48
0
        private int _Remove(IBaseFilter filter)
        {
            var hr = GraphBuilder.RemoveFilter(filter);

            return(hr);
        }
Esempio n. 49
0
        //
        // Main Dryad LINQ execution stuff
        //
        public int ExecLinqToDryad(Uri dfsDirectory, string[] args, out string errorString)
        {
            //
            // must be at least two arguments (program name and query XML file name)
            //
            if (args.Length < 2)
            {
                errorString = "Must provide at least query XML file name and VertexHost executable.";
                DryadLogger.LogCritical(errorString);
                return -1;
            }

            //
            // break if --break is included in arguments (and eliminate it, as it is not known downstream)
            //
            if (ConsumeSingleArgument("--break", ref args))
            {
                DebugHelper.WaitForDebugger();
            }

            // this is where we ensure the right type of scheduler is registered
            Microsoft.Research.Dryad.LocalScheduler.Registration.Ensure();

            //
            // parse the XML input, producing a DryadLINQ Query
            //
            Query query = new Query();
            QueryPlanParser parser = new QueryPlanParser();
            if (!parser.ParseQueryXml(args[1], query))
            {
                errorString = "Invalid query plan";
                DryadLogger.LogCritical(errorString);
                return -1;
            }

            //
            // upload the query plan to the job DFS directory for the benefit of debug tools
            //
            if (dfsDirectory != null)
            {
                DebugHelper.UploadToDfs(dfsDirectory, args[1]);
            }

            //
            // build internal app arguments
            //
            List<string> internalArgs = new List<string>();

            //
            // add the XmlExecHost args to the internal app arguments
            //
            foreach (string xmlExecHostArg in query.xmlExecHostArgs)

            {
                if (xmlExecHostArg == "--break")
                {
                    DebugHelper.WaitForDebugger();
                }
                else
                {
                    internalArgs.Add(xmlExecHostArg);
                }
            }

            //
            // combine internal arguments with any additional arguments received on the command line
            // don't include argv[0] and argv[1] (program name and query XML file name)
            //

            int internalArgc = (int)internalArgs.Count;
            int externalArgc = args.Length - 2;          // don't include argv[0] and argv[1]
            int combinedArgc = internalArgc + externalArgc;
            string[] combinedArgv = new string[combinedArgc];

            string msg = "";
            // internal arguments first
            for (int i=0; i<internalArgc; i++)
            {
                combinedArgv[i] = internalArgs[i];
                msg += String.Format("{0} ", combinedArgv[i]);
            }
            
            // then external arguments
            for (int i = 0; i<externalArgc; i++)
            {
                combinedArgv[i+internalArgc] = args[i+2]; // don't include argv[0] and argv[1]

                msg += String.Format("{0} ", combinedArgv[i+internalArgc]);
            }
            DryadLogger.LogInformation(String.Format("Arguments: {0}", msg));

            string jobClass = "DryadLINQ";
            string exeName = args[0];
            
            // create app and run it
            //
            DrGraphParameters p = DrDefaultParameters.Make(exeName, jobClass, query.enableSpeculativeDuplication);

            foreach (DrIReporter reporter in DebugHelper.Reporters())
            {
                p.m_reporters.Add(reporter);
            }
            p.m_intermediateCompressionMode = query.intermediateDataCompression;
            DrGraphExecutor graphExecutor = new DrGraphExecutor();
            DrGraph graph = graphExecutor.Initialize(p);
            if (graph == null)
            {
                errorString = "Failed to initialize Graph Executor";
                DryadLogger.LogCritical(errorString);
                return -1;
            }
            DryadLINQApp app = new DryadLINQApp(graph);
            
            // Initialize with arguments
            app.SetXmlFileName(args[1]);
            if (!app.ParseCommandLineFlags(combinedArgv))
            {
                errorString = "Bad command-line options";
                DryadLogger.LogCritical(errorString);
                return -1;
            }
            // Build graph from query plan
            GraphBuilder builder = new GraphBuilder();
            builder.BuildGraphFromQuery(app, query);

            // Run the app
            DryadLogger.LogInformation("Running the app");
            
            graphExecutor.Run();
            DrError exitStatus = graphExecutor.Join();

            DryadLogger.LogInformation("Finished running the app");
            
            if (exitStatus == null || exitStatus.m_code == 0)
            {
                FinalizeExecution(query, graph);
                DryadLogger.LogInformation("Application completed successfully.");
                errorString = null;
                return 0;
            }
            else
            {
                DryadLogger.LogCritical(String.Format("Application failed with error code 0x{0:X8}.\n", exitStatus.m_code));
                errorString = exitStatus.ToFullTextNative();
                return exitStatus.m_code;
            }
        }
Esempio n. 50
0
        public Graph <int, double> CreateGraphFromFile(string filePath)
        {
            FileInfo file = new FileInfo(filePath);

            if (file.Exists)
            {
                List <Vertex <int> >       verteces = new List <Vertex <int> >();
                List <Edge <int, double> > edges    = new List <Edge <int, double> >();

                using (StreamReader streamReader = file.OpenText())
                {
                    int lineNumber       = 1;
                    int numberOfVerteces = 0;

                    // Get number of verteces from first line
                    string line = streamReader.ReadLine();
                    if (line != null)
                    {
                        if (int.TryParse(line, out numberOfVerteces))
                        {
                            for (int i = 0; i < numberOfVerteces; i++)
                            {
                                verteces.Add(new Vertex <int>(i));
                            }
                        }
                        else
                        {
                            throw new ParserException($"Error while parsing file '{filePath}': expected vertex count on line 1.");
                        }
                    }
                    else
                    {
                        throw new ParserException($"Error while parsing file '{filePath}': file empty.");
                    }
                    lineNumber++;

                    // Read and set balances
                    for (int i = 0; i < numberOfVerteces; i++)
                    {
                        if ((line = streamReader.ReadLine()) != null)
                        {
                            if (double.TryParse(line, NumberStyles.Float, CultureInfo.InvariantCulture, out double balance))
                            {
                                verteces[i].SetAttribute(Constants.BALANCE, balance);
                            }
                            else
                            {
                                throw new ParserException($"Error while parsing file '{filePath}': expected a balance value at line {lineNumber}.");
                            }
                        }
                        else
                        {
                            throw new ParserException($"Error while parsing file '{filePath}': file ended unexpectedly at line {lineNumber}.");
                        }
                        lineNumber++;
                    }

                    // Read edges with and capacity as weight and set costs
                    while ((line = streamReader.ReadLine()) != null)
                    {
                        string[] components = line.Split('\t');
                        if (components.Length != 4)
                        {
                            throw new ParserException($"Error while parsing file '{filePath}': expected 4 elements at line {lineNumber}.");
                        }
                        if (int.TryParse(components[0], out int weightedStartingVertexValue) &&
                            int.TryParse(components[1], out int weightedTargetVertexValue) &&
                            double.TryParse(components[2], NumberStyles.Float, CultureInfo.InvariantCulture, out double costs) &&
                            double.TryParse(components[3], NumberStyles.Float, CultureInfo.InvariantCulture, out double weight))
                        {
                            Edge <int, double> edge = new Edge <int, double>(verteces[weightedStartingVertexValue], verteces[weightedTargetVertexValue], weight);
                            edge.SetAttribute(Constants.COSTS, costs);
                            edges.Add(edge);
                        }
                        else
                        {
                            throw new FormatException("Failed parsing text line, expected two integers and a floating point value.");
                        }
                    }
                }

                // Build and return graph
                GraphBuilder <int, double> builder = new GraphBuilder <int, double>(true);
                builder.AddVerteces(verteces);
                builder.AddEdges(edges);
                return(builder.Build());
            }
            else
            {
                throw new FileNotFoundException("Graph input file not found.", filePath);
            }
        }
Esempio n. 51
0
        public IEnumerable<IConfigurationSource> DiscoveredConfigurations(PluginGraphBuilder builder)
        {
            ConfigurationParser[] parsers = GetParsers(builder.Log);
            var graphBuilder = new GraphBuilder(builder.Graph);

            foreach (var p in parsers)
            {
                builder.Log.StartSource(p.Description);
                p.ParseRegistries(graphBuilder);
            }

            return graphBuilder.DiscoveredConfigurations;
        }
Esempio n. 52
0
        public static IWeightedGraph <TV, TW> FindShortestPath <TV, TW>(IWeightedGraph <TV, TW> graph,
                                                                        IVertex <TV> source,
                                                                        IVertex <TV> target,
                                                                        TW zeroValue,
                                                                        TW maxValue,
                                                                        Func <TW, TW, TW> combineCosts) where TV : IEquatable <TV> where TW : IComparable
        {
            Dictionary <IVertex <TV>, TW> distance = new Dictionary <IVertex <TV>, TW>();
            Dictionary <IVertex <TV>, IWeightedEdge <TV, TW> > predecessor = new Dictionary <IVertex <TV>, IWeightedEdge <TV, TW> >();

            // Initialize distance and predecessor maps
            foreach (IVertex <TV> vertex in graph.GetAllVerteces())
            {
                distance.Add(vertex, maxValue);
                predecessor.Add(vertex, null);
            }
            distance[source] = zeroValue;

            // Relax edges repeatedly
            IEnumerable <IWeightedEdge <TV, TW> > edges = graph.GetAllEdges();

            for (int i = 0; i < graph.VertexCount - 1; i++)
            {
                foreach (IWeightedEdge <TV, TW> edge in edges)
                {
                    if (graph.IsDirected)
                    {
                        try
                        {
                            IWeightedDirectedEdge <TV, TW> directedEdge = (IWeightedDirectedEdge <TV, TW>)edge;
                            RelaxEdge(distance, predecessor, directedEdge.OriginVertex, directedEdge.TargetVertex, directedEdge.Weight, directedEdge, combineCosts);
                        }
                        catch
                        {
                            throw new Exception("Failed casting edge to directed edge for directed graph.");
                        }
                    }
                    else
                    {
                        IVertex <TV> sourceVertex = edge.Verteces.First();
                        IVertex <TV> targetVertex = edge.ConnectedVertex(sourceVertex);
                        RelaxEdge(distance, predecessor, sourceVertex, targetVertex, edge.Weight, edge, combineCosts);
                        RelaxEdge(distance, predecessor, targetVertex, sourceVertex, edge.Weight, edge, combineCosts);
                    }
                }
            }

            // Check for negative - weight cycles
            foreach (IWeightedEdge <TV, TW> edge in graph.GetAllEdges())
            {
                if (graph.IsDirected)
                {
                    IWeightedDirectedEdge <TV, TW> directedEdge = (IWeightedDirectedEdge <TV, TW>)edge;
                    CheckForNegativeCycles(distance, directedEdge.OriginVertex, directedEdge.TargetVertex, directedEdge.Weight, combineCosts);
                }
                else
                {
                    IVertex <TV> sourceVertex = edge.Verteces.First();
                    IVertex <TV> targetVertex = edge.ConnectedVertex(sourceVertex);
                    CheckForNegativeCycles(distance, sourceVertex, targetVertex, edge.Weight, combineCosts);
                    CheckForNegativeCycles(distance, targetVertex, sourceVertex, edge.Weight, combineCosts);
                }
            }

            // Build and output path
            IVertex <TV>          currentVertex = target;
            GraphBuilder <TV, TW> builder       = new GraphBuilder <TV, TW>(true).AddVertex(target.Value);

            while (currentVertex != source)
            {
                IWeightedEdge <TV, TW> pathEdge       = predecessor[currentVertex];
                IVertex <TV>           previousVertex = pathEdge.ConnectedVertex(currentVertex);
                builder
                .AddVertex(previousVertex.Value)
                .AddEdge(previousVertex.Value, currentVertex.Value, pathEdge.Weight);
                currentVertex = previousVertex;
            }
            return(builder.Build());
        }
Esempio n. 53
0
        public void Configure(PluginGraphBuilder builder)
        {
            ConfigurationParser[] parsers = GetParsers(builder.Log);
            var graphBuilder = new GraphBuilder(builder.Graph);

            foreach (var p in parsers)
            {
                builder.Log.StartSource(p.Description);
                p.Parse(graphBuilder);
            }
        }
Esempio n. 54
0
        //------------------------------------------------------------------------------------------------------------------------
        public GenericRsp HandleGraphDeploymentReq(GraphDeploymentReq req, bool SupressSave)
        {
            lock (locker)
            {
                var res = new GenericRsp();
                try
                {
                    //get graphkey
                    var graphkey = (GraphKey)req.GraphKey;
                    if (graphkey.IsInvalid)
                    {
                        res.IsSuccess = false;
                        res.Message   = "Invalid GraphKey";
                        return(res);
                    }
                    if (graphkey.NodeId != this.Node.NodeKey.NodeID)
                    {
                        res.IsSuccess = false;
                        res.Message   = "Invalid NodeID in GraphKey";
                        return(res);
                    }

                    //collect sets
                    var sets = Node.BeginActiveThingsUpdate();

                    //deploy or undeploy?
                    if (req.IsDeployed)
                    {
                        //deserialize graph descriptor
                        GraphDescriptor graphDescriptor;
                        try { graphDescriptor = GraphBuilder.GetGraphDescriptorFromJson(req.GraphDescriptor, false); }
                        catch (Exception ex)
                        {
                            DebugEx.Assert(ex, "Could not deserialize graph descriptor");
                            res.IsSuccess = false;
                            res.Message   = "Could not deserialize graph descriptor";
                            return(res);
                        }
                        graphDescriptor.GraphKey = graphkey;

                        //Build Graph
                        Graph graph;
                        try { graph = BuildGraph(graphDescriptor); }
                        catch (Exception ex)
                        {
                            DebugEx.Assert(ex, "Could not build graph from graph descriptor (unhandled exception)");
                            res.IsSuccess = false;
                            res.Message   = "Could not  build graph from graph descriptor (unhandled exception)";
                            return(res);
                        }
                        if (graph == null)
                        {
                            DebugEx.Assert("Could not build graph from graph descriptor");
                            res.IsSuccess = false;
                            res.Message   = "Could not  build graph from graph descriptor";
                            return(res);
                        }

                        //set key
                        graph.GraphKey = graphkey;

                        //do i already have it?
                        if (Graphs.ContainsKey(graphkey))
                        {
                            //invalidate graph
                            _GraphManager.InvalidateGraph(graphkey);
                            //remove information
                            Graphs.Remove(graphkey);
                        }

                        //try deploy graph
                        try
                        {
                            Exception exception;
                            var       depres = graph.OnDeploy(true, null, out exception);
                            if (!depres)
                            {
                                res.IsSuccess = false;
                                res.Message   = "Graph OnDeploy() failed. Message : " + (exception?.Message ?? "null");
                                return(res);
                            }
                        }
                        catch (Exception ex)
                        {
                            DebugEx.Assert(ex, "Graph OnDeploy() failed");
                            res.IsSuccess = false;
                            res.Message   = "Graph OnDeploy() failed. Message : " + ex.Message;
                            return(res);
                        }

                        //add to lookup
                        var gi = new GraphInfo()
                        {
                            GraphKey              = graphkey,
                            GraphDescriptor       = graphDescriptor,
                            GraphDescriptorString = req.GraphDescriptor,
                            Graph = graph,
                        };
                        Graphs.Add(graphkey, gi);

                        //save!
                        if (IsInitialized && !SupressSave)
                        {
                            Save();
                        }

                        //associate block keys
                        foreach (var thingblock in graph.Blocks.OfType <BaseThings>())
                        {
                            //Add to Thing2Block set
                            {
                                //find block key set
                                var set = ThingKey2BlockKey.TryGetOrDefault(thingblock.ThingKey);
                                if (set == null)
                                {
                                    set = new HashSetTS <BlockKey>();
                                    ThingKey2BlockKey.Add(thingblock.ThingKey, set);
                                }
                                //add to loockup set
                                set.Add(thingblock.BlockKey);
                            }

                            //Add only for thingIn
                            if (thingblock.IsThingIn)
                            {
                                //find block key set
                                var set = ThingKey2ThingInBlockKey.TryGetOrDefault(thingblock.ThingKey);
                                if (set == null)
                                {
                                    set = new HashSetTS <BlockKey>();
                                    ThingKey2ThingInBlockKey.Add(thingblock.ThingKey, set);
                                }
                                //add to loockup set
                                set.Add(thingblock.BlockKey);
                            }
                        }

                        //Handle Deploy
                        res.IsSuccess = true;
                        res.Message   = "Graph Deployed Successfully";
                    }
                    else
                    {
                        //Handle UnDeploy
                        if (Graphs.ContainsKey(graphkey) == false)
                        {
                            res.IsSuccess = true;
                            res.Message   = "Graph Undeployed Successfully (was not deployed)";
                        }
                        else
                        {
                            //get graph
                            var gi    = Graphs[graphkey];
                            var graph = gi.Graph;
                            //inform graph
                            Exception exception;
                            try
                            {
                                if (graph.OnUndeploy(null, out exception) == false)
                                {
                                    DebugEx.Assert(exception, "Graph OnUndeploy failed");
                                }
                            }
                            catch (Exception ex) { DebugEx.Assert(ex, "Graph OnUndeploy failed"); }
                            //invalidate graph
                            _GraphManager.InvalidateGraph(graphkey);
                            //remove information
                            Graphs.Remove(graphkey);
                            //save!
                            if (IsInitialized && !SupressSave)
                            {
                                Save();
                            }
                            //disassociate block keys
                            if (graph != null)
                            {
                                foreach (var thingblock in gi.Graph.Blocks.OfType <BaseThings>())
                                {
                                    //remove from thing2block
                                    {
                                        var set = ThingKey2BlockKey.TryGetOrDefault(thingblock.ThingKey);
                                        if (set != null)
                                        {
                                            set.Remove(thingblock.BlockKey);
                                        }
                                    }

                                    //remove from thignIn2block
                                    if (thingblock.IsThingIn)
                                    {
                                        var set = ThingKey2ThingInBlockKey.TryGetOrDefault(thingblock.ThingKey);
                                        if (set != null)
                                        {
                                            set.Remove(thingblock.BlockKey);
                                        }
                                    }
                                }
                            }
                            //done
                            res.IsSuccess = true;
                            res.Message   = "Graph Undeployed Successfully";
                        }
                    }

                    //finish update
                    Node.EndActiveThingsUpdate(sets);
                }
                catch (Exception ex)
                {
                    res.IsSuccess = false;
                    res.Message   = "Unhandled exception in GraphDeploymentReq(). Message=" + ex.Message;
                }
                finally
                {
                    //begin activation state snapshot
                    var sets = Node.BeginActiveThingsUpdate();

                    //update active ports/things
                    var activeThings = ThingKey2BlockKey.Where(kv => kv.Value.Count > 0)
                                       .Select(kv => Node.Things.TryGetOrDefaultReadOnly(kv.Key))
                                       .WhereNotNull().ToHashSetTS();
                    var activeThingKeys = activeThings.Select(t => (ThingKey)t.ThingKey).ToHashSetTS();

                    var activePorts     = activeThings.SelectMany(t => t.Ports).ToHashSetTS();
                    var activePortsKeys = activePorts.Select(p => (PortKey)p.PortKey).ToHashSetTS();

                    //update sets
                    Interlocked.Exchange(ref _ActiveThings, activeThings);
                    Interlocked.Exchange(ref _ActivePorts, activePorts);
                    Interlocked.Exchange(ref _ActiveThingKeys, activeThingKeys);
                    Interlocked.Exchange(ref _ActivePortKeys, activePortsKeys);

                    //trigger node thing activation update
                    Node.EndActiveThingsUpdate(sets);
                }
                //return result msg
                return(res);
            }
        }
Esempio n. 55
0
 public AffectedGraph GetGraphFor(string cacheName, bool debug)
 {
     var strategy = new GraphBuilder(_cache, _testStrategies, new IfInTestAssemblyContinueInterfaceFollowingStrategy(_cache), debug, _numThreads);
     strategy.DebugMessage += (x,y) => InvokeMinimizerMessage(y.MessageType, y.Message);
     return strategy.GetCouplingGraphFor(cacheName);
 }
Esempio n. 56
0
        static void Main(string[] args)
        {
            ParseArguments(args);

            if (PdbFilePath == null)
            {
                Console.Error.WriteLine(@"PDBSharp.Dumper
  Usage: PDBSharp.Dumper <options> <file.pdb>
    [-dump]            Save individual PDB Streams to files
    [-dump-modules]    Verbose output for DBI Modules
    [-dump-leaves]     Verbose output for TPI Leaves
    [-dump-syms]       Verbose output for DBI Symbols
    [-print-decls]     Extract and print type definitions
    [-print-fpo]       Print FPO entries
    [-print-sc]        Print Section Contribution entries
    [-print-syms]      Print symbol entries
    [-print-types]     Print type
    [-print-tpihash]   Print TPIHash");
                Environment.Exit(1);
            }

            Console.WriteLine("Starting...");
            Stopwatch sw = new Stopwatch();

            sw.Start();

            PDBFile           pdb = PDBFile.Open(PdbFilePath);
            IServiceContainer sc  = pdb.Services;

            DBIReader         dbi         = sc.GetService <DBIReader>();
            TPIReader         tpi         = sc.GetService <TPIReader>();
            StreamTableReader streamTable = sc.GetService <StreamTableReader>();

            if (OptPrintDecls)
            {
                var tree = new GraphBuilder(sc).Build();
                if (tree != null)
                {
                    CodeWriter cw = new CodeWriter(tree);
                    cw.Write(Console.Out);
                }
            }

            if (OptDumpLeaves)
            {
                pdb.OnTpiInit += Pdb_OnTpiInit;
            }
            if (OptDumpModules || OptDumpSymbols)
            {
                pdb.OnDbiInit += Pdb_OnDbiInit;
            }

            if (OptDumpStreams)
            {
                DirectoryInfo dumpDir = Directory.CreateDirectory(Path.GetFileNameWithoutExtension(PdbFilePath));
                for (int i = 1; i < streamTable.NumStreams; i++)
                {
                    string dumpPath = Path.Combine(dumpDir.ToString(), $"stream{i}.bin");

                    byte[] stream = streamTable.GetStream(i);
                    File.WriteAllBytes(dumpPath, stream);
                }
            }

            /*
             * foreach(var type in ctx.TpiReader.Types) {
             *      //Console.WriteLine(type);
             * }*/

            TPIHashReader      tpiHash      = sc.GetService <TPIHashReader>();
            UdtNameTableReader udtNameTable = sc.GetService <UdtNameTableReader>();
            TypeResolver       resolver     = sc.GetService <TypeResolver>();

            if (tpiHash != null && tpiHash.NameIndexToTypeIndex != null && udtNameTable != null)
            {
                foreach (var pair in tpiHash.NameIndexToTypeIndex)
                {
                    string         name = udtNameTable.GetString(pair.Key);
                    ILeafContainer leaf = resolver.GetTypeByIndex(pair.Value);
                    if (OptPrintTpiHash)
                    {
                        Console.WriteLine($"=> {name} [NI={pair.Key}] [TI={pair.Value}]");
                        Console.WriteLine(leaf.Data.GetType().Name);
                    }
                }
            }

            if (dbi != null)
            {
                if (dbi.SectionContribs.SectionContribs != null)
                {
                    foreach (var contrib in dbi.SectionContribs.SectionContribs)
                    {
                        if (OptPrintSc)
                        {
                            ObjectDumper.Dump(contrib);
                        }
                    }
                }

                DebugReader debug = dbi.DebugInfo;
                if (debug != null && OptPrintFpo && debug.FPO != null)
                {
                    foreach (var frame in debug.FPO.Frames)
                    {
                        ObjectDumper.Dump(frame);
                    }
                }

                if (dbi.Modules != null)
                {
                    foreach (var container in dbi.Modules)
                    {
                        Console.WriteLine($"[MODULE => {container.Info.ModuleName}]");
                        Console.WriteLine($"[OBJECT => {container.Info.ObjectFileName}]");
                        Console.WriteLine($"[SRC    => {container.Info.SourceFileName}]");
                        if (container.Module != null)
                        {
                            Console.WriteLine($"[TYPE   => {container.Module.GetType().Name}");
                        }
                        Console.WriteLine();

                        IModule mod = container.Module;
                        if (mod != null)
                        {
                            foreach (var sym in mod.Symbols)
                            {
                                if (OptPrintSyms)
                                {
                                    Console.WriteLine(sym);
                                }
                            }
                        }
                    }
                }
            }

            foreach (var type in tpi.Types)
            {
                if (OptPrintTypes)
                {
                    Console.WriteLine(type.Type);
                }
            }

            sw.Stop();
            Console.WriteLine($"Finished in {sw.Elapsed.TotalSeconds} seconds");
        }
Esempio n. 57
0
 private IEnumerable<IList<MethodCall>> AddPathsToRoot(MethodCall call)
 {
     if (!DoesContainAssertion(call))
         return new IList<MethodCall>[0];
     var graph = CallGraph;
     // Create a graph with edges in the other direction so we can
     // backtrack from this method to the test method (root).
     var builder = new GraphBuilder<MethodCall>(graph.TailsFor);
     var backGraph = builder.Build(call);
     return backGraph.FindPaths(call, graph.Root);
 }
Esempio n. 58
0
            public ControlFlowGraph Build(List <BasicBlock> blocks)
            {
                if (!blocks.Any())
                {
                    Connect(_start, _end);
                }
                else
                {
                    Connect(_start, blocks.First());
                }

                foreach (var block in blocks)
                {
                    foreach (var statement in block.Statements)
                    {
                        _blockFromStatement.Add(statement, block);
                        if (statement is BoundLabelStatement labelStatement)
                        {
                            _blockFromLabel.Add(labelStatement.Label, block);
                        }
                    }
                }

                for (var i = 0; i < blocks.Count; i++)
                {
                    var current = blocks[i];
                    var next    = i == blocks.Count - 1 ? _end : blocks[i + 1];

                    foreach (var statement in current.Statements)
                    {
                        var isLastStatementInBlock = statement == current.Statements.Last();
                        switch (statement.Kind)
                        {
                        case BoundNodeKind.GotoStatement:
                            var gotoStatement = (BoundGotoStatement)statement;
                            var gotoBlock     = _blockFromLabel[gotoStatement.Label];
                            Connect(current, gotoBlock);
                            break;

                        case BoundNodeKind.ConditionalGotoStatement:
                            var cgs              = (BoundConditionalGotoStatement)statement;
                            var thenBlock        = _blockFromLabel[cgs.Label];
                            var elseBlock        = next;
                            var negatedCondition = GraphBuilder.Negate(cgs.Condition);
                            var thenCondition    = cgs.JumpIfTrue ? cgs.Condition : negatedCondition;
                            var elseCondition    = cgs.JumpIfTrue ? negatedCondition : cgs.Condition;
                            Connect(current, thenBlock, thenCondition);
                            Connect(current, elseBlock, elseCondition);
                            break;

                        case BoundNodeKind.ReturnStatement:
                            Connect(current, _end);
                            break;

                        case BoundNodeKind.VariableDeclaration:
                        case BoundNodeKind.LabelStatement:
                        case BoundNodeKind.ExpressionStatement:
                            if (isLastStatementInBlock)
                            {
                                Connect(current, next);
                            }
                            break;

                        default:
                            throw new Exception($"Unexpected statement: { statement.Kind }");
                        }
                    }
                }

ScanAgain:
                foreach (var block in blocks)
                {
                    if (!block.Incoming.Any())
                    {
                        RemoveBlock(blocks, block);
                        goto ScanAgain;
                    }
                }

                blocks.Insert(0, _start);
                blocks.Add(_end);

                return(new ControlFlowGraph(_start, _end, blocks, _branches));
            }
        void IPluginGraphConfiguration.Configure(PluginGraph graph)
        {
            var builder = new GraphBuilder(graph);

            ParseRegistries(builder);
            Parse(builder);
        }
Esempio n. 60
0
        public static IWeightedGraph <TV, TW> FindMaxFlow <TV, TW>(IWeightedGraph <TV, TW> graph,
                                                                   IVertex <TV> source,
                                                                   IVertex <TV> target,
                                                                   Func <TW, TW, TW> combineFlowValues,
                                                                   Func <TW, TW, TW> substractFlowValues,
                                                                   TW zeroValue) where TV : IEquatable <TV> where TW : IComparable
        {
            // Set initial flow to 0
            foreach (IWeightedEdge <TV, TW> edge in graph.GetAllEdges())
            {
                edge.SetAttribute(ATTR_FLOW, zeroValue);
            }

            // Augment flow until there are not augmenting paths in the residual graph left
            IWeightedGraph <TV, TW> residualGraph = null;
            bool anyPathLeft = true;

            do
            {
                // Build residual graph
                residualGraph = BuildResidualGraph(graph, substractFlowValues, zeroValue);

                // Find (s,t)-path in residual graph
                IVertex <TV> residualSource = residualGraph.GetFirstMatchingVertex(v => v.Value.Equals(source.Value));
                IVertex <TV> residualTarget = residualGraph.GetFirstMatchingVertex(v => v.Value.Equals(target.Value));
                if (TryFindPath(residualGraph, residualSource, residualTarget, out List <IWeightedEdge <TV, TW> > path))
                {
                    // Augment f according to the found path
                    TW augmentingFlowValue = path.Min(e => e.Weight);
                    foreach (IWeightedDirectedEdge <TV, TW> edge in path)
                    {
                        // Add or substract augmenting flow value from current value depending on edge direction
                        if (edge.GetAttribute <EdgeDirection>(ATTR_DIRECTION) == EdgeDirection.Forward)
                        {
                            IWeightedDirectedEdge <TV, TW> graphEdge = (IWeightedDirectedEdge <TV, TW>)
                                                                       graph.GetEdgeBetweenVerteces(edge.OriginVertex.Value, edge.TargetVertex.Value);
                            TW currentFlow = graphEdge.GetAttribute <TW>(ATTR_FLOW);
                            graphEdge.SetAttribute(ATTR_FLOW, combineFlowValues(currentFlow, augmentingFlowValue));
                        }
                        else
                        {
                            IWeightedDirectedEdge <TV, TW> graphEdge = (IWeightedDirectedEdge <TV, TW>)
                                                                       graph.GetEdgeBetweenVerteces(edge.TargetVertex.Value, edge.OriginVertex.Value);
                            TW currentFlow = graphEdge.GetAttribute <TW>(ATTR_FLOW);
                            graphEdge.SetAttribute(ATTR_FLOW, substractFlowValues(currentFlow, augmentingFlowValue));
                        }
                    }
                }
                else
                {
                    // Terminate if there is no (s,t)-path left in the residual graph
                    anyPathLeft = false;
                }
            } while (anyPathLeft);

            // Build copy of input graph with max flow as edge weight
            GraphBuilder <TV, TW> builder = new GraphBuilder <TV, TW>(true)
                                            .AddVerteces(graph.GetAllVerteces().Select(v => v.Value));

            foreach (IWeightedEdge <TV, TW> edge in graph.GetAllEdges())
            {
                IWeightedDirectedEdge <TV, TW> graphEdge = (IWeightedDirectedEdge <TV, TW>)edge;
                builder.AddEdge(graphEdge.OriginVertex.Value,
                                graphEdge.TargetVertex.Value,
                                graphEdge.GetAttribute <TW>(ATTR_FLOW));
            }
            return(builder.Build());
        }