Exemplo n.º 1
1
        static void Main(string[] args)
        {
            const int NumberOfAnimals = 10;
            Stack<Animal> animalStack = new Stack<Animal>();
            Queue<Animal> animalQueue = new Queue<Animal>();

            Console.WriteLine("/// ORDER OF ENTRY...");
            Random r = new Random();
            for (int index = 0; index < NumberOfAnimals; index++)
            {
                var animalShouldBeCat = (r.Next(2) == 0);
                uint nextWeight = (uint)r.Next(10, 40);
                Animal nextAnimal = animalShouldBeCat ? (Animal)(new Cat(nextWeight, "John")) : (Animal)(new Dog(nextWeight, "Dave"));
                animalStack.Push(nextAnimal);
                animalQueue.Enqueue(nextAnimal);
                Console.WriteLine(nextAnimal);
            }

            Console.WriteLine();
            Console.WriteLine("/// OUTPUT FROM STACK...");
            foreach (Animal animal in animalStack)
            {
                Console.WriteLine(animal);
            }

            Console.WriteLine();
            Console.WriteLine("/// OUTPUT FROM QUEUE...");
            foreach (Animal animal in animalQueue)
            {
                Console.WriteLine(animal);
            }
        }
 public BufferManager(Int32 totalBytes, Int32 totalBufferBytesInEachSaeaObject)
 {
     totalBytesInBufferBlock = totalBytes;
     this.currentIndex = 0;
     this.bufferBytesAllocatedForEachSaea = totalBufferBytesInEachSaeaObject;
     this.freeIndexPool = new Stack<int>();
 }
Exemplo n.º 3
1
 public IItem GetValue(IDictionary<string, IItem> variables) {
   var stack = new Stack<object>();
   int i = 0;
   try {
     for (; i < tokens.Count; i++) {
       var token = tokens[i];
       double d;
       if (TryParse(token, out d)) {
         stack.Push(d);
       } else if (token.StartsWith("\"")) {
         stack.Push(GetVariableValue(variables, token.Substring(1, token.Length - 2).Replace("\\\"", "\"")));
       } else if (token.StartsWith("'")) {
         stack.Push(token.Substring(1, token.Length - 2).Replace("\\'", "'"));
       } else {
         Apply(token, stack, variables);
       }
     }
   } catch (Exception x) {
     throw new Exception(string.Format(
       "Calculation of '{1}'{0}failed at token #{2}: {3} {0}current stack is: {0}{4}", Environment.NewLine,
       Formula, i, TokenWithContext(tokens, i, 3),
       string.Join(Environment.NewLine, stack.Select(AsString))),
       x);
   }
   if (stack.Count != 1)
     throw new Exception(
       string.Format("Invalid final evaluation stack size {0} (should be 1) in formula '{1}'",
       stack.Count, Formula));
   var result = stack.Pop();
   if (result is string) return new StringValue((string)result);
   if (result is int) return new IntValue((int)result);
   if (result is double) return new DoubleValue((double)result);
   if (result is bool) return new BoolValue((bool)result);
   return null;
 }
Exemplo n.º 4
0
        /// <summary>
        /// Happens before the action starts running
        /// </summary>
        /// <param name="filterContext">The filter Context.</param>
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var mp = MiniProfiler.Current;
            if (mp != null)
            {
                var stack = HttpContext.Current.Items[StackKey] as Stack<IDisposable>;
                if (stack == null)
                {
                    stack = new Stack<IDisposable>();
                    HttpContext.Current.Items[StackKey] = stack;
                }

                var profiler = MiniProfiler.Current;
                if (profiler != null)
                {
                    var tokens = filterContext.RouteData.DataTokens;
                    string area = tokens.ContainsKey("area") && !string.IsNullOrEmpty((string)tokens["area"]) ?
                        tokens["area"] + "." : string.Empty;
                    string controller = filterContext.Controller.ToString().Split('.').Last() + ".";
                    string action = filterContext.ActionDescriptor.ActionName;

                    stack.Push(profiler.Step("Controller: " + area + controller + action));
                }

            }
            base.OnActionExecuting(filterContext);
        }
Exemplo n.º 5
0
        static void Main(string[] args)
        {
            List<int> list = new List<int>
            {
                3,2,
            }; // 3, 2

            list.Add(5); // 3, 2, 5
            list.Add(6); // 3, 2, 5, 6
            list.Remove(5); // 3, 2, 6

            Queue<int> queue = new Queue<int>();
            queue.Enqueue(3);// 3
            queue.Enqueue(8);// 3, 8
            queue.Dequeue(); // 8

            Stack<int> stack = new Stack<int>();
            stack.Push(2); // 2
            stack.Push(7); // 7, 2
            stack.Push(8); // 8, 7, 2
            stack.Pop();   // 7, 2

            foreach (var i in stack)
            {
                Console.WriteLine(i);
            }

            LinkedList<int> linkedList = new LinkedList<int>();
            linkedList.AddFirst(9); // 9
            linkedList.AddAfter(linkedList.Find(9), 5); // 9, 5
            linkedList.Remove(9); // 5

            Console.Read();
        }
        ///<summary>Gets all files that indirectly depend on the specified file.</summary>
        public async Task<IEnumerable<string>> GetRecursiveDependentsAsync(string fileName)
        {
            HashSet<GraphNode> visited;
            fileName = Path.GetFullPath(fileName);
            using (await rwLock.ReadLockAsync())
            {
                GraphNode rootNode;
                if (!nodes.TryGetValue(fileName, out rootNode))
                    return Enumerable.Empty<string>();

                var stack = new Stack<GraphNode>();
                stack.Push(rootNode);
                visited = new HashSet<GraphNode> { rootNode };
                while (stack.Count > 0)
                {
                    foreach (var child in stack.Pop().Dependents)
                    {
                        if (!visited.Add(child)) continue;
                        stack.Push(child);
                    }
                }
                // Don't return the original file.
                visited.Remove(rootNode);
            }
            return visited.Select(n => n.FileName);
        }
Exemplo n.º 7
0
 public BufferManager(int totalBytes, int bufferSize)
 {
     _numberOfBytes = totalBytes;
     _bufferSize = bufferSize;
     _currentIndex = 0;
     _freeIndexPool = new Stack<int>();
 }
Exemplo n.º 8
0
        public static bool Validate(string lineOfMarkupLanguage)
        {
            string[] splitted = lineOfMarkupLanguage.Split(new char[] { '>' }, StringSplitOptions.RemoveEmptyEntries);
            Stack<string> mainStack = new Stack<string>();

            foreach (var tag in splitted)
            {
                if (IsOpeniningTag(tag))
                {
                    mainStack.Push(tag);
                }
                else
                {
                    if (mainStack.Count == 0)
                    {
                        return false;
                    }

                    string currentOpeningTag = mainStack.Pop();
                    if (!SpecialComparer(currentOpeningTag, tag))
                    {
                        return false;
                    }
                }
            }

            return (mainStack.Count == 0);
        }
        /// <summary>
        /// A class that checks for unpopped baloons and adds then to a stack.
        /// If there are unpopped baloons their positions are reset. If all baloons are 
        /// popped, red baloons are created in the emprty space.
        /// </summary>
        /// <param name="board">This method accepts a new instance of the Gameboard.</param>
        public override void Apply(Gameboard board)
        {
            for (int col = 0; col < board.BoardWidth; col++)
            {
                Stack<BoardComponent> columnContents = new Stack<BoardComponent>();

                for (int row = 0; row < board.BoardHeight; row++)
                {
                    var currentComponent = board.GetElement(row, col);

                    if (currentComponent.IsActive)
                    {
                        columnContents.Push(currentComponent);
                    }
                }

                for (int row = board.BoardHeight - 1; row >= 0; row--)
                {
                    if (columnContents.Count > 0)
                    {
                        board.SetElement(row, col, columnContents.Pop());
                    }
                    else
                    {
                        BalloonMaker balloonMaker = new BalloonMaker();
                        BoardComponent poppedBalloon = balloonMaker.MakeBalloon(BaloonColor.Red);
                        poppedBalloon.IsActive = false;

                        board.SetElement(row, col, poppedBalloon);
                    }
                }
            }
        }
Exemplo n.º 10
0
        public EventDevelopment(DevelopmentState a_backState, LinkedList<Event> a_events)
        {
            if (a_events == null)
            {
                throw new ArgumentNullException();
            }
            m_numOfAddedEvents = 0;
            m_state = State.neutral;
            m_backState = a_backState;
            m_buttonList = new LinkedList<Button>();
            m_guiList = new LinkedList<GuiObject>();
            m_buttonsToAdd = new Stack<Button>();
            m_buttonsToRemove = new Stack<Button>();

            m_eventsToRemove = new Stack<Button>();
            m_eventsToAdd = new Stack<Event>();
            m_events = new Dictionary<Button, Event>();
            m_effects = new Dictionary<Button, EventEffect>();
            m_triggers = new Dictionary<Button, EventTrigger>();
            m_stateButtons = new Stack<LinkedList<Button>>();

            foreach (Event t_e in a_events)
            {
                addEvent(t_e);
            }
        }
Exemplo n.º 11
0
        private static void CheckPath(int row, int col, int count, Stack<int> stack)
        {
            if (row < 0 || col < 0 ||
                row >= labyrinth.GetLength(0) || col >= labyrinth.GetLength(1))
            {
                return;
            }

            if (labyrinth[row, col] == "e")
            {
                Console.WriteLine("Exit found at [{0},{1}]", row, col);
                Print(new Stack<int>(stack));
            }

            if (labyrinth[row, col] != " ")
            {
                return;
            }

            stack.Push(count);
            labyrinth[row, col] = count.ToString();
            count++;
            CheckPath(row, col - 1, count, stack);
            CheckPath(row - 1, col, count, stack);
            CheckPath(row, col + 1, count, stack);
            CheckPath(row + 1, col, count, stack);

            labyrinth[row, col] = " ";
            if (stack.Count > 0)
            {
                stack.Pop();
            }
        }
Exemplo n.º 12
0
    private static void SaveAllConncectedComponents(Node<int> node,
        HashSet<int> visitedNodes, List<string> connectedComponents)
    {
        string graphs = string.Empty;
        Stack<Node<int>> nodesStack = new Stack<Node<int>>();
        nodesStack.Push(node);

        while (nodesStack.Count > 0)
        {
            Node<int> currentNode = nodesStack.Pop();
            visitedNodes.Add(currentNode.Value);
            graphs += " -> " + currentNode.Value;

            foreach (var child in currentNode.Children)
            {
                if (!visitedNodes.Contains(child.Value))
                {
                    visitedNodes.Add(child.Value);
                    nodesStack.Push(child);
                }
            }
        }

        connectedComponents.Add(graphs.Substring(4));
    }
Exemplo n.º 13
0
 private ExpansionContext(Stack<MethodBase> stack, Scope scope, NameGenerator names, IEnumerable<KeyValuePair<Sym, Expression>> env)
 {
     Stack = stack;
     Scope = scope;
     Names = names;
     Env = env.ToDictionary();
 }
Exemplo n.º 14
0
 public DrawState()
 {
     _worldMatrixStack = new Stack<Matrix>();
     _viewMatrixStack = new Stack<Matrix>();
     _projectionMatrixStack = new Stack<Matrix>();
     _rendererStack = new Stack<IRenderer>();
 }
Exemplo n.º 15
0
 public ExpansionContext SpinOff(MethodBase callee)
 {
     Stack.Contains(callee).AssertFalse();
     var new_stack = new Stack<MethodBase>();
     callee.Concat(Stack).Reverse().ForEach(new_stack.Push);
     return new ExpansionContext(new_stack, Scope, Names, Env){Parent = this};
 }
 static void Main()
 {
     int loops = int.Parse(Console.ReadLine());
     int number = int.Parse(Console.ReadLine());
     Stack<int> stack = new Stack<int>();
     Loop(loops, 1, number, stack);
 }
Exemplo n.º 17
0
		private string makeWhere(Uri url)
		{
			Stack<string> hostStack = new Stack<string>(url.Host.Split('.'));
			StringBuilder hostBuilder = new StringBuilder('.' + hostStack.Pop());
			string[] pathes = url.Segments;

			StringBuilder sb = new StringBuilder();
			sb.Append("WHERE (");

			bool needOr = false;
			while (hostStack.Count != 0) {
				if (needOr) {
					sb.Append(" OR");
				}

				if (hostStack.Count != 1) {
					hostBuilder.Insert(0, '.' + hostStack.Pop());
					sb.AppendFormat(" host = \"{0}\"", hostBuilder.ToString());
				} else {
					hostBuilder.Insert(0, '%' + hostStack.Pop());
					sb.AppendFormat(" host LIKE \"{0}\"", hostBuilder.ToString());
				}

				needOr = true;
			}

			sb.Append(')');
			return sb.ToString();
		}
        public override SummaryData GetStackSummaryData(Stack stack)
        {
            if (!stack.SignatureInfo.ContainsKeyWithValue("Type", Event.KnownTypes.FeatureUsage))
                return null;

            return new SummaryData("stack-feature-summary", new { Title = stack.Title });
        }
Exemplo n.º 19
0
    public bool PosTest2()
    {
        bool retVal = true;

        const string c_TEST_ID = "P002";
        string c_TEST_DESC = "PosTest2: Get the element at the current position of the enumerator from empty stack.";
        string errorDesc;

        Stack<int>.Enumerator enumerator;
        Stack<int> operandStack = new Stack<int>();
        TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
        try
        {
            enumerator = operandStack.GetEnumerator();
            retVal = this.VerifyEnumerator(c_TEST_ID, enumerator, new int[] { });
        }
        catch (Exception e)
        {
            errorDesc = "Unexpected exception: " + e + "\nThe stack is empty.";
            TestLibrary.TestFramework.LogError(c_TEST_ID + ".3", errorDesc);
            retVal = false;
        }

        return retVal;
    }
        /// <summary>
        /// Applys the rule instance to the public or system identifier in an
        /// attempt to locate the URI of a resource with can provide the required
        /// information.
        /// </summary>
        /// <param name="publicId">The public identifier of the external entity
        /// being referenced, or null if none was supplied.</param>
        /// <param name="systemId">The system identifier of the external entity
        /// being referenced.</param>
        /// <param name="catalogs">The stack of catalogs being processed.</param>
        /// <returns>A new URI if the rule was successfully applied, otherwise
        /// <b>null</b>.</returns>
        public String ApplyTo(String publicId, String systemId, Stack<GroupEntry> catalogs)
        {
            if (publicId.StartsWith (prefix))
                return (CatalogManager.Find (catalog).Definition.ApplyRules (publicId, systemId, catalogs));

            return (null);
        }
Exemplo n.º 21
0
        // Uses depth-first search to check if the graph induced by the subgraph given as a parameter is connected
        // In other words, we retreive all edges from the original graph and check the subgraph for connectedness
        public static bool Connected(Datastructures.Graph graph, BitSet subgraph)
        {
            // Vertices that are visited
            Set<int> visited = new Set<int>();

            // Stack of vertices yet to visit
            Stack<int> stack = new Stack<int>();

            // Initial vertex
            int s = subgraph.First();
            stack.Push(s);

            // Continue while there are vertices on the stack
            while (stack.Count > 0)
            {
                int v = stack.Pop();

                // If we have not encountered this vertex before, then we check for all neighbors if they are part of the subgraph
                // If a neighbor is part of the subgraph it means that we have to push it on the stack to explore it at a later stage
                if (!visited.Contains(v))
                {
                    visited.Add(v);

                    foreach (int w in graph.OpenNeighborhood(v))
                        if (subgraph.Contains(w))
                            stack.Push(w);
                }
            }

            // If we visited an equal number of vertices as there are vertices in the subgraph then the subgraph is connected
            return visited.Count == subgraph.Count;
        }
Exemplo n.º 22
0
    public bool PosTest1()
    {
        bool retVal = true;

        const string c_TEST_ID = "P001";
        string c_TEST_DESC = "PosTest1: Get the element at the current position of the enumerator from non-empty stack.";
        string errorDesc;

        Stack<int>.Enumerator enumerator;
        int[] operands = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
        Stack<int> operandStack = new Stack<int>((IEnumerable<int>)operands);
        TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
        try
        {
            int[] expectedValues = new int[] { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 };
            enumerator = operandStack.GetEnumerator();
            retVal = this.VerifyEnumerator(c_TEST_ID, enumerator, expectedValues);
        }
        catch (Exception e)
        {
            errorDesc = "Unexpected exception: " + e +
                "\nThe stack is " + GetStackData(operandStack);
            TestLibrary.TestFramework.LogError(c_TEST_ID + ".3", errorDesc);
            retVal = false;
        }

        return retVal;
    }
Exemplo n.º 23
0
    static void Main()
    {
        // Initialize
        Stack<int> stack = new Stack<int>();
        int count = int.Parse(Console.ReadLine());
        Stack<int> maxElements = new Stack<int>();
        maxElements.Push(0);

        // Get input
        for (int i = 0; i < count; i++)
        {
            string[] input = Console.ReadLine().Split(' ');
            switch (input[0])
            {
                case "1":
                    int numToPush = int.Parse(input.Last());
                    stack.Push(numToPush);
                    if (numToPush > maxElements.Peek())
                    {
                        maxElements.Push(numToPush);
                    }
                    break;
                case "2":
                    int numToRemove = stack.Pop();

                    if (numToRemove == maxElements.Peek())
                        maxElements.Pop();
                    break;
                case "3":
                    Console.WriteLine(maxElements.Peek());
                    break;
            }
        }
    }
 protected void StartFeed(Stack<ResponseNode> nodeStack, ODataFeedAnnotations feedAnnotations)
 {
     nodeStack.Push(new ResponseNode
     {
         Feed = new AnnotatedFeed(new List<AnnotatedEntry>()),
     });
 }
 protected void StartEntry(Stack<ResponseNode> nodeStack)
 {
     nodeStack.Push(new ResponseNode
     {
         Entry = new AnnotatedEntry(new Dictionary<string, object>())
     });
 }
Exemplo n.º 26
0
        //Returns the location of bracket mismatch
        //Rewrite this to make use of better suited container for brackets
        public int GetBracketMismatch(string code)
        {
            Dictionary<char, char> bracketMap = new Dictionary<char, char>()
            { {'{', '}'}, {'(', ')'}, {'[', ']'}, {'<', '>'} };//, {'\'', '\''} }; //{} () [] <> "" ''
            Stack<char> bracketStack = new Stack<char>();
            int counter = 0;

            foreach (char c in code)
            {
                if("(){}<>".Contains(c))
                {
                    if (!")}>".Contains(c))
                    {
                        bracketStack.Push(c);
                    }
                    else if (bracketMap.Any(q => q.Key == bracketMap[bracketStack.Last()]))
                    {
                        bracketStack.Pop();
                    }
                    else
                    {
                        return counter;
                    }
                }
                counter++;
            }

            return -1;
        }
Exemplo n.º 27
0
 private static Stack<WeakReference> GetChunkStack(int size)
 {
     Stack<WeakReference> s;
     if (!_chunks.TryGetValue(size, out s))
         s = _chunks[size] = new Stack<WeakReference>();
     return s;
 }
Exemplo n.º 28
0
        public void Execute(Machine machine, Stack<object> stack, Scope scope, Instruction instr)
        {
            int length = (int)machine.TakeByte();
            string name = machine.TakeBytes(length * sizeof(char)).AsString();

            scope.GetFunction(name).Call(machine);
        }
Exemplo n.º 29
0
        private static void Print(Stack<int> stack)
        {
            while (stack.Count > 0)
            {
                if (stack.Count == 1)
                {
                    Console.Write(stack.Pop());
                }
                else
                {
                    Console.Write(stack.Pop() + ",");
                }

            }
            Console.WriteLine();
            for (int i = 0; i < labyrinth.GetLength(0); i++)
            {
                for (int j = 0; j < labyrinth.GetLength(1); j++)
                {
                    Console.Write("{0, 2} ", labyrinth[i, j]);
                }
                Console.WriteLine();
            }
            Console.WriteLine();
        }
 protected void StartNavigationLink(Stack<ResponseNode> nodeStack, string linkName)
 {
     nodeStack.Push(new ResponseNode
     {
         LinkName = linkName,
     });
 }
Exemplo n.º 31
0
        // https://www.youtube.com/watch?v=SW14tOda_kI
        public void Revese(Stack <int> s)
        {
            var q = new Queue <int>();

            ReverseHelper(s, q);
        }
Exemplo n.º 32
0
    private void SLR_Parse(List <Dictionary <string, Tuple <string, int, string> > > LRTable, ref TreeNode productionTreeRoot)
    {
        Stack <int>      stateStack = new Stack <int>();
        Stack <TreeNode> nodeStack  = new Stack <TreeNode>();
        int tokenIndex = 0;

        stateStack.Push(0);

        try
        {
            while (true)
            {
                int    s = stateStack.Peek();
                string t;
                if (tokenIndex == tokens.Count)
                {
                    t = "$";
                }
                else
                {
                    t = tokens[tokenIndex].Symbol;
                }
                //Console.WriteLine("\nToken{0}: ' {1} ' out of {2} Tokens", tokenIndex, t, tokens.Count);
                if (!LRTable[s].ContainsKey(t))
                {
                    throw new Exception("Syntax Error!! State:\n'" + states[s].ToString() + "'\nNo Entry for Token:'" + t + "'");
                }
                else
                {
                    Tuple <string, int, string> action = LRTable[s][t];
                    //Console.WriteLine("S:{3} T:{4} \tAction: {0}, {1}, {2}", action.Item1, action.Item2, action.Item3, s, t);

                    if (action.Item1 == "S") //Shift
                    {
                        stateStack.Push(action.Item2);
                        nodeStack.Push(new TreeNode(t, tokens[tokenIndex]));
                        //if (tokenIndex < tokens.Count())
                        //Console.WriteLine("\tShift Item2:'{0}' Node:'{1}' TokenLex:'{2}'", action.Item2, t, tokens[tokenIndex].Lexeme);
                        tokenIndex++;
                    }
                    else                                         //Reduce
                    {
                        TreeNode n = new TreeNode(action.Item3); //Reduce to Symbol

                        //Console.WriteLine("Popping {0} items:", action.Item2);
                        for (int popNum = 0; popNum < action.Item2; popNum++)
                        {
                            //Console.WriteLine("\tPop: {0}\t: {1}, {2}", stateStack.Peek(), nodeStack.Peek().Symbol, nodeStack.Peek().Token == null ? "null" : nodeStack.Peek().Token.Lexeme);
                            stateStack.Pop();
                            n.Children.Insert(0, nodeStack.Pop());
                        }
                        //Console.WriteLine("Reduced To: {0}, {1}", action.Item3, LRTable[stateStack.Peek()][action.Item3].Item2);
                        if (action.Item3 == "program" || action.Item3 == "S'")
                        {
                            if (tokenIndex == tokens.Count && t == "$")
                            {
                                //Console.WriteLine("ROOT: {0}", n.Symbol);
                                productionTreeRoot = n;
                                return;
                            }
                            else
                            {
                                throw new Exception("Compiler Error!!! " +
                                                    "Token is either not at the end or symbol is not '$'\n" +
                                                    "Token index: '" + tokenIndex + "', Token:'" + t + "'");
                            }
                        }
                        stateStack.Push(LRTable[stateStack.Peek()][action.Item3].Item2);
                        nodeStack.Push(n);
                    }
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("Line:{0} ERROR: " + e.Message, e.Source);
            int stackCount = stateStack.Count;
            Console.WriteLine("\tStateStack Contents:");
            while (stackCount-- > 0)
            {
                Console.WriteLine("\t\t" + stateStack.Pop().ToString());
            }
            stackCount = nodeStack.Count;
            Console.WriteLine("\tNodeStack Contents:");
            while (stackCount-- >= 0)
            {
                TreeNode node = nodeStack.Pop();
                Console.Write("\t\t{0}", node.Symbol);
                if (node.Token != null)
                {
                    Console.WriteLine(": {1} {2}", node.Token.Symbol, node.Token.Lexeme);
                }
            }
            throw new Exception(e.Message);
        }
    }
Exemplo n.º 33
0
 //constructor
 public SweepstakesStackManager()
 {
     stack = new Stack <Sweepstakes>();
 }
Exemplo n.º 34
0
        public static Tuple <string, int> performComparison(int index, int line, List <Token> tokens, MainWindow window)
        {
            List <Token> expression = new List <Token>();
            Stack        calculator = new Stack();
            int          j          = index;
            int          flag       = j - 1;

            while (tokens[j].getCategory() != "Line Delimiter" && tokens [j].getLexeme() != "BTW" && tokens[j].getCategory() != "Newline Suppressor")
            {
                /* AN */
                if (tokens[j].getCategory() == "Conjunctor")
                {
                    j++;
                    continue;
                }
                if (tokens[j].getLexeme() == "BTW")
                {
                    j++;
                    break;                     //Leensey:added this to catch <Comparison> <op1> AN <op2> BTW <comment>
                }
                else if (tokens[j].getLexeme() == "!")
                {
                    if (tokens[flag].getLexeme() == "VISIBLE")
                    {
                        j++;
                        break;
                    }
                    else
                    {
                        window.print("\nError(" + line + "): '!' is not used validly!");
                        return(null);                           //different error
                    }
                }
                /* NESTABLE OPERATIONS */
                else if (
                    (tokens[j].getCategory() == "Equality Comparison") ||
                    (tokens[j].getCategory() == "Inequality Comparison") ||
                    (tokens[j].getCategory() == "Addition Operator") ||
                    (tokens[j].getCategory() == "Subtraction Operator") ||
                    (tokens[j].getCategory() == "Multiplication Operator") ||
                    (tokens[j].getCategory() == "Division Operator") ||
                    (tokens[j].getCategory() == "Modulo Operator") ||
                    (tokens[j].getCategory() == "Max Operator") ||
                    (tokens[j].getCategory() == "Min Operator") ||
                    (tokens[j].getCategory() == "Logical AND") ||
                    (tokens[j].getCategory() == "Logical OR") ||
                    (tokens[j].getCategory() == "Logical XOR") ||
                    (tokens[j].getCategory() == "Logical NOT")
                    )
                {
                    expression.Add(tokens[j]);
                }

                /* INFINITE ARITY */
                else if ((tokens[j].getCategory() == "String Concatenator"))
                {
                    var result = InfiniteArity.smoosh(j, line, tokens, window);
                    if (result == null)
                    {
                        return(null);
                    }
                    expression.Add(new Token(result.Item1, "String Literal"));
                    j = result.Item2;
                }
                else if ((tokens[j].getCategory() == "Infinite arity AND") || (tokens[j].getCategory() == "Infinite arity OR"))
                {
                    var result = InfiniteArity.any_all(j, line, tokens, window);
                    if (result == null)
                    {
                        return(null);
                    }
                    expression.Add(new Token((result.Item1 == true.ToString())? "WIN":"FAIL", "Boolean Literal"));
                    j = result.Item2;
                }

                /* LITERALS */
                else if (
                    (tokens[j].getCategory() == "Integer Literal") ||
                    (tokens[j].getCategory() == "Float Literal") ||
                    (tokens[j].getCategory() == "String Literal") ||
                    (tokens[j].getCategory() == "Boolean Literal")
                    )
                {
                    expression.Add(tokens[j]);
                }
                /* VARIABLES */
                else if (tokens[j].getCategory() == "Identifier" || tokens[j].getCategory() == "Implicit Variable")
                {
                    if (window.var_basket.ContainsKey(tokens[j].getLexeme()))
                    {
                        expression.Add(tokens[j]);
                    }
                    else
                    {
                        window.print("Error(" + line + "): " + tokens[j].getLexeme() + " is not declared!");
                        return(null);
                    }
                }
                /* error operand */
                else
                {
                    window.print("Error(" + line + "): " + tokens[j].getLexeme() + " not a valid operand!");
                    return(null);
                }
                j++;
            }
            if (tokens[j - 1].getCategory() == "Conjunctor")
            {
                window.print("Error(" + line + "): Expected another operand after 'AN', before newline!");
                return(null);
            }

            expression.Reverse();

            /*
             * CHECK IF THERE IS 'AN'
             *
             *
             * problem w/ mod of
             */
            for (int i = 0, len = expression.Count; i < len; i++)
            {
                if ((expression[i].getCategory() == "Equality Comparison"))
                {
                    try{
                        bool res = (calculator.Pop().ToString() == calculator.Pop().ToString());
                        calculator.Push(res);
                    }catch (Exception e) {
                        window.print("Error(" + line + "): Invalid expression!");
                        return(null);
                    }
                }
                else if ((expression[i].getCategory() == "Inequality Comparison"))
                {
                    try{
                        bool res = (calculator.Pop().ToString() != calculator.Pop().ToString());
                        calculator.Push(res);
                    }
                    catch (Exception e) {
                        window.print("Error(" + line + "): Invalid expression!");
                        return(null);
                    }
                }
                else if ((expression[i].getCategory() == "Addition Operator"))
                {
                    try{
                        string a = calculator.Pop().ToString().Replace("\"", ""), b = calculator.Pop().ToString().Replace("\"", "");
                        int    x = 0, y = 0; float c = 0, d = 0;

                        if (int.TryParse(a, out x) && int.TryParse(b, out y))
                        {
                            calculator.Push(x + y);
                        }
                        else if (float.TryParse(a, out c) && float.TryParse(b, out d))
                        {
                            float res = c + d;
                            calculator.Push((res % 1 != 0)? res.ToString(): res.ToString() + ".0");
                        }
                        else
                        {
                            window.print("Error(" + line + "): Cannot perform SUM OF '" + a + "' AN '" + b + "' \n");
                        }
                    }
                    catch (Exception e) {
                        window.print("Error(" + line + "): Invalid expression!");
                        return(null);
                    }
                }
                else if ((expression[i].getCategory() == "Subtraction Operator"))
                {
                    try{
                        string a = calculator.Pop().ToString().Replace("\"", ""), b = calculator.Pop().ToString().Replace("\"", "");
                        int    x = 0, y = 0; float c = 0, d = 0;

                        if (int.TryParse(a, out x) && int.TryParse(b, out y))
                        {
                            calculator.Push(x - y);
                        }
                        else if (float.TryParse(a, out c) && float.TryParse(b, out d))
                        {
                            float res = c - d;
                            calculator.Push((res % 1 != 0)? res.ToString(): res.ToString() + ".0");
                        }
                        else
                        {
                            window.print("Error(" + line + "): Cannot perform DIFF OF '" + a + "' AN '" + b + "' \n");
                        }
                    }
                    catch (Exception e) {
                        window.print("Error(" + line + "): Invalid expression!");
                        return(null);
                    }
                }
                else if ((expression[i].getCategory() == "Multiplication Operator"))
                {
                    try{
                        string a = calculator.Pop().ToString().Replace("\"", ""), b = calculator.Pop().ToString().Replace("\"", "");
                        int    x = 0, y = 0; float c = 0, d = 0;

                        if (int.TryParse(a, out x) && int.TryParse(b, out y))
                        {
                            calculator.Push(x * y);
                        }
                        else if (float.TryParse(a, out c) && float.TryParse(b, out d))
                        {
                            float res = c * d;
                            calculator.Push((res % 1 != 0)? res.ToString(): (res.ToString() + ".0"));
                        }
                        else
                        {
                            window.print("Error(" + line + "): Cannot perform PRODUKT OF '" + a + "' AN '" + b + "' \n");
                        }
                    }
                    catch (Exception e) {
                        window.print("Error(" + line + "): Invalid expression!");
                        return(null);
                    }
                }
                else if ((expression[i].getCategory() == "Division Operator"))
                {
                    try{
                        string a = calculator.Pop().ToString().Replace("\"", ""), b = calculator.Pop().ToString().Replace("\"", "");
                        int    x = 0, y = 0; float c = 0, d = 0;

                        if (int.TryParse(a, out x) && int.TryParse(b, out y))
                        {
                            calculator.Push(x / y);
                        }
                        else if (float.TryParse(a, out c) && float.TryParse(b, out d))
                        {
                            float res = c / d;
                            calculator.Push((res % 1 != 0)? res.ToString(): (res.ToString() + ".0"));
                        }
                        else
                        {
                            window.print("Error(" + line + "): Cannot perform QUOSHUNT OF '" + a + "' AN '" + b + "' \n");
                        }
                    }
                    catch (Exception e) {
                        window.print("Error(" + line + "): Invalid expression!");
                        return(null);
                    }
                }
                else if ((expression[i].getCategory() == "Modulo Operator"))
                {
                    try{
                        string a = calculator.Pop().ToString().Replace("\"", ""), b = calculator.Pop().ToString().Replace("\"", "");
                        int    x = 0, y = 0; float c = 0, d = 0;

                        if (int.TryParse(a, out x) && int.TryParse(b, out y))
                        {
                            calculator.Push(x % y);
                        }
                        else if (float.TryParse(a, out c) && float.TryParse(b, out d))
                        {
                            float res = c % d;
                            calculator.Push((res % 1 != 0)? res.ToString(): (res.ToString() + ".0"));
                        }
                        else
                        {
                            window.print("Error(" + line + "): Cannot perform MOD OF '" + a + "' AN '" + b + "' \n");
                        }
                    }
                    catch (Exception e) {
                        window.print("Error(" + line + "): Invalid expression!");
                        return(null);
                    }
                }
                else if ((expression[i].getCategory() == "Max Operator"))
                {
                    try{
                        string a = calculator.Pop().ToString().Replace("\"", ""), b = calculator.Pop().ToString().Replace("\"", "");
                        int    x = 0, y = 0; float c = 0, d = 0;

                        if (int.TryParse(a, out x) && int.TryParse(b, out y))
                        {
                            calculator.Push((x > y)? x:y);
                        }
                        else if (float.TryParse(a, out c) && float.TryParse(b, out d))
                        {
                            float res = (c > d)? c:d;
                            calculator.Push((res % 1 != 0)? res.ToString(): (res.ToString() + ".0"));
                        }
                        else
                        {
                            window.print("Error(" + line + "): Cannot perform BIGGR OF '" + a + "' AN '" + b + "' \n");
                        }
                    }
                    catch (Exception e) {
                        window.print("Error(" + line + "): Invalid expression!");
                        return(null);
                    }
                }
                else if ((expression[i].getCategory() == "Min Operator"))
                {
                    try{
                        try{
                            string a = calculator.Pop().ToString().Replace("\"", ""), b = calculator.Pop().ToString().Replace("\"", "");
                            int    x = 0, y = 0; float c = 0, d = 0;

                            if (int.TryParse(a, out x) && int.TryParse(b, out y))
                            {
                                calculator.Push((x < y)? x:y);
                            }
                            else if (float.TryParse(a, out c) && float.TryParse(b, out d))
                            {
                                float res = (c < d)? c:d;
                                calculator.Push((res % 1 != 0)? res.ToString(): (res.ToString() + ".0"));
                            }
                            else
                            {
                                window.print("Error(" + line + "): Cannot perform SMALLR OF '" + a + "' AN '" + b + "' \n");
                            }
                        }
                        catch (Exception e) {
                            window.print("Error(" + line + "): Invalid expression!");
                            return(null);
                        }
                    }
                    catch (Exception e) {
                        window.print("Error(" + line + "): Invalid expression!");
                        return(null);
                    }
                }
                else if ((expression[i].getCategory() == "Logical AND"))
                {
                    try{
                        bool a = (bool)calculator.Pop(), b = (bool)calculator.Pop();
                        calculator.Push(a && b);
                    }
                    catch (Exception e) {
                        window.print("Error(" + line + "): Invalid expression!");
                        return(null);
                    }
                }
                else if ((expression[i].getCategory() == "Logical OR"))
                {
                    try{
                        bool a = (bool)calculator.Pop(), b = (bool)calculator.Pop();
                        calculator.Push(a || b);
                    }
                    catch (Exception e) {
                        window.print("Error(" + line + "): Invalid expression!");
                        return(null);
                    }
                }
                else if ((expression[i].getCategory() == "Logical XOR"))
                {
                    try{
                        bool a = (bool)calculator.Pop(), b = (bool)calculator.Pop();
                        calculator.Push(a ^ b);
                    }
                    catch (Exception e) {
                        window.print("Error(" + line + "): Invalid expression!");
                        return(null);
                    }
                }
                else if ((expression[i].getCategory() == "Logical NOT"))
                {
                    try{
                        bool a = (bool)calculator.Pop();
                        calculator.Push(!a);
                    }
                    catch (Exception e) {
                        window.print("Error(" + line + "): Invalid expression!");
                        return(null);
                    }
                }
                /* OPERAND */
                else
                {
                    /* boolean */
                    if (expression[i].getCategory() == "Boolean Literal")
                    {
                        calculator.Push(expression[i].getLexeme() == "WIN"? true: false);
                    }

                    /*YARN, NUMBR, NUMBAR*/
                    else if (
                        (expression[i].getCategory() == "String Literal") ||
                        (expression[i].getCategory() == "Integer Literal") ||
                        (expression[i].getCategory() == "Float Literal")
                        )
                    {
                        calculator.Push(expression[i].getLexeme());
                    }

                    else if (expression[i].getCategory() == "Identifier" || expression[i].getCategory() == "Implicit Variable")
                    {
                        if (window.var_basket[expression[i].getLexeme()] == "WIN" || window.var_basket[expression[i].getLexeme()] == "FAIL")
                        {
                            calculator.Push(window.var_basket[expression[i].getLexeme()] == "WIN" ? true: false);
                        }
                        else
                        {
                            calculator.Push(window.var_basket[expression[i].getLexeme()]);
                        }
                    }
                    else
                    {
                        window.print("Error(" + line + "): " + expression[i].getLexeme() + " invalid operand!");
                    }
                }
            }
            if (calculator.Count != 1)
            {
                window.print("Error(" + line + "): Invalid expression!");
                return(null);
            }
            return(new Tuple <string, int>(calculator.Pop().ToString(), j - 1));         // j-1 para mabilang yung line delimiter sa syntax analyzer
        }
Exemplo n.º 35
0
 public GameHistory()
 {
     History = new Stack <RobotMemento>();
 }
Exemplo n.º 36
0
 internal LargeBufferPool(int bufferSize, int limit)
     : base(bufferSize, limit)
 {
     this.items = new Stack <byte[]>(limit);
 }
Exemplo n.º 37
0
        public IMetaValue Parse(MetaFile meta)
        {
            var blockKeys = new List <int>();
            var blocks    = new List <List <IMetaValue> >();

            //////////////////////////////////////////////////
            // first step: flat conversion
            //////////////////////////////////////////////////

            foreach (var block in meta.DataBlocks)
            {
                blockKeys.Add(block.StructureNameHash);
                switch (block.StructureNameHash)
                {
                case 0x00000007:
                    blocks.Add(ReadBlock(block, () => new MetaGeneric()));     // has no special type declaration in .meta -> pointer
                    break;

                case 0x00000010:
                    blocks.Add(ReadBlock(block, () => new MetaByte_A()));     // char_array
                    break;

                case 0x00000011:
                    blocks.Add(ReadBlock(block, () => new MetaByte_B()));      // has no special type declaration in .meta -> string
                    break;

                case 0x00000013:
                    blocks.Add(ReadBlock(block, () => new MetaInt16_B()));     // probably short_array
                    break;

                case 0x00000015:
                    blocks.Add(ReadBlock(block, () => new MetaInt32_B()));     // int_array
                    break;

                case 0x00000021:
                    blocks.Add(ReadBlock(block, () => new MetaFloat()));     // float_array
                    break;

                case 0x00000033:
                    blocks.Add(ReadBlock(block, () => new MetaFloat4_XYZ()));     // vector3_array
                    break;

                case 0x0000004A:
                    blocks.Add(ReadBlock(block, () => new MetaInt32_Hash()));     // probably list of <Item>HASH_OF_SOME_NAME</Item>
                    break;

                default:
                    blocks.Add(ReadBlock(block, () => new MetaStructure(meta, GetInfo(meta, block.StructureNameHash))));     // has no special type declaration in .meta -> structure
                    break;
                }
            }

            //////////////////////////////////////////////////
            // second step: map references
            //////////////////////////////////////////////////

            var referenced = new HashSet <IMetaValue>();
            var stack      = new Stack <IMetaValue>();

            foreach (var block in blocks)
            {
                foreach (var entry in block)
                {
                    stack.Push(entry);
                }
            }
            while (stack.Count > 0)
            {
                var entry = stack.Pop();
                if (entry is MetaArray)
                {
                    var arrayEntry     = entry as MetaArray;
                    var realBlockIndex = arrayEntry.BlockIndex - 1;
                    if (realBlockIndex >= 0)
                    {
                        arrayEntry.Entries = new List <IMetaValue>();
                        var realEntryIndex = arrayEntry.Offset / GetSize(meta, blockKeys[realBlockIndex]);
                        for (int i = 0; i < arrayEntry.NumberOfEntries; i++)
                        {
                            var x = blocks[realBlockIndex][realEntryIndex + i];
                            arrayEntry.Entries.Add(x);
                            referenced.Add(x);
                        }
                    }
                }
                if (entry is MetaCharPointer)
                {
                    var charPointerEntry = entry as MetaCharPointer;
                    var realBlockIndex   = charPointerEntry.DataBlockIndex - 1;
                    if (realBlockIndex >= 0)
                    {
                        string value = "";
                        for (int i = 0; i < charPointerEntry.StringLength; i++)
                        {
                            var x = (MetaByte_A)blocks[realBlockIndex][i + charPointerEntry.DataOffset];
                            value += (char)x.Value;
                        }
                        charPointerEntry.Value = value;
                    }
                }
                if (entry is MetaDataBlockPointer)
                {
                    var dataPointerEntry = entry as MetaDataBlockPointer;
                    var realBlockIndex   = dataPointerEntry.BlockIndex - 1;
                    if (realBlockIndex >= 0)
                    {
                        byte[] b = ToBytes(meta.DataBlocks[realBlockIndex].Data);
                        dataPointerEntry.Data = b;
                    }
                }
                if (entry is MetaGeneric)
                {
                    var genericEntry   = entry as MetaGeneric;
                    var realBlockIndex = genericEntry.BlockIndex - 1;
                    var realEntryIndex = genericEntry.Offset * 16 / GetSize(meta, blockKeys[realBlockIndex]);
                    var x = blocks[realBlockIndex][realEntryIndex];
                    genericEntry.Value = x;
                    referenced.Add(x);
                }
                if (entry is MetaStructure)
                {
                    var structureEntry = entry as MetaStructure;
                    foreach (var x in structureEntry.Values)
                    {
                        stack.Push(x.Value);
                    }
                }
            }

            //////////////////////////////////////////////////
            // third step: find root
            //////////////////////////////////////////////////

            var rootSet = new HashSet <IMetaValue>();

            foreach (var x in blocks)
            {
                foreach (var y in x)
                {
                    if (y is MetaStructure && !referenced.Contains(y))
                    {
                        rootSet.Add(y);
                    }
                }
            }

            var res = rootSet.First();

            if (res != blocks[(int)meta.RootBlockIndex - 1][0])
            {
                throw new System.Exception("wrong root block index");
            }

            return(res);
        }
Exemplo n.º 38
0
 public void Dispose()
 {
     progress = null;
 }
Exemplo n.º 39
0
 protected override Node SelectEnemyNeighbourNode(Stack <UnitMove> previousUnitsMoves = null)
 {
     return(null);
 }
Exemplo n.º 40
0
    private void addStates(State state, Dictionary <string, HashSet <LR0Item> > transitions, Dictionary <HashSet <LR0Item>, State> seen, Stack <State> todo)
    {
        foreach (KeyValuePair <string, HashSet <LR0Item> > key in transitions)
        {
            computeClosure(key.Value);
            if (!checkSeen(key.Value, seen))
            {
                State newState = new State();
                newState.Items = key.Value;

                states.Add(newState);
                seen.Add(key.Value, newState);
                todo.Push(newState);
            }
            state.Transitions[key.Key] = seen[key.Value];
        }
    }
Exemplo n.º 41
0
 protected virtual void Analyze(Stack stack, string stackPointer)
 {
 }
Exemplo n.º 42
0
 public void Reset()
 {
     progress = null;
     current  = null;
 }
Exemplo n.º 43
0
        /// <summary>
        /// Поиск всех вариантов движения, начиная с указанного отделения.
        /// </summary>
        /// <param name="firstDivision">Первое отделение (откуда старт)</param>
        /// <param name="ms">Движения между отделениями</param>
        /// <returns>Результат в виде списка индексов переходов между отделениями в исходном массиве</returns>
        static List <Movement> FindMovements(int firstDivision, Movement[] ms, List <List <int> > ways, List <List <int> > uniqueWays)
        {
            var counter = 0;

            var    MyStack   = new Stack <Movement>();
            var    startedge = (ms.Where(edge => edge.From == firstDivision)).ToArray();
            Random random    = new Random();
            int    start2    = random.Next(0, startedge.Length);

            MyStack.Push(startedge[start2]);

            List <int> sublist = new List <int>();

            while (MyStack.Count > 0 && counter != 29)
            {
                var edge = MyStack.Pop();

                sublist.Add(edge.index);
                counter++;
                edge.visited = true;
                var rnd = new Random();
                var adj = ms.Where(mov => mov.From == edge.To).OrderBy(x => rnd.Next()).ToList();
                // var shuffledList = adj.OrderBy(x => rnd.Next()).ToList();


                foreach (var neighbor in adj)
                {
                    if (neighbor.visited != true)
                    {
                        MyStack.Push(neighbor);
                    }
                    else if (adj.Count() == 0 || adj.All(u => u.visited == true))
                    {
                        //var lastItem = ways[0].LastOrDefault();
                        //ways[0].RemoveAt(ways[0].Count()-1);
                        // Console.WriteLine("out of options");
                        var adj1 = ms.Where(mov => mov.To == edge.From);
                        foreach (var neighbor1 in adj1)
                        {
                            neighbor1.visited = false;
                        }
                    }
                }
            }
            if (counter == 29)
            {
                if (!ways.Contains(sublist) && ways.Distinct().ToList().Count < 1944)
                {
                    ways.Add(sublist);

                    foreach (var sub in ms)
                    {
                        sub.visited = false;
                    }

                    var a = ways.Distinct().ToList().Count;
                    foreach (var sub in ways.Distinct().ToList())
                    {
                        bool isUnique = sub.Distinct().Count() == sub.Count();
                        if (isUnique == true)
                        {
                            foreach (var value in sub)
                            {
                                Console.WriteLine("unique ways number: " + a);
                                //Console.Write(value);
                            }
                        }
                    }
                    // Console.WriteLine(ways.Where(x => x.Distinct().ToList().Count == x.Count).SelectMany(x => x).ToList());
                    FindMovements(firstDivision, ms, ways, uniqueWays);
                }
            }
            return(null);
        }
Exemplo n.º 44
0
 public override bool RearrangeIfCan(Stack <UnitMove> unitsMovesStack)
 {
     return(false);
 }
Exemplo n.º 45
0
        static void Main()
        {
            Console.WriteLine("Bienvenido al gestior de patentes.\nCrearemos una pila donde almacenaremos los datos que ingreses.");
            Stack  pila_patentes = new Stack();
            string guardamos;

            menu();

            int seleccion()
            {
                int opcion;

                int[] posibles = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0 };
                do
                {
                    Console.WriteLine("Selecciona una opción del menú.");
                    Console.WriteLine("1. Borrar pila.");
                    Console.WriteLine("2. Agregar patente a pila.");
                    Console.WriteLine("3. Eliminar patente.");                    //Elimina CIMA
                    Console.WriteLine("4. Mostrar las patentes almacenadas.");
                    Console.WriteLine("5. Mostrar la primer patente ingresada."); // PISO de pila
                    Console.WriteLine("6. Mostrar la última patente ingresada."); // CIMA de pila
                    Console.WriteLine("7. Mostrar la cantidad de patentes almacenadas.");
                    Console.WriteLine("8. Buscar patente.");
                    Console.WriteLine("9. Función"); //Inventar una función.
                    Console.WriteLine("0. Salir del programa.");
                    opcion = Convert.ToInt32(Console.ReadLine());
                    return(opcion);
                } while (posibles.Contains(opcion) == false);
            }

            void menu()
            {
                switch (seleccion())
                {
                case 1:
                    pila_patentes.Clear();
                    Console.WriteLine("Se han eliminado todas las patentes de la pila.");
                    menu();
                    break;

                case 2:
                    agregar(ref pila_patentes);
                    menu();
                    break;

                case 3:
                    eliminar_elemento(ref pila_patentes);
                    menu();
                    break;

                case 4:
                    mostrar_patentes(ref pila_patentes);
                    menu();
                    break;

                case 5:
                    mostrar_primera(ref pila_patentes);
                    menu();
                    break;

                case 6:
                    mostrar_ultima(ref pila_patentes);
                    menu();
                    break;

                case 7:
                    Console.WriteLine("La pila tiene: {0} patentes cargadas.", cantidad_elementos(ref pila_patentes));
                    menu();
                    break;

                case 8:
                    buscar(ref pila_patentes);
                    menu();
                    break;

                case 9:
                    Console.WriteLine("Agregar Función 9");
                    break;

                case 0:
                    Console.WriteLine("Antes de salir, deseas guardar la información en un archivo? si/no");
                    guardamos = Console.ReadLine().ToLower();
                    if (guardamos == "si")
                    {
                        guardar_info(ref pila_patentes);
                        Thread.Sleep(1500);
                        salir();
                    }
                    else
                    {
                        salir();
                    }
                    break;
                }
                Console.ReadLine();
            }
        }
 public SecurityParser() : base()
 {
     stack = new Stack();
 }
Exemplo n.º 47
0
 public MinStack()
 {
     minStack = new Stack <int>();
     stack    = new Stack <int>();
 }
Exemplo n.º 48
0
 /// <summary>
 /// Initializes a new instance of the PSTransactionManager class.
 /// </summary>
 internal PSTransactionManager()
 {
     _transactionStack = new Stack <PSTransaction>();
     _transactionStack.Push(null);
 }
Exemplo n.º 49
0
        private static unsafe void QuickSort(IntPtr array, Comparer <TemplateStructType> comparer, Stack <int> stack)
        {
            TemplateStructType *pointer = (TemplateStructType *)array.ToPointer();

            while (stack.Count > 0)
            {
                int start = stack.Pop();
                int end   = stack.Pop();
                int index = QuickSortPartion(pointer, start, end, comparer);
                if (start < index - 1)
                {
                    stack.Push(index - 1); stack.Push(start);
                }
                if (index + 1 < end)
                {
                    stack.Push(end); stack.Push(index + 1);
                }
            }
        }
Exemplo n.º 50
0
 // For testing purpose
 public Context(Stack <int> s, Dictionary <string, int> d)
 {
     this.S = s;
     this.D = d;
 }
Exemplo n.º 51
0
        private void OnNext(object obj)
        {
            if (obj.ToString() == "Next")
            {
                click += 1;
                if (ChartViewModel.Item == null)
                {
                    if (CurrentItem != null)
                    {
                        ((CurrentItem as OrgNodeViewModel).Content as Employee).IsFocus = NodeFocusState.Normal;
                    }
                    if (PreviousItem != null)
                    {
                        ((PreviousItem as OrgNodeViewModel).Content as Employee).IsFocus = NodeFocusState.Normal;
                    }
                    ChartViewModel.StartSearch();
                    ChartViewModel.Item = ChartViewModel.Searchview.SearchResult.GetEnumerator();
                    MoveNext();
                    previousstack = new Stack <OrgNodeViewModel>();
                }
                else
                {
                    PreviousItem = CurrentItem;
                    if (PreviousItem != null)
                    {
                        ((PreviousItem as OrgNodeViewModel).Content as Employee).IsFocus = NodeFocusState.Normal;
                    }

                    if (PreviousItem != null && previousstack != null)
                    {
                        ((PreviousItem as OrgNodeViewModel).Content as Employee).IsFocus = NodeFocusState.Normal;
                        if (!previousstack.Contains((PreviousItem as OrgNodeViewModel)))
                        {
                            (previousstack as Stack <OrgNodeViewModel>).Push((PreviousItem as OrgNodeViewModel));
                        }
                    }
                    MoveNext();
                    if (CurrentItem == null)
                    {
                        ChartViewModel.Item.Reset();
                        MoveNext();
                    }
                }
            }
            else if (obj.ToString() == "Previous")
            {
                if (previousstack == null)
                {
                    previousstack = new Stack <OrgNodeViewModel>();
                    foreach (var item in ChartViewModel.Searchview.SearchResult)
                    {
                        previousstack.Push(item as OrgNodeViewModel);
                    }
                }
                if (previousstack != null && previousstack.Count > 0)
                {
                    if (CurrentItem != null)
                    {
                        ((CurrentItem as OrgNodeViewModel).Content as Employee).IsFocus = NodeFocusState.Normal;
                    }
                    if (previous == null)
                    {
                        previous = previousstack.GetEnumerator();
                        MovePrevious();
                    }
                    else
                    {
                        PreviousItem = previous.Current;
                        if (previous.Current != null)
                        {
                            if (previousstack.Last <OrgNodeViewModel>() == previous.Current)
                            {
                                ((PreviousItem as OrgNodeViewModel).Content as Employee).IsFocus = NodeFocusState.Normal;
                                previous.Reset();
                            }
                            else
                            {
                                ((PreviousItem as OrgNodeViewModel).Content as Employee).IsFocus = NodeFocusState.Normal;
                            }
                        }
                        else
                        {
                            previous.Reset();
                        }
                        MovePrevious();
                    }
                }
            }
        }
Exemplo n.º 52
0
        protected virtual void CreateRootBreadcrumbItem(Stack <BreadcrumbItemViewModel> stack, string homeUrl, CultureInfo cultureInfo)
        {
            var item = CreateBreadcrumbItem(LocalizeString("General", "L_Home", cultureInfo), homeUrl);

            stack.Push(item);
        }
Exemplo n.º 53
0
 public NumberingListStyleCollection(MainDocumentPart mainPart)
 {
     this.mainPart     = mainPart;
     this.numInstances = new Stack <KeyValuePair <Int32, int> >();
     InitNumberingIds();
 }
Exemplo n.º 54
0
 public Context()
 {
     S = new Stack <int>();
     D = new Dictionary <string, int>();
 }
    public static void Main()
    {
        string[] input = Console.ReadLine().Split();

        Queue <string> waitingForServiceVehicles = new Queue <string>(input);

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

        StringBuilder sb = new StringBuilder();

        string command = Console.ReadLine();

        while (command != "End")
        {
            switch (command)
            {
            case "Service":
                if (waitingForServiceVehicles.Count > 0)
                {
                    string currentVehicle = waitingForServiceVehicles.Dequeue();

                    sb.AppendLine($"Vehicle {currentVehicle} got served.");

                    servedVehicles.Push(currentVehicle);
                }

                break;

            case "History":

                sb.AppendLine(string.Join(", ", servedVehicles));
                break;

            default:
                string[] vehicleData = command.Split('-');
                string   modelName   = vehicleData[1];

                if (servedVehicles.Contains(modelName))
                {
                    sb.AppendLine("Served.");
                }
                else if (waitingForServiceVehicles.Contains(modelName))
                {
                    sb.AppendLine("Still waiting for service.");
                }
                break;
            }

            command = Console.ReadLine();
        }

        if (waitingForServiceVehicles.Count > 0)
        {
            sb.AppendLine($"Vehicles for service: {string.Join(", ", waitingForServiceVehicles)}");
        }

        if (servedVehicles.Count > 0)
        {
            sb.AppendLine($"Served vehicles: {string.Join(", ", servedVehicles)}");
        }


        Console.Write(sb);
    }
Exemplo n.º 56
0
        public JsValue Serialize(JsValue value, JsValue replacer, JsValue space)
        {
            _stack = new Stack <object>();

            // for JSON.stringify(), any function passed as the first argument will return undefined
            // if the replacer is not defined. The function is not called either.
            if (value.Is <ICallable>() && replacer == Undefined.Instance)
            {
                return(Undefined.Instance);
            }

            if (replacer.IsObject())
            {
                if (replacer.Is <ICallable>())
                {
                    _replacerFunction = replacer;
                }
                else
                {
                    var replacerObj = replacer.AsObject();
                    if (replacerObj.Class == "Array")
                    {
                        _propertyList = new List <string>();
                    }

                    foreach (var property in replacerObj.GetOwnProperties().Select(x => x.Value))
                    {
                        JsValue v    = _engine.GetValue(property);
                        string  item = null;
                        if (v.IsString())
                        {
                            item = v.AsString();
                        }
                        else if (v.IsNumber())
                        {
                            item = TypeConverter.ToString(v);
                        }
                        else if (v.IsObject())
                        {
                            var propertyObj = v.AsObject();
                            if (propertyObj.Class == "String" || propertyObj.Class == "Number")
                            {
                                item = TypeConverter.ToString(v);
                            }
                        }

                        if (item != null && !_propertyList.Contains(item))
                        {
                            _propertyList.Add(item);
                        }
                    }
                }
            }

            if (space.IsObject())
            {
                var spaceObj = space.AsObject();
                if (spaceObj.Class == "Number")
                {
                    space = TypeConverter.ToNumber(spaceObj);
                }
                else if (spaceObj.Class == "String")
                {
                    space = TypeConverter.ToString(spaceObj);
                }
            }

            // defining the gap
            if (space.IsNumber())
            {
                if (space.AsNumber() > 0)
                {
                    _gap = new System.String(' ', (int)System.Math.Min(10, space.AsNumber()));
                }
                else
                {
                    _gap = string.Empty;
                }
            }
            else if (space.IsString())
            {
                var stringSpace = space.AsString();
                _gap = stringSpace.Length <= 10 ? stringSpace : stringSpace.Substring(0, 10);
            }
            else
            {
                _gap = string.Empty;
            }

            var wrapper = _engine.Object.Construct(Arguments.Empty);

            wrapper.DefineOwnProperty("", new PropertyDescriptor(value, true, true, true), false);

            return(Str("", wrapper));
        }
Exemplo n.º 57
0
 public void Reset()
 {
     this.mCurrentView    = new Stack <RunTimeView>();
     this.mCurrentProject = null;
 }
Exemplo n.º 58
0
 public StateController()
 {
     rollBackStack = new Stack <T>();
     forwardStack  = new Stack <T>();
 }
Exemplo n.º 59
0
 internal void SaveStack(vThread from)
 {
     currentstack = new Stack <object>(from.stack);
 }
Exemplo n.º 60
0
 static void mostrar_ultima(ref Stack pila)
 {
     Console.WriteLine(pila.Peek());
 }