Example #1
0
        public void testTricky()
        {
            Core.Tree tree = new Core.Tree(db);
            tree.AddFile("a.b");
            tree.AddFile("a.c");
            tree.AddFile("a/b.b/b");
            tree.AddFile("a/b");
            tree.AddFile("a/c");
            tree.AddFile("a=c");
            tree.AddFile("a=d");

            TreeIterator i = MakeIterator(tree);

            Assert.IsTrue(i.hasNext());
            Assert.AreEqual("a.b", i.next().FullName);
            Assert.IsTrue(i.hasNext());
            Assert.AreEqual("a.c", i.next().FullName);
            Assert.IsTrue(i.hasNext());
            Assert.AreEqual("a/b", i.next().FullName);
            Assert.IsTrue(i.hasNext());
            Assert.AreEqual("a/b.b/b", i.next().FullName);
            Assert.IsTrue(i.hasNext());
            Assert.AreEqual("a/c", i.next().FullName);
            Assert.IsTrue(i.hasNext());
            Assert.AreEqual("a=c", i.next().FullName);
            Assert.IsTrue(i.hasNext());
            Assert.AreEqual("a=d", i.next().FullName);
            Assert.IsFalse(i.hasNext());
        }
Example #2
0
        public void testEmpty()
        {
            Core.Tree    tree = new Core.Tree(db);
            TreeIterator i    = MakeIterator(tree);

            Assert.IsFalse(i.hasNext());
        }
        public bool FindTarget(TreeNode root, int k)
        {
            var left  = new TreeIterator(root, true);
            var right = new TreeIterator(root, false);

            while (left.Current != right.Current)
            {
                int sum = left.Current.val + right.Current.val;
                if (sum == k)
                {
                    return(true);
                }

                if (sum < k)
                {
                    left.MoveNext();
                }
                else
                {
                    right.MoveNext();
                }
            }

            return(false);
        }
Example #4
0
            internal bool IsSupersetOf(Node other)
            {
                if (other.Count > Count)
                {
                    return(false);
                }
                var iter = new TreeIterator(this);

                return(other.ForEachWhileNode(node => {
                    if (!iter.MoveNext())
                    {
                        return false;
                    }
                    var myCur = iter.Current;
                    var compare = Comparer.Compare(node.Key, myCur.Key);
                    if (compare > 0)
                    {
                        while ((compare = Comparer.Compare(node.Key, iter.Current.Key)) > 0)
                        {
                            if (!iter.MoveNext())
                            {
                                return false;
                            }
                        }
                    }
                    return compare == 0;
                }));
            }
Example #5
0
        private long?TryFindSmallValue(Transaction tx, TreeIterator it, int num)
        {
            do
            {
                var stream = it.CreateReaderForCurrent();
                {
                    var current          = new StreamBitArray(stream);
                    var currentSectionId = it.CurrentKey.CreateReader().ReadBigEndianInt64();

                    long?page;
                    if (current.SetCount < num)
                    {
                        if (TryFindSmallValueMergingTwoSections(tx, it, num, current, currentSectionId, out page))
                        {
                            return(page);
                        }
                        continue;
                    }

                    if (TryFindContinuousRange(tx, it, num, current, currentSectionId, out page))
                    {
                        return(page);
                    }

                    //could not find a continuous so trying to merge
                    if (TryFindSmallValueMergingTwoSections(tx, it, num, current, currentSectionId, out page))
                    {
                        return(page);
                    }
                }
            } while (it.MoveNext());

            return(null);
        }
Example #6
0
        /// <summary>
        /// Formats the tree to look nicely.
        /// </summary>
        public void PositionNodesNicely()
        {
            var bt = window.tree;

            // Assumption for Nicify:
            // There must be a root set.
            if (bt.Root == null)
            {
                return;
            }

            // This is for the node editor to use to place the nodes.
            var positions = new Dictionary <BehaviourNode, Vector2>();
            var levels    = calculateLevels();
            var posParams = new PositioningParameters();

            Action <BehaviourNode> positionInPlace = (node) =>
            {
                positionNode(node, positions, levels, posParams);
            };

            TreeIterator <BehaviourNode> .Traverse(bt.Root, positionInPlace, Traversal.PostOrder);

            foreach (var editorNode in canvas.Nodes)
            {
                var behaviour = editorNode.behaviour;

                if (positions.ContainsKey(behaviour))
                {
                    Vector2 pos = positions[behaviour];
                    editorNode.bodyRect.position = pos;
                }
            }
        }
Example #7
0
        internal void CalculatePanelSizes()
        {
            int count = 0;

            if (MatrixModel?.Hierarchy != null)
            {
                TreeIterator <Element> iterator = new TreeIterator <Element>(MatrixModel.Hierarchy);
                TreeNode <Element>     treeNode = iterator.Next();

                while (treeNode != null)
                {
                    if (treeNode.IsCollapsed)
                    {
                        count++;
                        treeNode = iterator.Skip();
                    }
                    else
                    {
                        treeNode = iterator.Next();
                    }
                }
            }

            _selector.Size = new Size(_selector.Width,
                                      count * _displayOptions.CellHeight + _displayOptions.RootHeight);

            _matrix.Size = new Size(count * _displayOptions.CellHeight,
                                    count * _displayOptions.CellHeight + _displayOptions.RootHeight);
        }
Example #8
0
        public void TestFlatAB()
        {
            ITreeAdaptor  adaptor = new CommonTreeAdaptor();
            TreeWizard    wiz     = new TreeWizard(adaptor, tokens);
            CommonTree    t       = (CommonTree)wiz.Create("(nil A B)");
            TreeIterator  it      = new TreeIterator(t);
            StringBuilder buf     = new StringBuilder();
            bool          first   = true;

            while (it.MoveNext())
            {
                CommonTree n = (CommonTree)it.Current;

                if (!first)
                {
                    buf.Append(" ");
                }

                first = false;
                buf.Append(n);
            }
            string expecting = "nil DOWN A B UP EOF";
            string found     = buf.ToString();

            Assert.AreEqual(expecting, found);
        }
Example #9
0
        private static bool TryFindSmallValueMergingTwoSections(Transaction tx, TreeIterator it, int num, StreamBitArray current, long currentSectionId, out long?result)
        {
            result = -1;
            var currentRange = current.GetEndRangeCount();

            if (currentRange == 0)
            {
                return(false);
            }

            var nextSectionId = currentSectionId + 1;

            var nextId = new Slice(EndianBitConverter.Big.GetBytes(nextSectionId));
            var read   = tx.State.FreeSpaceRoot.Read(nextId);

            if (read == null)
            {
                return(false);
            }

            var next = new StreamBitArray(read.Reader);

            var nextRange = num - currentRange;

            if (next.HasStartRangeCount(nextRange) == false)
            {
                return(false);
            }

            if (next.SetCount == nextRange)
            {
                tx.State.FreeSpaceRoot.Delete(nextId);
            }
            else
            {
                for (int i = 0; i < nextRange; i++)
                {
                    next.Set(i, false);
                }
                tx.State.FreeSpaceRoot.Add(nextId, next.ToStream());
            }

            if (current.SetCount == currentRange)
            {
                tx.State.FreeSpaceRoot.Delete(it.CurrentKey);
            }
            else
            {
                for (int i = 0; i < currentRange; i++)
                {
                    current.Set(NumberOfPagesInSection - 1 - i, false);
                }
                tx.State.FreeSpaceRoot.Add(nextId, next.ToStream());
            }


            result = currentSectionId * NumberOfPagesInSection + currentRange;
            return(true);
        }
Example #10
0
        public void testSimpleT()
        {
            Core.Tree tree = new Core.Tree(db);
            tree.AddTree("a");
            TreeIterator i = MakeIterator(tree);

            Assert.IsFalse(i.hasNext());
        }
Example #11
0
        private static long CopyFixedSizeTrees(StorageEnvironment compactedEnv, Action <StorageCompactionProgress> progressReport, Transaction txr,
                                               TreeIterator rootIterator, string treeName, long copiedTrees, long totalTreesCount, TransactionPersistentContext context, CancellationToken token)
        {
            var treeNameSlice = rootIterator.CurrentKey.Clone(txr.Allocator);

            var header = (FixedSizeTreeHeader.Embedded *)txr.LowLevelTransaction.RootObjects.DirectRead(treeNameSlice);

            var fst = txr.FixedTreeFor(treeNameSlice, header->ValueSize);

            Report(copiedTrees, totalTreesCount, 0, fst.NumberOfEntries, progressReport, $"Copying fixed size tree '{treeName}'. Progress: 0/{fst.NumberOfEntries} entries.", treeName);

            using (var it = fst.Iterate())
            {
                var copiedEntries = 0L;
                if (it.Seek(Int64.MinValue) == false)
                {
                    return(copiedTrees);
                }

                do
                {
                    token.ThrowIfCancellationRequested();
                    using (var txw = compactedEnv.WriteTransaction(context))
                    {
                        var snd             = txw.FixedTreeFor(treeNameSlice, header->ValueSize);
                        var transactionSize = 0L;

                        do
                        {
                            token.ThrowIfCancellationRequested();

                            Slice val;
                            using (it.Value(out val))
                                snd.Add(it.CurrentKey, val);
                            transactionSize += fst.ValueSize + sizeof(long);
                            copiedEntries++;

                            var reportRate = fst.NumberOfEntries / 33 + 1;
                            if (copiedEntries % reportRate == 0)
                            {
                                Report(copiedTrees, totalTreesCount, copiedEntries, fst.NumberOfEntries, progressReport, $"Copying fixed size tree '{treeName}'. Progress: {copiedEntries}/{fst.NumberOfEntries} entries.", treeName);
                            }
                        } while (transactionSize < compactedEnv.Options.MaxScratchBufferSize / 2 && it.MoveNext());

                        txw.Commit();
                    }

                    if (fst.NumberOfEntries == copiedEntries)
                    {
                        copiedTrees++;
                        Report(copiedTrees, totalTreesCount, copiedEntries, fst.NumberOfEntries, progressReport, $"Finished copying fixed size tree '{treeName}'. Progress: {copiedEntries}/{fst.NumberOfEntries} entries.", treeName);
                    }

                    compactedEnv.FlushLogToDataFile();
                } while (it.MoveNext());
            }
            return(copiedTrees);
        }
Example #12
0
            public IEnumerator <KeyValuePair <TKey, TValue> > GetEnumerator()
            {
                var iterator = new TreeIterator(this);

                while (iterator.MoveNext())
                {
                    yield return(Kvp.Of(iterator.Current.Key, iterator.Current.Value));
                }
            }
        public void testEmpty()
        {
            var          tree = new Core.Tree(db);
            TreeIterator i    = makeIterator(tree);

            Assert.IsTrue(i.hasNext());
            Assert.AreEqual("", i.next().FullName);
            Assert.IsFalse(i.hasNext());
        }
Example #14
0
        public void testSimpleF1()
        {
            Core.Tree tree = new Core.Tree(db);
            tree.AddFile("x");
            TreeIterator i = MakeIterator(tree);

            Assert.IsTrue(i.hasNext());
            Assert.AreEqual("x", i.next().Name);
        }
Example #15
0
 public void Run(MetadataModel yaml, ResolverContext context)
 {
     TreeIterator.Preorder(yaml.TocYamlViewModel, null,
                           s => s.IsInvalid ? null : s.Items,
                           (current, parent) =>
     {
         current.Parent = parent;
         return(true);
     });
 }
Example #16
0
            /// <summary>
            /// Adds and removes children types based on current types selected.
            /// </summary>
            public void UpdateParentChildren()
            {
                _parentsToSetChildren.Clear();
                _parentsToClearChildren.Clear();

                TreeIterator <TypeSelectionNode> .Traverse(_root, markAdditionsAndRemovals);

                setParentChildren();
                clearParentChildren();
            }
Example #17
0
 private TocItemViewModel GetDefaultHomepageItem(TocViewModel toc)
 {
     foreach (var item in toc)
     {
         var tocItem = TreeIterator.PreorderFirstOrDefault(item, s => s.Items, s => IsValidHomepageLink(s));
         if (tocItem != null)
         {
             return(tocItem);
         }
     }
     return(null);
 }
Example #18
0
        public void testSimpleT()
        {
            Core.Tree tree = new Core.Tree(db);
            tree.AddTree("a");
            TreeIterator i = MakeIterator(tree);

            Assert.IsTrue(i.hasNext());
            Assert.AreEqual("", i.next().FullName);
            Assert.IsTrue(i.hasNext());
            Assert.AreEqual("a", i.next().FullName);
            Assert.IsFalse(i.hasNext());
        }
Example #19
0
 private string GetDefaultHomepage(TocViewModel toc)
 {
     foreach (var item in toc)
     {
         var href = TreeIterator.PreorderFirstOrDefault(item, s => s.Items, s => IsValidHomepageLink(s.Href));
         if (href != null)
         {
             return(href.Href);
         }
     }
     return(null);
 }
Example #20
0
    public static void Main(string [] args)
    {
        Tree <int>   T1 = new Tree <int>(1, null, null);
        Tree <int>   T2 = new Tree <int>(3, null, null);
        Tree <int>   T3 = new Tree <int>(5, null, null);
        Tree <int>   T4 = new Tree <int>(7, null, null);
        Tree <int>   T5 = new Tree <int>(2, T1, T2);
        Tree <int>   T6 = new Tree <int>(6, T3, T4);
        Tree <int>   T7 = new Tree <int>(4, T5, T6);
        TreeIterator t  = new TreeIterator();

        t.display(T7);
    }
Example #21
0
        private void AllocateIds()
        {
            int i = 1;
            TreeIterator <Element> it = new TreeIterator <Element>(Hierarchy);

            TreeNode <Element> treeNode = it.Next();

            while (treeNode != null)
            {
                treeNode.NodeValue.Id = i;
                i++;
                treeNode = it.Next();
            }
        }
Example #22
0
        private void CalculateParentWeights()
        {
            _directRelationCount = 0;
            TreeIterator <Element> it1          = new TreeIterator <Element>(Hierarchy);
            TreeNode <Element>     providerNode = it1.Next();

            while (providerNode != null)
            {
                Relation[] relations = GetProviderRelations(providerNode.NodeValue).ToArray();
                foreach (Relation rel in relations)
                {
                    _directRelationCount++;

                    TreeNode <Element> consumerNode = FindNode(rel.Consumer.FullName);

                    if (consumerNode != null)
                    {
                        TreeNode <Element> currentConsumer = consumerNode;
                        while (currentConsumer != null)
                        {
                            TreeNode <Element> currentProvider = providerNode;
                            while (currentProvider != null)
                            {
                                if ((providerNode.NodeValue != null) &&
                                    (currentProvider.NodeValue != null) &&
                                    (consumerNode.NodeValue != null) &&
                                    (currentConsumer.NodeValue != null))
                                {
                                    if ((currentConsumer.NodeValue.Id != consumerNode.NodeValue.Id) || (currentProvider.NodeValue.Id != providerNode.NodeValue.Id))
                                    {
                                        AddRelation(currentConsumer.NodeValue, currentProvider.NodeValue, "", rel.Weight, false, true);
                                    }
                                }
                                else
                                {
                                    Logger.LogError($"Node value null consumer={rel.Consumer.FullName} provider={rel.Provider.FullName}");
                                }

                                currentProvider = currentProvider.Parent;
                            }

                            currentConsumer = currentConsumer.Parent;
                        }
                    }
                }

                providerNode = it1.Next();
            }
        }
Example #23
0
        private bool TryFindContinuousRange(Transaction tx, TreeIterator it, int num, StreamBitArray current, long currentSectionId, out long?page)
        {
            page = -1;
            var start = -1;
            var count = 0;

            for (int i = 0; i < NumberOfPagesInSection; i++)
            {
                if (current.Get(i))
                {
                    if (start == -1)
                    {
                        start = i;
                    }
                    count++;
                    if (count == num)
                    {
                        page = currentSectionId * NumberOfPagesInSection + start;
                        break;
                    }
                }
                else
                {
                    start = -1;
                    count = 0;
                }
            }

            if (count != num)
            {
                return(false);
            }

            if (current.SetCount == num)
            {
                tx.State.FreeSpaceRoot.Delete(it.CurrentKey);
            }
            else
            {
                for (int i = 0; i < num; i++)
                {
                    current.Set(i + start, false);
                }

                tx.State.FreeSpaceRoot.Add(it.CurrentKey, current.ToStream());
            }

            return(true);
        }
        public void testSimpleF2()
        {
            var tree = new Core.Tree(db);

            tree.AddFile("a");
            tree.AddFile("x");
            TreeIterator i = makeIterator(tree);

            Assert.IsTrue(i.hasNext());
            Assert.AreEqual("a", i.next().Name);
            Assert.AreEqual("x", i.next().Name);
            Assert.IsTrue(i.hasNext());
            Assert.AreEqual("", i.next().FullName);
            Assert.IsFalse(i.hasNext());
        }
 public static void TestItr <AnyType>(string type, TreeIterator <AnyType> itr)
 {
     try
     {
         Console.WriteLine(type + ":");
         for (itr.First( ); itr.IsValid( ); itr.Advance( ))
         {
             Console.Write(" " + itr.Retrieve( ));
         }
         Console.WriteLine( );
         itr.Advance( );
     }
     catch (IndexOutOfRangeException e)
     { Console.WriteLine(e + " (as expected)"); }
 }
Example #26
0
            public IEnumerator <KeyValuePair <TKey, TValue> > GetEnumerator()
            {
                var iterator = new TreeIterator(this);

                while (iterator.MoveNext())
                {
                    var bucket = iterator.Current.Bucket;
                    while (!bucket.IsEmpty)
                    {
                        yield return(Kvp.Of(bucket.Key, bucket.Value));

                        bucket = bucket.Next;
                    }
                }
            }
Example #27
0
 public void Run(MetadataModel yaml, ResolverContext context)
 {
     TreeIterator.Preorder(
         yaml.TocYamlViewModel,
         null,
         s => s.IsInvalid ? null : s.Items,
         (current, parent) =>
     {
         if (current.InheritDoc != null)
         {
             InheritDoc(current, context);
             current.InheritDoc = null;
         }
         return(true);
     });
 }
Example #28
0
        /// <summary>
        /// Sets the position of the subtree at an offset.
        /// </summary>
        /// <param name="pos">The position of the subtree. </param>
        /// <param name="offset">Additional offset.</param>
        /// <param name="root">The subtree root.</param>
        public void SetSubtreePosition(Vector2 pos, Vector2 offset, BonsaiNode root)
        {
            float min = float.MinValue;

            if (root.Input.outputConnection != null)
            {
                float nodeTop      = root.Input.bodyRect.yMin;
                float parentBottom = root.Input.outputConnection.bodyRect.yMax;

                // The root cannot be above its parent.
                if (nodeTop < parentBottom)
                {
                    min = parentBottom;
                }
            }

            // Record the old position so we can know by how much the root moved
            // so all children can be shifted by the pan delta.
            Vector2 oldPos = root.bodyRect.position;

            // Clamp the position so it does not go above the parent.
            Vector2 diff = pos - offset;

            diff.y = Mathf.Clamp(diff.y, min, float.MaxValue);

            Vector2 rounded = SnapPosition(diff);

            root.bodyRect.position = rounded;

            // Calculate the change of position of the root.
            Vector2 pan = root.bodyRect.position - oldPos;

            // Move the entire subtree of the root.
            Action <BonsaiNode> subtreeDrag = (node) =>
            {
                // For all children, pan by the same amount that the parent changed by.
                if (node != root)
                {
                    node.bodyRect.position += SnapPosition(pan);
                }
            };

            TreeIterator <BonsaiNode> .Traverse(root, subtreeDrag);
        }
        private static long CopyFixedSizeTrees(StorageEnvironment compactedEnv, Action <CompactionProgress> progressReport, Transaction txr,
                                               TreeIterator rootIterator, string treeName, long copiedTrees, long totalTreesCount)
        {
            var fst = txr.FixedTreeFor(rootIterator.CurrentKey.Clone(txr.Allocator), 0);

            Report(treeName, copiedTrees, totalTreesCount, 0,
                   fst.NumberOfEntries,
                   progressReport);
            using (var it = fst.Iterate())
            {
                var copiedEntries = 0L;
                if (it.Seek(Int64.MinValue) == false)
                {
                    return(copiedTrees);
                }
                do
                {
                    using (var txw = compactedEnv.WriteTransaction())
                    {
                        var snd             = txw.FixedTreeFor(rootIterator.CurrentKey.Clone(txr.Allocator));
                        var transactionSize = 0L;
                        do
                        {
                            snd.Add(it.CurrentKey, it.Value);
                            transactionSize += fst.ValueSize + sizeof(long);
                            copiedEntries++;
                        } while (transactionSize < compactedEnv.Options.MaxLogFileSize / 2 && it.MoveNext());

                        txw.Commit();
                    }
                    if (fst.NumberOfEntries == copiedEntries)
                    {
                        copiedTrees++;
                    }

                    Report(treeName, copiedTrees, totalTreesCount, copiedEntries,
                           fst.NumberOfEntries,
                           progressReport);
                    compactedEnv.FlushLogToDataFile();
                } while (it.MoveNext());
            }
            return(copiedTrees);
        }
Example #30
0
            /// <summary>
            ///     Returns an iterator for retrieving all the elements shared between this tree and another tree.
            /// </summary>
            /// <param name="other"></param>
            /// <returns></returns>
            public IEnumerable <StructTuple <Node, Node> > IntersectElements(Node other)
            {
                if (IsEmpty || other.IsEmpty)
                {
                    yield break;
                }
                var aIterator = new TreeIterator(this);
                var bIterator = new TreeIterator(other);
                var pivotInA  = true;
                var success   = aIterator.MoveNext();
                var pivot     = aIterator.Current;

                while (!aIterator.IsEnded || !bIterator.IsEnded)
                {
                    var trySeekIn = pivotInA ? bIterator : aIterator;
                    int cmpResult;
                    success = trySeekIn.SeekGreaterThan(pivot.Key, out cmpResult);
                    if (!success)
                    {
                        break;
                    }
                    var maybePivot = trySeekIn.Current;
                    if (cmpResult == 0)
                    {
                        yield return(pivotInA ? StructTuple.Create(pivot, maybePivot) : StructTuple.Create(maybePivot, pivot));

                        pivotInA  = !pivotInA;
                        trySeekIn = pivotInA ? aIterator : bIterator;
                        success   = trySeekIn.MoveNext();
                        if (!success)
                        {
                            break;
                        }
                        pivot = trySeekIn.Current;
                    }
                    else
                    {
                        pivot    = maybePivot;
                        pivotInA = !pivotInA;                         //If the pivot was in X, it's now in Y...
                    }
                }
            }
Example #31
0
        public void TestAB()
        {
            ITreeAdaptor adaptor = new CommonTreeAdaptor();
            TreeWizard wiz = new TreeWizard( adaptor, tokens );
            CommonTree t = (CommonTree)wiz.Create( "(A B)" );
            TreeIterator it = new TreeIterator( t );
            StringBuilder buf = new StringBuilder();
            bool first = true;
            while ( it.MoveNext() )
            {
                CommonTree n = (CommonTree)it.Current;

                if ( !first )
                    buf.Append( " " );

                first = false;
                buf.Append( n );
            }
            string expecting = "A DOWN B UP EOF";
            string found = buf.ToString();
            Assert.AreEqual( expecting, found );
        }
Example #32
0
		/// <exception cref="System.IO.IOException"></exception>
		private void Walk(Tree tree, Tree auxTree)
		{
			TreeIterator mi = new TreeIterator(tree, TreeIterator.Order.POSTORDER);
			TreeIterator ai = new TreeIterator(auxTree, TreeIterator.Order.POSTORDER);
			TreeEntry m = mi.HasNext() ? mi.Next() : null;
			TreeEntry a = ai.HasNext() ? ai.Next() : null;
			int curIndexPos = indexCounter;
			GitIndex.Entry i = indexCounter < indexMembers.Length ? indexMembers[indexCounter
				++] : null;
			while (m != null || a != null || i != null)
			{
				int cmpma = Compare(m, a);
				int cmpmi = Compare(m, i);
				int cmpai = Compare(a, i);
				TreeEntry pm = cmpma <= 0 && cmpmi <= 0 ? m : null;
				TreeEntry pa = cmpma >= 0 && cmpai <= 0 ? a : null;
				GitIndex.Entry pi = cmpmi >= 0 && cmpai >= 0 ? i : null;
				if (pi != null)
				{
					VisitEntry(pm, pa, pi);
				}
				else
				{
					FinishVisitTree(pm, pa, curIndexPos);
				}
				if (pm != null)
				{
					m = mi.HasNext() ? mi.Next() : null;
				}
				if (pa != null)
				{
					a = ai.HasNext() ? ai.Next() : null;
				}
				if (pi != null)
				{
					i = indexCounter < indexMembers.Length ? indexMembers[indexCounter++] : null;
				}
			}
		}