コード例 #1
0
        static void Main()
        {
            var tree = new Tree<string>("grandparent");

            tree.AddChild(new Tree<string>("parent")
                                    .AddChild("child1")
                                    .AddChild("child2")
                                    .AddChild(new Tree<string>("child3")
                                                    .AddChild("grandchild of 3(1)")
                                                    .AddChild("grandchild of 3(2)")))
                                .AddChild("kuzman");

            var iterator = new Treeterator<string>(tree);

            while(!iterator.Finished)
            {
                Console.WriteLine(iterator.Next);
            }

            // or
            Console.WriteLine("\n\n");

            foreach (var item in tree)
            {
                Console.WriteLine(item);
            }
        }
コード例 #2
0
ファイル: ContentWindow.cs プロジェクト: zhanggvi/FlaxEngine
        /// <inheritdoc />
        public override void OnInit()
        {
            // Setup content root node
            _root = new RootContentTreeNode();
            _root.ChildrenIndent = 0;
            _root.Expand(true);
            foreach (var project in Editor.ContentDatabase.Projects)
            {
                AddFolder2Root(project);
            }
            Editor.ContentDatabase.Game?.Expand(true);
            _tree.Margin = new Margin(0.0f, 0.0f, -16.0f, 2.0f); // Hide root node
            _tree.AddChild(_root);
            _root.SortChildrenRecursive();

            // Setup navigation
            _navigationUnlocked = true;
            _tree.Select(_root);
            NavigationClearHistory();

            // Update UI layout
            UnlockChildrenRecursive();
            PerformLayout();

            // Load last viewed folder
            if (Editor.ProjectCache.TryGetCustomData(ProjectDataLastViewedFolder, out var lastViewedFolder))
            {
                if (Editor.ContentDatabase.Find(lastViewedFolder) is ContentFolder folder)
                {
                    _tree.Select(folder.Node);
                }
            }
        }
コード例 #3
0
        /// <inheritdoc />
        public override void OnInit()
        {
            // Setup content root node
            _root = new RootContentTreeNode();
            _root.Expand();
            addFolder2Root(Editor.ContentDatabase.ProjectContent);
            addFolder2Root(Editor.ContentDatabase.ProjectSource);
            if (Editor.IsDevInstance)
            {
                // Flax internal assets locations
                addFolder2Root(Editor.ContentDatabase.EnginePrivate);
                addFolder2Root(Editor.ContentDatabase.EditorPrivate);
            }
            _tree.AddChild(_root);
            _root.SortChildrenRecursive();

            // Setup navigation
            _navigationUnlocked = true;
            _tree.Select(_root);
            NavigationClearHistory();

            // Update UI layout
            UnlockChildrenRecursive();
            PerformLayout();

            // TODO: load last viewed folder
        }
コード例 #4
0
ファイル: SceneTreeWindow.cs プロジェクト: stefnotch/FlaxAPI
        /// <summary>
        /// Initializes a new instance of the <see cref="SceneTreeWindow"/> class.
        /// </summary>
        /// <param name="editor">The editor.</param>
        public SceneTreeWindow(Editor editor)
            : base(editor, true, ScrollBars.Both)
        {
            Title = "Scene";

            // Scene searching query input box
            var headerPanel = new ContainerControl();

            headerPanel.DockStyle    = DockStyle.Top;
            headerPanel.IsScrollable = true;
            headerPanel.Parent       = this;
            _searchBox               = new TextBox(false, 4, 4, headerPanel.Width - 8);
            _searchBox.AnchorStyle   = AnchorStyle.Upper;
            _searchBox.WatermarkText = "Search...";
            _searchBox.Parent        = headerPanel;
            _searchBox.TextChanged  += OnSearchBoxTextChanged;
            headerPanel.Height       = _searchBox.Bottom + 6;

            // Create scene structure tree
            var root = editor.Scene.Root;

            root.TreeNode.ChildrenIndent = 0;
            root.TreeNode.Expand();
            _tree        = new Tree(true);
            _tree.Y      = headerPanel.Bottom;
            _tree.Margin = new Margin(0.0f, 0.0f, -16.0f, 0.0f); // Hide root node
            _tree.AddChild(root.TreeNode);
            _tree.SelectedChanged += Tree_OnSelectedChanged;
            _tree.RightClick      += Tree_OnRightClick;
            _tree.Parent           = this;
        }
コード例 #5
0
        private static void AddChild(
            Link link,
            ref Tree <Data> tree,
            ref IList <Link> links,
            ref Dictionary <long, Data> workitemStat)
        {
            if (tree.Contains(link.Id))
            {
                return;
            }

            if (link.ParentId != null && !tree.Contains((int)link.ParentId))
            {
                //find parent and add child to
                var parent = links.FirstOrDefault(x => x.Id == link.ParentId) ??
                             new Link {
                    ParentId = null, Id = (int)link.ParentId
                };

                AddChild(parent, ref tree, ref links, ref workitemStat);
            }

            tree.AddChild(
                link.ParentId,
                link.Id,
                workitemStat[link.Id]);
        }
コード例 #6
0
        public void can_continue_a_sibling_chain_without_going_to_parent()
        {
            var mem     = new MemorySimulator(Mega.Bytes(1));
            var subject = new Tree <SampleElement>(new Allocator(0, Mega.Bytes(1), mem), mem);

            //##### BUILD #####
            subject.SetRootValue(Sample[0]);

            // First child of root
            var ptrRes = subject.AddChild(subject.Root, Sample[1]); if (!ptrRes.Success)

            {
                Assert.Fail("Failed to add child");
            }

            // Second child of root
            ptrRes = subject.AddChild(subject.Root, Sample[2]); if (!ptrRes.Success)
            {
                Assert.Fail("Failed to add child");
            }
            var rc2 = ptrRes.Value;

            // Child of second child
            ptrRes = subject.AddChild(rc2, Sample[3]); if (!ptrRes.Success)
            {
                Assert.Fail("Failed to add child");
            }

            //##### ACTION #####
            // add a third child to root by second child
            ptrRes = subject.AddSibling(rc2, Sample[4]);
            if (!ptrRes.Success)
            {
                Assert.Fail("Failed to add sibling");
            }

            //##### WALK #####
            var wres = subject.Child(subject.Root);

            wres = subject.SiblingR(wres);
            wres = subject.SiblingR(wres);

            Assert.That(wres.Success, Is.True, "Failed to get full chain");
            var final = subject.ReadBody(wres.Value);

            Assert.That(final, Is.EqualTo(Sample[4]), "Incorrect data");
        }
コード例 #7
0
        public void Parent_ChildIdDoesntExist_ReturnsNull()
        {
            Tree t = new Tree();

            t.AddChild(0, 1);

            Assert.IsNull(t.Parent(100));
        }
コード例 #8
0
        public void NbSiblings_VertexWithNoSiblings_ReturnsZero()
        {
            Tree t = new Tree();

            int firstChild = t.AddChild(t.root);

            Assert.AreEqual(t.NbSiblings(firstChild), 0);
        }
コード例 #9
0
        public void after_deleting_root_node_all_memory_should_be_released()
        {
            var mem   = new MemorySimulator(Mega.Bytes(1));
            var alloc = new Allocator(0, Mega.Bytes(1), mem);

            alloc.GetState(out var bytes, out _, out _, out _, out _, out _);
            Assert.That(bytes, Is.Zero, "Allocator did not start empty");

            //##### BUILD #####
            var subject = new Tree <SampleElement>(alloc, mem);

            subject.SetRootValue(Sample[0]);

            // First child of root
            var ptrRes = subject.AddChild(subject.Root, Sample[1]);

            if (!ptrRes.Success)
            {
                Assert.Fail("Failed to add child");
            }

            // Second child of root
            ptrRes = subject.AddChild(subject.Root, Sample[2]);
            if (!ptrRes.Success)
            {
                Assert.Fail("Failed to add child");
            }
            var rc2 = ptrRes.Value;

            // Child of second child
            ptrRes = subject.AddChild(rc2, Sample[3]);
            if (!ptrRes.Success)
            {
                Assert.Fail("Failed to add child");
            }

            alloc.GetState(out bytes, out _, out _, out _, out _, out _);
            Assert.That(bytes, Is.Not.Zero, "No memory was allocated");

            //##### Destroy #####
            subject.Deallocate();

            alloc.GetState(out bytes, out _, out _, out _, out _, out _);
            Assert.That(bytes, Is.Zero, "Not all memory was released");
        }
コード例 #10
0
ファイル: TreeTests.cs プロジェクト: AlFasGD/Garyon
        public void AddChildTest()
        {
            var tree  = new Tree <char>(testTree);
            var child = tree.GetNode('A');

            tree.AddChild(child, 'K');
            AssertContainedAgainstBaseTree(tree, child, 'K', true);
            Assert.AreEqual(testTree.Count + 1, tree.Count);
        }
コード例 #11
0
        public void Siblings_VertexWithoutSiblings_ReturnsEmptyList()
        {
            Tree t = new Tree();

            int        firstChild   = t.AddChild(t.root);
            List <int> expectedList = new List <int>();

            CollectionAssert.AreEqual(expectedList, t.Siblings(firstChild));
        }
コード例 #12
0
        private static void FillNextLevel(IEnumerable <Folder> folders, IEnumerable <Product> products, Tree <ImgTwinModel> tree,
                                          int?parentId)
        {
            var targetFolders  = new List <Folder>();
            var targetProducts = new List <Product>();

            if (folders != null && folders.Any())
            {
                targetFolders = folders.Where(p => p.parent_id == parentId).ToList();
            }

            if (products != null && products.Any())
            {
                targetProducts = products.Where(p => p.folder_id == parentId).ToList();
            }

            if (targetFolders.Any() || targetProducts.Any())
            {
                foreach (var folder in targetFolders)
                {
                    var child = tree.AddChild(new ImgTwinModel
                    {
                        id       = folder.id,
                        folder   = folder.folder,
                        isFile   = false,
                        fullpath = tree.Value.fullpath + "/" + folder.folder
                    });
                    FillNextLevel(folders, products, child, folder.id);
                }

                foreach (var product in targetProducts)
                {
                    var imgName = product.id + "." + product.name + "." +
                                  (product.Image != null ? product.Image.img_type : "");
                    tree.AddChild(new ImgTwinModel
                    {
                        id       = product.id,
                        folder   = imgName,
                        isFile   = true,
                        fullpath = tree.Value.fullpath + "/" + imgName
                    });
                }
            }
        }
コード例 #13
0
        public void attempting_to_remove_from_an_invalid_index_is_ignored()
        {
            var mem     = new MemorySimulator(Mega.Bytes(1));
            var subject = new Tree <SampleElement>(new Allocator(0, Mega.Bytes(1), mem), mem);

            //##### BUILD #####
            subject.SetRootValue(Sample[0]);

            // First child of root
            var ptrRes = subject.AddChild(subject.Root, Sample[1]); if (!ptrRes.Success)

            {
                Assert.Fail("Failed to add child 1");
            }

            // ( 1 )

            // Second child of root
            ptrRes = subject.AddChild(subject.Root, Sample[2]); if (!ptrRes.Success)
            {
                Assert.Fail("Failed to add child 2");
            }
            // ( 1, 2 )

            //##### ACTION #####
            // Delete invalid item
            subject.RemoveChild(parent: subject.Root, targetIndex: 100);
            // ( 1, 2 )


            //##### WALK #####
            var wres1 = subject.Child(subject.Root);
            var wres2 = subject.SiblingR(wres1);

            Assert.That(wres2.Success, Is.True, "Failed to get full chain");

            var newChild1 = subject.ReadBody(wres1.Value);

            Assert.That(newChild1, Is.EqualTo(Sample[1]), "Incorrect data (1)");

            var newChild2 = subject.ReadBody(wres2.Value);

            Assert.That(newChild2, Is.EqualTo(Sample[2]), "Incorrect data (2)");
        }
コード例 #14
0
ファイル: TreeTests.cs プロジェクト: berendgermain/TreeLinq
        public void GivenATreeWithoutSiblings_Siblings_ReturnsEmptyList()
        {
            var onlyChild = Tree(new Species("A"));

            _root.AddChild(onlyChild);

            Assert.Empty(onlyChild.Siblings);
        }
コード例 #15
0
        public void AddChild_NormalScenario_OneChildAdded()
        {
            Tree t = new Tree();

            int childId = t.AddChild(0);

            Assert.IsTrue(t.Children(0).Contains(childId));
            Assert.AreEqual(t.Children(0).Count(), 1);
            Assert.AreEqual(t.Parent(childId), 0);
        }
コード例 #16
0
        public void Children_NoChildren_ReturnsEmptyList()
        {
            Tree t = new Tree();

            int childId = t.AddChild(t.root);

            CollectionAssert.AreEqual(new List <int>()
            {
            }, t.Children(childId));
        }
コード例 #17
0
        private async Task FillTree(int parentId, Tree <Folder> tree, NpgsqlConnection db)
        {
            var sql      = "select * from \"Folders\" where parent_id = " + parentId;
            var children = await db.QueryAsync <Folder>(sql);

            foreach (var child in children)
            {
                var ch = tree.AddChild(child);
                await FillTree(child.id, ch, db);
            }
        }
コード例 #18
0
        public void AddChild_ChildIdDoesntExist_SpecificIdCreated()
        {
            Tree t = new Tree();

            int childId = t.AddChild(0, 5);

            Assert.AreEqual(childId, 5);
            Assert.IsTrue(t.Children(0).Contains(childId));
            Assert.AreEqual(t.Children(0).Count(), 1);
            Assert.AreEqual(t.Parent(childId), 0);
        }
コード例 #19
0
        private void LoadTreeFromBattleObject(Game game, BattleObject activeBattleObject)
        {
            Tree<string> optionTree = new Tree<string>("root");
            optionTree.AddChild("Attack");
            foreach(var attack in activeBattleObject.AttackList) {
                optionTree.GetFirstChild("Attack").AddChild(attack);
            }

            optionTree.AddChild("Magic");
            foreach(var magic in activeBattleObject.MagicList) {
                optionTree.GetFirstChild("Magic").AddChild(magic);
            }

            optionTree.AddChild("Item");
            foreach(var item in activeBattleObject.ItemList) {
                optionTree.GetFirstChild("Item").AddChild(item);
            }

            _menuItemView.SetTree(optionTree);
            _menuItemView.SetFirstSelected();
        }
コード例 #20
0
        public void NbVertices_ChildrenAdded_ReturnsCorrectNumberOfVertices()
        {
            Tree t = new Tree();

            // Add 9 new vertices

            t.AddChild(0);
            t.AddChild(0);
            t.AddChild(0);
            t.AddChild(0);
            t.AddChild(0);
            t.AddChild(0);
            t.AddChild(0);
            t.AddChild(0);
            t.AddChild(0);

            Assert.AreEqual(t.NbVertices(), 10);
        }
コード例 #21
0
        public void RemoveVertex_NormalScenario_ChildRemoved()
        {
            Tree t = new Tree();

            int childId = t.AddChild(0);

            CollectionAssert.Contains(t.Children(0), childId);

            t.RemoveVertex(childId, true);

            CollectionAssert.DoesNotContain(t.Children(0), childId);
            Assert.IsNull(t.Parent(childId));
            Assert.IsNull(t.Children(childId));
        }
コード例 #22
0
ファイル: TreeTest.cs プロジェクト: quinnc/Tree
        public void Initialize()
        {
            _rootId   = 42;
            _rootData = new Dummy {
                Foo = "root"
            };

            _child1Id   = 1;
            _child1Data = new Dummy {
                Foo = "child 1"
            };

            _child2Id   = 2;
            _child2Data = new Dummy {
                Foo = "child 2"
            };

            _tree = new Tree <Dummy>();

            _tree.AddChild(null, _rootId, _rootData);
            _tree.AddChild(_rootId, _child1Id, _child1Data);
            _tree.AddChild(_rootId, _child2Id, _child2Data);
        }
コード例 #23
0
        private void FillTreeByPath(IEnumerable <string> pathParts, int index, Tree <Folder> tree)
        {
            if (index >= pathParts.Count())
            {
                return;
            }

            var child = tree.AddChild(new Folder
            {
                folder      = pathParts.ElementAt(index),
                business_id = tree.Value.business_id
            });

            FillTreeByPath(pathParts, index + 1, child);
        }
コード例 #24
0
 public static Tree GetSolutionFoldersTree(DTE dte)
 {
     var tree = new Tree();
     var projects = (dte.Solution as Solution2)?.Projects;
     if (projects == null) return tree;
     foreach (Project project in projects)
     {
         if (project?.Kind != ProjectKinds.vsProjectKindSolutionFolder) continue;
         var node = new Node(project.Name);
         var subProjects = project.ProjectItems.Cast<ProjectItem>().Select(p => new ProjectNode(p));
         node.AddChilds(subProjects);
         tree.AddChild(node);
     }
     return tree;
 }
コード例 #25
0
        public void AddChild_SpecifyChildId_IdIsNotRepeated()
        {
            Tree t = new Tree();

            int firstChild  = t.AddChild(t.root);    //Should be equal to 1
            int secondChild = t.AddChild(t.root, 2); //Should be equal to 2
            int thirdChild  = t.AddChild(t.root);    //Should be equal to 3

            //All children have been added to the root
            Assert.AreEqual(t.Children(t.root).Count(), 3);
            Assert.IsTrue(t.Children(t.root).Contains(firstChild));
            Assert.IsTrue(t.Children(t.root).Contains(secondChild));
            Assert.IsTrue(t.Children(t.root).Contains(thirdChild));

            //All children have the right id (2 isn't repeated)
            Assert.AreEqual(firstChild, 1);
            Assert.AreEqual(secondChild, 2);
            Assert.AreEqual(thirdChild, 3);

            //All children have the right parent
            Assert.AreEqual(t.Parent(firstChild), t.root);
            Assert.AreEqual(t.Parent(secondChild), t.root);
            Assert.AreEqual(t.Parent(thirdChild), t.root);
        }
コード例 #26
0
        public void InsertParent_ParentWithFourChildren_ParentWithFourChildrenAndGrandChild()
        {
            Tree tree = new Tree();

            int firstChild  = tree.AddChild(tree.root);
            int secondChild = tree.AddChild(tree.root);
            int thirdChild  = tree.AddChild(tree.root);
            int fourthChild = tree.AddChild(tree.root);

            Assert.AreEqual(tree.root, tree.Parent(firstChild));
            Assert.AreEqual(tree.root, tree.Parent(secondChild));
            Assert.AreEqual(tree.root, tree.Parent(thirdChild));
            Assert.AreEqual(tree.root, tree.Parent(fourthChild));

            CollectionAssert.AreEqual(new List <int>()
            {
                firstChild, secondChild, thirdChild, fourthChild
            }, tree.Children(tree.root));

            int newParent = tree.InsertParent(thirdChild);

            Assert.AreEqual(tree.root, tree.Parent(firstChild));
            Assert.AreEqual(tree.root, tree.Parent(secondChild));
            Assert.AreEqual(newParent, tree.Parent(thirdChild));
            Assert.AreEqual(tree.root, tree.Parent(fourthChild));
            Assert.AreEqual(tree.root, tree.Parent(newParent));

            CollectionAssert.AreEqual(new List <int>()
            {
                firstChild, secondChild, newParent, fourthChild
            }, tree.Children(tree.root));
            CollectionAssert.AreEqual(new List <int>()
            {
                thirdChild
            }, tree.Children(newParent));
        }
コード例 #27
0
        protected override void OnInitialized()
        {
            base.OnInitialized();
            level = (ParentTreeItem?.level + 1) ?? 0;
            var treeItemModel = new TreeItemModel()
            {
                Direction = "right",
                Expanded  = false,
                ParentId  = ParentTreeItem?.Id ?? 0,
                Text      = Text,
                Level     = level,
                Id        = Id
            };

            Tree.AddChild(treeItemModel);
        }
コード例 #28
0
ファイル: Program.cs プロジェクト: EBojilova/SoftUni-3
        static void Traverse(string startingDirectory, Tree<Folder> root)
        {
            var dirs = new DirectoryInfo(startingDirectory).GetDirectories();

            foreach (var dir in dirs)
            {
                var childNode = new Tree<Folder>(new Folder(dir.Name));
                var files = dir.GetFiles();
                foreach (var file in files)
                {
                    childNode.Value.AddFile(new File(file.Name, (int)file.Length));
                }
                root.AddChild(childNode);
                Traverse(dir.FullName, childNode);
            }
        }
コード例 #29
0
        public static async Task <Tree <TreeNode> > GetPublicMethodsFromSolution(string slnPath)
        {
            MSBuildWorkspace workspace = MSBuildWorkspace.Create();
            Solution         solution  = await workspace.OpenSolutionAsync(slnPath);

            Tree <TreeNode> sol = new Tree <TreeNode>(new SolutionNode(Path.GetFileName(solution.FilePath)),
                                                      ItemType.Solution);

            foreach (ProjectId projectId in solution.ProjectIds)
            {
                Project project = solution.GetProject(projectId);
                var     proj    = sol.AddChild(new ProjectNode(project.Name), ItemType.Project);

                await TraverseProject(project, proj);
            }
            return(sol);
        }
コード例 #30
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SceneTreeWindow"/> class.
        /// </summary>
        /// <param name="editor">The editor.</param>
        public SceneTreeWindow(Editor editor)
            : base(editor, true, ScrollBars.Both)
        {
            Title        = "Scene";
            ScrollMargin = new Margin(0, 0, 0, 100.0f);

            // Scene searching query input box
            var headerPanel = new ContainerControl
            {
                AnchorPreset = AnchorPresets.HorizontalStretchTop,
                IsScrollable = true,
                Offsets      = new Margin(0, 0, 0, 18 + 6),
                Parent       = this,
            };

            _searchBox = new TextBox
            {
                AnchorPreset  = AnchorPresets.HorizontalStretchMiddle,
                WatermarkText = "Search...",
                Parent        = headerPanel,
                Bounds        = new Rectangle(4, 4, headerPanel.Width - 8, 18),
            };
            _searchBox.TextChanged += OnSearchBoxTextChanged;

            // Create scene structure tree
            var root = editor.Scene.Root;

            root.TreeNode.ChildrenIndent = 0;
            root.TreeNode.Expand();
            _tree = new Tree(true)
            {
                Y      = headerPanel.Bottom,
                Margin = new Margin(0.0f, 0.0f, -16.0f, 0.0f), // Hide root node
            };
            _tree.AddChild(root.TreeNode);
            _tree.SelectedChanged += Tree_OnSelectedChanged;
            _tree.RightClick      += Tree_OnRightClick;
            _tree.Parent           = this;

            // Setup input actions
            InputActions.Add(options => options.TranslateMode, () => Editor.MainTransformGizmo.ActiveMode = TransformGizmoBase.Mode.Translate);
            InputActions.Add(options => options.RotateMode, () => Editor.MainTransformGizmo.ActiveMode    = TransformGizmoBase.Mode.Rotate);
            InputActions.Add(options => options.ScaleMode, () => Editor.MainTransformGizmo.ActiveMode     = TransformGizmoBase.Mode.Scale);
            InputActions.Add(options => options.FocusSelection, () => Editor.Windows.EditWin.Viewport.FocusSelection());
            InputActions.Add(options => options.Rename, Rename);
        }
コード例 #31
0
    // Use this for initialization
    void Start()
    {
        tree = new Tree <string>();
        tree.AddRoot("test");

        t1 = new Tree <string>();
        t1.AddRoot("t2");

        List <string> ab = new Node <string>();

        ab.Add("first");
        for (int i = 0; i < 10; i++)
        {
            ab.Add("" + i);
        }
        t1.AddChild(ab, "what");
    }
コード例 #32
0
ファイル: SceneTreeWindow.cs プロジェクト: equalent/FlaxAPI
        /// <summary>
        /// Initializes a new instance of the <see cref="SceneTreeWindow"/> class.
        /// </summary>
        /// <param name="editor">The editor.</param>
        public SceneTreeWindow(Editor editor)
            : base(editor, true, ScrollBars.Both)
        {
            Title = "Scene";

            // Create scene structure tree
            var root = editor.Scene.Root;

            root.TreeNode.ChildrenIndent = 0;
            root.TreeNode.Expand();
            _tree        = new Tree(true);
            _tree.Margin = new Margin(0.0f, 0.0f, -14.0f, 0.0f); // Hide root node
            _tree.AddChild(root.TreeNode);
            _tree.SelectedChanged += Tree_OnSelectedChanged;
            _tree.RightClick      += Tree_OnRightClick;
            _tree.Parent           = this;
        }
コード例 #33
0
        public Move GetNextMove(Field[][] board)
        {
            Console.WriteLine();
            Console.WriteLine("AI: Building Game Tree...");

            gameTree = new Tree <Move>(new Move(-1, -1, -1, -1));
            var possibleMoves = GetPossibleMoves(board.DeepCopy(), true);

            foreach (Move myPossibleMove in possibleMoves)
            {
                var isMaxing = true;
                CalculateChildTree(AI_TREEDEPTH, gameTree.AddChild(myPossibleMove), board.DeepCopy(), isMaxing);
            }

            Move nextMove = GetBestMove(gameTree);

            return(nextMove);
        }
コード例 #34
0
        private static async Task TraverseDocument(Tree <TreeNode> proj, Document document, Tree <TreeNode> file)
        {
            bool foundPublicMethods = false;
            var  root = await document.GetSyntaxRootAsync();

            foreach (var c in root.DescendantNodes().OfType <ClassDeclarationSyntax>())
            {
                foreach (var m in c.GetPublicEntryPoints())
                {
                    foundPublicMethods = true;
                    file.AddChild(new PublicMethodNode(m, document.FilePath), ItemType.Method);
                }
            }
            if (foundPublicMethods)
            {
                proj.AppendChildNode(file);
            }
        }
コード例 #35
0
        public static void AddProjectsToTree(Solution solution,ref Tree tree)
        {
            var projects = solution.Projects.ToList();
            var allreadyAddedProjects = tree.DescendantNodes().OfType<ProjectNode>().ToList();

            foreach (var project in projects)
            {
                var existingProject = allreadyAddedProjects.WithName(project.Name);
                if (existingProject != null)
                {
                    existingProject.Documents = project.Documents.ToList();
                }
                else
                {
                    existingProject = new ProjectNode(project);
                    tree.AddChild(existingProject);
                }
            }
        }
コード例 #36
0
        /// <summary>
        /// If things match, this method destructively changes the children list
        /// of the tree t.  When this method is called, t is an NP and there must
        /// be at least two children to the right of ccIndex.
        /// </summary>
        /// <param name="t">The tree to transform a conjunction in</param>
        /// <param name="ccIndex">The index of the CC child</param>
        /// <returns>t</returns>
        private static Tree TransformCc(Tree t, int ccIndex)
        {
            // use the factories of t to create new nodes
            ITreeFactory tf = t.TreeFactory();
            ILabelFactory lf = t.Label().LabelFactory();

            Tree[] ccSiblings = t.Children();

            //check if other CC
            var ccPositions = new List<int>();
            for (int i = ccIndex + 1; i < ccSiblings.Length; i++)
            {
                if (ccSiblings[i].Value().StartsWith(PartsOfSpeech.CoordinatingConjunction) && i < ccSiblings.Length - 1)
                {
                    // second conjunct to ensure that a CC we add isn't the last child
                    ccPositions.Add(i);
                }
            }

            // a CC b c ... -> (a CC b) c ...  with b not a DT
            string beforeSibling = ccSiblings[ccIndex - 1].Value();
            if (ccIndex == 1 &&
                (beforeSibling == PartsOfSpeech.Determiner
                || beforeSibling == PartsOfSpeech.Adjective 
                || beforeSibling == PartsOfSpeech.Adverb 
                || !(ccSiblings[ccIndex + 1].Value() == PartsOfSpeech.Determiner)) 
                && !(beforeSibling.StartsWith("NP")
                || beforeSibling.Equals("ADJP")
                || beforeSibling == PartsOfSpeech.NounPlural))
            {
                // && (ccSiblings.Length == ccIndex + 3 || !ccPositions.isEmpty())) {  // something like "soya or maize oil"
                string leftHead = GetHeadTag(ccSiblings[ccIndex - 1]);
                //create a new tree to be inserted as first child of t
                Tree left = tf.NewTreeNode(lf.NewLabel(leftHead), null);
                for (int i = 0; i < ccIndex + 2; i++)
                {
                    left.AddChild(ccSiblings[i]);
                }

                // remove all the children of t before ccIndex+2
                for (int i = 0; i < ccIndex + 2; i++)
                {
                    t.RemoveChild(0);
                }

                // if stuff after (like "soya or maize oil and vegetables")
                // we need to put the tree in another tree
                if (ccPositions.Any())
                {
                    bool comma = false;
                    int index = ccPositions[0];
                    if (ccSiblings[index - 1].Value() == PartsOfSpeech.Comma)
                    {
                        //to handle the case of a comma ("soya and maize oil, and vegetables")
                        index = index - 1;
                        comma = true;
                    }
                    string head = GetHeadTag(ccSiblings[index - 1]);

                    if (ccIndex + 2 < index)
                    {
                        Tree tree = tf.NewTreeNode(lf.NewLabel(head), null);
                        tree.AddChild(0, left);

                        int k = 1;
                        for (int j = ccIndex + 2; j < index; j++)
                        {
                            t.RemoveChild(0);
                            tree.AddChild(k, ccSiblings[j]);
                            k++;
                        }
                        t.AddChild(0, tree);
                    }
                    else
                    {
                        t.AddChild(0, left);
                    }

                    Tree rightTree = tf.NewTreeNode(lf.NewLabel(Noun), null);
                    int start = 2;
                    if (comma)
                    {
                        start++;
                    }
                    while (start < t.NumChildren())
                    {
                        Tree sib = t.GetChild(start);
                        t.RemoveChild(start);
                        rightTree.AddChild(sib);
                    }
                    t.AddChild(rightTree);
                }
                else
                {
                    t.AddChild(0, left);
                }
            }
            // DT a CC b c -> DT (a CC b) c
            else if (ccIndex == 2 && ccSiblings[0].Value().StartsWith("DT") &&
                     ccSiblings[ccIndex - 1].Value() != PartsOfSpeech.NounPlural &&
                     (ccSiblings.Length == 5 || (ccPositions.Any() && ccPositions[0] == 5)))
            {
                string head = GetHeadTag(ccSiblings[ccIndex - 1]);
                //create a new tree to be inserted as second child of t (after the determiner
                Tree child = tf.NewTreeNode(lf.NewLabel(head), null);

                for (int i = 1; i < ccIndex + 2; i++)
                {
                    child.AddChild(ccSiblings[i]);
                }

                // remove all the children of t between the determiner and ccIndex+2
                for (int i = 1; i < ccIndex + 2; i++)
                {
                    t.RemoveChild(1);
                }

                t.AddChild(1, child);
            }
            // ... a, b CC c ... -> ... (a, b CC c) ...
            else if (ccIndex > 2 && ccSiblings[ccIndex - 2].Value() == PartsOfSpeech.Comma &&
                     ccSiblings[ccIndex - 1].Value() != PartsOfSpeech.NounPlural)
            {
                string head = GetHeadTag(ccSiblings[ccIndex - 1]);
                Tree child = tf.NewTreeNode(lf.NewLabel(head), null);

                for (int j = ccIndex - 3; j < ccIndex + 2; j++)
                {
                    child.AddChild(ccSiblings[j]);
                }

                int i = ccIndex - 4;
                while (i > 0 && ccSiblings[i].Value() == PartsOfSpeech.Comma)
                {
                    child.AddChild(0, ccSiblings[i]); // add the comma
                    child.AddChild(0, ccSiblings[i - 1]); // add the word before the comma
                    i = i - 2;
                }

                if (i < 0)
                {
                    i = -1;
                }

                // remove the old children
                for (int j = i + 1; j < ccIndex + 2; j++)
                {
                    t.RemoveChild(i + 1);
                }
                // put the new tree
                t.AddChild(i + 1, child);
            }

                // something like "the new phone book and tour guide" -> multiple heads
                // we want (NP the new phone book) (CC and) (NP tour guide)
            else
            {
                bool commaLeft = false;
                bool commaRight = false;
                bool preconj = false;
                int indexBegin = 0;
                Tree conjT = tf.NewTreeNode(lf.NewLabel(PartsOfSpeech.CoordinatingConjunction), null);

                // create the left tree
                string leftHead = GetHeadTag(ccSiblings[ccIndex - 1]);
                Tree left = tf.NewTreeNode(lf.NewLabel(leftHead), null);


                // handle the case of a preconjunct (either, both, neither)
                Tree first = ccSiblings[0];
                string leaf = first.FirstChild().Value().ToLower();
                if (leaf.Equals("either") || leaf.Equals("neither") || leaf.Equals("both"))
                {
                    preconj = true;
                    indexBegin = 1;
                    conjT.AddChild(first.FirstChild());
                }

                for (int i = indexBegin; i < ccIndex - 1; i++)
                {
                    left.AddChild(ccSiblings[i]);
                }
                // handle the case of a comma ("GM soya and maize, and food ingredients")
                if (ccSiblings[ccIndex - 1].Value() ==  PartsOfSpeech.Comma)
                {
                    commaLeft = true;
                }
                else
                {
                    left.AddChild(ccSiblings[ccIndex - 1]);
                }

                // create the CC tree
                Tree cc = ccSiblings[ccIndex];

                // create the right tree
                int nextCc;
                if (!ccPositions.Any())
                {
                    nextCc = ccSiblings.Length;
                }
                else
                {
                    nextCc = ccPositions[0];
                }
                string rightHead = GetHeadTag(ccSiblings[nextCc - 1]);
                Tree right = tf.NewTreeNode(lf.NewLabel(rightHead), null);
                for (int i = ccIndex + 1; i < nextCc - 1; i++)
                {
                    right.AddChild(ccSiblings[i]);
                }
                // handle the case of a comma ("GM soya and maize, and food ingredients")
                if (ccSiblings[nextCc - 1].Value() ==  PartsOfSpeech.Comma)
                {
                    commaRight = true;
                }
                else
                {
                    right.AddChild(ccSiblings[nextCc - 1]);
                }

                // put trees together in old t, first we remove the old nodes
                for (int i = 0; i < nextCc; i++)
                {
                    t.RemoveChild(0);
                }
                if (ccPositions.Any())
                {
                    // need an extra level
                    Tree tree = tf.NewTreeNode(lf.NewLabel(Noun), null);

                    if (preconj)
                    {
                        tree.AddChild(conjT);
                    }
                    if (left.NumChildren() > 0)
                    {
                        tree.AddChild(left);
                    }
                    if (commaLeft)
                    {
                        tree.AddChild(ccSiblings[ccIndex - 1]);
                    }
                    tree.AddChild(cc);
                    if (right.NumChildren() > 0)
                    {
                        tree.AddChild(right);
                    }
                    if (commaRight)
                    {
                        t.AddChild(0, ccSiblings[nextCc - 1]);
                    }
                    t.AddChild(0, tree);
                }
                else
                {
                    if (preconj)
                    {
                        t.AddChild(conjT);
                    }
                    if (left.NumChildren() > 0)
                    {
                        t.AddChild(left);
                    }
                    if (commaLeft)
                    {
                        t.AddChild(ccSiblings[ccIndex - 1]);
                    }
                    t.AddChild(cc);
                    if (right.NumChildren() > 0)
                    {
                        t.AddChild(right);
                    }
                    if (commaRight)
                    {
                        t.AddChild(ccSiblings[nextCc - 1]);
                    }
                }
            }
            return t;
        }
コード例 #37
0
ファイル: SessionManager.cs プロジェクト: mkramers/Projects
        private void Update(string _path, Tree<RemoteFileInfo> _tree)
        {
            try
            {
                RemoteDirectoryInfo directory = m_session.ListDirectory(_path);

                foreach (WinSCP.RemoteFileInfo fileInfo in directory.Files)
                {
                    if (fileInfo.Name != "..")
                    {
                        if (fileInfo.IsDirectory)
                        {
                            //if the entry not cached - add the directory and then update its contents
                            if (Tree<RemoteFileInfo>.Find(m_ignoreTree, i => i.Name == fileInfo.Name && i.IsDirectory) == null)
                            {
                                _tree.AddChild(new RemoteFileInfo(fileInfo));

                                Update(_path + "/" + fileInfo.Name, _tree.GetChild(_tree.Children.Count - 1));
                            }
                        }
                        else
                        {
                            //if we are not ignoring the file
                            if (Tree<RemoteFileInfo>.Find(m_ignoreTree, i => i.Name == fileInfo.Name && !i.IsDirectory) == null)
                            {
                                //if the file extension is one we care about add it to list, other wise add to the ignore list
                                //if (!m_ignoredExtensions.Contains(Utilities.GetExtensionFromFileName(fileInfo.Name)))
                                {
                                    _tree.AddChild(new RemoteFileInfo(fileInfo));
                                }
                                //else
                                //{
                                //    m_ignoreTree.AddChild(new RemoteFileInfo2(fileInfo));
                                //}
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                LOG.ErrorFormat("Error: {0}", e);
            }
        }
コード例 #38
0
        static void Main()
        {
            var root = new Tree<string>("Grandfather");

            var child11 = new Tree<string>("Father");
            var child12 = new Tree<string>("Aunt");

            var child211 = new Tree<string>("Sister");
            var child212 = new Tree<string>("Brother");

            var child221 = new Tree<string>("Cousin 1");
            var child222 = new Tree<string>("Cousin 2");

            root.AddChild(child11
                            .AddChild(child211)
                            .AddChild(child212)
                         )
                        .AddChild(child12
                                     .AddChild(child221)
                                     .AddChild(child222)
                                 );

            // var dfs = new DFSRecursive<string>(root);

            // dfs.TraverseWithAction(root, Console.WriteLine);

            // var dfsIterative = new DFSIterative<string>();

            // Console.WriteLine("\n\nITERATIVE BELOW\n\n");

            // dfsIterative.TraverseWithAction(root, x => Console.WriteLine(x));

            // represent a graph using adjacency list
            var graphRepresentaion = new Dictionary<IGraphNode<string>, IList<IGraphNode<string>>>()
            {
                // random links
                {root, new List<IGraphNode<string>>(){child11, child12, child222}},
                {child11, new List<IGraphNode<string>>(){root, child211}},
                {child12, new List<IGraphNode<string>>(){child212, child211}},
                {child212, new List<IGraphNode<string>>(){child11, root, child211}},
                {child211, new List<IGraphNode<string>>(){root}}
            };

            // realize the links
            foreach (var node in graphRepresentaion)
            {
                foreach (var neighbor in node.Value)
                {
                    if(!node.Key.Children.Contains(neighbor))
                    {
                        node.Key.AddChild(neighbor);
                    }
                }
            }

            // var visited = new List<IGraphNode<string>>();

            // var nodes = new Queue<IGraphNode<string>>();

            // new GraphBFS().TraverseWithAction(root, x => Console.WriteLine(x));

            var gosho = new int[] { 1, 2, 3, 4, 5, 6, 7 }.Where(x => x % 2 == 0).Select(x => x + 3).ToArray();

            var pesho = new int[,] { { 2, 3 }, { 3, 4 }, { -1, 17 } };
        }
コード例 #39
0
ファイル: PennTreeReader.cs プロジェクト: gblosser/OpenNlp
        private Tree GetTreeFromInputStream()
        {
            int wordIndex = 0;

            // FSA
            //label:
            while (tokenizer.HasNext())
            {
                string token = tokenizer.Next();

                switch (token)
                {
                    case LeftParen:

                        // cdm 20100225: This next line used to have "" instead of null, but the traditional and current tree normalizers depend on the label being null not "" when there is no label on a tree (like the outermost English PTB level)
                        string label = (tokenizer.Peek().Equals(LeftParen)) ? null : tokenizer.Next();
                        if (RightParen.Equals(label))
                        {
//Skip past empty trees
                            continue;
                        }
                        else if (treeNormalizer != null)
                        {
                            label = treeNormalizer.NormalizeNonterminal(label);
                        }

                        if (label != null)
                        {
                            label = StarPattern.Replace(label, "*");
                            label = SlashPattern.Replace(label, "/");
                        }

                        Tree newTree = treeFactory.NewTreeNode(label, null); // dtrs are added below

                        if (currentTree == null)
                            stack.Add(newTree);
                        else
                        {
                            currentTree.AddChild(newTree);
                            stack.Add(currentTree);
                        }

                        currentTree = newTree;

                        break;
                    case RightParen:
                        if (!stack.Any())
                        {
                            // Warn that file has too many right parens
                            //break label;
                            goto post_while_label;
                        }

                        //Accept
                        currentTree = stack.Last();
                        stack.RemoveAt(stack.Count - 1); // i.e., stack.pop()

                        if (!stack.Any()) return currentTree;

                        break;
                    default:

                        if (currentTree == null)
                        {
                            // A careful Reader should warn here, but it's kind of useful to
                            // suppress this because then the TreeReader doesn't print a ton of
                            // messages if there is a README file in a directory of Trees.
                            //break label;
                            goto post_while_label;
                        }

                        string terminal = (treeNormalizer == null) ? token : treeNormalizer.NormalizeTerminal(token);
                        terminal = StarPattern.Replace(terminal, "*");
                        terminal = SlashPattern.Replace(terminal, "/");
                        Tree leaf = treeFactory.NewLeaf(terminal);
                        if (leaf.Label() is IHasIndex)
                        {
                            var hi = (IHasIndex) leaf.Label();
                            hi.SetIndex(wordIndex);
                        }
                        if (leaf.Label() is IHasWord)
                        {
                            var hw = (IHasWord) leaf.Label();
                            hw.SetWord(leaf.Label().Value());
                        }
                        wordIndex++;

                        currentTree.AddChild(leaf);
                        // cdm: Note: this implementation just isn't as efficient as the old recursive descent parser (see 2008 code), where all the daughters are gathered before the tree is made....
                        break;
                }
            }
            post_while_label:
            {
            }

            //Reject
            return null;
        }
コード例 #40
0
 public void TestRecursion()
 {
     StringTemplateGroup group = new StringTemplateGroup( "dummy", ".", typeof( AngleBracketTemplateLexer ) );
     group.DefineTemplate( "tree",
     "<if(it.firstChild)>" +
       "( <it.text> <it.children:tree(); separator=\" \"> )" +
     "<else>" +
       "<it.text>" +
     "<endif>" );
     StringTemplate tree = group.GetInstanceOf( "tree" );
     // build ( a b (c d) e )
     Tree root = new Tree( "a" );
     root.AddChild( new Tree( "b" ) );
     Tree subtree = new Tree( "c" );
     subtree.AddChild( new Tree( "d" ) );
     root.AddChild( subtree );
     root.AddChild( new Tree( "e" ) );
     tree.SetAttribute( "it", root );
     string expecting = "( a b ( c d ) e )";
     Assert.AreEqual( expecting, tree.ToString() );
 }