예제 #1
1
 private void InitTreeBuilder()
 {
     m_treeBuilder              = new TreeBuilder(m_treeDT);
     m_treeBuilder.BGColor      = Color.White;
     m_treeBuilder.FontColor    = Color.Black;
     m_treeBuilder.BoxFillColor = Color.LightGoldenrodYellow;
     m_treeBuilder.BoxHeight    = 30; m_treeBuilder.BoxWidth = 70;
 }
예제 #2
0
        public void ComparerTest()
        {
            ulong[] Test = new ulong[256];
            Test[97]  = 6;
            Test[98]  = 2;
            Test[32]  = 5;
            Test[99]  = 5;
            Test[100] = 1;
            Test[101] = 2;
            Test[102] = 2;
            Test[52]  = 2;
            TreeBuilder builder = new TreeBuilder(Test);

            for (int i = 0; i < 5; i++)
            {
                InnerNode n = new InnerNode((ulong)i, i);
                builder.Forest.Add(n);
            }
            while (builder.Forest.Count > 0)
            {
                var a = builder.Forest.Min;
                Console.WriteLine(a.GetType());
                Console.WriteLine(a.Weight);
                builder.Forest.Remove(a);
            }
        }
예제 #3
0
        public void CompressContentTest()
        {
            Stream       s      = File.OpenWrite(@"D:\MFF\ZS_2019\c#_repos\Huffman1\Huffman1Tests\bin\Debug\netcoreapp3.0\TestFiles\Huff2\Outs\Compressed.out");
            BinaryWriter writer = new BinaryWriter(s);

            Stream       ins    = File.OpenRead(@"D:\MFF\ZS_2019\c#_repos\Huffman1\Huffman1Tests\bin\Debug\netcoreapp3.0\TestFiles\Huff2\Ins\simple4.in");
            BinaryReader reader = new BinaryReader(ins);


            HuffmanReader HuffReader = new HuffmanReader(reader);
            bool          NotEmpty   = HuffReader.ReadFileUsingBuffer();
            //Build Huffman tree
            TreeBuilder Builder = new TreeBuilder(HuffReader.ProvideSymbolsWihtWeights());
            Node        Root    = Builder.BuildHuffTree();

            ins.Seek(0, 0);

            HuffCompresor.CompressContent(Root, writer, reader);

            writer.Close();
            reader.Close();
            bool same = Utils.FileDiff(@"D:\MFF\ZS_2019\c#_repos\Huffman1\Huffman1Tests\bin\Debug\netcoreapp3.0\TestFiles\Huff2\Outs\Compressed.huff", @"D:\MFF\ZS_2019\c#_repos\Huffman1\Huffman1Tests\bin\Debug\netcoreapp3.0\TestFiles\Huff2\Outs\Compressed.out");

            Assert.IsTrue(same);
        }
예제 #4
0
        public void CodeBytesTest() //no assert!
        {
            Stream       ins    = File.OpenRead(@"D:\MFF\ZS_2019\c#_repos\Huffman1\Huffman1Tests\bin\Debug\netcoreapp3.0\TestFiles\Huff2\Ins\simple4.in");
            BinaryReader reader = new BinaryReader(ins);

            HuffmanReader HuffReader = new HuffmanReader(reader);
            bool          NotEmpty   = HuffReader.ReadFileUsingBuffer();
            //Build Huffman tree
            TreeBuilder Builder = new TreeBuilder(HuffReader.ProvideSymbolsWihtWeights());
            Node        Root    = Builder.BuildHuffTree();

            TreePrinter.PrintNiceTree(Root, 0);

            Stack <byte> path = new Stack <byte>();

            HuffCompresor.CodeBytes(Root, path);

            for (int i = 0; i < HuffCompresor.Codes.Length; i++)
            {
                if (HuffCompresor.Codes[i] != null)
                {
                    Console.Write($"{i}: ");
                    for (int j = 0; j < HuffCompresor.Codes[i].Length; j++)
                    {
                        Console.Write($"{HuffCompresor.Codes[i][j]} ");
                    }
                    Console.WriteLine();
                }
            }
        }
        public static void Run()
        {
            Tokeniser    tokeniser = new Tokeniser(Console.ReadLine());
            List <Token> tokens    = tokeniser.Tokenise().ToList();

            TreeNode bin1 = TreeBuilder.BuildAST(tokens); // e.g "5 * 2 + 1" -> "5 2 * 1 +"

            // Using TreeNode type, not BinOp (Binary Operator) as we cannot guarantee the root node of the abstract syntax tree will be an operator.

            Console.WriteLine("To postfix:");
            foreach (TreeNode node in Traversal.postOrder(bin1))
            {
                Console.Write(node.value + " ");
            }
            Console.WriteLine("\nTo infix:");
            foreach (TreeNode node in Traversal.inOrder(bin1))
            {
                Console.Write(node.value + " ");
            }
            Console.WriteLine("\nTo prefix:");
            foreach (TreeNode node in Traversal.preOrder(bin1))
            {
                Console.Write(node.value + " ");
            }
            Console.WriteLine();

            // Now using reverse polish notation, calculate what the result is. This takes in a postfix-ordered list of TreeNodes.
            Console.WriteLine("Answer: " + RPN.Evaluate(Traversal.postOrder(bin1)));
        }
        public void TwoLevels()
        {
            var args = new NameValueCollection();

            args.Add("customer.name", "hammett");
            args.Add("customer.age", "26");
            args.Add("customer.location.code", "pt-br");
            args.Add("customer.location.country", "55");

            var builder = new TreeBuilder();

            CompositeNode root = builder.BuildSourceNode(args);

            Assert.IsNotNull(root);

            var node = (CompositeNode)root.GetChildNode("customer");

            Assert.IsNotNull(root);

            var locationNode = (CompositeNode)node.GetChildNode("location");

            Assert.IsNotNull(locationNode);

            Assert.AreEqual("pt-br", ((LeafNode)locationNode.GetChildNode("code")).Value);
            Assert.AreEqual("55", ((LeafNode)locationNode.GetChildNode("country")).Value);
        }
예제 #7
0
		public void EntriesStartingWithDotShouldBeConsideredSimple()
		{
			var nameValueColl = new NameValueCollection();

			nameValueColl.Add(".name", "hammett");
			nameValueColl.Add(".age", "27");

			var builder = new TreeBuilder();
			CompositeNode root = builder.BuildSourceNode(nameValueColl);

			Assert.IsNotNull(root);
			Assert.AreEqual(2, root.ChildrenCount);

			var entry = (LeafNode) root.GetChildNode(".name");
			Assert.IsNotNull(entry);
			Assert.IsFalse(entry.IsArray);
			Assert.AreEqual(".name", entry.Name);
			Assert.AreEqual(NodeType.Leaf, entry.NodeType);
			Assert.AreEqual("hammett", entry.Value);

			entry = (LeafNode) root.GetChildNode(".age");
			Assert.IsNotNull(entry);
			Assert.IsFalse(entry.IsArray);
			Assert.AreEqual(".age", entry.Name);
			Assert.AreEqual(NodeType.Leaf, entry.NodeType);
			Assert.AreEqual("27", entry.Value);
		}
예제 #8
0
    public void Cycle_indirectly()
    {
        var records = new[]
        {
            new TreeBuildingRecord {
                RecordId = 5, ParentId = 2
            },
            new TreeBuildingRecord {
                RecordId = 3, ParentId = 2
            },
            new TreeBuildingRecord {
                RecordId = 2, ParentId = 6
            },
            new TreeBuildingRecord {
                RecordId = 4, ParentId = 1
            },
            new TreeBuildingRecord {
                RecordId = 1, ParentId = 0
            },
            new TreeBuildingRecord {
                RecordId = 0, ParentId = 0
            },
            new TreeBuildingRecord {
                RecordId = 6, ParentId = 3
            }
        };

        Assert.Throws <ArgumentException>(() => TreeBuilder.BuildTree(records));
    }
    // Start is called before the first frame update
    void Start()
    {
        #region Selector test

        BehaviourTree tree = TreeBuilder.Init("testTree1", "JsonTest1")
                             .Selector().Do("TestAction1", TestAction1)
                             .Do("TestAction2", TestAction2)
                             .Condition("ConditionTest1", TestCondition1)
                             .End()
                             .Build();

        tree.Run(new BaseInput());

        #endregion

        #region Sequence test

        tree = TreeBuilder.Init("testTree1", "JsonTest1")
               .Sequence().Do("TestAction1", TestAction1)
               .Do("TestAction2", TestAction2)
               .Condition("ConditionTest1", TestCondition1)
               .End()
               .Build();

        tree.Run(new BaseInput());

        #endregion
    }
예제 #10
0
 public TextTree(string text)
 {
     var nodeFromText = new TreeBuilder().GetTree(text);
     Tag = nodeFromText.Tag;
     Children = nodeFromText.Children;
     IsComplete = nodeFromText.IsComplete;
 }
예제 #11
0
		public void CompositeEntries()
		{
			var nameValueColl = new NameValueCollection();

			nameValueColl.Add("customer.name", "hammett");
			nameValueColl.Add("customer.age", "27");
			nameValueColl.Add("customer.age", "28");

			var builder = new TreeBuilder();
			CompositeNode root = builder.BuildSourceNode(nameValueColl);

			Assert.IsNotNull(root);
			Assert.AreEqual(1, root.ChildrenCount);

			var node = (CompositeNode) root.GetChildNode("customer");
			Assert.IsNotNull(node);
			Assert.AreEqual("customer", node.Name);
			Assert.AreEqual(NodeType.Composite, node.NodeType);

			var entry = (LeafNode) node.GetChildNode("name");
			Assert.IsNotNull(entry);
			Assert.IsFalse(entry.IsArray);
			Assert.AreEqual("name", entry.Name);
			Assert.AreEqual(NodeType.Leaf, entry.NodeType);
			Assert.AreEqual("hammett", entry.Value);

			entry = (LeafNode) node.GetChildNode("age");
			Assert.IsNotNull(entry);
			Assert.IsTrue(entry.IsArray);
			Assert.AreEqual("age", entry.Name);
			Assert.AreEqual(NodeType.Leaf, entry.NodeType);
			Assert.AreEqual(new[] {"27", "28"}, entry.Value);
		}
예제 #12
0
		public void SimpleEntries()
		{
			NameValueCollection nameValueColl = new NameValueCollection();
			
			nameValueColl.Add("name", "hammett");
			nameValueColl.Add("age", "27");
			nameValueColl.Add("age", "28");
			
			TreeBuilder builder = new TreeBuilder();
			CompositeNode root = builder.BuildSourceNode(nameValueColl);
			
			Assert.IsNotNull(root);
			Assert.AreEqual(2, root.ChildrenCount);
			
			LeafNode entry = (LeafNode) root.GetChildNode("name");
			Assert.IsNotNull(entry);
			Assert.IsFalse(entry.IsArray);
			Assert.AreEqual("name", entry.Name);
			Assert.AreEqual(NodeType.Leaf, entry.NodeType);
			Assert.AreEqual("hammett", entry.Value);
			
			entry = (LeafNode) root.GetChildNode("age");
			Assert.IsNotNull(entry);
			Assert.IsTrue(entry.IsArray);
			Assert.AreEqual("age", entry.Name);
			Assert.AreEqual(NodeType.Leaf, entry.NodeType);
			Assert.AreEqual(new String[] { "27", "28" }, entry.Value);
		}
예제 #13
0
        public override void DoWork(Action <string, double> ReportProgress, Action Done)
        {
            Parent.Message = "Receiving...";
            var Converter = (Parent as ReceiveLocalComponent).Converter;
            var @base     = Operations.Receive(localDataId).Result;

            if (Converter.CanConvertToNative(@base))
            {
                var converted = Converter.ConvertToNative(@base);
                data = new GH_Structure <IGH_Goo>();
                data.Append(Utilities.TryConvertItemToNative(converted, Converter));
            }
            else if (@base.GetDynamicMembers().Count() == 1)
            {
                var treeBuilder = new TreeBuilder(Converter);
                var tree        = treeBuilder.Build(@base[@base.GetDynamicMembers().ElementAt(0)]);
                data = tree;
            }
            else
            {
                data = new GH_Structure <IGH_Goo>();
                data.Append(new GH_SpeckleBase(@base));
            }
            Done();
        }
        public void IndexedContent()
        {
            var args = new NameValueCollection();

            args.Add("customer[0].name", "hammett");
            args.Add("customer[0].age", "26");
            args.Add("customer[0].all", "yada yada yada");
            args.Add("customer[10].name", "frasier");
            args.Add("customer[10].age", "50");
            args.Add("customer[10].all", "yada");

            var builder = new TreeBuilder();

            CompositeNode root = builder.BuildSourceNode(args);

            var node = (IndexedNode)root.GetChildNode("customer");

            Assert.IsNotNull(node);
            Assert.AreEqual(2, node.ChildrenCount);

            var cnode = (CompositeNode)node.GetChildNode("0");

            Assert.AreEqual("hammett", ((LeafNode)cnode.GetChildNode("name")).Value);
            Assert.AreEqual("26", ((LeafNode)cnode.GetChildNode("age")).Value);
            Assert.AreEqual("yada yada yada", ((LeafNode)cnode.GetChildNode("all")).Value);

            cnode = (CompositeNode)node.GetChildNode("10");

            Assert.AreEqual("frasier", ((LeafNode)cnode.GetChildNode("name")).Value);
            Assert.AreEqual("50", ((LeafNode)cnode.GetChildNode("age")).Value);
            Assert.AreEqual("yada", ((LeafNode)cnode.GetChildNode("all")).Value);
        }
예제 #15
0
        public async Task ShouldVerifyChildTraversal()
        {
            // Arrange
            var extender = new ServiceCollection()
                           .AddAsyncXtender <uint>((b, _) => b.Default()
                                                   .Attach <Node <string>, NodeExtension <string> >()
                                                   .Attach <Node <int>, NodeExtension <int> >())
                           .BuildServiceProvider()
                           .GetRequiredService <IAsyncExtender <uint> >();

            var tree = TreeBuilder.New()
                       .CreateByValue("root", 1, builder => builder
                                      .AddByValue("1A", "value-1A", inner => inner
                                                  .AddByValue("1B", "value-1B")
                                                  .AddByValue("2B", 3))
                                      .AddByValue("2A", "value-2A", inner => inner
                                                  .AddByValue("1C", "value-1C")
                                                  .AddByValue("2C", 4))
                                      .AddByValue("3A", 2));

            extender.State = 0;

            // Act
            await tree.Root.Accept(extender);

            // Assert
            Assert.Equal(8U, extender.State);
        }
		public void IndexedContent()
		{
			var args = new NameValueCollection();

			args.Add("customer[0].name", "hammett");
			args.Add("customer[0].age", "26");
			args.Add("customer[0].all", "yada yada yada");
			args.Add("customer[10].name", "frasier");
			args.Add("customer[10].age", "50");
			args.Add("customer[10].all", "yada");

			var builder = new TreeBuilder();

			CompositeNode root = builder.BuildSourceNode(args);

			var node = (IndexedNode) root.GetChildNode("customer");

			Assert.IsNotNull(node);
			Assert.AreEqual(2, node.ChildrenCount);

			var cnode = (CompositeNode) node.GetChildNode("0");

			Assert.AreEqual("hammett", ((LeafNode) cnode.GetChildNode("name")).Value);
			Assert.AreEqual("26", ((LeafNode) cnode.GetChildNode("age")).Value);
			Assert.AreEqual("yada yada yada", ((LeafNode) cnode.GetChildNode("all")).Value);

			cnode = (CompositeNode) node.GetChildNode("10");

			Assert.AreEqual("frasier", ((LeafNode) cnode.GetChildNode("name")).Value);
			Assert.AreEqual("50", ((LeafNode) cnode.GetChildNode("age")).Value);
			Assert.AreEqual("yada", ((LeafNode) cnode.GetChildNode("all")).Value);
		}
예제 #17
0
    public void Cycle_directly()
    {
        var records = new[]
        {
            new TreeBuildingRecord {
                RecordId = 5, ParentId = 2
            },
            new TreeBuildingRecord {
                RecordId = 3, ParentId = 2
            },
            new TreeBuildingRecord {
                RecordId = 2, ParentId = 2
            },
            new TreeBuildingRecord {
                RecordId = 4, ParentId = 1
            },
            new TreeBuildingRecord {
                RecordId = 1, ParentId = 0
            },
            new TreeBuildingRecord {
                RecordId = 0, ParentId = 0
            },
            new TreeBuildingRecord {
                RecordId = 6, ParentId = 3
            }
        };

        Assert.That(() => TreeBuilder.BuildTree(records), Throws.Exception);
    }
예제 #18
0
        public void Update(TokenPage page, CompilationEnvironment environment)
        {
            _flatStatements.Clear();

            Pattern pattern = MainPattern.Instance;

            foreach (PageLine line in page)
            {
                pattern.TryMatch(line,
                                 environment.Messages, out Expression expression);

                if (expression != null)
                {
                    _flatStatements.Add(expression);
                }
            }

            Root = TreeBuilder.Build(_flatStatements, environment);

            foreach (ITreeTransform transform in _transforms)
            {
                transform.Apply(Root, environment);
            }

            ParseTestCommands(page, environment.Messages);
        }
예제 #19
0
파일: Command.cs 프로젝트: tom-vd/dmake
            internal static void RegisterType()
            {
                PsiHelperNode.RegisterType();
                XBOSS.Types.Array <PsiHelperNode> .RegisterType();

                if (Command.TypeRegistered)
                {
                    return;
                }

                TreeBuilder.RegisterType <Command>(Command.PublicTypeName, (XElement el, Node_base Parent, Document owner) => {
                    IEnumerable <XElement> Children = el.Elements();
                    var ret = new Command(el.Name.ToString(), Parent, owner);
                    foreach (XElement c in Children)
                    {
                        String Name = c.Name.ToString();
                        if (Name.Equals("dependencies"))
                        {
                            ret.DepIdx = ret.Children.Count;
                            ret.Children.Add(TreeBuilder.InvokeParser(c, Parent, owner));
                        }
                        else if (Name.Equals("run"))
                        {
                            ret.RunIdx = ret.Children.Count;
                            ret.Children.Add(TreeBuilder.InvokeParser(c, Parent, owner));
                        }                 // if
                    }                     // foreach
                    return(ret);
                }, (Node_base N, i32 lvl, StringBuilderEx sb) => {
                    TreeBuilder.CheckChildCount(N, 0, 0);
                    ((Command)N).ToXML(lvl, sb);
                });

                Command.TypeRegistered = true;
            }
예제 #20
0
        public void CanBuildTreeForSingleItemInFolder()
        {
            InitializeEnvironment(@"c:\Project", @"c:\Project");

            var gitStatusEntries  = new List <GitStatusEntry>();
            var gitCommitTargets  = new List <GitCommitTarget>();
            var foldedTreeEntries = new List <string>();

            var newGitStatusEntries = new List <GitStatusEntry> {
                gitObjectFactory.CreateGitStatusEntry(@"folder\file1.txt", GitFileStatus.Modified)
            };

            var treeRoot = TreeBuilder.BuildTreeRoot(newGitStatusEntries, gitStatusEntries, gitCommitTargets,
                                                     foldedTreeEntries);

            gitStatusEntries.Count.Should().Be(1);
            gitCommitTargets.Count.Should().Be(1);
            foldedTreeEntries.Count.Should().Be(0);

            var treeRootChidren = treeRoot.Children.ToArray();

            treeRootChidren.Length.Should().Be(1);

            var file1 = treeRootChidren[0];

            file1.Label.Should().Be("file1.txt");
            file1.Open.Should().BeTrue();
            file1.Path.Should().Be("file1.txt");
            file1.RepositoryPath.Should().Be(@"folder\file1.txt");
            file1.State.Should().Be(CommitState.None);
            file1.Target.Should().Be(gitCommitTargets[0]);

            file1.Children.Should().BeEmpty();
        }
            public void Update()
            {
                CreateNode();
                NodeAttributes ats = TreeBuilder.GetAttributes(this, node.BuilderChain, node.DataItem);

                UpdateNode(node, node.BuilderChain, ats, node.DataItem);
            }
예제 #22
0
        internal Tree Build(Repository repository)
        {
            WrapAllTreeDefinitions(repository);

            using (var builder = new TreeBuilder())
            {
                var builtTreeEntryDefinitions = new List <Tuple <string, TreeEntryDefinition> >(entries.Count);

                foreach (KeyValuePair <string, TreeEntryDefinition> kvp in entries)
                {
                    string name             = kvp.Key;
                    TreeEntryDefinition ted = kvp.Value;

                    var transient = ted as TransientBlobTreeEntryDefinition;

                    if (transient == null)
                    {
                        builder.Insert(name, ted);
                        continue;
                    }

                    Blob blob = transient.Builder(repository.ObjectDatabase);
                    TreeEntryDefinition ted2 = TreeEntryDefinition.From(blob, ted.Mode);
                    builtTreeEntryDefinitions.Add(new Tuple <string, TreeEntryDefinition>(name, ted2));

                    builder.Insert(name, ted2);
                }

                builtTreeEntryDefinitions.ForEach(t => entries[t.Item1] = t.Item2);

                ObjectId treeId = builder.Write(repository);
                return(repository.Lookup <Tree>(treeId));
            }
        }
        public void Test(int treeDepth, string[] nodeProducingRuleToSymbols, string[] expectedProducedSymbols)
        {
            SymbolsSet<int> s = new SymbolsSet<int>(new []
            {
                new Symbol<int>("Node0"),
                new Symbol<int>("Node1"),
                new Symbol<int>("Node2"),
                new Symbol<int>("Node")
            });

            // Node -> Node0|Node1|Node2
            nodeProducingRuleToSymbols = nodeProducingRuleToSymbols ?? new [] {"Node0", "Node1", "Node2"};
            OrRule<int> nodeProducingRule = new OrRule<int>(s["Node"], nodeProducingRuleToSymbols.Select(n => s[n]));

            TreeBuilder<int> treeBuilder = new TreeBuilder<int>();
            TreeGeneratingRuleSelector<int> ruleSelector = new TreeGeneratingRuleSelector<int>(treeDepth, treeBuilder, nodeProducingRule.Rules);

            List<string> producedSymbols = new List<string>();
            while(!treeBuilder.IsTreeReady)
            {
                Rule<int> rule = ruleSelector.Next();
                string sn = rule.Produce().First().Name;
                int v = int.Parse(sn.Replace("Node", ""));
                treeBuilder.Append(v, v);
                producedSymbols.Add(sn);
            }

            Assert.AreElementsEqual(expectedProducedSymbols, producedSymbols);
        }
예제 #24
0
    public static int Main(string[] args)
    {
        // Create scanner that reads from standard input
        Scanner scanner = new Scanner(Console.In);

        if (args.Length > 1 ||
            (args.Length == 1 && ! args[0].Equals("-d")))
        {
            Console.Error.WriteLine("Usage: mono SPP [-d]");
            return 1;
        }

        // If command line option -d is provided, debug the scanner.
        if (args.Length == 1 && args[0].Equals("-d"))
        {
            // Console.Write("Scheme 4101> ");
            Token tok = scanner.getNextToken();
            while (tok != null)
            {
                TokenType tt = tok.getType();

                Console.Write(tt);
                if (tt == TokenType.INT)
                    Console.WriteLine(", intVal = " + tok.getIntVal());
                else if (tt == TokenType.STRING)
                    Console.WriteLine(", stringVal = " + tok.getStringVal());
                else if (tt == TokenType.IDENT)
                    Console.WriteLine(", name = " + tok.getName());
                else
                    Console.WriteLine();

                // Console.Write("Scheme 4101> ");
                tok = scanner.getNextToken();
            }
            return 0;
        }

        // Create parser
        TreeBuilder builder = new TreeBuilder();
        Parser parser = new Parser(scanner, builder);
        Node root;

        // TODO: Create and populate the built-in environment and
        // create the top-level environment
        var env = new Tree.Environment(); // create built in environment for scheme functions
        var id = new Ident("car");
        // TODO: create lines for definitions of built in functions from first page of docs
        id = new Ident("b+");
        env.define(id, new BuiltIn(id)); // populates environment--puts car into built in environment--define manages tree for you
        env = new Tree.Environment(env); //
        root = (Node) parser.parseExp();
        while (root != null)
        {
            root.print(0);
            root = (Node) parser.parseExp();
        }

        return 0;
    }
예제 #25
0
 public void BuildTreeFromArrayList()
 {
     var list = new ArrayList()
     {
         1, 2, 3, null, 5, 6, 7
     };
     var root = TreeBuilder.BuildTree(list);
 }
예제 #26
0
        /// <summary>
        /// Decoding of encoded bytes by Huffman algorithm.
        /// </summary>
        /// <param name="bytes"> Encoded bytes</param>
        /// <returns> Decoded bytes</returns>
        public static byte[] Decode(byte[] bytes)
        {
            var result = DictionarySerializer.Deserialize(bytes);

            return(Decode(bytes,
                          result.SizeOfBytes,
                          TreeBuilder.BuildTree(new TreeBuilderQueue(result.Dictionary))));
        }
예제 #27
0
        private void UpdateSeed(int newSeed)
        {
            var treeRndSource = new RandomWrapper(newSeed);
            var treeBuilder   = new TreeBuilder(treeRndSource);

            trunk       = treeBuilder.BuildTree();
            grassRandom = new RandomWrapper(newSeed);
        }
 public void addToTreeVeiw(System.Windows.Forms.TreeNode root, TreeBuilder tb)
 {
     foreach (string key in tb.childs.Keys)
     {
         System.Windows.Forms.TreeNode t = root.Nodes.Add(tb.childs[key].text);
         addToTreeVeiw(t, tb.childs[key]);
     }
 }
예제 #29
0
        static void Main(string[] args)
        {
            var  tree   = TreeBuilder.Build(KeyJoin);
            bool result = tree.Root.Evaluate();

            Console.WriteLine(result);
            Console.Read();
        }
예제 #30
0
        public string RenderTree_WhenIncorrectTag_TagNodeContainThisText(string str)
        {
            var tree     = TreeBuilder.RenderTree <MarkDown>(str);
            var tagNode  = tree.ChildNode.First() as TagNode;
            var textNode = tagNode.ChildNode.First() as TextNode;

            return(textNode.Value);
        }
예제 #31
0
		public object Bind(HttpContextBase httpContext, ParameterDescriptor descriptor)
		{
			var binder = new DataBinder();

			var node = new TreeBuilder().BuildSourceNode(httpContext.Request.Params);

			return binder.BindObject(descriptor.Type, Prefix ?? descriptor.Name, Exclude, Allow, node);
		}
예제 #32
0
        public void CanBuildTreeForHierarchyWhenProjectNestedInRepo()
        {
            InitializeEnvironment(@"c:\Repo", @"c:\Repo\Project");

            var gitStatusEntries  = new List <GitStatusEntry>();
            var gitCommitTargets  = new List <GitCommitTarget>();
            var foldedTreeEntries = new List <string>();

            var newGitStatusEntries = new List <GitStatusEntry> {
                gitObjectFactory.CreateGitStatusEntry("file1.txt", GitFileStatus.Modified),
                gitObjectFactory.CreateGitStatusEntry(@"folder\file2.txt", GitFileStatus.Modified)
            };

            var treeRoot = TreeBuilder.BuildTreeRoot(newGitStatusEntries, gitStatusEntries, gitCommitTargets,
                                                     foldedTreeEntries);

            gitStatusEntries.Count.Should().Be(2);
            gitCommitTargets.Count.Should().Be(2);
            foldedTreeEntries.Count.Should().Be(0);

            var treeRootChidren = treeRoot.Children.ToArray();

            treeRootChidren.Length.Should().Be(2);

            var file1  = treeRootChidren[0];
            var folder = treeRootChidren[1];

            file1.Path.Should().Be("file1.txt");
            file1.Label.Should().Be("file1.txt");
            file1.RepositoryPath.Should().Be(@"Project\file1.txt");
            file1.Open.Should().BeTrue();
            file1.State.Should().Be(CommitState.None);
            file1.Target.Should().Be(gitCommitTargets[0]);

            file1.Children.Should().BeEmpty();

            folder.Path.Should().Be("folder");
            folder.Label.Should().Be("folder");
            folder.RepositoryPath.Should().Be(@"Project\folder");
            folder.Open.Should().BeTrue();
            folder.State.Should().Be(CommitState.None);
            folder.Target.Should().BeNull();

            var folderChildren = folder.Children.ToArray();

            folderChildren.Length.Should().Be(1);

            var file2 = folderChildren[0];

            file2.Label.Should().Be("file2.txt");
            file2.Open.Should().BeTrue();
            file2.Path.Should().Be(@"folder\file2.txt");
            file2.RepositoryPath.Should().Be(@"Project\folder\file2.txt");
            file2.State.Should().Be(CommitState.None);
            file2.Target.Should().Be(gitCommitTargets[1]);

            file2.Children.Should().BeEmpty();
        }
        /// <summary>
        /// Esta funcion se encarga de generar un arbol de las celulas disponibles para dicho usuario, incluidas a las cuales es lider, lider del lider y la misma que el usuario mismo asiste
        /// </summary>
        /// <param name="usuarioId"></param>
        /// <param name="mostrarCheckboxes"></param>
        /// <returns></returns>
        public Ext.Net.TreeNode GenerarArbolDeCelulas(int usuarioId, ThreeStateBool mostrarCheckboxes, bool expandido)
        {
            ManejadorDeCelulas manejadorCelulas = new ManejadorDeCelulas();

            List <Celula> celulasPermitidas = manejadorCelulas.ObtenerCelulasPermitidasPorMiembroComoCelulas(usuarioId);

            TreeData.TreeDataTableDataTable dt = new TreeData.TreeDataTableDataTable();

            //Agregamos la celula a la que el miembro asiste, aun y cuando sera de solo lectura; solamente si no existia ya en la lista de celulas permitidas (es decir, asiste y es lider a la vez)
            Miembro miembro = (from o in SesionActual.Instance.getContexto <IglesiaEntities>().Miembro where o.MiembroId == usuarioId select o).SingleOrDefault();

            if (!(celulasPermitidas.Any(o => o.CelulaId == miembro.CelulaId)))
            {
                dt.AddTreeDataTableRow(miembro.CelulaId.ToString(), string.Empty, miembro.Celula.Descripcion, atributoDeSoloLectura);
            }

            string celulaId;
            string miembroCelulaId;
            string atributoExtra;

            foreach (Celula c in celulasPermitidas)
            {
                celulaId = c.CelulaId.ToString();
                if (c.CelulaLider.Count > 0)
                {
                    CelulaLider celulaLider = c.CelulaLider.FirstOrDefault(o => o.Borrado == false && o.Miembro.Borrado == false);
                    if (celulaLider != null)
                    {
                        miembroCelulaId = celulaLider.Miembro.CelulaId.ToString();
                        miembroCelulaId = (celulaId.Equals(miembroCelulaId)) ? string.Empty : miembroCelulaId; //Evitamos un loop infinito al momento en que el miembro sea lider de la celula a la que asiste
                        atributoExtra   = (string.IsNullOrEmpty(miembroCelulaId)) ? atributoDeSoloLectura : string.Empty;
                        dt.AddTreeDataTableRow(celulaId, miembroCelulaId, c.Descripcion, atributoExtra);
                    }
                }
            }

            //Obtenemos las celulas sin "lideres"
            List <Celula> celulasSinLider = manejadorCelulas.ObtenerCelulasSinLideresComoCelulas();

            if (celulasSinLider.Count > 0)
            {
                int idNodoCelulasSinLideres = 9999999;
                dt.AddTreeDataTableRow(idNodoCelulasSinLideres.ToString(), miembro.CelulaId.ToString(), "Celulas sin Asignacion de Lider", atributoDeSoloLectura);
                foreach (Celula c in celulasSinLider)
                {
                    dt.AddTreeDataTableRow(c.CelulaId.ToString(), idNodoCelulasSinLideres.ToString(), c.Descripcion, string.Empty);
                }
            }

            Ext.Net.TreeNode navegacion = new Ext.Net.TreeNode("Celulas");
            navegacion.Expanded = expandido;
            if ((celulasPermitidas != null) && (celulasPermitidas.Count > 0))
            {
                generarNodos(navegacion, TreeBuilder.GenerateTree(miembro.CelulaId.ToString(), dt), mostrarCheckboxes, expandido); //La celula inicial es la celula a la que el usuario asiste
            }

            return(navegacion);
        }
예제 #34
0
    public static int Main(string[] args)
    {
        // Create scanner that reads from standard input
        Scanner scanner = new Scanner(Console.In);

        if (args.Length > 1 ||
            (args.Length == 1 && ! args[0].Equals("-d")))
        {
            Console.Error.WriteLine("Usage: mono SPP [-d]");
            return 1;
        }

        // If command line option -d is provided, debug the scanner.
        if (args.Length == 1 && args[0].Equals("-d"))
        {
            // Console.Write("Scheme 4101> ");
            Token tok = scanner.getNextToken();
            while (tok != null)
            {
                TokenType tt = tok.getType();

                Console.Write(tt);
                if (tt == TokenType.INT)
                    Console.WriteLine(", intVal = " + tok.getIntVal());
                else if (tt == TokenType.STRING)
                    Console.WriteLine(", stringVal = " + tok.getStringVal());
                else if (tt == TokenType.IDENT)
                    Console.WriteLine(", name = " + tok.getName());
                else
                    Console.WriteLine();

                // Console.Write("Scheme 4101> ");
                tok = scanner.getNextToken();
            }
            return 0;
        }

        // Create parser
        TreeBuilder builder = new TreeBuilder();
        Parser parser = new Parser(scanner, builder);
        Node root;

        // TODO: Create and populate the built-in environment and
        // create the top-level environment

        // Read-eval-print loop

        // TODO: print prompt and evaluate the expression
        root = (Node) parser.parseExp();
        while (root != null)
        {
            root.print(0);
            root = (Node) parser.parseExp();
        }

        return 0;
    }
예제 #35
0
        public void RenderTree_WhenNull_TrowArgumentException()
        {
            Action action = () =>
            {
                var tree = TreeBuilder.RenderTree <MarkDown>(null);
            };

            action.Should().Throw <ArgumentException>();
        }
예제 #36
0
        public void RenderTree_WhenOnlyText_TreeContainOneTextNodeWithThisText(string str)
        {
            var tree = TreeBuilder.RenderTree <MarkDown>(str);

            tree.ChildNode.Should().HaveCount(1);
            var textNode = tree.ChildNode.First() as TextNode;

            textNode.Value.Should().Be(str);
        }
예제 #37
0
        public TagType RenderTree_WhenOneTag_TreeContainOneTagNodeWithTypeOfNode(string str)
        {
            var tree = TreeBuilder.RenderTree <MarkDown>(str);

            tree.ChildNode.Should().HaveCount(1);
            var tagNode = tree.ChildNode.First() as TagNode;

            return(tagNode.TypeTag);
        }
예제 #38
0
        private static void BadTypeExceptionShouldBeThrownForType <T>(string message)
        {
            Action action = () => TreeBuilder.BuildTreeForType(typeof(T));

            action.Should()
            .ThrowExactly <BadTypeException>()
            .WithMessage(message)
            .Where(e => typeof(T) == e.Type);
        }
        public string ConvertTextToHtml(string text)
        {
            var treeBuilder = new TreeBuilder();
            var paragraphs = SplitToParagraphs(text)
                .Select(x => treeBuilder.GetTree(x))
                .Select(ConvertTreeToHtml);

            return String.Join("", paragraphs);
        }
        public void TestThatIncompleteTreeResultsInProperError()
        {
            var tb = new TreeBuilder<INode>();
            tb.Group<NameNode>().As(nn => new PartNode { Part = PartNode.Strip(nn.Text) });

            var nn1 = new NameNode { Text = "X.Y" };
            var nn2 = new NameNode { Text = "A.B" };

            Assert.Throws<ArgumentException>(() => tb.Build(new[] {nn1, nn2}));
        }
        public void GivenATreeBuiltWithNameGroupingOnly()
        {
            var tb = new TreeBuilder<INode>();
            tb.Group<NameNode>().As(nn => new PartNode { Part = PartNode.Strip(nn.Text) });

            var nn1 = new NameNode { Text = "X.Y.U" };
            var nn2 = new NameNode { Text = "X.Y.V" };

            _result = tb.Build(new[] { nn1, nn2 });
        }
예제 #42
0
        public void GivenATreeBuiltWithMultipleSteps()
        {
            var tb = new TreeBuilder<INode>();
            tb.Group<NameNode>().As(nn => new PartNode { Part = PartNode.Strip(nn.Text) });
            tb.Group<PartNode>()
                .When(pn => pn.Part.Contains("."))
                .As(pn => new PartNode { Part = PartNode.Strip(pn.Part) });

            _result = tb.Build(_names.Select(name => new NameNode { Text = name }));
        }
예제 #43
0
		public void Init()
		{
			binder = new DataBinder();
			builder = new TreeBuilder();
			
			CultureInfo en = CultureInfo.CreateSpecificCulture("en");

			Thread.CurrentThread.CurrentCulture	= en;
			Thread.CurrentThread.CurrentUICulture = en;
		}
		public void Init()
		{
			binder = new DataBinder();
			builder = new TreeBuilder();
			binder.Validator = new ValidatorRunner(new CachedValidationRegistry());

			CultureInfo en = CultureInfo.CreateSpecificCulture("en");

			Thread.CurrentThread.CurrentCulture = en;
			Thread.CurrentThread.CurrentUICulture = en;
		}
		public void NoValidEntries()
		{
			NameValueCollection args = new NameValueCollection();

			args.Add("customername", "x");
			args.Add("customerage", "x");
			args.Add("customerall", "x");

			TreeBuilder builder = new TreeBuilder();

			CompositeNode root = builder.BuildSourceNode(args);
			Assert.IsNull(root.GetChildNode("customer"));
		}
예제 #46
0
        public void TestTesterSerialization1()
        {
            var tester = new TreeBuilder<DataClass>();

            tester.Push("name", "steve", comparison.Equals)
                .Push("name", "jeff", comparison.Equals)
                .Or();
            var lambda = tester.Build();

            var json = JsonConvert.SerializeObject(tester.tree);
            Assert.IsNotNull(json);

            var tree = JsonConvert.DeserializeObject<Node>(json);
            Assert.IsNotNull(tree);

            Console.WriteLine(json);
        }
		public void OneLevelNode()
		{
			NameValueCollection args = new NameValueCollection();

			args.Add("customer.name", "hammett");
			args.Add("customer.age", "26");
			args.Add("customer.all", "yada yada yada");

			TreeBuilder builder = new TreeBuilder();

			CompositeNode root = builder.BuildSourceNode(args);
			
			CompositeNode node = (CompositeNode) root.GetChildNode("customer");
			
			Assert.IsNotNull(node);

			Assert.AreEqual("hammett", ((LeafNode)node.GetChildNode("name")).Value);
			Assert.AreEqual("26", ((LeafNode)node.GetChildNode("age")).Value);
			Assert.AreEqual("yada yada yada", ((LeafNode)node.GetChildNode("all")).Value);
		}
		public void TwoLevels()
		{
			NameValueCollection args = new NameValueCollection();

			args.Add("customer.name", "hammett");
			args.Add("customer.age", "26");
			args.Add("customer.location.code", "pt-br");
			args.Add("customer.location.country", "55");

			TreeBuilder builder = new TreeBuilder();

			CompositeNode root = builder.BuildSourceNode(args);
			Assert.IsNotNull(root);
			
			CompositeNode node = (CompositeNode) root.GetChildNode("customer");
			Assert.IsNotNull(root);

			CompositeNode locationNode = (CompositeNode) node.GetChildNode("location");
			Assert.IsNotNull(locationNode);

			Assert.AreEqual("pt-br", ((LeafNode)locationNode.GetChildNode("code")).Value);
			Assert.AreEqual("55", ((LeafNode)locationNode.GetChildNode("country")).Value);
		}
예제 #49
0
        public void TestPropTesterBasic()
        {
            var matched = new List<string>();
            var not_matched = new List<string>();
            var should_matched = new List<string> { "steve", "jeff" };
            var should_not_matched = new List<string> { "jimbo", "george" };

            var tester = new TreeBuilder<DataClass>();
            tester.Push("name", "steve", comparison.Equals)
                   .Push("name", "jeff", comparison.Equals)
                    .Or();
            var lambda = tester.Build();

            foreach (var item in MakeSomeDataObjs())
            {
                if (lambda(item))
                    matched.Add(item.name);
                else
                    not_matched.Add(item.name);
            }

            Assert.IsTrue(Enumerable.SequenceEqual(matched.OrderBy(p => p), should_matched.OrderBy(p => p)));
            Assert.IsTrue(Enumerable.SequenceEqual(not_matched.OrderBy(p => p), should_not_matched.OrderBy(p => p)));
        }
		public void Init()
		{
			builder = new TreeBuilder();
			binder = new DataBinder();
		}
예제 #51
0
		public void IndexedEntries()
		{
			var nameValueColl = new NameValueCollection();

			nameValueColl.Add("customer[0].name", "hammett");
			nameValueColl.Add("customer[0].age", "27");
			nameValueColl.Add("customer[0].age", "28");
			nameValueColl.Add("customer[1].name", "hamilton");
			nameValueColl.Add("customer[1].age", "28");
			nameValueColl.Add("customer[1].age", "29");

			var builder = new TreeBuilder();
			CompositeNode root = builder.BuildSourceNode(nameValueColl);

			Assert.IsNotNull(root);
			Assert.AreEqual(1, root.ChildrenCount);

			var indexNode = (IndexedNode) root.GetChildNode("customer");
			Assert.IsNotNull(indexNode);
			Assert.AreEqual(2, indexNode.ChildrenCount);

			var node = (CompositeNode) indexNode.GetChildNode("0");
			Assert.IsNotNull(node);
			Assert.AreEqual(2, node.ChildrenCount);

			var entry = (LeafNode) node.GetChildNode("name");
			Assert.IsNotNull(entry);
			Assert.IsFalse(entry.IsArray);
			Assert.AreEqual("name", entry.Name);
			Assert.AreEqual(NodeType.Leaf, entry.NodeType);
			Assert.AreEqual("hammett", entry.Value);

			node = (CompositeNode) indexNode.GetChildNode("1");
			Assert.IsNotNull(node);
			Assert.AreEqual(2, node.ChildrenCount);

			entry = (LeafNode) node.GetChildNode("name");
			Assert.IsNotNull(entry);
			Assert.IsFalse(entry.IsArray);
			Assert.AreEqual("name", entry.Name);
			Assert.AreEqual(NodeType.Leaf, entry.NodeType);
			Assert.AreEqual("hamilton", entry.Value);
		}
예제 #52
0
		public void IndexedFlatEntries()
		{
			var nameValueColl = new NameValueCollection();

			nameValueColl.Add("emails[0]", "*****@*****.**");
			nameValueColl.Add("emails[1]", "*****@*****.**");
			nameValueColl.Add("emails[2]", "*****@*****.**");

			var builder = new TreeBuilder();
			CompositeNode root = builder.BuildSourceNode(nameValueColl);

			Assert.IsNotNull(root);
			Assert.AreEqual(1, root.ChildrenCount);

			var indexNode = (IndexedNode) root.GetChildNode("emails");
			Assert.IsNotNull(indexNode);
			Assert.AreEqual(3, indexNode.ChildrenCount);

			Node[] entries = indexNode.ChildNodes;
			Assert.IsNotNull(entries);
			Assert.AreEqual(3, entries.Length);

			Assert.AreEqual("*****@*****.**", ((LeafNode) entries[0]).Value);
			Assert.AreEqual("*****@*****.**", ((LeafNode) entries[1]).Value);
			Assert.AreEqual("*****@*****.**", ((LeafNode) entries[2]).Value);
		}
예제 #53
0
 private void DispatchParserQueueEvent (TreeBuilder treeBuilder)
 { 
     treeBuilder.HandleAsyncQueueItem (); 
 }
예제 #54
0
 public void Refresh()
 {
     ITreeBuilder builder = new TreeBuilder (pad, currentIter);
     builder.UpdateAll ();
 }
예제 #55
0
 public void Setup()
 {
     _files = new List<IVirtualFile>();
     _treeBuilder = new TreeBuilder();
 }
예제 #56
0
        internal Tree Build(Repository repository)
        {
            WrapAllTreeDefinitions(repository);

            using (var builder = new TreeBuilder())
            {
                var builtTreeEntryDefinitions = new List<Tuple<string, TreeEntryDefinition>>(entries.Count);

                foreach (KeyValuePair<string, TreeEntryDefinition> kvp in entries)
                {
                    string name = kvp.Key;
                    TreeEntryDefinition ted = kvp.Value;

                    var transient = ted as TransientBlobTreeEntryDefinition;

                    if (transient == null)
                    {
                        builder.Insert(name, ted);
                        continue;
                    }

                    Blob blob = transient.Builder(repository.ObjectDatabase);
                    TreeEntryDefinition ted2 = TreeEntryDefinition.From(blob, ted.Mode);
                    builtTreeEntryDefinitions.Add(new Tuple<string, TreeEntryDefinition>(name, ted2));

                    builder.Insert(name, ted2);
                }

                builtTreeEntryDefinitions.ForEach(t => entries[t.Item1] = t.Item2);

                ObjectId treeId = builder.Write(repository);
                return repository.Lookup<Tree>(treeId);
            }
        }
예제 #57
0
    public static int Main(string[] args)
    {
        // Create scanner that reads from standard input
        Scanner scanner = new Scanner(Console.In);

        if (args.Length > 1 ||
            (args.Length == 1 && ! args[0].Equals("-d")))
        {
            Console.Error.WriteLine("Usage: mono SPP [-d]");
            return 1;
        }

        // If command line option -d is provided, debug the scanner.
        if (args.Length == 1 && args[0].Equals("-d"))
        {
            // Console.Write("Scheme 4101> ");
            Token tok = scanner.getNextToken();
            while (tok != null)
            {
                TokenType tt = tok.getType();

                Console.Write(tt);
                if (tt == TokenType.INT)
                    Console.WriteLine(", intVal = " + tok.getIntVal());
                else if (tt == TokenType.STRING)
                    Console.WriteLine(", stringVal = " + tok.getStringVal());
                else if (tt == TokenType.IDENT)
                    Console.WriteLine(", name = " + tok.getName());
                else
                    Console.WriteLine();

                // Console.Write("Scheme 4101> ");
                tok = scanner.getNextToken();
            }
            return 0;
        }

        // Create parser
        TreeBuilder builder = new TreeBuilder();
        Parser parser = new Parser(scanner, builder);
        Node root;

        Tree.Environment env = new Tree.Environment(); // create built-in environment
        //Populate the builtin environment
        Ident id;
        string[] builtins = new string[] {"symbol?","number?","b+","b-","b*","b/","b=","b<","car","cdr","cons","set-car!","set-cdr!","null?","pair?","eq?","procedure?","read","write","display","newline","eval","apply","interaction-environment" };
        foreach(string function in builtins)
        {
            id = new Ident(function);
            env.define(id, new BuiltIn(id));
        }
        env = new Tree.Environment(env); // create top-level environment
        // Read-eval-print loop

        // TODO: print prompt and evaluate the expression
        root = (Node) parser.parseExp();
        while (root != null)
        {
            root.eval(env).print(0);
            root = (Node) parser.parseExp();
        }

        return 0;
    }
 public int[] FindCodeTagIndices(string text)
 {
     var treeBuilder = new TreeBuilder();
     var actual = treeBuilder.FindCodeTagIndices(text);
     return actual;
 }
예제 #59
0
		public void RepeatedNamesForNodes()
		{
			var nameValueColl = new NameValueCollection();

			nameValueColl.Add("profile.Process", "test");
			nameValueColl.Add("profile.Process.Id", "1");

			var builder = new TreeBuilder();
			CompositeNode root = builder.BuildSourceNode(nameValueColl);
		}
예제 #60
-1
    public void More_than_two_children()
    {
        var records = new[]
        {
            new TreeBuildingRecord {
                RecordId = 3, ParentId = 0
            },
            new TreeBuildingRecord {
                RecordId = 2, ParentId = 0
            },
            new TreeBuildingRecord {
                RecordId = 1, ParentId = 0
            },
            new TreeBuildingRecord {
                RecordId = 0, ParentId = 0
            }
        };

        var tree = TreeBuilder.BuildTree(records);

        AssertTreeIsBranch(tree, id: 0, childCount: 3);
        AssertTreeIsLeaf(tree.Children[0], id: 1);
        AssertTreeIsLeaf(tree.Children[1], id: 2);
        AssertTreeIsLeaf(tree.Children[2], id: 3);
    }