Exemplo n.º 1
0
 private static void addStackToBack(System.Collections.Generic.Stack<int> s, int m)
 {
     if (s.Count == 0)
     {
         s.Push(m);
     }
     else
     {
         int data = s.Pop();
         addStackToBack(s, m);
         s.Push(data);
     }
 }
Exemplo n.º 2
0
        private static void SnipVoidRound(DirectoryInfo dTarget, System.Collections.Stack stackDirs)
        {
            DirectoryInfo currentDir = null;
            try
            {
                foreach (DirectoryInfo diNext in dTarget.GetDirectories())
                    stackDirs.Push(diNext);

                while (stackDirs.Count > 0)
                {
                    currentDir = (DirectoryInfo)stackDirs.Pop();

                    //Process dir
                    if (currentDir.GetFiles().Length == 0)
                    {
                        if (currentDir.GetDirectories().Length == 0)
                            currentDir.Delete();
                        else
                            //Process Subdirectories
                            foreach (DirectoryInfo diNext in currentDir.GetDirectories())
                                stackDirs.Push(diNext);
                    }
                }
            }
            catch (Exception e)
            {
                if (currentDir != null)
                    throw new Exception(String.Format(Resources.errorNoDelete, currentDir.FullName, e.ToString()));
                else
                    throw;
            }
        }
Exemplo n.º 3
0
		/// <summary>
		/// Given a key, search the node where the key is stored in the tree with root as the root node.
		/// </summary>
		/// <param name="root"></param>
		/// <param name="key"></param>
		/// <param name="pos">the location the key is stored in</param>
		/// <param name="visisted">all the visisted parent is saved in the stack.</param>
		/// <returns></returns>
		public BNode FindNode(BNode root, IKey key, ref int pos, System.Collections.Stack visited, System.Collections.Stack via)
		{
			Debug.Assert(visited != null);

			BNode n = root;
			pos = -1;
			IKey temp = null;
			while (!n.Leaf)
			{
				temp = n.SearchKey(key, ref pos);
				if (temp == null)
				{
					uint nextNodeId = n.GetChildAt(pos);
					visited.Push(n);
					via.Push(pos);
					
					n = (BNode)m_sgManager.GetSegment(nextNodeId, m_nodeFactory, m_keyFactory);
				}
				else
					return n;
			}

			//n is leaf
			temp = n.SearchKey(key, ref pos);
			if (temp == null)
				return null;
			else
				return n;
		}
Exemplo n.º 4
0
		/*******************************/
		/// <summary>
		/// Adds an element to the top end of a Stack instance.
		/// </summary>
		/// <param name="stack">The Stack instance</param>
		/// <param name="element">The element to add</param>
		/// <returns>The element added</returns>  
		public static System.Object StackPush(System.Collections.Stack stack, System.Object element)
		{
			stack.Push(element);
			return element;
		}
        public async Task<Errorable<TreeNode>> PersistTree(TreeID rootid, ImmutableContainer<TreeID, TreeNode> trees)
        {
            if (trees == null) throw new ArgumentNullException("trees");
            // TODO: better return value than `null`
            if (trees.Count == 0) return (TreeNode)null;

            // Start a query to check what Trees exist already:
            var existTrees = await db.ExecuteListQueryAsync(new QueryTreesExist(trees.Keys), expectedCapacity: trees.Count);

            // This code scans the tree breadth-first and builds a reversed depth-ordered stack:

            var reverseDepthOrder = new { id = rootid, depth = 0 }.StackOf(trees.Count);
            reverseDepthOrder.Pop();

            var breadthFirstQueue = new { id = rootid, depth = 0 }.QueueOf(trees.Count);
            while (breadthFirstQueue.Count > 0)
            {
                var curr = breadthFirstQueue.Dequeue();
                // Add it to the reverse stack:
                reverseDepthOrder.Push(curr);

                TreeNode node;
                if (!trees.TryGetValue(curr.id, out node))
                {
                    // TODO: didn't find the TreeID in the given collection, assume already persisted?
                    continue;
                }

                // Queue up the child TreeIDs:
                foreach (var trtr in node.Trees)
                    breadthFirstQueue.Enqueue(new { id = trtr.TreeID, depth = curr.depth + 1 });
            }

            // This code takes the reverse depth-ordered stack and persists the tree nodes in groups per depth level.
            // This ensures that all child nodes across the breadth of the tree at each depth level are persisted
            // before moving up to their parents.

            List<Task<Errorable<TreeNode>>> persistTasks = new List<Task<Errorable<TreeNode>>>();
            // Initialize the `isPersisting` set with the set of TreeIDs that already exist.
            HashSet<TreeID> isPersisting = new HashSet<TreeID>(existTrees);

            int lastDepth = reverseDepthOrder.Peek().depth;
            foreach (var curr in reverseDepthOrder)
            {
                Debug.WriteLine(String.Format("{0}: {1}", curr.depth, curr.id.ToString(firstLength: 7)));
                // An invariant of the algorithm, enforced via assert:
                Debug.Assert(curr.depth <= lastDepth);

                // Did we move to the next depth group:
                if ((persistTasks.Count > 0) && (curr.depth != lastDepth))
                {
                    Debug.WriteLine(String.Format("Awaiting depth group {0}...", lastDepth));
                    // Wait for the last depth group to finish persisting:
                    await Task.WhenAll(persistTasks);

                    // Start a new depth group:
                    persistTasks = new List<Task<Errorable<TreeNode>>>();
                }

                // Don't re-persist the same TreeID (this is a legit case - the same TreeID may be seen in different nodes of the tree):
                if (isPersisting.Contains(curr.id))
                {
                    Debug.WriteLine(String.Format("Already persisting {0}", curr.id.ToString(firstLength: 7)));

                    // Keep track of the last depth level:
                    lastDepth = curr.depth;
                    continue;
                }

                // Get the TreeNode and persist it:
                TreeNode node = trees[curr.id];
                isPersisting.Add(curr.id);

                // Fire up a task to persist this tree node:
                var tsk = db.ExecuteNonQueryAsync(new PersistTree(node));

                // Add the task to the depth group to await:
                Debug.WriteLine(String.Format("Adding to depth group {0}...", curr.depth));
                persistTasks.Add(tsk);

                // Keep track of the last depth level:
                lastDepth = curr.depth;
            }

            Debug.Assert(lastDepth == 0);
            if (persistTasks.Count > 0)
            {
                // Await the last group (the root node):
                Debug.WriteLine(String.Format("Awaiting depth group {0}...", lastDepth));
                await Task.WhenAll(persistTasks);
            }

            // Return the root TreeNode:
            return trees[rootid];
        }
Exemplo n.º 6
0
 private void GetStackToVirtualParent(System.Collections.Stack cStack, IParentChildList cNode)
 {
     cStack.Push(cNode);
     if (cNode.ParentNode() != null) GetStackToVirtualParent(cStack, cNode.ParentNode()); // Recursive call
     // Got to the root
 }
Exemplo n.º 7
0
 internal void GetStackToVirtualParent(System.Collections.Stack cStack)
 {
     cStack.Push(this);
     if (this.ParentNode() != null) GetStackToVirtualParent(cStack, this.ParentNode());
     // Got to the root
 }
Exemplo n.º 8
0
 public void PushCopiesEvenWithNullParams()
 {
     var xs = new[] { 1234, 456, 789 };
     Assert.AreNotSame(xs, xs.Push(null));
 }
        private IEnumerable<TagName> getAllTagNames()
        {
            // Create a new stack of an anonymous type:
            var s = new { di = system.getTagsDirectory(), parts = new string[0] }.StackOf();
            while (s.Count > 0)
            {
                var curr = s.Pop();

                // Yield all files as TagNames in this directory:
                FileInfo[] files = curr.di.GetFiles();
                for (int i = 0; i < files.Length; ++i)
                    yield return (TagName)curr.parts.AppendAsArray(files[i].Name);

                // Push all the subdirectories to the stack:
                DirectoryInfo[] dirs = curr.di.GetDirectories();
                for (int i = 0; i < dirs.Length; ++i)
                    s.Push(new { di = dirs[i], parts = curr.parts.AppendAsArray(dirs[i].Name) });
            }
        }