Push() 공개 메소드

public Push ( Object obj ) : void
obj Object
리턴 void
        static void Main(string[] args)
        {
            int edad = 66;
            Persona objetoPersona = new Persona("Persona", edad);
            int legajo = 333;
            //Alumno objetoAlumo = new Alumno(objetoPersona, legajo);
            Alumno objetoAlumo = new Alumno(new Persona("alumno",77), legajo);
            DateTime fechaEgreso = DateTime.Now;
            //AlumnoEgresado objetoAlumnoEgresado = new AlumnoEgresado(objetoAlumo, fechaEgreso);
            AlumnoEgresado objetoAlumnoEgresado = new AlumnoEgresado(new Alumno(22,8888," alumnoEgresado"),DateTime.Now);
            Profesor objetoProfesor = new Profesor(new Persona("profesor",55), 999);
            Persona[] conjuntoDePersonas= new Persona[4];
            conjuntoDePersonas[0] = objetoPersona;
            conjuntoDePersonas[1] = objetoAlumo;
            conjuntoDePersonas[2] = objetoAlumnoEgresado;
            conjuntoDePersonas[3] = objetoProfesor;

            foreach (Persona item in conjuntoDePersonas)
            {
                Console.WriteLine(item.ToString());
            }
            //no genericas --- que no tienen genero , proceso inbox
            ArrayList vector = new ArrayList();
            vector.Add(3);
            vector.Add(objetoAlumo);
            vector.Add("alguna palabra");
            int dato=  vector.Capacity;
            int dato2 = vector.Count;

            Stack pilaDeDatos = new Stack();

            pilaDeDatos.Push(1);
            pilaDeDatos.Push(1);
        }
예제 #2
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());

        }
        /// <summary>
        /// Creates recursively the hierarchy for the given item.
        /// Returns the complete hierarchy.
        /// </summary>
        /// <param name="itemHierarchy">The item hierarchy.</param>
        /// <param name="item">The item.</param>
        private static void CreateItemHierarchy(
            Stack itemHierarchy, 
            object item)
        {
            ProjectItem projectItem = item as ProjectItem;

            if (projectItem != null)
            {
                ProjectItem pi = projectItem;
                itemHierarchy.Push(pi);
                CreateItemHierarchy(itemHierarchy, pi.Collection.Parent);
            }
            else
            {
                Project project = item as Project;

                if (project != null)
                {
                    Project p = project;
                    itemHierarchy.Push(p);

                    if (p.ParentProjectItem != null)
                    {
                        //// top nodes dont have solution as parent, but is null
                        CreateItemHierarchy(itemHierarchy, p.ParentProjectItem);
                    }
                }
            }
        }
        private static void F1(string path)
        {
            Stack<string> dir = new Stack<string>(); /// Создаю стэк из строк, при этом не указывая размер
            Console.WriteLine(path + ":" + Directory.GetFiles(path).Length); 
            /// Выводим количество файлов
            /// в главной папке
            if (Directory.Exists(path))
            {
                dir.Push(path); /// Если папка с таким названием есть на компьютере, то добавляем ее в стэк
            }
            else
            {
                Console.WriteLine("Error!No such directory in a computer!!!"); /// Если нет, выводим сообщение об ошибке

            }

            /// Условие, что пока в стэке есть элементы, продолжать действия
            while (dir.Count > 0)
            {
                string[] subDirs = Directory.GetDirectories(dir.Pop()); /// Массив из строк (подпапки)             
                foreach (string s in subDirs) /// Находим количество файлов в папках через foreach
                {
                    Console.WriteLine(s + ": " + Directory.GetFiles(s).Length);
                    dir.Push(s); 
                    /// Закидываем папку в стэк и продолжаем действовать, до тех пор пока 
                    /// while не пробежит все подпапки нашего заданного пути
                }
            }
        }
예제 #5
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();
        }
예제 #6
0
파일: Form1.cs 프로젝트: adsort/mfeditor
        private void button2_Click(object sender, EventArgs e)
        {
            //ʵ����
            Stack myStack = new Stack();
            //ʹ��Push������ջ
            myStack.Push("A");
            myStack.Push("B");
            myStack.Push("C");
            myStack.Push("C");

            //����ջԪ��
            Console.WriteLine("\nmyStack:");
            foreach (string item in myStack)
            {
                Console.WriteLine("|_" + item);
            }

            //ʹ��Pop������ջ
            Console.WriteLine("\nItem pulled from myStack: " + myStack.Pop().ToString());
            Console.WriteLine("\nAfter myStack.Pop(),myStack:");
            foreach (string item in myStack)
            {
                Console.WriteLine("|_" + item);
            }

            //Peek����ֻ����ջ��Ԫ�أ�����ջ��ɾ��
            Console.WriteLine("\nmyStack.Peek() : " + myStack.Peek().ToString());
            Console.WriteLine("\nAfter myStack.Peek(),myStack:");
            foreach (string item in myStack)
            {
                Console.WriteLine("|_" + item);
            }
        }
예제 #7
0
		///<summary>
		/// Determine order, walk the tree and push the nodes onto the stack
		///</summary>
		public RedBlackEnumerator(RedBlack redBlack, RedBlackNode tnode, bool keys, bool ascending) 
        {

            this.stack = new Stack();
            this.keys = keys;
            this.ascending = ascending;
            this.redBlack = redBlack;
			
            // use depth-first traversal to push nodes into stack
            // the lowest node will be at the top of the stack
            if(ascending)
			{   // find the lowest node
                while (tnode != redBlack.sentinelNode)
				{
					stack.Push(tnode);
					tnode = tnode.Left;
				}
			}
			else
			{
                // the highest node will be at top of stack
                while (tnode != redBlack.sentinelNode)
				{
					stack.Push(tnode);
					tnode = tnode.Right;
				}
			}
			
		}
        private static void ValidateDepth(SelectExpandClause selectExpand, int maxDepth)
        {
            // do a DFS to see if there is any node that is too deep.
            Stack<Tuple<int, SelectExpandClause>> nodesToVisit = new Stack<Tuple<int, SelectExpandClause>>();
            nodesToVisit.Push(Tuple.Create(0, selectExpand));
            while (nodesToVisit.Count > 0)
            {
                Tuple<int, SelectExpandClause> tuple = nodesToVisit.Pop();
                int currentDepth = tuple.Item1;
                SelectExpandClause currentNode = tuple.Item2;

                if (currentNode.Expansion != null)
                {
                    IEnumerable<ExpandItem> expandItems = currentNode.Expansion.ExpandItems;
                    if (expandItems.Any() && currentDepth == maxDepth)
                    {
                        throw new ODataException(
                            Error.Format(SRResources.MaxExpandDepthExceeded, maxDepth, "MaxExpansionDepth"));
                    }

                    IEnumerable<SelectExpandClause> children = expandItems.Select(i => i.SelectExpandOption);
                    foreach (SelectExpandClause child in children)
                    {
                        nodesToVisit.Push(Tuple.Create(currentDepth + 1, child));
                    }
                }
            }
        }
예제 #9
0
        static void Main(string[] args)
        {
            // Declare stack collection
            Stack myStack = new Stack();

            // Push elements onto the stack
            myStack.Push("item 1");
            myStack.Push("item 2");
            myStack.Push("item 3");

            // Display number of items
            Console.WriteLine("{0} Items on the stack", myStack.Count);

            // Have a peek at the item on top
            Console.WriteLine("{0}", myStack.Peek());

            // Pop off an element
            myStack.Pop(); // gets top value

            // Have a peek at the item on top
            Console.WriteLine("{0}", myStack.Peek());

            // Clear stack
            myStack.Clear();

            // Display number of items
            Console.WriteLine("{0} Items on the stack", myStack.Count);

            Console.ReadLine();
        }
예제 #10
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);
            }
예제 #11
0
        //Main_7_9_6
        public static void Main_7_9_6()
        {
            Queue myQueue = new Queue();
            //��Queueβ�����Ԫ��
            myQueue.Enqueue("��");
            myQueue.Enqueue("��");
            myQueue.Enqueue("˭");

            //����Queueu��ʼ��Ԫ��
            Console.WriteLine(myQueue.Peek());
            //���ز��Ƴ�Queue��ʼ��Ԫ��
            myQueue.Dequeue();

            //����Queue
            foreach (object o in myQueue)
                Console.WriteLine(o.ToString());

            Stack myStack = new Stack();
            //��Stack��������Ԫ��
            myStack.Push("��");
            myStack.Push("��");
            myStack.Push("˭");

            //����Stack������Ԫ��
            Console.WriteLine(myStack.Peek());
            //���ز��Ƴ�Stack������Ԫ��
            myStack.Pop();

            //����Stack
            foreach (object o in myStack)
                Console.WriteLine(o.ToString());
        }
        /// <summary>
        ///     Creates recursively the hierarchy for the given item.
        ///     Returns the complete hierarchy.
        /// </summary>
        private static void CreateItemHierarchy(Stack itemHierarchy, object item)
        {
            if (item is ProjectItem)
            {
                var pi = (ProjectItem) item;

                itemHierarchy.Push(pi);

                CreateItemHierarchy(itemHierarchy, pi.Collection.Parent);
            }

            else if (item is Project)
            {
                var p = (Project) item;

                itemHierarchy.Push(p);

                if (p.ParentProjectItem != null)
                {
                    //top nodes dont have solution as parent, but is null
                    CreateItemHierarchy(itemHierarchy, p.ParentProjectItem);
                }
            }

            else if (item is Solution)
            {
                //doesn't seem to ever happend...
                var sol = (Solution) item;
            }

            else
            {
                throw new Exception("unknown item");
            }
        }
예제 #13
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;
        }
예제 #14
0
        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();
        }
예제 #15
0
파일: UniPage.cs 프로젝트: NingMoe/UniICWeb
 public void PushHistory()
 {
     //if (!IsPostBack)
     {
         URLHISTORY_NODE          node      = new URLHISTORY_NODE();
         System.Collections.Stack stSession = (System.Collections.Stack)Session["URLHistoryStack"];
         node.szKey = Request.FilePath.ToLower();
         node.szURL = Request.Url.ToString();
         if (stSession != null)
         {
             if (stSession.Count > 0)
             {
                 URLHISTORY_NODE topnode = (URLHISTORY_NODE)stSession.Peek();
                 if (topnode.szKey != node.szKey)
                 {
                     stSession.Push(node);
                 }
             }
             else
             {
                 stSession.Push(node);
             }
         }
         else
         {
             System.Collections.Stack stNow = new System.Collections.Stack();
             stNow.Push(node);
             Session["URLHistoryStack"] = stNow;
         }
     }
 }
        public void PerformAnalysis(BasicBlocks basicBlocks)
        {
            // Create dictionary of referenced blocks
            Dictionary<BasicBlock, int> referenced = new Dictionary<BasicBlock, int>(basicBlocks.Count);

            // Allocate list of ordered Blocks
            blockOrder = new BasicBlock[basicBlocks.Count];
            int orderBlockCnt = 0;

            // Create sorted worklist
            var workList = new Stack<BasicBlock>();

            foreach (var head in basicBlocks.HeadBlocks)
            {
                workList.Push(head);

                while (workList.Count != 0)
                {
                    var block = workList.Pop();

                    if (!referenced.ContainsKey(block))
                    {
                        referenced.Add(block, 0);
                        blockOrder[orderBlockCnt++] = block;

                        foreach (var successor in block.NextBlocks)
                            if (!referenced.ContainsKey(successor))
                                workList.Push(successor);
                    }
                }
            }
        }
예제 #17
0
파일: Game.cs 프로젝트: Lyloox/Abimn
        protected override void Draw(GameTime gameTime)
        {
            if (G.currentGame.Count == 0)
                return;

            Stack<GameType> buffer = new Stack<GameType>();

            GraphicsDevice.Clear(Color.Black);

            while (G.currentGame.Count != 1 && !G.currentGame.Peek().IsFullScreen)
                buffer.Push(G.currentGame.Pop());
            buffer.Push(G.currentGame.Pop());
            G.spriteBatch.Begin();
            while (buffer.Count != 0)
            {
                buffer.Peek().Draw();
                G.currentGame.Push(buffer.Pop());
            }
            Cursor.Draw();

            black.Draw();
            white.Draw();

            G.spriteBatch.End();

            base.Draw(gameTime);
        }
        /**
        * https://github.com/yuzhangcmu/LeetCode/blob/master/tree/TreeDemo.java
        *  后序遍历迭代解法
        *
        *  从左到右的后序 与从右到左的前序的逆序是一样的,所以就简单喽! 哈哈
        *  用另外一个栈进行翻转即可喽
         *  julia's comment:
         *  1. When to push node into stack for output, second stack?
         *     when the first stack pops a node, it is time to push the node into output stack;
         *     otherwise, node is gone.
         *     when the first stack pushs a node into the stack, second stack do nothing.
         *  2. Post order:  left, right, root

        */
        public static void postorderTraversal_Iterative(Node root)
        {
            if (root == null)
            {
                return;
            }

            Stack s = new Stack();
            Stack outS = new Stack();

            s.Push(root);
            while (s.Count > 0)
            {
                Node cur = (Node)s.Pop();
                outS.Push(cur);

                if (cur.left != null)
                {
                    s.Push(cur.left);
                }
                if (cur.right != null)
                {
                    s.Push(cur.right);
                }
            }

            while (outS.Count > 0)
            {
                Node cur = (Node)outS.Pop();
                Console.WriteLine(cur.value + " ");
            }
        }
예제 #19
0
 /// <summary>
 /// Быстрая сортировка - нерекурсивная реализация
 /// </summary>
 public static void QuickSortStacked(List<Item> data, int l, int r)
 {
     Stack<int> s = new Stack<int>();
     s.Push(r);
     s.Push(l);
     while (s.Count != 0)
     {
         l = s.Pop();
         r = s.Pop();
         if (r <= l)
         {
             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);
         }
     }
 }
 private ViewResult InvokeViewShared(string viewType, object model = null, string viewName = null)
 {
     Stack parameters = new Stack();
     if (model == null)
     {
         if (viewName == null)
         {
         }
         else 
         {
             parameters.Push(viewName);
         }
     }
     else
     {
         if (viewName == null)
         {
             parameters.Push(model);
         }
         else
         {
             parameters.Push(viewName);
             parameters.Push(model);
         } 
     }
     return (ViewResult)_controller.GetType().GetMethod(viewType, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic, null, parameters.Cast<Object>().Select(p => p.GetType()).ToArray(), null).Invoke(_controller, parameters.ToArray());
 }
예제 #21
0
		public RedBlackEnumerator(RedBlack redBlack, RedBlackNode tnode, bool keys, bool ascending) 
        {

            this.stack = new Stack();
            this.keys = keys;
            this.ascending = ascending;
            this.redBlack = redBlack;
			
            if(ascending)
			{  
                while (tnode != redBlack.sentinelNode)
				{
					stack.Push(tnode);
					tnode = tnode.Left;
				}
			}
			else
			{
                while (tnode != redBlack.sentinelNode)
				{
					stack.Push(tnode);
					tnode = tnode.Right;
				}
			}
			
		}
예제 #22
0
        /// <summary>
        /// Recursively create a list of directories and files from the given path.
        /// </summary>
        public static List<string> GetFilesRecursive(string path)
        {
            List<string> result = new List<string>();
            Stack<string> stack = new Stack<string>();
            stack.Push(path);

            while (stack.Count > 0)
            {
                string dir = stack.Pop();
                try
                {
                    result.AddRange(Directory.GetFiles(dir, "*.*"));

                    foreach (string d in
                        Directory.GetDirectories(dir).Where(d => !d.EndsWith(Path.DirectorySeparatorChar + ".git")
                        || Properties.Settings.Default.ShowDotGitFolders))
                    {
                        stack.Push(d);
                    }
                }
                catch (Exception ex)
                {
                    App.PrintLogMessage(ex.Message, MessageType.Error);
                }
            }
            return result;
        }
예제 #23
0
        static void Main(string[] args)
        {
            // Stack - A LIFO collection

            Stack<string> stack = new Stack<string>();

            stack.Push("A");  // Push adds to the stack
            stack.Push("B");
            stack.Push("C");
            stack.Push("D");

            Console.WriteLine(stack.Peek()); // D - Peek returns the last added value without removing it

            Console.WriteLine(stack.Pop()); // D - Pop returna the last added value and removes it

            Console.WriteLine(stack.Peek());  // C

            // Queue - A FIFO collection

            Queue<string> queue = new Queue<string>();

            queue.Enqueue("a"); // Enqueue adds to the queue
            queue.Enqueue("b");
            queue.Enqueue("c");
            queue.Enqueue("d");

            Console.WriteLine(queue.Peek()); // a - Peek returns the beginning value without removing it

            Console.WriteLine(queue.Dequeue()); // a - Dequeue returns the beginning value and removes it

            Console.WriteLine(queue.Peek()); // b

            //--
            Console.ReadKey();
        }
        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();
        }
예제 #25
0
        /// <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;
        }
예제 #26
0
 static void Main(string[] args)
 {
     string valor;
     Stack mipila = new Stack();
     //ingreso de elementos a la pila
     mipila.Push("z");
     mipila.Push("ba");
     mipila.Push("nom");
     //imprimir elementos de la pila pueden ser de tipo char, int, string o
     //cualquier otro tipo ya que es un tipo object dependera de lo que el
     //usuario necesite
     foreach (string var in mipila)
     {
         Console.WriteLine(var);
     }
     Console.WriteLine("\n\n");
     //Peek RETORNA el valor que esta al tope de la pila sin eliminarlo
     Console.WriteLine("El tope de la pila es");
     Console.WriteLine(mipila.Peek());
     //retorna el valor del tope eliminandolo
     valor = mipila.Pop().ToString();
     Console.WriteLine("eliminado de la pila: " + valor);
     Console.WriteLine("\n\n");
     //mostrando contenido de la pila
     foreach (string var in mipila)
     {
         Console.WriteLine(var);
     }
     Console.ReadLine();
 }
 public int LongestValidParentheses(string s)
 {
     Stack<int> stack = new Stack<int>();
     char[] arr = s.ToCharArray();
     int result = 0;
     for (int i = 0; i < arr.Length; i++)
     {
         if (arr[i] == '(')
         {
             stack.Push(i);
         }
         else
         {
             if (stack.Count != 0 && arr[stack.Peek()] == '(')
             {
                 stack.Pop();
                 result = Math.Max((stack.Count == 0 ? i + 1 : i - stack.Peek()), result);
             }
             else
             {
                 stack.Push(i);
             }
         }
     }
     return result;
 }
예제 #28
0
        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;
        }
예제 #29
0
        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
        }
예제 #30
0
        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();
        }
 //Generic stack
 static Stack<int> GetStack()
 {
     Stack<int> stack = new Stack<int>();
     stack.Push(100);
     stack.Push(1000);
     stack.Push(10000);
     return stack;
 }
예제 #32
0
 public void Test_BigList_SouldWorkCorectly()
 {
     BigList<int> List = new BigList<int>();
     Stack stack = new Stack();
     stack.Push(3);
     stack.Push('d');
     ;
 }
예제 #33
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);
        }
예제 #34
0
        /// <summary>
        /// Sets the enumerator to its initial position, which is before
        /// the first element in the random access list.
        /// </summary>
        public void Reset()
        {
            index          = -1;
            currentTopNode = head;
            treeStack.Clear();

            //  If the list is not empty.
            if (count > 0)
            {
                // Push the first node in the list onto the stack.
                treeStack.Push(head.Root);
            }
        }
예제 #35
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());
            }
        }
예제 #36
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);
        }
예제 #37
0
        /// <summary>
        /// Sets the enumerator to its initial position, which is before
        /// the first element in the AVL tree.
        /// </summary>
        public void Reset()
        {
            index = 0;

            nodeStack.Clear();

            IAvlNode currentNode = root;

            // Push nodes on to the stack to get to the first item.
            while (currentNode != AvlNode.NullNode)
            {
                nodeStack.Push(currentNode);
                currentNode = currentNode.LeftChild;
            }
        }
예제 #38
0
        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);
            }
        }
예제 #39
0
 /// <summary>  set the current template name on top of stack
 /// *
 /// </summary>
 /// <param name="s">current template name
 ///
 /// </param>
 public virtual void  PushCurrentTemplateName(System.String s)
 {
     System.Object temp_object;
     temp_object = s;
     System.Object generatedAux = temp_object;
     templateNameStack.Push(temp_object);
     return;
 }
예제 #40
0
        public static void PushStack()
        {
            System.Collections.Stack cars = new System.Collections.Stack();

            cars.Push("volkswagen");
            cars.Push("opel ");
            cars.Push("audi");
            cars.Push("BMW");
            cars.Push("nissan");

            foreach (var car in cars)
            {
                Console.WriteLine(car);
            }

            //  Выполнение через цикл for
            //  for (int i = 0; i < cars.Count; i++)
            //  Console.WriteLine(cars[i]);
        }
예제 #41
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);
        }
예제 #42
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);
        }
예제 #43
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));
            }
        }
예제 #44
0
 public void PushMenu(UIManager.State g)
 {
     if (GetMenuForState(g).isPopup == false)
     {
         if (navigationStack.Count != 0)
         {
             HideMenuAtState(NavigationStackPeek());
         }
     }
     navigationStack.Push(g);
     InformUIManager(g);
     ShowMenuAtState(g);
     previousState = currentState;
     currentState  = g;
 }
예제 #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
예제 #46
0
        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);
        }
예제 #47
0
        private void Timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                bool    isNewAppl = false;
                IntPtr  hWnd      = W32.getForegroundWindow();
                Int32   pid       = W32.GetWindowProcessID(hWnd);
                Process p         = Process.GetProcessById(pid);
                appName   = p.ProcessName;
                appltitle = W32.ActiveAppTitle().Trim().Replace("\0", "");

                if (!applnames.Contains(appltitle + appName))
                {
                    applnames.Push(appltitle + appName);
                    applhash.Add(appltitle + appName, 0);
                    isNewAppl = true;
                }

                if (preValue != (appltitle + appName))
                {
                    IDictionaryEnumerator en = applhash.GetEnumerator();
                    applfocusinterval = DateTime.Now.Subtract(applfocustime);

                    while (en.MoveNext())
                    {
                        if (en.Key.ToString() == preValue)
                        {
                            double prevseconds = Convert.ToDouble(en.Value);
                            applhash.Remove(preValue);
                            applhash.Add(preValue, (applfocusinterval.TotalSeconds + prevseconds));
                            break;
                        }
                    }
                    preValue      = appltitle + appName;
                    applfocustime = DateTime.Now;
                }
                if (isNewAppl)
                {
                    applfocustime = DateTime.Now;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message + " : " + ex.StackTrace);
            }
        }
예제 #48
0
        public void SetAction(Action Action)
        {
            //			if (!Action.WorksOnLayoutView)
            //			{	// das ist jetzt besser gelöst mit "OnlyThisView" etc.
            //				frame.AssureModelView(); // geht nur mit ModelView!
            //			}
            if (Action.ChangeTabInControlCenter)
            {
                Action.returnToTabPage = frame.GetActivePropertyDisplay();
                frame.ShowPropertyDisplay("Action");
            }
            Action.ActionStack = this;
            Action.OnSetAction(); // erstes Ereigniss für die neue Aktion (noch nicht auf dem Stack)
            Frame.RaiseActionStartedEvent(Action);
            Action OldAction = null;

            if (Actions.Count > 0)
            {
                OldAction = Actions.Peek() as Action;
            }
            // folgende Schleife ist notwendig, da bei Inactivate eine Aktion sich
            // selbst entfernen kann. Dann aber bekommt die drunterliegende ein Activate
            // was gleich wieder von einem Inactivate gefolgt werden muss
            while (OldAction != null)
            {
                OldAction.OnInactivate(Action, false); // alte Aktion inaktivieren (kann sich auch verabschieden)
                if (Actions.Count > 0)
                {
                    if (OldAction != Actions.Peek())
                    {
                        OldAction = Actions.Peek() as Action;
                    }
                    else
                    {
                        OldAction = null;
                    }
                }
                else
                {
                    OldAction = null;
                }
            }
            Actions.Push(Action);
            Action.OnActivate(OldAction, true);
        }
        public void MethodStack()
        {
            s = new Stack(20);

            s.Push("Element");

            if (!(s.Peek().Equals("Element")))
            {
                Environment.Exit(-1);
            }

            Object[] objs = s.ToArray();

            if (!(objs[0].Equals("Element")))
            {
                Environment.Exit(-1);
            }
        }
예제 #50
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);
        }
예제 #51
0
    public void Populate()
    {
        #region Types of Keywords

        FieldPublicDynamic = new { PropPublic1 = "A", PropPublic2 = 1, PropPublic3 = "B", PropPublic4 = "B", PropPublic5 = "B", PropPublic6 = "B", PropPublic7 = "B", PropPublic8 = "B", PropPublic9 = "B", PropPublic10 = "B", PropPublic11 = "B", PropPublic12 = new { PropSubPublic1 = 0, PropSubPublic2 = 1, PropSubPublic3 = 2 } };
        FieldPublicObject  = new StringBuilder("Object - StringBuilder");
        FieldPublicInt32   = int.MaxValue;
        FieldPublicInt64   = long.MaxValue;
        FieldPublicULong   = ulong.MaxValue;
        FieldPublicUInt    = uint.MaxValue;
        FieldPublicDecimal = 100000.999999m;
        FieldPublicDouble  = 100000.999999d;
        FieldPublicChar    = 'A';
        FieldPublicByte    = byte.MaxValue;
        FieldPublicBoolean = true;
        FieldPublicSByte   = sbyte.MaxValue;
        FieldPublicShort   = short.MaxValue;
        FieldPublicUShort  = ushort.MaxValue;
        FieldPublicFloat   = 100000.675555f;

        FieldPublicInt32Nullable   = int.MaxValue;
        FieldPublicInt64Nullable   = 2;
        FieldPublicULongNullable   = ulong.MaxValue;
        FieldPublicUIntNullable    = uint.MaxValue;
        FieldPublicDecimalNullable = 100000.999999m;
        FieldPublicDoubleNullable  = 100000.999999d;
        FieldPublicCharNullable    = 'A';
        FieldPublicByteNullable    = byte.MaxValue;
        FieldPublicBooleanNullable = true;
        FieldPublicSByteNullable   = sbyte.MaxValue;
        FieldPublicShortNullable   = short.MaxValue;
        FieldPublicUShortNullable  = ushort.MaxValue;
        FieldPublicFloatNullable   = 100000.675555f;

        #endregion

        #region System

        FieldPublicDateTime         = new DateTime(2000, 1, 1, 1, 1, 1);
        FieldPublicTimeSpan         = new TimeSpan(1, 10, 40);
        FieldPublicEnumDateTimeKind = DateTimeKind.Local;

        // Instantiate date and time using Persian calendar with years,
        // months, days, hours, minutes, seconds, and milliseconds
        FieldPublicDateTimeOffset = new DateTimeOffset(1387, 2, 12, 8, 6, 32, 545,
                                                       new System.Globalization.PersianCalendar(),
                                                       new TimeSpan(1, 0, 0));

        FieldPublicIntPtr         = new IntPtr(100);
        FieldPublicTimeZone       = TimeZone.CurrentTimeZone;
        FieldPublicTimeZoneInfo   = TimeZoneInfo.Utc;
        FieldPublicTuple          = Tuple.Create <string, int, decimal>("T-string\"", 1, 1.1m);
        FieldPublicType           = typeof(object);
        FieldPublicUIntPtr        = new UIntPtr(100);
        FieldPublicUri            = new Uri("http://www.site.com");
        FieldPublicVersion        = new Version(1, 0, 100, 1);
        FieldPublicGuid           = new Guid("d5010f5b-0cd1-44ca-aacb-5678b9947e6c");
        FieldPublicSingle         = Single.MaxValue;
        FieldPublicException      = new Exception("Test error", new Exception("inner exception"));
        FieldPublicEnumNonGeneric = EnumTest.ValueA;
        FieldPublicAction         = () => true.Equals(true);
        FieldPublicAction2        = (a, b) => true.Equals(true);
        FieldPublicFunc           = () => true;
        FieldPublicFunc2          = (a, b) => true;

        #endregion

        #region Arrays and Collections

        FieldPublicArrayUni    = new string[2];
        FieldPublicArrayUni[0] = "[0]";
        FieldPublicArrayUni[1] = "[1]";

        FieldPublicArrayTwo       = new string[2, 2];
        FieldPublicArrayTwo[0, 0] = "[0, 0]";
        FieldPublicArrayTwo[0, 1] = "[0, 1]";
        FieldPublicArrayTwo[1, 0] = "[1, 0]";
        FieldPublicArrayTwo[1, 1] = "[1, 1]";

        FieldPublicArrayThree          = new string[1, 1, 2];
        FieldPublicArrayThree[0, 0, 0] = "[0, 0, 0]";
        FieldPublicArrayThree[0, 0, 1] = "[0, 0, 1]";

        FieldPublicJaggedArrayTwo    = new string[2][];
        FieldPublicJaggedArrayTwo[0] = new string[5] {
            "a", "b", "c", "d", "e"
        };
        FieldPublicJaggedArrayTwo[1] = new string[4] {
            "a1", "b1", "c1", "d1"
        };

        FieldPublicJaggedArrayThree          = new string[1][][];
        FieldPublicJaggedArrayThree[0]       = new string[1][];
        FieldPublicJaggedArrayThree[0][0]    = new string[2];
        FieldPublicJaggedArrayThree[0][0][0] = "[0][0][0]";
        FieldPublicJaggedArrayThree[0][0][1] = "[0][0][1]";

        FieldPublicMixedArrayAndJagged = new int[3][, ]
        {
            new int[, ] {
                { 1, 3 }, { 5, 7 }
            },
            new int[, ] {
                { 0, 2 }, { 4, 6 }, { 8, 10 }
            },
            new int[, ] {
                { 11, 22 }, { 99, 88 }, { 0, 9 }
            }
        };

        FieldPublicDictionary = new System.Collections.Generic.Dictionary <string, string>();
        FieldPublicDictionary.Add("Key1", "Value1");
        FieldPublicDictionary.Add("Key2", "Value2");
        FieldPublicDictionary.Add("Key3", "Value3");
        FieldPublicDictionary.Add("Key4", "Value4");

        FieldPublicList = new System.Collections.Generic.List <int>();
        FieldPublicList.Add(0);
        FieldPublicList.Add(1);
        FieldPublicList.Add(2);

        FieldPublicQueue = new System.Collections.Generic.Queue <int>();
        FieldPublicQueue.Enqueue(10);
        FieldPublicQueue.Enqueue(11);
        FieldPublicQueue.Enqueue(12);

        FieldPublicHashSet = new System.Collections.Generic.HashSet <string>();
        FieldPublicHashSet.Add("HashSet1");
        FieldPublicHashSet.Add("HashSet2");

        FieldPublicSortedSet = new System.Collections.Generic.SortedSet <string>();
        FieldPublicSortedSet.Add("SortedSet1");
        FieldPublicSortedSet.Add("SortedSet2");
        FieldPublicSortedSet.Add("SortedSet3");

        FieldPublicStack = new System.Collections.Generic.Stack <string>();
        FieldPublicStack.Push("Stack1");
        FieldPublicStack.Push("Stack2");
        FieldPublicStack.Push("Stack3");

        FieldPublicLinkedList = new System.Collections.Generic.LinkedList <string>();
        FieldPublicLinkedList.AddFirst("LinkedList1");
        FieldPublicLinkedList.AddLast("LinkedList2");
        FieldPublicLinkedList.AddAfter(FieldPublicLinkedList.Find("LinkedList1"), "LinkedList1.1");

        FieldPublicObservableCollection = new System.Collections.ObjectModel.ObservableCollection <string>();
        FieldPublicObservableCollection.Add("ObservableCollection1");
        FieldPublicObservableCollection.Add("ObservableCollection2");

        FieldPublicKeyedCollection = new MyDataKeyedCollection();
        FieldPublicKeyedCollection.Add(new MyData()
        {
            Data = "data1", Id = 0
        });
        FieldPublicKeyedCollection.Add(new MyData()
        {
            Data = "data2", Id = 1
        });

        var list = new List <string>();
        list.Add("list1");
        list.Add("list2");
        list.Add("list3");

        FieldPublicReadOnlyCollection = new ReadOnlyCollection <string>(list);

        FieldPublicReadOnlyDictionary           = new ReadOnlyDictionary <string, string>(FieldPublicDictionary);
        FieldPublicReadOnlyObservableCollection = new ReadOnlyObservableCollection <string>(FieldPublicObservableCollection);
        FieldPublicCollection = new Collection <string>();
        FieldPublicCollection.Add("collection1");
        FieldPublicCollection.Add("collection2");
        FieldPublicCollection.Add("collection3");

        FieldPublicArrayListNonGeneric = new System.Collections.ArrayList();
        FieldPublicArrayListNonGeneric.Add(1);
        FieldPublicArrayListNonGeneric.Add("a");
        FieldPublicArrayListNonGeneric.Add(10.0m);
        FieldPublicArrayListNonGeneric.Add(new DateTime(2000, 01, 01));

        FieldPublicBitArray    = new System.Collections.BitArray(3);
        FieldPublicBitArray[2] = true;

        FieldPublicSortedList = new System.Collections.SortedList();
        FieldPublicSortedList.Add("key1", 1);
        FieldPublicSortedList.Add("key2", 2);
        FieldPublicSortedList.Add("key3", 3);
        FieldPublicSortedList.Add("key4", 4);

        FieldPublicHashtableNonGeneric = new System.Collections.Hashtable();
        FieldPublicHashtableNonGeneric.Add("key1", 1);
        FieldPublicHashtableNonGeneric.Add("key2", 2);
        FieldPublicHashtableNonGeneric.Add("key3", 3);
        FieldPublicHashtableNonGeneric.Add("key4", 4);

        FieldPublicQueueNonGeneric = new System.Collections.Queue();
        FieldPublicQueueNonGeneric.Enqueue("QueueNonGeneric1");
        FieldPublicQueueNonGeneric.Enqueue("QueueNonGeneric2");
        FieldPublicQueueNonGeneric.Enqueue("QueueNonGeneric3");

        FieldPublicStackNonGeneric = new System.Collections.Stack();
        FieldPublicStackNonGeneric.Push("StackNonGeneric1");
        FieldPublicStackNonGeneric.Push("StackNonGeneric2");

        FieldPublicIEnumerable = FieldPublicSortedList;

        FieldPublicBlockingCollection = new System.Collections.Concurrent.BlockingCollection <string>();
        FieldPublicBlockingCollection.Add("BlockingCollection1");
        FieldPublicBlockingCollection.Add("BlockingCollection2");

        FieldPublicConcurrentBag = new System.Collections.Concurrent.ConcurrentBag <string>();
        FieldPublicConcurrentBag.Add("ConcurrentBag1");
        FieldPublicConcurrentBag.Add("ConcurrentBag2");
        FieldPublicConcurrentBag.Add("ConcurrentBag3");

        FieldPublicConcurrentDictionary = new System.Collections.Concurrent.ConcurrentDictionary <string, int>();
        FieldPublicConcurrentDictionary.GetOrAdd("ConcurrentDictionary1", 0);
        FieldPublicConcurrentDictionary.GetOrAdd("ConcurrentDictionary2", 0);

        FieldPublicConcurrentQueue = new System.Collections.Concurrent.ConcurrentQueue <string>();
        FieldPublicConcurrentQueue.Enqueue("ConcurrentQueue1");
        FieldPublicConcurrentQueue.Enqueue("ConcurrentQueue2");

        FieldPublicConcurrentStack = new System.Collections.Concurrent.ConcurrentStack <string>();
        FieldPublicConcurrentStack.Push("ConcurrentStack1");
        FieldPublicConcurrentStack.Push("ConcurrentStack2");

        // FieldPublicOrderablePartitioner = new OrderablePartitioner();
        // FieldPublicPartitioner;
        // FieldPublicPartitionerNonGeneric;

        FieldPublicHybridDictionary = new System.Collections.Specialized.HybridDictionary();
        FieldPublicHybridDictionary.Add("HybridDictionaryKey1", "HybridDictionary1");
        FieldPublicHybridDictionary.Add("HybridDictionaryKey2", "HybridDictionary2");

        FieldPublicListDictionary = new System.Collections.Specialized.ListDictionary();
        FieldPublicListDictionary.Add("ListDictionaryKey1", "ListDictionary1");
        FieldPublicListDictionary.Add("ListDictionaryKey2", "ListDictionary2");
        FieldPublicNameValueCollection = new System.Collections.Specialized.NameValueCollection();
        FieldPublicNameValueCollection.Add("Key1", "Value1");
        FieldPublicNameValueCollection.Add("Key2", "Value2");

        FieldPublicOrderedDictionary = new System.Collections.Specialized.OrderedDictionary();
        FieldPublicOrderedDictionary.Add(1, "OrderedDictionary1");
        FieldPublicOrderedDictionary.Add(2, "OrderedDictionary1");
        FieldPublicOrderedDictionary.Add("OrderedDictionaryKey2", "OrderedDictionary2");

        FieldPublicStringCollection = new System.Collections.Specialized.StringCollection();
        FieldPublicStringCollection.Add("StringCollection1");
        FieldPublicStringCollection.Add("StringCollection2");

        #endregion

        #region Several

        PropXmlDocument = new XmlDocument();
        PropXmlDocument.LoadXml("<xml>something</xml>");

        var tr = new StringReader("<Root>Content</Root>");
        PropXDocument         = XDocument.Load(tr);
        PropStream            = GenerateStreamFromString("Stream");
        PropBigInteger        = new System.Numerics.BigInteger(100);
        PropStringBuilder     = new StringBuilder("StringBuilder");
        FieldPublicIQueryable = new List <string>()
        {
            "IQueryable"
        }.AsQueryable();

        #endregion

        #region Custom

        FieldPublicMyCollectionPublicGetEnumerator           = new MyCollectionPublicGetEnumerator("a b c", new char[] { ' ' });
        FieldPublicMyCollectionInheritsPublicGetEnumerator   = new MyCollectionInheritsPublicGetEnumerator("a b c", new char[] { ' ' });
        FieldPublicMyCollectionExplicitGetEnumerator         = new MyCollectionExplicitGetEnumerator("a b c", new char[] { ' ' });
        FieldPublicMyCollectionInheritsExplicitGetEnumerator = new MyCollectionInheritsExplicitGetEnumerator("a b c", new char[] { ' ' });
        FieldPublicMyCollectionInheritsTooIEnumerable        = new MyCollectionInheritsTooIEnumerable("a b c", new char[] { ' ' });

        FieldPublicEnumSpecific = EnumTest.ValueB;
        MyDelegate            = MethodDelegate;
        EmptyClass            = new EmptyClass();
        StructGeneric         = new ThreeTuple <int>(0, 1, 2);
        StructGenericNullable = new ThreeTuple <int>(0, 1, 2);
        FieldPublicNullable   = new Nullable <ThreeTuple <int> >(StructGeneric);

        #endregion
    }
예제 #52
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;
 }
예제 #53
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public ParseTreeNode convertInfixNotationToASTForIcePlugin(String paramString) throws Exception
        public virtual ParseTreeNode convertInfixNotationToASTForIcePlugin(string paramString)
        {
            System.Collections.Stack stack1 = new System.Collections.Stack();
            System.Collections.Stack stack2 = new System.Collections.Stack();
            string[] arrayOfString          = paramString.Split("", true);
            sbyte    b1    = 0;
            string   str   = "";
            bool     @bool = true;

            for (sbyte b2 = 0; b2 < arrayOfString.Length; b2++)
            {
                string str2;
                bool   bool1;
                string str1;
                if (arrayOfString[b2].Equals(" ") || arrayOfString[b2].Equals(""))
                {
                    b1 = 1;
                }
                else if (arrayOfString[b2].Equals("("))
                {
                    b1 = 2;
                }
                else if (arrayOfString[b2].Equals(")"))
                {
                    b1 = 3;
                }
                else
                {
                    b1 = 4;
                }
                switch (b1)
                {
                case 1:
                    break;

                case 2:
                    stack1.Push("(");
                    break;

                case 3:
                    while (true)
                    {
                        if (stack1.Count > 0)
                        {
                            string str3 = (string)stack1.Pop();
                            if ("(".Equals(str3))
                            {
                                break;
                            }
                            addNode(stack2, str3);
                            continue;
                        }
                        throw new System.InvalidOperationException("Unbalanced right parentheses");
                    }
                    break;

                default:
                    if (this.operators.ContainsKey(arrayOfString[b2]))
                    {
                        @bool = false;
                        BaseOperator baseOperator1 = (BaseOperator)this.operators[arrayOfString[b2]];
                        BaseOperator baseOperator2;
                        while (stack1.Count > 0 && null != (baseOperator2 = (BaseOperator)this.operators[stack1.Peek()]) && ((!baseOperator1.RightAssociative && 0 == baseOperator1.comparePrecedence(baseOperator2)) || baseOperator1.comparePrecedence(baseOperator2) < 0))
                        {
                            stack1.Pop();
                            addNode(stack2, baseOperator2.Symbol + "");
                        }
                        stack1.Push(arrayOfString[b2]);
                        break;
                    }
                    str1  = arrayOfString[b2];
                    bool1 = b2 + true;
                    while (b2 + true < arrayOfString.Length && !arrayOfString[b2 + true].Equals(" ") && !arrayOfString[b2 + true].Equals("(") && !arrayOfString[b2 + true].Equals(")") && !this.operators.ContainsKey(arrayOfString[b2 + true]))
                    {
                        str1 = str1 + arrayOfString[b2 + true];
                        b2++;
                    }
                    str2 = str1;
                    str1 = createValidNameForInput(str1);
                    if (str1.EndsWith("R", StringComparison.Ordinal) && str1.IndexOf("R", StringComparison.Ordinal) != 0)
                    {
                        string str3 = str1.Substring(0, str1.Length - 1);
                        str1 = "( ROUND( (" + str3 + "- INT(" + str3 + ")) * (10^( LEN(ROUND(" + str3 + " - INT(" + str3 + "),2))-2)),4))";
                    }
                    else if (str1.EndsWith("L", StringComparison.Ordinal) && str1.IndexOf("L", StringComparison.Ordinal) != 0)
                    {
                        str1 = "INT(" + str1.Substring(0, str1.Length - 1) + ")";
                    }
                    else if (str1.EndsWith("\"", StringComparison.Ordinal))
                    {
                        if (str1.Substring(0, str1.Length - 1).EndsWith("R", StringComparison.Ordinal) && str1.IndexOf("R", StringComparison.Ordinal) != 0)
                        {
                            string str3 = str1.Substring(0, str1.Length - 2);
                            str1 = "( ROUND( (" + str3 + "- INT(" + str3 + ")) * (10^( LEN(ROUND(" + str3 + " - INT(" + str3 + "),2))-2)),4))";
                        }
                        else if (str1.Substring(0, str1.Length - 1).EndsWith("L", StringComparison.Ordinal) && str1.IndexOf("L", StringComparison.Ordinal) != 0)
                        {
                            str1 = "INT(" + str1.Substring(0, str1.Length - 1) + "\")";
                        }
                    }
                    stack2.Push(new ParseTreeNode(str1, null, null));
                    break;
                }
            }
            while (stack1.Count > 0)
            {
                addNode(stack2, (string)stack1.Pop());
            }
            return((ParseTreeNode)stack2.Pop());
        }
예제 #54
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public ParseTreeNode convertInfixNotationToAST(String paramString) throws Exception
        public virtual ParseTreeNode convertInfixNotationToAST(string paramString)
        {
            System.Collections.Stack stack1 = new System.Collections.Stack();
            System.Collections.Stack stack2 = new System.Collections.Stack();
            string[] arrayOfString          = paramString.Split("", true);
            sbyte    b1    = 0;
            string   str   = "";
            bool     @bool = true;

            for (sbyte b2 = 0; b2 < arrayOfString.Length; b2++)
            {
                bool   bool1;
                string str1;
                if (arrayOfString[b2].Equals(" "))
                {
                    b1 = 1;
                }
                else if (arrayOfString[b2].Equals("("))
                {
                    b1 = 2;
                }
                else if (arrayOfString[b2].Equals(")"))
                {
                    b1 = 3;
                }
                else
                {
                    b1 = 4;
                }
                switch (b1)
                {
                case 1:
                    break;

                case 2:
                    stack1.Push("(");
                    break;

                case 3:
                    while (true)
                    {
                        if (stack1.Count > 0)
                        {
                            string str2 = (string)stack1.Pop();
                            if ("(".Equals(str2))
                            {
                                break;
                            }
                            addNode(stack2, str2);
                            continue;
                        }
                        throw new System.InvalidOperationException("Unbalanced right parentheses");
                    }
                    break;

                default:
                    if (this.operators.ContainsKey(arrayOfString[b2]))
                    {
                        @bool = false;
                        BaseOperator baseOperator1 = (BaseOperator)this.operators[arrayOfString[b2]];
                        BaseOperator baseOperator2;
                        while (stack1.Count > 0 && null != (baseOperator2 = (BaseOperator)this.operators[stack1.Peek()]) && ((!baseOperator1.RightAssociative && 0 == baseOperator1.comparePrecedence(baseOperator2)) || baseOperator1.comparePrecedence(baseOperator2) < 0))
                        {
                            stack1.Pop();
                            addNode(stack2, baseOperator2.Symbol + "");
                        }
                        stack1.Push(arrayOfString[b2]);
                        break;
                    }
                    str1  = arrayOfString[b2];
                    bool1 = b2 + true;
                    while (b2 + true < arrayOfString.Length && !arrayOfString[b2 + true].Equals(" ") && !arrayOfString[b2 + true].Equals("(") && !arrayOfString[b2 + true].Equals(")") && !this.operators.ContainsKey(arrayOfString[b2 + true]))
                    {
                        str1 = str1 + arrayOfString[b2 + true];
                        b2++;
                    }
                    stack2.Push(new ParseTreeNode(str1, null, null));
                    break;
                }
            }
            while (stack1.Count > 0)
            {
                addNode(stack2, (string)stack1.Pop());
            }
            return((ParseTreeNode)stack2.Pop());
        }
예제 #55
0
        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);
        }
 /// <summary>
 /// Push(f) adds f to the top of the stack.
 /// </summary>
 /// <param name="f">a frame to push</param>
 internal void Push(Frame f)
 {
     _frames.Push(f);
 }
예제 #57
0
        public ParseTreeBuilder(string grammarName)
        {
            ParseTree root = Create("<grammar " + grammarName + ">");

            callStack.Push(root);
        }
예제 #58
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);
        }
예제 #59
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));
        }
예제 #60
0
 public static void push(ref System.Collections.Stack st, int x)
 {
     st.Push(x);
 }