Pop() public method

public Pop ( ) : Object
return Object
Example #1
1
        private static void Main()
        {
            string inputSentence = SampleSentence;
            string splitPattern = @"(\s+|\s*\,\s*|\s*\-\s*|\s*\!|\s*\.)";
            string[] elements = Regex.Split(inputSentence, splitPattern);

            Stack words = new Stack();
            Queue separators = new Queue();
            StringBuilder result = new StringBuilder();

            foreach (var element in elements)
            {
                if (Regex.IsMatch(element, splitPattern))
                {
                    separators.Enqueue(element);
                }
                else if (Regex.IsMatch(element, @"\S"))
                {
                    words.Push(element);
                }
            }

            while (words.Count > 0)
            {
                result.Append(words.Pop());
                result.Append(separators.Dequeue());
            }

            Console.WriteLine(result);
        }
Example #2
0
 //[int, int] ==> [int]
 public Stack IntMult(Stack s)
 {
     var x = (int) s.Pop();
     var y = (int) s.Pop();
     s.Push(x*y);
     return s;
 }
        internal static TreeViewItemViewModel Expand(TreeViewItemModelItemViewModel rootTreeViewItem, ModelItem modelItemToExpandTo)
        {
            Fx.Assert(modelItemToExpandTo != null && rootTreeViewItem != null, "rootTreeViewItem and modelItemToExpand should not have null value");

            // ModelItems with HidePropertyInOutlineViewAttribute are invisible in the designerTree.
            if (ExtensibilityAccessor.GetAttribute<HidePropertyInOutlineViewAttribute>(modelItemToExpandTo) != null)
            {
                return null;
            }

            Stack pathStack = new Stack();

            TreeViewItemViewModel itemToBeSelected = null;

            if (GetExpandingPath(modelItemToExpandTo, pathStack, new HashSet<ModelItem>()))
            {
                // If the root of modelItemToExpandTo differs from the root of the designerTree, it means modelItemToExpandTo doesn't belong to the designerTree.
                if (pathStack.Pop() != rootTreeViewItem.VisualValue)
                {
                    return null;
                }

                object item = null;
                TreeViewItemViewModel treeViewItem = rootTreeViewItem;
                TreeViewItemViewModel tempTreeViewItem = rootTreeViewItem;

                // Using the path to the root, expand the corresponding tree node. Ignore the items which is not visible on the designerTree.
                while (pathStack.Count > 0)
                {
                    if (tempTreeViewItem != null)
                    {
                        treeViewItem = tempTreeViewItem;
                        treeViewItem.IsExpanded = true;
                    }

                    item = pathStack.Pop();
                    tempTreeViewItem = (from child in treeViewItem.Children
                                        where (child is TreeViewItemModelItemViewModel && ((TreeViewItemModelItemViewModel)child).VisualValue == item as ModelItem)
                                        || (child is TreeViewItemModelPropertyViewModel && ((TreeViewItemModelPropertyViewModel)child).VisualValue == item as ModelProperty)
                                        || (child is TreeViewItemKeyValuePairModelItemViewModel && ((TreeViewItemKeyValuePairModelItemViewModel)child).VisualValue.Value == item as ModelItem)
                                        select child).FirstOrDefault();

                    // For TreeViewItemKeyValuePairModelItemViewModel, its path to the children is very complicated.
                    // Take Switch as example: Switch(ModelItem) -> Cases(ModelProperty) -> KeyDictionaryCollection(ModelItem) -> ItemsCollection(ModelProperty) -> ModelItemKeyValuePair<T, Activity>(ModelItem) -> Value(ModelProperty) -> Children
                    // All the path nodes except Switch and Children are invisible and can be ignored, the child node in the path is used twice to search for TreeViewItemKeyValuePairModelItemViewModel and its children in designerTree.
                    if (tempTreeViewItem is TreeViewItemKeyValuePairModelItemViewModel)
                    {
                        // For further searching
                        pathStack.Push(item);
                    }

                    if (pathStack.Count == 0)
                    {
                        itemToBeSelected = tempTreeViewItem;
                    }
                }
            }

            return itemToBeSelected;
        }
Example #4
0
 ///
 /// Tạo một cây nhị phân 3 node với node gốc là toán tử, 2 node lá là toán hạng
 ///
 /// <param name="node" />
 /// <param name="opStack" />
 /// <param name="nodeStack" />
 private  void CreateSubTree(Stack<BinaryTreeNode> opStack, Stack<BinaryTreeNode> nodeStack)
 {
     BinaryTreeNode node = opStack.Pop();
     node.RightChild = nodeStack.Pop();
     node.LeftChild = nodeStack.Pop();
     nodeStack.Push(node);
 }
Example #5
0
 /// <summary>
 /// Быстрая сортировка - нерекурсивная реализация со вспомогательной сортировкой вставками
 /// </summary>
 public static void QuickSortStackedInsertion(List<Item> data, int l, int r)
 {
     Stack<int> s = new Stack<int>();
     s.Push(r);
     s.Push(l);
     int M = 9;
     while (s.Count != 0)
     {
         l = s.Pop();
         r = s.Pop();
         if (r - 1 < M)
         {
             continue;
         }
         int i = Partition(data, l, r);
         if (i - 1 < r - i && r > l)
         {
             s.Push(i - 1);
             s.Push(l);
             s.Push(r);
             s.Push(i + 1);
         }
         else if (r > l)
         {
             s.Push(r);
             s.Push(i + 1);
             s.Push(i - 1);
             s.Push(l);
         }
     }
     Insertion.InsertionSortLv3(data, l, r);
 }
Example #6
0
		/// <summary>
		/// Returns a line composed of the words in the stack that would
		/// fit into the label.	
		/// The line is returned when the next word wouldn't fit or the last poped
		/// word was a newline.
		/// 
		/// The stack is requiered to have all characters and all whitespaces in
		/// separate elements. The labels text must be blank.
		/// </summary>
		public static string getLine( Stack<string> words, UILabel targetLabel, bool doLinePadding ){
			string line = "";
			string currWord = "";
			Vector2 labelSize = new Vector2( targetLabel.width, targetLabel.height );
			Vector2 textSize  = new Vector2();
			targetLabel.UpdateNGUIText();
			
			//Add next word to the current line as long as the line would fit in the label
			//and not cause a newline.
			while( words.Count > 0 ){
				currWord = words.Peek();
				textSize = NGUIText.CalculatePrintedSize(line + currWord);
				
				if( textSize.y > labelSize.y ){	
					//Check if the current word is a whitespace. If it is, remove it
					if( currWord.Trim() == string.Empty ){
						words.Pop();
						line.Trim();
					}
					textSize = NGUIText.CalculatePrintedSize(line + " ");
					while( textSize.y < labelSize.y && doLinePadding ){
						line += " ";
						textSize = NGUIText.CalculatePrintedSize(line + " ");
					}
					return line;
				}
				line += words.Pop();
			}
			
			return line;
		}			
Example #7
0
 //[int, int] ==> [int]
 public Stack IntAdd(Stack s)
 {
     var x = (int) s.Pop();
     var y = (int) s.Pop();
     s.Push(x + y);
     return s;
 }
        static void Main(string[] args)
        {
            Stack ast = new Stack();
            ast.Push("Item 1");
            ast.Push("Item 2");
            ast.Push("Item 3");
            ast.Push("Item 4");

            Console.WriteLine("Count:    {0}", ast.Count);
            PrintValues(ast);

            // Peek item but do not remove
            object item = ast.Peek();
            Console.WriteLine("Peek: {0}", item);
            PrintValues(ast);

            // Peek and cast but do not remove
            string itemString = ast.Peek() as string;   // fast cast
            Console.WriteLine("Peek: {0}", item);
            PrintValues(ast);

            // Contains
            Boolean contains = ast.Contains("Item 3");
            Console.WriteLine("Contains: {0}", contains);

            // Remove items
            object item4 = ast.Pop();
            object item3 = ast.Pop();
            Console.WriteLine("Pop: {0}  {1}", item4, item3);
            PrintValues(ast);
            Console.WriteLine("Count:    {0}", ast.Count);

            // no TrimToSize method
        }
        public int Calculate(string rpn)
        {
            string[] parts = rpn.Split(' ');
            var stack = new Stack<int>();
            foreach (string part in parts)
            {
                int digit;
                bool isDigit = int.TryParse(part, out digit);
                if (isDigit)
                {
                    stack.Push(digit);
                    continue;
                }

                bool isOperator = Array.IndexOf(operators, part) >= 0;

                if (isOperator)
                {
                    int digit2 = stack.Pop();
                    int digit1 = stack.Pop();
                    int value = InternalCalcul(digit1, digit2, part);
                    stack.Push(value);
                }
            }
            return stack.Pop();
        }
        public void ZnajdzOtoczke(List<Punkt> lista)
        {
            List<Punkt> listaTmp = new List<Punkt>();
            Stack stos = new Stack();

            stos.Push(lista[0]);
            stos.Push(lista[1]);
            stos.Push(lista[2]);

            listaTmp.Add(lista[0]);
            listaTmp.Add(lista[1]);
            listaTmp.Add(lista[2]);

            for (int i = 3; i < lista.Count; i++)
            {
                int j = i;
                while (ObliczDet(listaTmp[stos.Count - 2], listaTmp[stos.Count - 1], lista[i]) < 0)
                {
                    //Console.WriteLine(ObliczDet(lista[j - 2], lista[j - 1], lista[i]));
                    stos.Pop();
                    listaTmp.RemoveRange(stos.Count, 1);
                }
                stos.Push(lista[i]);
                listaTmp.Add(lista[i]);
            }
            int ileWierz = stos.Count;
            for (int i = 0; i < ileWierz; i++)
            {
                wierzcholki.Add((Punkt)stos.Pop());
            }
            wierzcholki.Reverse();
        }
        /// <summary>
        /// Get local fair counter example
        /// </summary>
        /// <param name="newSCC"></param>
        /// <param name="localCallStack"></param>
        /// <param name="isDeadLock"></param>
        public void GetLocalFairCounterExample(Stack<LocalPair> localCallStack, List<ConfigurationBase> cycle, bool isDeadLock)
        {
            localCallStack.Pop();
            int traceLen = localCallStack.Count;
            List<ConfigurationBase> trace = new List<ConfigurationBase>(traceLen);
            while (localCallStack.Count > 0)
            {
                LocalPair tmp = localCallStack.Pop();
                trace.Insert(0, tmp.configuration);

                if (tmp.configuration.Event == Constants.INITIAL_EVENT)
                {
                    break;
                }
            }

            lock (globalCounterExampleLocker)
            {
                if (isGlobalStop)
                {
                    return;
                }

                if (!isDeadLock)
                {
                    finalLoopIndex = trace.Count;
                }
                trace.AddRange(cycle);
                finalTrace = trace;
                isGlobalStop = true;
            }
        }
Example #12
0
        static void Main(string[] args)
        {
            //ArrayList
            ArrayList arrayList = new ArrayList();
            arrayList.Add("First item");
            arrayList.Add(5);
            arrayList.Add('c');

            foreach (var item in arrayList) {
                Console.WriteLine("Element of arrayList: {0}", item);
            }

            //HashTable
            Hashtable hashtable = new Hashtable();
            hashtable.Add(0, "Zero item");
            hashtable[1] = "First item";
            hashtable["2"] = "Second item";
            hashtable[Guid.NewGuid()] = "Third item";

            ICollection keys = hashtable.Keys;
            foreach (var key in keys)
            {
                Console.WriteLine("Key: {0}, Value: {1}", key, hashtable[key]);
            }

            //SortedList
            SortedList sl = new SortedList();

            sl.Add("007", "Ritesh Saikia");
            sl.Add("001", "Zara Ali");
            sl.Add("002", "Abida Rehman");
            sl.Add("003", "Joe Holzner");
            sl.Add("004", "Mausam Benazir Nur");
            sl.Add("006", "M. Amlan");
            sl.Add("005", "M. Arif");

            ICollection slValues = sl.Values;
            foreach (var s in slValues) {
                Console.WriteLine("SortedList value: {0}", s);
            }
             //Queue is FIFO: First in First out
            Queue que = new Queue();
            que.Enqueue("Student_1");
            que.Enqueue(5);
            que.Enqueue("Student_2");
            que.Enqueue("Student_3");

            Console.WriteLine(que.Dequeue().ToString());
            Console.WriteLine(que.Dequeue().ToString());

            // Stack is FILO: First in Last out
            Stack StackPop = new Stack();
            StackPop.Push("Student_1");
            StackPop.Push("Student_2");
            StackPop.Push("Student_3");
            Console.WriteLine(StackPop.Pop().ToString());
            Console.WriteLine(StackPop.Pop().ToString());

            Console.ReadLine();
        }
        static void Main(string[] args)
        {
            int T = int.Parse(Console.ReadLine());
            for (int i = 0; i < T; i++)
            {
                char[] line = Console.ReadLine().ToCharArray();
                Stack<char> ops = new Stack<char>();
                char opFound;
                StringBuilder postFix = new StringBuilder();
                for (int j = 0; j < line.Length; j++)
                {
                    char c =line[j];

                    if (c != '(' && c != ')' && c != '*' && c != '+' && c != '/' && c != '-' && c != '^')
                    {
                        postFix.Append(c);
                    }
                    else if(c=='(')
                    {
                        ops.Push(c);
                    }
                    else if(c==')')
                    {
                        opFound = ops.Pop();
                        while (opFound != '(')
                        {
                            postFix.Append(opFound);
                            opFound = ops.Pop();
                        }
                    }
                    else
                    {
                        if((ops.Count!=0)&& Predecessor(ops.Peek(),c)){
                            opFound = ops.Pop();
                            while(Predecessor(opFound,c)){
                                postFix.Append(opFound);
                                if (ops.Count == 0)
                                    break;
                                opFound = ops.Pop();
                            }
                            ops.Push(c);
                        }
                        else
                        {
                            ops.Push(c);
                        }
                    }

                }
                while (ops.Count > 0)
                {
                    opFound = ops.Pop();
                    postFix.Append(opFound);
                }
                Console.WriteLine(postFix.ToString());

            }
            Console.ReadLine();
        }
Example #14
0
        private bool function(string token, Stack<CValue> values, int x, int y, List<CellReference> refs)
        {
            switch (token.ToLowerInvariant()) {
                case "$": {// value at coords
                        var ry = (int)values.Pop().NumericValue;
                        var rx = (int)values.Pop().NumericValue;
                        var g = sourceArray[rx, ry] as GridCell;

                        if (g == null) values.Push(new CValue());
                        else values.Push(new CValue(g.Value, true));

                        refs.Add(new CellReference(rx, ry));
                        return true;
                    }
                case "$f": {// function string at coords
                        var ry = (int)values.Pop().NumericValue;
                        var rx = (int)values.Pop().NumericValue;
                        var g = sourceArray[rx, ry] as GridCell;

                        if (g == null) values.Push(new CValue());
                        else values.Push(new CValue(g.Formula));

                        refs.Add(new CellReference(rx, ry));
                        return true;
                    }
                case "$n": {// name at coords
                        var ry = (int)values.Pop().NumericValue;
                        var rx = (int)values.Pop().NumericValue;
                        var g = sourceArray[rx, ry] as GridCell;

                        if (g == null) values.Push(new CValue());
                        else values.Push(new CValue(g.Name));

                        refs.Add(new CellReference(rx, ry));
                        return true;
                    }
                case "floor":
                    values.Push(CValue.Floor(values.Pop()));
                    return true;
                case "ceil":
                    values.Push(CValue.Ceil(values.Pop()));
                    return true;
                case "sqrt":
                    values.Push(new CValue((decimal)Math.Sqrt((double)values.Pop().NumericValue)));
                    return true;
                case "cos":
                    values.Push(new CValue((decimal)Math.Cos((double)values.Pop().NumericValue)));
                    return true;
                case "sin":
                    values.Push(new CValue((decimal)Math.Sin((double)values.Pop().NumericValue)));
                    return true;
                case "sign":
                    values.Push(new CValue(Math.Sign((double)values.Pop().NumericValue)));
                    return true;
            }
            return false;
        }
Example #15
0
 //[XmlBuilder, AttrBuilder] ==> [XmlBuilder]    // add a finished XmlAttribute to the XmlBuilder
 public Stack XmlAttrVal(Stack stack)
 {
     var val = (string) stack.Pop();
     var ab = (AttrBuilder)stack.Pop();
     ab.SetAttrValue(val);
     var xeb = (XmlBuilder) stack.Pop();
     xeb.AddAttr(ab.Complete());
     stack.Push(xeb);
     return stack;
 }
Example #16
0
		/// <summary>
		/// Encontra cores de fundo em um bitmap
		/// </summary>
		/// <param name="origem">Imagem original</param>
		/// <returns>Dicionário de cores do fundo</returns>
		private Dictionary<Color, Color> EncontrarCoresFundo(Bitmap origem)
		{
			Dictionary<Color, Color> cores = new Dictionary<Color, Color>();	// Cores do fundo
			Stack	  pilha = new Stack();		                // Pilha para flood-fill
			bool [,]  marcado;					                // Pontos marcados no flood-fill

			marcado = new bool[origem.Width, origem.Height];

			/* A cor de fundo é encontrada realizando um flood-fill
				 * nas bordas da imagem. As cores encontradas cujo brilho
				 * se difere de um determinado limiar são consideradas como
				 * cores de fundos.
				 */
			InserirPilha(pilha, origem.GetPixel(0, 0).GetBrightness(), 0, 0);
			InserirPilha(pilha, origem.GetPixel(origem.Width - 1, 0).GetBrightness(), origem.Width - 1, 0);
			InserirPilha(pilha, origem.GetPixel(origem.Width - 1, origem.Height - 1).GetBrightness(), origem.Width - 1, 0);
			InserirPilha(pilha, origem.GetPixel(0, origem.Height - 1).GetBrightness(), 0, origem.Height - 1);
			
			while (pilha.Count > 0)
			{
				Point ponto;
				float brilhoAnterior;
				Color corAtual;

				ponto = (Point) pilha.Pop();
				brilhoAnterior = (float) pilha.Pop();

				if (ponto.X < 0 || ponto.X >= origem.Width
					|| ponto.Y < 0 || ponto.Y >= origem.Height
					|| marcado[ponto.X, ponto.Y])
					continue;

				corAtual = origem.GetPixel(ponto.X, ponto.Y);

				if (Math.Abs(corAtual.GetBrightness() - brilhoAnterior) < limiarBrilho)
				{
					float brilhoAtual = corAtual.GetBrightness();

					cores[corAtual] = Color.Black;
					marcado[ponto.X, ponto.Y] = true;
						
					InserirPilha(pilha, brilhoAtual, ponto.X - 1, ponto.Y - 1);
					InserirPilha(pilha, brilhoAtual, ponto.X - 1, ponto.Y - 1);
					InserirPilha(pilha, brilhoAtual, ponto.X, ponto.Y - 1);
					InserirPilha(pilha, brilhoAtual, ponto.X + 1, ponto.Y - 1);
					InserirPilha(pilha, brilhoAtual, ponto.X + 1, ponto.Y);
					InserirPilha(pilha, brilhoAtual, ponto.X + 1, ponto.Y + 1);
					InserirPilha(pilha, brilhoAtual, ponto.X, ponto.Y + 1);
					InserirPilha(pilha, brilhoAtual, ponto.X - 1, ponto.Y + 1);
					InserirPilha(pilha, brilhoAtual, ponto.X - 1, ponto.Y);
				}
			}

			return cores;
		}
 private void Print(Node node)
 {
     var seqStack = new Stack<int> ();
     while (node != null) {
         seqStack.Push (node.Value);
         node = node.Prev;
     }
     while (seqStack.Count > 1) {
         Console.Write ("{0} -> ", seqStack.Pop ());
     }
     Console.WriteLine ("{0}", seqStack.Pop ());
 }
        public void TestStackPopFromEmpty()
        {
            Stack<int> stack = new Stack<int>();
            for (int i = 0; i <= 5; i++)
                stack.Push(i);

            for (int i = 5; i >= 0; i--)
            {
                Assert.AreEqual(stack.Pop(), i);
            }

            stack.Pop();
        }
Example #19
0
        static void Main(string[] args)
        {
            Stack test = new Stack();
            int i = 3;
            float f = 3.5F;
            double d = 3.5348347284;
            decimal m = 39438483434;


            test.Push("Une grosse string");
            test.Push(i);
            test.Push(f);
            test.Push(d);
            test.Push(m);

            Console.WriteLine(test);

            foreach (object o in test)
                Console.WriteLine(o);


            // Voir le dernier élément
            Console.WriteLine(test.Peek());

            // Obtenir le dernier élément et le retirer de la pile
            object a = test.Pop();

            // On sait que le type du dernier est un decimal, on le transtype ici en decimal
            Console.WriteLine(a.GetType());
            decimal a2 = (decimal)a;

            Console.WriteLine(a2);

            while ((i = test.Count)>0)
                test.Pop();

            Console.ReadLine();
            Console.WriteLine(test.Count);
            
            // On peut se sauver d'un Stack empty simplement par l'utilisation d'un try / catch
            // Pas nécessairement une bonne pratique,  veut mieux valider par la propriété Count.
            try { 
                test.Pop();
            }
            catch
            {
                Console.WriteLine("On se sauve");
            }


        }
Example #20
0
 public string[] ConvertToPostfixNotation(string input)
 {
     List<string> outputSeparated = new List<string>();
     Stack<string> stack = new Stack<string>();
     foreach (string c in Separate(input))
     {
         if (operators.Contains(c))
         {
             if (stack.Count > 0 && !c.Equals("("))
             {
                 if (c.Equals(")"))
                 {
                     string s = stack.Pop();
                     while (s != "(")
                     {
                         outputSeparated.Add(s);
                         s = stack.Pop();
                     }
                 }
                 else if (GetPriority(c) > GetPriority(stack.Peek()))
                 {
                     stack.Push(c);
                 }
                 else
                 {
                     while (stack.Count > 0 && GetPriority(c) <= GetPriority(stack.Peek()))
                     {
                         outputSeparated.Add(stack.Pop());
                     }
                     stack.Push(c);
                 }
             }
             else
             {
                 stack.Push(c);
             }
         }
         else
         {
             outputSeparated.Add(c);
         }
     }
     if (stack.Count > 0)
     {
         foreach (string c in stack)
         {
             outputSeparated.Add(c);
         }
     }
     return outputSeparated.ToArray();
 }
Example #21
0
 public string PopHistory()
 {
     System.Collections.Stack stSession = (System.Collections.Stack)Session["URLHistoryStack"];
     if (stSession != null)
     {
         if (stSession.Count > 1)
         {
             stSession.Pop();
             URLHISTORY_NODE topnode = (URLHISTORY_NODE)stSession.Pop();
             return(topnode.szURL);
         }
     }
     return(null);
 }
Example #22
0
        public void Enqueue(int x)
        {
            while (s1.Count > 0)
            {
                s2.Push(s1.Pop());
            }

            s1.Push(x);

            while (s2.Count > 0)
            {
                s1.Push(s2.Pop());
            }
        }
Example #23
0
		/*
		 * Evaluate a postfix mathematical expression
		 */
		public static double evaluatePostfixExpression( string sPostfixExpression ) {
			double result = 0;
			Stack<double> operandStack = new Stack<double> ();

			var tokenRegex = new Regex (@"[\d\.]+|[" + Regex.Escape( operators ) + "]", RegexOptions.IgnoreCase); // Match a number or an operand
			MatchCollection tokenMatches = tokenRegex.Matches (sPostfixExpression);

			foreach (Match tokenMatch in tokenMatches) {
				string token = tokenMatch.Groups[0].Value;
				if (isNumeric (token)) {
					operandStack.Push (Double.Parse (token));
				} else if (operandStack.Count > 1) { // If its not a number then it must be an operator and if the stack count is less than 2 then something must be wrong with the expression

					// The first number popped from the stack will be the second operator because Stacks are LIFO
					var b = operandStack.Pop ();
					var a = operandStack.Pop ();

					switch (token) {
					case "^":
						result = Math.Pow (a, b);
						break;
					case "*":
					case "x":
						result = a * b;
						break;
					case "/":
						result = a / b;
						break;
					case "%":
						result = a % b;
						break;
					case "+":
						result = a + b;
						break;
					case "-":
						result = a - b;
						break;
					}

					operandStack.Push (result);
				} else {
					// We've got ourselves an invalid expression that caused our stack count to be off
					return 0;
				}
					
			}

			return operandStack.Pop ();
		}
    static void Main(string[] args)
    {
        bool   correct;
        string expression;

        while (!string.IsNullOrEmpty(expression = Console.ReadLine()))
        {
            System.Collections.Stack stack = new System.Collections.Stack();

            correct = true;

            foreach (char c in expression)
            {
                if (c == '(')
                {
                    stack.Push(c);
                }
                else if (c == ')')
                {
                    if (stack.Count == 0)
                    {
                        correct = false;
                    }
                    else
                    {
                        stack.Pop();
                    }
                }
            }

            Console.WriteLine((correct && stack.Count == 0) ? "correct" : "incorrect");
        }
    }
Example #25
0
        {           // with using stack
            // for ")" - error
            public bool IsValid(string s)
            {
                if (string.IsNullOrEmpty(s))
                {
                    return(true);
                }
                System.Collections.Stack closesbr = new System.Collections.Stack();
                for (int index = 0; index < s.Length; index++)
                {
                    switch (s[index])
                    {
                    case '(': closesbr.Push(')'); break;

                    case '{': closesbr.Push('}'); break;

                    case '[': closesbr.Push(']'); break;

                    default: {
                        if ((closesbr.Count == 0) ||
                            (s[index] != (char)closesbr.Pop()))
                        {
                            return(false);
                        }
                        break;
                    }
                    }
                }
                return(closesbr.Count == 0);
            }
Example #26
0
    static void Main(string[] args)
    {
        short diamonds;
        int   N = Int32.Parse(Console.ReadLine());

        System.Collections.Stack stack = new System.Collections.Stack();

        for (int i = 0; i < N; i++)
        {
            diamonds = 0;

            foreach (char c in Console.ReadLine())
            {
                if (c == '<')
                {
                    stack.Push(c);
                }
                else if (c == '>' && stack.Count > 0)
                {
                    stack.Pop();
                    diamonds++;
                }
            }

            stack.Clear();

            Console.WriteLine(diamonds);
        }
    }
Example #27
0
        static void Main(string[] args)
        {
            string frase; //string que contendra la frase digitada por el usuario
            Stack mipila = new Stack(); //Pila que contendra la frase por partes
            int contadorPalabrasIguales = 0; //contador que contara la cantidad de palabras iguales
            string valor;

            Console.WriteLine("Digite una frase: "); //Le indico que necesito que digite una frase
            frase = Console.ReadLine(); //Guardo la frase en la variable "frase"

            for (int i = 0; i < frase.Length; i++) //para i = 0 hasta que i sea menor al tamaño de la frase
            {
                mipila.Push(frase.Substring(i,1)); //Enviar a la pila una subcadena de la frase
            }
            for (int i = 0; i < frase.Length; i++)
            {
                valor = mipila.Pop().ToString();
                if (valor == frase.Substring(i,1))
                {
                    contadorPalabrasIguales++;
                }
            }
            if (contadorPalabrasIguales == frase.Length)
            {
                Console.WriteLine("La frase es palindromo");
            }
            else
            {
                Console.WriteLine("La frase no es palindromo");
            }
            Console.WriteLine("Presione una tecla para salir...");
            Console.ReadKey();
        }
Example #28
0
        public List<DBVHNode> BoundsQuery(Bounds bounds)
        {
            List<DBVHNode> results = new List<DBVHNode>();

            if (nodes.Count > 0){

            Stack<DBVHNode> stack = new Stack<DBVHNode>();
            stack.Push(nodes[0]);
            while(stack.Count > 0)
            {

                DBVHNode node = stack.Pop();

                if (node.content != null){ //leaf node

                    if (bounds.Intersects(node.content.bounds))
                        results.Add(node);

                }else{

                    if (NodeExists(node.Left) && bounds.Intersects(nodes[node.Left].bounds))
                        stack.Push(nodes[node.Left]);

                    if (NodeExists(node.Right) && bounds.Intersects(nodes[node.Right].bounds))
                        stack.Push(nodes[node.Right]);

                }

            }
            }

            return results;
        }
        public Dictionary<HClusterNode,System.Drawing.Color> MarkNodes(List<string> toMark,System.Drawing.Color color)
        {
            Dictionary<HClusterNode, System.Drawing.Color> returnList = new Dictionary<HClusterNode, System.Drawing.Color>();
            Stack<HClusterNode> st = new Stack<HClusterNode>();
            HClusterNode current = null;

            st.Push(this);

            while (st.Count != 0)
            {
                current = st.Pop();
                if (current.joined == null || current.joined.Count == 0)
                {
                    foreach(var item in toMark)
                        if(current.setStruct.Contains(item))
                        {
                            returnList.Add(current,color);
                            break;
                        }
                }
                else
                    if (current.joined != null)
                        foreach (var item in current.joined)
                            st.Push(item);

            }
            return returnList;
        }
		internal static String Format(Exception exception, IFormatProvider formatProvider)
		{
			if (exception == null)
				return null;

			// push all inner exceptions onto stack
			var exceptionStack = new Stack<Exception>();
			var currentException = exception;
			while (currentException != null)
			{
				exceptionStack.Push(currentException);
				currentException = currentException.InnerException;
			}

			// go through inner exceptions in reverse order
			var sb = new StringBuilder();
			for (Int32 i = 1; exceptionStack.Count > 0; i++)
			{
				currentException = exceptionStack.Pop();
				FormatSingleException(formatProvider, sb, currentException, i);
			}

			// that's it; return result
			return sb.ToString();
		}
Example #31
0
        private void stackButton_Click(object sender, EventArgs e)
        {
            Stack pilha = new Stack();

            //Adicionando itens
            pilha.Push("banana");
            pilha.Push("laranja");
            pilha.Push("uva");

            //Exibindo os itens da coleção
            foreach (string elemento in pilha)
            {
                listBox1.Items.Add(elemento);
            }
            listBox1.Items.Add("--------------");

            //Exibindo o item do topo da pilha
            listBox1.Items.Add("topo da pilha");
            listBox1.Items.Add(pilha.Peek());
            listBox1.Items.Add("--------------");

            //Retirando um elemento da pilha (do topo)
            pilha.Pop();

            //Exibindo o item do topo da pilha
            listBox1.Items.Add("topo da pilha");
            listBox1.Items.Add(pilha.Peek());

        }
        public IList<IList<int>> LevelOrderBottom(TreeNode root)
        {
            IList<IList<int>> result = new List<IList<int>>();
            if (root == null)
                return result;

            Stack<IList<int>> stack = new Stack<IList<int>>();
            Queue<TreeNode> queue = new Queue<TreeNode>();
            queue.Enqueue(root);
            while (queue.Count > 0)
            {
                IList<int> items = new List<int>();
                int num = queue.Count;
                for (int i = 0; i < num; i++)
                {
                    TreeNode node = queue.Dequeue();
                    items.Add(node.val);

                    if (node.left != null)
                        queue.Enqueue(node.left);
                    if (node.right != null)
                        queue.Enqueue(node.right);
                }
                stack.Push(items);
            }

            while (stack.Count > 0)
                result.Add(stack.Pop());

            return result;
        }
        /// <summary>
        /// returns true if path exists from startVertex to endVertex
        /// </summary>
        private bool depthFirstSearch(object startVertex, object endVertex)
        {
            var stack = new Stack();
            var vertextQueue = new Queue();
            bool found = false;

            graph.clearMarks();
            stack.Push(startVertex);
            do
            {
                object vertex = stack.Pop();

                if (vertex == endVertex) // general case when path is found
                    found = true;
                else
                {
                    if (!graph.isMarked(vertex)) // if not marked
                    {
                        graph.markVertex(vertex); // then mark that vertex
                        vertextQueue = graph.getToVertices(vertex); //get all adjecent vertexes

                        while (vertextQueue.Count > 0) // then for each of those adjecent vertexes
                        {
                            object item = vertextQueue.Dequeue();

                            if (!graph.isMarked(item))
                                stack.Push(item);
                        }
                    }
                }
            } while (stack.Count > 0 && !found);

            return found;
        }
Example #34
0
        public static mysToken Evaluate(
			mysSymbol symbol,
			mysToken value,
			Stack<mysSymbolSpace> spaceStack
		)
        {
            // NOTICE THIS
            // since each function has it's own internal space
            // before grabbing our reference to the space in which
            // we want to define our symbol, we need to pop the
            // internal off, or we're going to be defining the symbol
            // in our internal space, i.e. it will scope out as soon as
            // we're done. So we pop the internal off, grab our reference
            // to the space outside of that, then push the internal back on.
            mysSymbolSpace top = spaceStack.Pop();
            mysSymbolSpace ss = spaceStack.Peek();

            if ( value.Type == typeof(mysFunction) ) {
                defineFunction(
                    symbol,
                    value.Value as mysFunction,
                    spaceStack.Peek()
                );
            } else {
                mysSymbolSpace space = symbol.DefinedIn( spaceStack );
                if ( space != null ) {
                    space.Define( symbol, value );
                } else {
                    ss.Define( symbol, value );
                }
            }

            spaceStack.Push( top );
            return null;
        }
Example #35
0
        /// <summary>
        /// Advances the enumerator to the next element of the AVL tree.
        /// </summary>
        /// <returns>
        /// <b>true</b> if the enumerator was successfully advanced to the
        /// next element; <b>false</b> if the enumerator has passed the end
        /// of the collection.
        /// </returns>
        public bool MoveNext()
        {
            bool result;

            // If the end of the AVL tree has not yet been reached.
            if (index < count)
            {
                // Get the next node.
                IAvlNode currentNode = (IAvlNode)nodeStack.Pop();

                current = currentNode.Data;

                currentNode = currentNode.RightChild;

                while (currentNode != AvlNode.NullNode)
                {
                    nodeStack.Push(currentNode);
                    currentNode = currentNode.LeftChild;
                }

                index++;

                result = true;
            }
            else
            {
                result = false;
            }

            return(result);
        }
Example #36
0
 public static string ReadPassword()
 {
     var passbits = new Stack<string>();
     //keep reading
     for (ConsoleKeyInfo cki = Console.ReadKey(true); cki.Key != ConsoleKey.Enter; cki = Console.ReadKey(true))
     {
         if (cki.Key == ConsoleKey.Backspace)
         {
             //rollback the cursor and write a space so it looks backspaced to the user
             Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
             Console.Write(" ");
             Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
             passbits.Pop();
         }
         else
         {
             Console.Write("*");
             passbits.Push(cki.KeyChar.ToString());
         }
     }
     string[] pass = passbits.ToArray();
     Array.Reverse(pass);
     Console.Write(Environment.NewLine);
     return string.Join(string.Empty, pass);
 }
Example #37
0
 public void PopMenu()
 {
     if (navigationStack.Count != 0)
     {
         HideMenuAtState(NavigationStackPeek());
     }
     if (navigationStack.Count == 1)
     {
         return;
     }
     navigationStack.Pop();
     UIManager.State g = NavigationStackPeek();
     InformUIManager(g);
     ShowMenuAtState(g);
     previousState = currentState;
     currentState  = g;
     //GameManager.Instance.GetComponent<AudioSource>().PlayOneShot(GameManager.Instance.click);
 }
Example #38
0
        public int solution2(int[] A, int[] B)
        {
            // 37%
            // Correctness 50%
            // Performance 25%
            var count = 0;

            System.Collections.Stack list = new System.Collections.Stack();

            for (int i = 0; i < A.Length; i++)
            {
                var current = new fishObj()
                {
                    Size = A[i], Direction = B[i]
                };

                if (list.Count == 0 && current.Direction == 0)
                {
                    count++;
                    continue;
                }

                if (current.Direction == 1)
                {
                    list.Push(current);
                }
                else
                {
                    for (int x = 0; x < list.Count; x++)
                    {
                        var compare = (fishObj)list.Pop();

                        if (compare.Size > current.Size)
                        {
                            list.Push(compare);
                            break;
                        }
                        else if (x == list.Count)
                        {
                            count++; // bug aqui
                        }
                        else
                        {
                            current = compare;
                        }
                    }
                }
            }
            //Console.WriteLine($"{solution2(new int[]{2,6,4,3,1,5}, new int[]{0,1,0,1,0,0})} - 2");
            //0 - esquerda, 1 - direita)
            count = count + list.Count; // ou aqui

            return(count);
        }
Example #39
0
    public override void VisitClassDeclaration(ClassDeclarationSyntax node)
    {
        var typeSymbol = semanticModel.GetDeclaredSymbol(node);

        FAMIX.Type type = type = importer.EnsureType(typeSymbol, typeof(FAMIX.Class));
        node.Modifiers.ToList <SyntaxToken>().ForEach(token => type.Modifiers.Add(token.Text));
        var superType = typeSymbol.BaseType;

        if (superType != null)
        {
            FAMIX.Type baseType = null;
            if (superType.DeclaringSyntaxReferences.Length == 0)
            {
                baseType = importer.EnsureBinaryType(superType);
            }
            else
            {
                baseType = importer.EnsureType(typeSymbol.BaseType, typeof(FAMIX.Class));
            }
            Inheritance inheritance = importer.CreateNewAssociation <Inheritance>(typeof(FAMIX.Inheritance).FullName);
            inheritance.subclass   = type;
            inheritance.superclass = baseType;
            baseType.AddSubInheritance(inheritance);
            type.AddSuperInheritance(inheritance);
        }

        //type.name = node.Identifier.ToString();
        AddSuperInterfaces(typeSymbol, type);
        AddAnnotations(typeSymbol, type);
        AddParameterTypes(typeSymbol, type);
        currentTypeStack.Push(type);
        importer.CreateSourceAnchor(type, node);
        type.isStub = false;
        if (type.container != null)
        {
            type.container.isStub = false;
        }
        base.VisitClassDeclaration(node);
        ComputeFanout(currentTypeStack.Peek() as FAMIX.Type);
        currentTypeStack.Pop();
    }
Example #40
0
        public int solution3(int[] A, int[] B)
        {
            //100%
            // seguindo tutorial
            //nao usar esse

            System.Collections.Stack list = new System.Collections.Stack();
            var count = 0;

            for (int i = 0; i < A.Length; i++)
            {
                int weight = A[i];

                if (B[i] == 1) // direita
                {
                    list.Push(weight);
                }
                else
                {
                    int weightDown = list.Count == 0 ? -1 : (int)list.Pop();

                    while (weightDown != -1 && weightDown < weight)
                    {
                        weightDown = list.Count == 0 ? -1 : (int)list.Pop();
                    }

                    if (weightDown == -1)
                    {
                        count++;
                    }
                    else
                    {
                        list.Push(weightDown);
                    }
                }
            }

            return(count + list.Count);
        }
 static public int Pop(IntPtr l)
 {
     try {
         System.Collections.Stack self = (System.Collections.Stack)checkSelf(l);
         var ret = self.Pop();
         pushValue(l, true);
         pushValue(l, ret);
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
Example #42
0
        override public void ExitRule(string filename, string ruleName)
        {
            if (backtracking > 0)
            {
                return;
            }
            ParseTree ruleNode = (ParseTree)callStack.Peek();

            if (ruleNode.ChildCount == 0)
            {
                ruleNode.AddChild(EpsilonNode());
            }
            callStack.Pop();
        }
Example #43
0
        static void Main(string[] args)
        {
            System.Collections.Stack st = new System.Collections.Stack();
            st.Push(10);
            st.Push(20);
            st.Push(30);
            var top = st.Pop();

            foreach (var c in st)
            {
                Console.WriteLine(c);
            }
            Console.WriteLine(top);
        }
 static int Pop(IntPtr L)
 {
     try
     {
         ToLua.CheckArgsCount(L, 1);
         System.Collections.Stack obj = (System.Collections.Stack)ToLua.CheckObject(L, 1, typeof(System.Collections.Stack));
         object o = obj.Pop();
         ToLua.Push(L, o);
         return(1);
     }
     catch (Exception e)
     {
         return(LuaDLL.toluaL_exception(L, e));
     }
 }
Example #45
0
        /// <summary>
        /// Returns a list of all properties in the class.  Note that it will create
        /// a DOGenerator class for each DataObject entity that it finds as a property and
        /// will call that class to get it's entities.
        /// </summary>
        /// <param name="namePrefix">Prefix to add to the name representing parent entities.</param>
        /// <param name="entities">List of all entities in system.  Used to determine if property is a DataObject entity type</param>
        /// <param name="parentEntities">Stack of all parent entities.  Used to avoid loops.</param>
        /// <returns></returns>
        public static ArrayList GetPropertyNames(ConfigurationElement options, IList entities, EntityElement entity, String prefix, System.Collections.Stack parentEntities)
        {
            ArrayList propertyNames = new ArrayList();

            // avoid loops
            bool matchedParent = false;

            foreach (EntityElement searchEntity in parentEntities)
            {
                if (ReferenceEquals(searchEntity, entity))
                {
                    matchedParent = true;
                    break;
                }
            }

            // Add current entity to parent stack
            parentEntities.Push(entity);

            if (!matchedParent)
            {
                foreach (PropertyElement property in entity.Properties)
                {
                    if (property.Name.IndexOf(".") < 0)
                    {
                        PropertyName propertyName = new PropertyName(prefix, property.Name);
                        propertyNames.Add(propertyName);

                        // Determine if this is a data object and if so append it's members.
                        foreach (EntityElement subEntity in entities)
                        {
                            if (property.Type != null && property.Type.Name.Equals(options.GetDOClassName(subEntity.Name)) || ReferenceEquals(subEntity, property.EntityType))
                            {
                                ArrayList subProperties = GetPropertyNames(options, entities, subEntity, PropertyName.AppendPrefix(prefix, property.Name), parentEntities);
                                foreach (PropertyName subProperty in subProperties)
                                {
                                    propertyNames.Add(subProperty);
                                }
                                break;
                            }
                        } // end of loop through entities
                    }     // end of if on indexOf(".")
                }         // end of loop through fields.
            }             // end of matched parent check

            parentEntities.Pop();
            return(propertyNames);
        } // end of GetPropertyNames
        public static Stack SortStackMethod(Stack input)
        {
            Stack helperStack = new System.Collections.Stack();

            while (input.Count != 0)
            {
                int temp = (int)input.Pop();
                while (helperStack.Count > 0 && (int)helperStack.Peek() > temp)
                {
                    input.Push(helperStack.Pop());
                }

                helperStack.Push(temp);
            }
            return(helperStack);
        }
        public static void PopElement()
        {
            System.Collections.Stack cars = new System.Collections.Stack();
            cars.Push("volkswagen");
            cars.Push("opel ");
            cars.Push("audi");
            cars.Push("BMW");
            cars.Push("nissan");

            var popedCar = cars.Pop();

            foreach (var car in cars)
            {
                Console.WriteLine(car);
            }
        }
Example #48
0
        // A size
        // B direction (0 - esquerda, 1 - direita)
        public int solution(int[] A, int[] B)
        {
            // 37%
            // Correctness 50%
            // Performance 25%
            System.Collections.Stack list = new System.Collections.Stack();

            for (int i = 0; i < A.Length; i++)
            {
                var current = new fishObj()
                {
                    Size = A[i], Direction = B[i]
                };

                if (list.Count == 0)
                {
                    list.Push(current);
                    continue;
                }

                var last = (fishObj)list.Pop();

                if (last.Direction == 0 && current.Direction == 1 || last.Direction == current.Direction)
                {
                    list.Push(last);
                    list.Push(current);
                }
                else
                {
                    if (last.Size > current.Size)
                    {
                        list.Push(last);
                    }
                    else
                    {
                        list.Push(current);
                    }
                }
            }

            return(list.Count);
        }
Example #49
0
            public override void execute3(RunTimeValueBase thisObj,FunctionDefine functionDefine,SLOT returnSlot,SourceToken token,StackFrame stackframe,out bool success)
            {
                System.Collections.Stack stack =
                    (System.Collections.Stack)((LinkObj <object>)((ASBinCode.rtData.rtObjectBase)thisObj).value).value;

                try
                {
                    object obj = stack.Pop();

                    stackframe.player.linktypemapper.storeLinkObject_ToSlot(obj,functionDefine.signature.returnType,returnSlot,bin,stackframe.player);
                    //returnSlot.setValue((int)array.GetValue(index));
                    success = true;
                }
                catch (RuntimeLinkTypeMapper.TypeLinkClassException tlc)
                {
                    success = false;
                    stackframe.throwAneException(token,tlc.Message);
                }
                catch (KeyNotFoundException)
                {
                    success = false;
                    stackframe.throwAneException(token,"Stack内的值没有链接到脚本");
                }
                catch (ArgumentException a)
                {
                    success = false;
                    stackframe.throwAneException(token,a.Message);
                }
                catch (IndexOutOfRangeException i)
                {
                    success = false;
                    stackframe.throwAneException(token,i.Message);
                }
                catch (InvalidOperationException io)
                {
                    success = false;
                    stackframe.throwAneException(token,io.Message);
                }
            }
Example #50
0
        public void Main()
        {
            myStack.Push("Ashin");
            myStack.Push(true);
            myStack.Push(null);
            myStack.Push(4);
            myStack.Push(62.2);
            foreach (var item in myStack)
            {
                Console.WriteLine(Convert.ToString(item));
            }
            myStack.Pop();
            foreach (var item in myStack)
            {
                Console.WriteLine(Convert.ToString(item));
            }

            Console.WriteLine(myStack.Peek());
            foreach (var item in myStack)
            {
                Console.WriteLine(Convert.ToString(item));
            }
        }
Example #51
0
 /// <summary>  remove the current template name from stack
 /// </summary>
 public virtual void  PopCurrentTemplateName()
 {
     templateNameStack.Pop();
     return;
 }
Example #52
0
        /// <summary>
        /// Get Suffix expressions . eg:1+2*3 --> 123*+
        /// </summary>
        /// <param name="MathExpressions"></param>
        /// <returns></returns>
        public List <string> Parse(string MathExpressions)
        {
            int    i, j = 0;
            string temp, tempSec;
            Stack  myStack = new System.Collections.Stack();
            //return value
            List <string> listResult = new List <string>();

            List <string> strListA = StringSpit(MathExpressions);

            //temp string
            string[] strB = new string[strListA.Count];

            foreach (string strch in strListA)
            {
                temp = strch;
                //if is digit input it to strB[]
                if (IsOperand(temp))
                {
                    strB[j++] = temp;
                }
                else
                {
                    if (temp == "(")
                    {
                        myStack.Push(temp);
                    }
                    else if (temp == ")")
                    {
                        while (!IsEmpty(myStack)) //Stack pop until ')'
                        {
                            temp = (string)myStack.Pop();
                            if (temp == "(")
                            {
                                break;
                            }
                            else
                            {
                                strB[j++] = temp;
                            }
                        }
                    }
                    else
                    {
                        if (!IsEmpty(myStack))
                        {
                            do
                            {
                                tempSec = (string)myStack.Pop();
                                if (Priority(temp) > Priority(tempSec))
                                {
                                    myStack.Push(tempSec);
                                    myStack.Push(temp);
                                    break;
                                }
                                else
                                {
                                    strB[j++] = tempSec;
                                    if (IsEmpty(myStack))
                                    {
                                        myStack.Push(temp);
                                        break;
                                    }
                                }
                            } while (!IsEmpty(myStack));
                        }
                        else
                        {
                            myStack.Push(temp);
                        }
                    }
                }
            }
            while (!IsEmpty(myStack))
            {
                strB[j++] = (string)myStack.Pop();
            }
            for (i = 0; i < strB.Length; i++)
            {
                if (!string.IsNullOrEmpty(strB[i]))
                {
                    listResult.Add(strB[i]);
                }
            }
            return(listResult);
        }
        public static IEnumerable <IDomainTrust> Get_DomainTrustMapping(Args_Get_DomainTrustMapping args = null)
        {
            if (args == null)
            {
                args = new Args_Get_DomainTrustMapping();
            }

            // keep track of domains seen so we don't hit infinite recursion
            var SeenDomains = new Dictionary <string, string>();

            // our domain status tracker
            var Domains = new System.Collections.Stack();

            var DomainTrustArguments = new Args_Get_DomainTrust
            {
                API             = args.API,
                NET             = args.NET,
                LDAPFilter      = args.LDAPFilter,
                Properties      = args.Properties,
                SearchBase      = args.SearchBase,
                Server          = args.Server,
                SearchScope     = args.SearchScope,
                ResultPageSize  = args.ResultPageSize,
                ServerTimeLimit = args.ServerTimeLimit,
                Tombstone       = args.Tombstone,
                Credential      = args.Credential
            };

            // get the current domain and push it onto the stack
            string CurrentDomain = null;

            if (args.Credential != null)
            {
                CurrentDomain = GetDomain.Get_Domain(new Args_Get_Domain {
                    Credential = args.Credential
                }).Name;
            }
            else
            {
                CurrentDomain = GetDomain.Get_Domain().Name;
            }
            Domains.Push(CurrentDomain);

            var DomainTrustMappings = new List <IDomainTrust>();

            while (Domains.Count != 0)
            {
                string Domain = Domains.Pop() as string;

                // if we haven't seen this domain before
                if (Domain != null && Domain.Trim() != @"" && !SeenDomains.ContainsKey(Domain))
                {
                    Logger.Write_Verbose($@"[Get-DomainTrustMapping] Enumerating trusts for domain: '{Domain}'");

                    // mark it as seen in our list
                    SeenDomains.Add(Domain, "");

                    try
                    {
                        // get all the trusts for this domain
                        DomainTrustArguments.Domain = Domain;
                        var Trusts = GetDomainTrust.Get_DomainTrust(DomainTrustArguments);

                        // get any forest trusts, if they exist
                        if (args.NET)
                        {
                            var ForestTrustArguments = new Args_Get_Forest
                            {
                                Forest     = args.Forest,
                                Credential = args.Credential
                            };
                            Trusts.Union(GetForestTrust.Get_ForestTrust(ForestTrustArguments));
                        }

                        if (Trusts != null)
                        {
                            // enumerate each trust found
                            foreach (var Trust in Trusts)
                            {
                                if (Trust.SourceName.IsNotNullOrEmpty() && Trust.TargetName.IsNotNullOrEmpty())
                                {
                                    // make sure we process the target
                                    Domains.Push(Trust.TargetName);
                                    DomainTrustMappings.Add(Trust);
                                }
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Logger.Write_Verbose($@"[Get-DomainTrustMapping] Error: {e}");
                    }
                }
            }
            return(DomainTrustMappings);
        }
Example #54
0
 public static void pop(ref System.Collections.Stack st)
 {
     st.Pop();
 }
Example #55
0
        public static string[] braces(string[] values)
        {
            string[] returnstrarr = new string[values.Length];
            for (int i = 0; i < values.Length; i++)
            {
                string str                   = values[i];
                bool   isMatched             = true;
                System.Collections.Stack obj = new System.Collections.Stack();
                char popChar;

                foreach (char c in str)
                {   //adjust sums
                    if (c == '{' || c == '[' || c == '(')
                    {
                        obj.Push(c);
                    }
                    if (obj.Count == 0)
                    {
                        isMatched = false;
                        continue;
                    }
                    if (c == '}')
                    {
                        popChar = Convert.ToChar(obj.Pop());
                        if (popChar == '{')
                        {
                            continue;
                        }
                        else
                        {
                            isMatched = false;
                            continue;
                        }
                    }
                    if (c == ']')
                    {
                        popChar = Convert.ToChar(obj.Pop());
                        if (popChar == '[')
                        {
                            continue;
                        }
                        else
                        {
                            isMatched = false;
                            continue;
                        }
                    }
                    if (c == ')')
                    {
                        popChar = Convert.ToChar(obj.Pop());
                        if (popChar == '(')
                        {
                            continue;
                        }
                        else
                        {
                            isMatched = false;
                            continue;
                        }
                    }
                }

                if (obj.Count > 0)
                {
                    isMatched = false;
                }

                returnstrarr[i] = string.Format("index {0} is balanced {1}", i, isMatched ? "YES" : "NO");
            }
            return(returnstrarr);
        }
Example #56
0
 void ProcOpRefresh(string selection)
 {
     //SySal.OperaDb.OperaDbConnection Conn = null;
     System.Windows.Forms.Cursor oldcursor = Cursor;
     Cursor = Cursors.WaitCursor;
     try
     {
         if (Conn == null)
         {
             Conn = new SySal.OperaDb.OperaDbConnection(Credentials.DBServer, Credentials.DBUserName, Credentials.DBPassword);
             Conn.Open();
         }
         ProcOpTree.BeginUpdate();
         ProcOpTree.Nodes.Clear();
         System.Data.DataSet ds = new System.Data.DataSet();
         SySal.OperaDb.OperaDbDataAdapter da = new SySal.OperaDb.OperaDbDataAdapter("SELECT /*+INDEX_RANGE (TB_PROC_OPERATIONS IX_PROC_OPERATIONS_PARENT) */ TB_PROC_OPERATIONS.ID, TB_PROGRAMSETTINGS.DESCRIPTION, TB_PROGRAMSETTINGS.EXECUTABLE, TB_PROC_OPERATIONS.STARTTIME, TB_PROC_OPERATIONS.SUCCESS, TB_PROC_OPERATIONS.ID_EVENTBRICK, TB_PROC_OPERATIONS.ID_PLATE FROM TB_PROC_OPERATIONS INNER JOIN TB_PROGRAMSETTINGS ON (TB_PROC_OPERATIONS.ID_PROGRAMSETTINGS = TB_PROGRAMSETTINGS.ID) WHERE (TB_PROC_OPERATIONS.ID_PARENT_OPERATION IS NULL " + selection + ") ORDER BY STARTTIME DESC", Conn, null);
         da.Fill(ds);
         System.Collections.Stack nodestack = new System.Collections.Stack();
         foreach (System.Data.DataRow dr in ds.Tables[0].Rows)
         {
             int image = 2;
             if (dr[4].ToString() == "N")
             {
                 image = 1;
             }
             else if (dr[4].ToString() == "Y")
             {
                 image = 0;
             }
             string addinfo = " ";
             if (dr[5] != System.DBNull.Value)
             {
                 addinfo += "B#" + dr[5].ToString() + " ";
             }
             if (dr[6] != System.DBNull.Value)
             {
                 addinfo += "P#" + dr[6].ToString() + " ";
             }
             TreeNode tn = new TreeNode("#" + dr[0].ToString() + ": " + dr[1].ToString() + addinfo + "(" + dr[2].ToString() + ") - (" + Convert.ToDateTime(dr[3]).ToString("dd/MM/yyyy HH:mm:ss") + ")", image, image);
             tn.Tag = Convert.ToInt64(dr[0]);
             ProcOpTree.Nodes.Add(tn);
             nodestack.Push(tn);
         }
         TreeNode nextnode = null;
         while (nodestack.Count > 0)
         {
             nextnode = (TreeNode)nodestack.Pop();
             ds       = new System.Data.DataSet();
             da       = new SySal.OperaDb.OperaDbDataAdapter("SELECT /*+INDEX(TB_PROC_OPERATIONS IX_PROC_OPERATIONS_PARENT) */ TB_PROC_OPERATIONS.ID FROM TB_PROC_OPERATIONS WHERE (TB_PROC_OPERATIONS.ID_PARENT_OPERATION = " + nextnode.Tag.ToString() + ") ORDER BY STARTTIME DESC", Conn, null);
             da.Fill(ds);
             foreach (System.Data.DataRow dr in ds.Tables[0].Rows)
             {
                 TreeNode tn = new TreeNode("");
                 tn.Tag = Convert.ToInt64(dr[0]);
                 nextnode.Nodes.Add(tn);
                 nodestack.Push(tn);
             }
         }
         ProcOpTree.EndUpdate();
         //Conn.Close();
     }
     catch (Exception x)
     {
         if (Conn != null)
         {
             Conn.Close();
             Conn = null;
         }
         ProcOpTree.EndUpdate();
         MessageBox.Show(x.ToString(), "Error refreshing process operation information");
     }
     Cursor = oldcursor;
 }
Example #57
0
        /// <summary>
        /// Advances the enumerator to the next element in the random access
        /// list.
        /// </summary>
        /// <returns>
        /// <b>true</b> if the enumerator was successfully advanced to the
        /// next element; <b>false</b> if the enumerator has passed the end
        /// of the collection.
        /// </returns>
        public bool MoveNext()
        {
            // Move index to the next position.
            index++;

            // If the index has moved beyond the end of the list, return false.
            if (index >= count)
            {
                return(false);
            }

            RalTreeNode currentNode;

            // Get the node at the top of the stack.
            currentNode = (RalTreeNode)treeStack.Peek();

            // Get the value at the top of the stack.
            current = currentNode.Value;

            // If there are still left children to traverse.
            if (currentNode.LeftChild != null)
            {
                // If the left child is not null, the right child should not be
                // null either.
                Debug.Assert(currentNode.RightChild != null);

                // Push left child onto stack.
                treeStack.Push(currentNode.LeftChild);
            }
            // Else the bottom of the tree has been reached.
            else
            {
                // If the left child is null, the right child should be null,
                // too.
                Debug.Assert(currentNode.RightChild == null);

                // Move back up in the tree to the parent node.
                treeStack.Pop();

                RalTreeNode previousNode;

                // Whild the stack is not empty.
                while (treeStack.Count > 0)
                {
                    // Get the previous node.
                    previousNode = (RalTreeNode)treeStack.Peek();

                    // If the bottom of the left tree has been reached.
                    if (currentNode == previousNode.LeftChild)
                    {
                        // Push the right child onto the stack so that the
                        // right tree will now be traversed.
                        treeStack.Push(previousNode.RightChild);

                        // Finished.
                        break;
                    }
                    // Else the bottom of the right tree has been reached.
                    else
                    {
                        // Keep track of the current node.
                        currentNode = previousNode;

                        // Pop the stack to move back up the tree.
                        treeStack.Pop();
                    }
                }

                // If the stack is empty.
                if (treeStack.Count == 0)
                {
                    // Move to the next tree in the list.
                    currentTopNode = currentTopNode.NextNode;

                    // If the end of the list has not yet been reached.
                    if (currentTopNode != null)
                    {
                        // Begin with the next tree.
                        treeStack.Push(currentTopNode.Root);
                    }
                }
            }

            return(true);
        }
Example #58
0
        public bool Read()
        {
            // find the next <element>
            int  intElementSpace   = 0;
            int  intElementNameEnd = 0;
            bool blnElementFound   = false;

            while (!(blnElementFound || mintCurrentPosition >= mstrInput.Length))
            {
                switch (mstrInput.Substring(mintCurrentPosition, 1))
                {
                case "<":                                               // element start (or end)
                    if (mstrInput.Substring(mintCurrentPosition, 2) == "</")
                    {
                        // element end
                        mstrName = mobjStack.Peek().ToString();
                        if (mstrInput.Substring(mintCurrentPosition, mstrName.Length + 3) == "</" + mstrName + ">")
                        {
                            // long-form element close, pop the current stack item
                            mobjStack.Pop();
                        }
                        mintCurrentPosition = mintCurrentPosition + (mstrName.Length + 3);
                    }
                    else
                    {
                        // element start
                        if (mstrInput.Substring(mintCurrentPosition, 2) == "<?")
                        {
                            // xml or other declaration, skip
                            intElementNameEnd   = mstrInput.Substring(mintCurrentPosition).IndexOf(">");
                            mintCurrentPosition = mintCurrentPosition + intElementNameEnd;
                        }
                        else
                        {
                            intElementNameEnd = mstrInput.Substring(mintCurrentPosition).IndexOf(">");
                            intElementSpace   = mstrInput.Substring(mintCurrentPosition).IndexOf(" ");
                            if (intElementSpace > 0 && intElementSpace < intElementNameEnd)
                            {
                                mstrName            = mstrInput.Substring(mintCurrentPosition + 1, intElementSpace - 1);
                                mintCurrentPosition = mintCurrentPosition + intElementSpace + 1;
                            }
                            else
                            {
                                mstrName            = mstrInput.Substring(mintCurrentPosition + 1, intElementNameEnd - 1);
                                mintCurrentPosition = mintCurrentPosition + intElementNameEnd + 1;
                            }
                            mobjStack.Push(mstrName);
                            blnElementFound = true;
                        }
                    }
                    break;

                case "/":                                               // short-form element close
                    if (mstrInput.Substring(mintCurrentPosition, 2) == "/>")
                    {
                        //  pop the current stack item
                        mobjStack.Pop();
                        mstrName            = mobjStack.Peek().ToString();
                        mintCurrentPosition = mintCurrentPosition + 2;
                    }
                    else
                    {
                        mintCurrentPosition = mintCurrentPosition + 1;
                    }
                    break;

                default:
                    mintCurrentPosition = mintCurrentPosition + 1;
                    break;
                }
            }
            return(!(mobjStack.Count == 0) & !(mintCurrentPosition >= mstrInput.Length));
        }
 /// <summary>
 /// Remove and return the top element in the stack.
 /// </summary>
 /// <exception cref="InvalidOperationException">Thrown when stack is empty.</exception>
 internal Frame Pop()
 {
     return((Frame)(_frames.Pop()));
 }
Example #60
0
 /// <summary>
 /// Ends the current state, returning to the prior state
 /// </summary>
 public static void EndCurrentState()
 {
     _state.Pop();
 }