Ejemplo n.º 1
0
 public int solution(int[] A, int[] B)
 {
     var ret = 0;
     var up = new System.Collections.Generic.Stack<int>();
     for (int i = A.Length - 1; i >= 0; i--)
     {
         if (B[i] == 1)
         {
             while (up.Count > 0)
             {
                 var fishSize = up.Peek();
                 if (A[i] > fishSize)
                     up.Pop(); // remove one from stack
                 else
                     break; // downFish was eaten, break circle
             }
             if (up.Count == 0)
                 ret++; // downFish ate all upFishes
         }
         else
         {
             up.Push(A[i]);
         }
     }
     while (up.Count > 0)
     {
         var fishSize = up.Pop();
         ret++;
     }
     return ret;
 }
Ejemplo n.º 2
0
 public static bool verifyPalindromeIterate(LinkedNode head)
 {
     System.Collections.Generic.Stack<double> stack = new System.Collections.Generic.Stack<double>();
     LinkedNode SlowRunner = head;
     LinkedNode FastRunner = head;
     while (FastRunner != null && FastRunner.Next != null)
     {
         stack.Push(SlowRunner.Data);
         FastRunner = FastRunner.Next.Next;
         SlowRunner = SlowRunner.Next;
     }
     SlowRunner = SlowRunner.Next;
     while (SlowRunner!=null)
     {
         if (stack.Pop() == SlowRunner.Data)
         {
             SlowRunner = SlowRunner.Next;
         }
         else
         {
             return false;
         }
     }
     return true;
 }
Ejemplo n.º 3
0
 public int solution(string S)
 {
     var stack = new System.Collections.Generic.Stack<char>();
     foreach (var s in S)
     {
         if (-1 == "{[(".IndexOf(s))
         {
             if (stack.Count == 0)
                 return 0;
             var z = stack.Pop();
             switch (s)
             {
                 case '}':
                     if (z != '{')
                         return 0;
                     break;
                 case ']':
                     if (z != '[')
                         return 0;
                     break;
                 case ')':
                     if (z != '(')
                         return 0;
                     break;
             }
         }
         else
         {
             stack.Push(s);
         }
     }
     return (stack.Count == 0) ? 1 : 0;
 }
Ejemplo n.º 4
0
    //Evaluating RPN
    public static void evalu(string output)
    {
        int num1 = 0;
            int num2 = 0;
            System.Collections.Generic.Stack<int> myStack = new System.Collections.Generic.Stack<int>();
            foreach (char token in output)
            {
                if (Char.IsNumber(token) == true)
                {
                    myStack.Push(int.Parse(token.ToString()));
                }
                if (token == '+' || token == '-' || token == '*' || token == '/')
                {
                    if (token == '+')
                    {
                        num1 = myStack.Peek();
                        myStack.Pop();
                        num2 = myStack.Peek();
                        myStack.Pop();
                        myStack.Push(num1 + num2);
                    }

                    if (token == '-')
                    {
                        num1 = myStack.Peek();
                        myStack.Pop();
                        num2 = myStack.Peek();
                        myStack.Pop();
                        myStack.Push(num2 - num1);
                    }
                    if (token == '*')
                    {
                        num1 = myStack.Peek();
                        myStack.Pop();
                        num2 = myStack.Peek();
                        myStack.Pop();
                        myStack.Push(num1 * num2);
                    }
                    if (token == '/')
                    {
                        num1 = myStack.Peek();
                        myStack.Pop();
                        num2 = myStack.Peek();
                        myStack.Pop();
                        myStack.Push(num1 / num2);
                    }
                }
            }
        PrintValues(myStack, ' ');
    }
Ejemplo n.º 5
0
            public int solution(int[] H)
            {
                var blockCount = 0;
                var stack = new System.Collections.Generic.Stack<Tuple<int, int>>();

                foreach (var h in H)
                {
                    var lastBlockBottom = 0;
                    var lastBlockTop = 0;
                    if (stack.Count != 0)
                    {
                        var lastBlock = stack.Peek();
                        lastBlockBottom = lastBlock.Item1;
                        lastBlockTop = lastBlock.Item2;
                    }
                    if (h > lastBlockTop)
                    {
                        stack.Push(new Tuple<int, int>(lastBlockTop, h));
                    }
                    else if (h < lastBlockTop)
                    {
                        stack.Pop();
                        blockCount++;

                        while (h < lastBlockBottom)
                        {
                            var lastBlock = stack.Pop();
                            blockCount++;
                            lastBlockBottom = lastBlock.Item1;
                        }
                        if (h > lastBlockBottom)
                        {
                            stack.Push(new Tuple<int, int>(lastBlockBottom, h));
                        }
                    }
                }

                return blockCount + stack.Count;
            }
        public static void Main()
        {
            System.Collections.Generic.Stack<int> stack =
                new System.Collections.Generic.Stack<int>();
            int number;
            // ...

            // This code is conceptual, not the actual code.
            while(stack.Pop() != -1) //this is actually not the right logic, but the point is the while, not stack
            {
                number = stack.Peek();
                Console.WriteLine(number);
            }
        }
Ejemplo n.º 7
0
 public static System.Collections.Generic.List<i3DML.ObjectModel.Light> GetWorldLights(this i3DML.ObjectModel.World w)
 {
     var ret = new System.Collections.Generic.List<i3DML.ObjectModel.Light>();
     var stack = new System.Collections.Generic.Stack<i3DML.ObjectModel.PlaceBase>();
     stack.Push(w);
     while (stack.Count > 0)
     {
         i3DML.ObjectModel.PlaceBase p = stack.Pop();
         for (int i = 0; i < p.Length; i++)
         {
             if (p[i] is i3DML.ObjectModel.Light)
                 ret.Add(p[i] as i3DML.ObjectModel.Light);
             if (p[i] is i3DML.ObjectModel.PlaceBase)
                 stack.Push(p[i] as i3DML.ObjectModel.PlaceBase);
         }
     }
     return ret;
 }
Ejemplo n.º 8
0
 /// <summary>
 /// Executes a quicksort algorithm given the value and swap methods.
 /// </summary>
 public static void Sort(Func<long, long> value, Action<long, long> swap, long left, long right)
 {
     if (left < right)
     {
         var stack = new System.Collections.Generic.Stack<Pair>();
         stack.Push(new Pair(left, right));
         while (stack.Count > 0)
         {
             var pair = stack.Pop();
             var pivot = QuickSort.Partition(value, swap, pair.Left, pair.Right);
             if (pair.Left < pivot)
             {
                 stack.Push(new Pair(pair.Left, pivot - 1));
             }
             if (pivot < pair.Right)
             {
                 stack.Push(new Pair(pivot + 1, pair.Right));
             }
         }
     }
 }
Ejemplo n.º 9
0
        //revision:clear 12/2/2012
        public static bool validatePushPop(double[] pop)
        {
            int i = 0, length = pop.Length;
            bool[] positioned = new bool[1 + length];
            System.Collections.Generic.Stack<int> s = new System.Collections.Generic.Stack<int>();
            while (i < length)
            {
                if (s.Count == 0 || s.Peek() != pop[i])
                {
                    int n = 1; bool f = true;
                    while (n <= pop[i])
                    {
                        if (!positioned[n])
                        {
                            f = false;
                            s.Push(n);
                            positioned[n] = true;
                        }
                        n++;
                    }
                    if (f)
                    {
                        return false;
                    }
                }
                else if (s.Count != 0 && s.Peek() == pop[i])
                {
                    s.Pop();
                    i++;
                }
                else
                {
                    return false;
                }

            }

            return true;
        }
Ejemplo n.º 10
0
        private static SelectionCriterion _ParseCriterion(String s)
        {
            if (s == null)
            {
                return(null);
            }

            // shorthand for filename glob
            if (s.IndexOf(" ") == -1)
            {
                s = "name = " + s;
            }

            // inject spaces after open paren and before close paren
            string[] prPairs = { @"\((\S)", "( $1", @"(\S)\)", "$1 )", };
            for (int i = 0; i + 1 < prPairs.Length; i += 2)
            {
                Regex rgx = new Regex(prPairs[i]);
                s = rgx.Replace(s, prPairs[i + 1]);
            }

            // split the expression into tokens
            string[] tokens = s.Trim().Split(' ', '\t');

            if (tokens.Length < 3)
            {
                throw new ArgumentException(s);
            }

            SelectionCriterion current = null;

            LogicalConjunction pendingConjunction = LogicalConjunction.NONE;

            ParseState state;
            var        stateStack = new System.Collections.Generic.Stack <ParseState>();
            var        critStack  = new System.Collections.Generic.Stack <SelectionCriterion>();

            stateStack.Push(ParseState.Start);

            for (int i = 0; i < tokens.Length; i++)
            {
                switch (tokens[i].ToLower())
                {
                case "and":
                case "xor":
                case "or":
                    state = stateStack.Peek();
                    if (state != ParseState.CriterionDone)
                    {
                        throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));
                    }

                    if (tokens.Length <= i + 3)
                    {
                        throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));
                    }

                    pendingConjunction = (LogicalConjunction)Enum.Parse(typeof(LogicalConjunction), tokens[i].ToUpper());
                    current            = new CompoundCriterion {
                        Left = current, Right = null, Conjunction = pendingConjunction
                    };
                    stateStack.Push(state);
                    stateStack.Push(ParseState.ConjunctionPending);
                    critStack.Push(current);
                    break;

                case "(":
                    state = stateStack.Peek();
                    if (state != ParseState.Start && state != ParseState.ConjunctionPending && state != ParseState.OpenParen)
                    {
                        throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));
                    }

                    if (tokens.Length <= i + 4)
                    {
                        throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));
                    }

                    stateStack.Push(ParseState.OpenParen);
                    break;

                case ")":
                    state = stateStack.Pop();
                    if (stateStack.Peek() != ParseState.OpenParen)
                    {
                        throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));
                    }

                    stateStack.Pop();
                    stateStack.Push(ParseState.CriterionDone);
                    break;

                case "atime":
                case "ctime":
                case "mtime":
                    if (tokens.Length <= i + 2)
                    {
                        throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));
                    }

                    DateTime t;
                    try
                    {
                        t = DateTime.ParseExact(tokens[i + 2], "yyyy-MM-dd-HH:mm:ss", null);
                    }
                    catch (FormatException)
                    {
                        t = DateTime.ParseExact(tokens[i + 2], "yyyy-MM-dd", null);
                    }
                    t       = DateTime.SpecifyKind(t, DateTimeKind.Local).ToUniversalTime();
                    current = new TimeCriterion
                    {
                        Which    = (WhichTime)Enum.Parse(typeof(WhichTime), tokens[i]),
                        Operator = (ComparisonOperator)EnumUtil.Parse(typeof(ComparisonOperator), tokens[i + 1]),
                        Time     = t
                    };
                    i += 2;
                    stateStack.Push(ParseState.CriterionDone);
                    break;


                case "length":
                case "size":
                    if (tokens.Length <= i + 2)
                    {
                        throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));
                    }

                    Int64  sz = 0;
                    string v  = tokens[i + 2];
                    if (v.ToUpper().EndsWith("K"))
                    {
                        sz = Int64.Parse(v.Substring(0, v.Length - 1)) * 1024;
                    }
                    else if (v.ToUpper().EndsWith("KB"))
                    {
                        sz = Int64.Parse(v.Substring(0, v.Length - 2)) * 1024;
                    }
                    else if (v.ToUpper().EndsWith("M"))
                    {
                        sz = Int64.Parse(v.Substring(0, v.Length - 1)) * 1024 * 1024;
                    }
                    else if (v.ToUpper().EndsWith("MB"))
                    {
                        sz = Int64.Parse(v.Substring(0, v.Length - 2)) * 1024 * 1024;
                    }
                    else if (v.ToUpper().EndsWith("G"))
                    {
                        sz = Int64.Parse(v.Substring(0, v.Length - 1)) * 1024 * 1024 * 1024;
                    }
                    else if (v.ToUpper().EndsWith("GB"))
                    {
                        sz = Int64.Parse(v.Substring(0, v.Length - 2)) * 1024 * 1024 * 1024;
                    }
                    else
                    {
                        sz = Int64.Parse(tokens[i + 2]);
                    }

                    current = new SizeCriterion
                    {
                        Size     = sz,
                        Operator = (ComparisonOperator)EnumUtil.Parse(typeof(ComparisonOperator), tokens[i + 1])
                    };
                    i += 2;
                    stateStack.Push(ParseState.CriterionDone);
                    break;

                case "filename":
                case "name":
                {
                    if (tokens.Length <= i + 2)
                    {
                        throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));
                    }

                    ComparisonOperator c =
                        (ComparisonOperator)EnumUtil.Parse(typeof(ComparisonOperator), tokens[i + 1]);

                    if (c != ComparisonOperator.NotEqualTo && c != ComparisonOperator.EqualTo)
                    {
                        throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));
                    }

                    string m = tokens[i + 2];
                    // handle single-quoted filespecs (used to include spaces in filename patterns)
                    if (m.StartsWith("'"))
                    {
                        int ix = i;
                        if (!m.EndsWith("'"))
                        {
                            do
                            {
                                i++;
                                if (tokens.Length <= i + 2)
                                {
                                    throw new ArgumentException(String.Join(" ", tokens, ix, tokens.Length - ix));
                                }
                                m += " " + tokens[i + 2];
                            } while (!tokens[i + 2].EndsWith("'"));
                        }
                        // trim off leading and trailing single quotes
                        m = m.Substring(1, m.Length - 2);
                    }

                    current = new NameCriterion
                    {
                        MatchingFileSpec = m,
                        Operator         = c
                    };
                    i += 2;
                    stateStack.Push(ParseState.CriterionDone);
                }
                break;

                case "attributes":
                {
                    if (tokens.Length <= i + 2)
                    {
                        throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));
                    }

                    ComparisonOperator c =
                        (ComparisonOperator)EnumUtil.Parse(typeof(ComparisonOperator), tokens[i + 1]);

                    if (c != ComparisonOperator.NotEqualTo && c != ComparisonOperator.EqualTo)
                    {
                        throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));
                    }

                    current = new AttributesCriterion
                    {
                        AttributeString = tokens[i + 2],
                        Operator        = c
                    };
                    i += 2;
                    stateStack.Push(ParseState.CriterionDone);
                }
                break;

                case "":
                    // NOP
                    stateStack.Push(ParseState.Whitespace);
                    break;

                default:
                    throw new ArgumentException("'" + tokens[i] + "'");
                }

                state = stateStack.Peek();
                if (state == ParseState.CriterionDone)
                {
                    stateStack.Pop();
                    if (stateStack.Peek() == ParseState.ConjunctionPending)
                    {
                        while (stateStack.Peek() == ParseState.ConjunctionPending)
                        {
                            var cc = critStack.Pop() as CompoundCriterion;
                            cc.Right = current;
                            current  = cc;    // mark the parent as current (walk up the tree)
                            stateStack.Pop(); // the conjunction is no longer pending

                            state = stateStack.Pop();
                            if (state != ParseState.CriterionDone)
                            {
                                throw new ArgumentException("??");
                            }
                        }
                    }
                    else
                    {
                        stateStack.Push(ParseState.CriterionDone);   // not sure?
                    }
                }

                if (state == ParseState.Whitespace)
                {
                    stateStack.Pop();
                }
            }

            return(current);
        }
Ejemplo n.º 11
0
        public string PrettyPrint(string input)
        {
            System.Text.StringBuilder output = new System.Text.StringBuilder(input.Length * 2);
            char c;

            for (int i = 0; i < input.Length; i++)
            {
                c = input[i];

                switch (c)
                {
                case '{':
                    if (!InString())
                    {
                        if (inVariableAssignment || (context.Count > 0 && context.Peek() != JsonContextType.Array))
                        {
                            output.Append(NewLine);
                            BuildIndents(context.Count, output);
                        }
                        output.Append(c);
                        context.Push(JsonContextType.Object);
                        output.Append(NewLine);
                        BuildIndents(context.Count, output);
                    }
                    else
                    {
                        output.Append(c);
                    }

                    break;

                case '}':
                    if (!InString())
                    {
                        output.Append(NewLine);
                        context.Pop();
                        BuildIndents(context.Count, output);
                        output.Append(c);
                    }
                    else
                    {
                        output.Append(c);
                    }

                    break;

                case '[':
                    output.Append(c);

                    if (!InString())
                    {
                        context.Push(JsonContextType.Array);
                    }

                    break;

                case ']':
                    if (!InString())
                    {
                        output.Append(c);
                        context.Pop();
                    }
                    else
                    {
                        output.Append(c);
                    }

                    break;

                case '=':
                    output.Append(c);
                    break;

                case ',':
                    output.Append(c);

                    if (!InString() && context.Peek() != JsonContextType.Array)
                    {
                        BuildIndents(context.Count, output);
                        output.Append(NewLine);
                        BuildIndents(context.Count, output);
                        inVariableAssignment = false;
                    }

                    break;

                case '\'':
                    if (!inDoubleString && prevChar != '\\')
                    {
                        inSingleString = !inSingleString;
                    }

                    output.Append(c);
                    break;

                case ':':
                    if (!InString())
                    {
                        inVariableAssignment = true;
                        output.Append(Space);
                        output.Append(c);
                        output.Append(Space);
                    }
                    else
                    {
                        output.Append(c);
                    }

                    break;

                case '"':
                    if (!inSingleString && prevChar != '\\')
                    {
                        inDoubleString = !inDoubleString;
                    }

                    output.Append(c);
                    break;

                case ' ':
                    if (InString())
                    {
                        output.Append(c);
                    }
                    break;

                default:
                    output.Append(c);
                    break;
                }
                prevChar = c;
            }

            return(output.ToString());
        }
Ejemplo n.º 12
0
        TraverseTree(string filterPattern, string root)
        {
            string[] arrayExclusionPatterns = strSearchExcludePattern.Split(';');
            for (int i = 0; i < arrayExclusionPatterns.Length; i++)
            {
                arrayExclusionPatterns[i] = arrayExclusionPatterns[i].ToLower().ToString().Replace("*", "");
            }

            System.Collections.Generic.List <System.IO.FileInfo> myFileList =
                new System.Collections.Generic.List <System.IO.FileInfo>();

            // Data structure to hold names of subfolders to be
            // examined for files.
            System.Collections.Generic.Stack <string> dirs =
                new System.Collections.Generic.Stack <string>(20);

            if (!System.IO.Directory.Exists(root))
            {
                System.Console.WriteLine(root + " - folder did not exist");
                // MessageBox.Show(root + " - folder did not exist");
            }


            dirs.Push(root);

            while (dirs.Count > 0)
            {
                string   currentDir = dirs.Pop();
                string[] subDirs;
                try
                {
                    subDirs = System.IO.Directory.GetDirectories(currentDir);
                }
                // An UnauthorizedAccessException exception will be thrown if we do not have
                // discovery permission on a folder or file. It may or may not be acceptable
                // to ignore the exception and continue enumerating the remaining files and
                // folders. It is also possible (but unlikely) that a DirectoryNotFound exception
                // will be raised. This will happen if currentDir has been deleted by
                // another application or thread after our call to Directory.Exists. The
                // choice of which exceptions to catch depends entirely on the specific task
                // you are intending to perform and also on how much you know with certainty
                // about the systems on which this code will run.
                catch (System.UnauthorizedAccessException e)
                {
                    System.Console.WriteLine(e.Message);
                    continue;
                }
                catch (System.IO.DirectoryNotFoundException e)
                {
                    System.Console.WriteLine(e.Message);
                    continue;
                }

                string[] files = null;
                try
                {
                    files = System.IO.Directory.GetFiles(currentDir, filterPattern);
                }
                catch (System.UnauthorizedAccessException e)
                {
                    System.Console.WriteLine(e.Message);
                    continue;
                }
                catch (System.IO.DirectoryNotFoundException e)
                {
                    System.Console.WriteLine(e.Message);
                    continue;
                }

                // Perform the required action on each file here.
                // Modify this block to perform your required task.
                foreach (string file in files)
                {
                    try
                    {
                        // Perform whatever action is required in your scenario.
                        System.IO.FileInfo fi         = new System.IO.FileInfo(file);
                        bool boolFileHasGoodExtension = true;
                        foreach (var item in arrayExclusionPatterns)
                        {
                            if (fi.FullName.ToLower().Contains(item))
                            {
                                boolFileHasGoodExtension = false;
                            }
                        }
                        if (boolFileHasGoodExtension)
                        {
                            myFileList.Add(fi);
                        }
                        //    Console.WriteLine("{0}: {1}, {2}", fi.Name, fi.Length, fi.CreationTime);
                    }
                    catch (System.IO.FileNotFoundException e)
                    {
                        // If file was deleted by a separate application
                        //  or thread since the call to TraverseTree()
                        // then just continue.
                        System.Console.WriteLine(e.Message);
                        continue;
                    }
                }

                // Push the subdirectories onto the stack for traversal.
                // This could also be done before handing the files.
                foreach (string str in subDirs)
                {
                    dirs.Push(str);
                }
            }
            return(myFileList);
        }
 public T Pop()
 {
     return(stack.Pop());
 }
Ejemplo n.º 14
0
 /// <summary>
 /// Find an element with a specified name by looking to the descendants of this element.
 /// </summary>
 /// <param name="Name">Name of the element we are looking for</param>
 /// <returns>The found element</returns>
 public Drawable FindElement(string Name)
 {
     if (this.Name == Name)
         return this;
     var plcs=new System.Collections.Generic.Stack<PlaceBase>();
     if (this is PlaceBase)
         plcs.Push(this as PlaceBase);
     while (plcs.Count != 0)
     {
         PlaceBase pop=plcs.Pop();
         if (pop.Name == Name)
             return pop;
         for (int i = 0; i < pop.Length; i++)
         {
             if (pop[i] is PlaceBase)
                 plcs.Push(pop[i] as PlaceBase);
             else if (pop[i].Name == Name)
                 return pop[i];
         }
     }
     return null;
 }
        private static string InfixToRpn(string infix)
        {
            // Replace comma separator with white space for function-like use of operators.
            infix = infix.Replace(Interpreter.CommaSeparatorChar, Interpreter.WhiteSpaceChar);

            // Add operator markers.
            for (int index = 0; index < infix.Length; ++index)
            {
                if (infix[index] == Interpreter.VarPrefixChar)
                {
                    index = Interpreter.SkipString(infix, index + 2);
                }
                else if (Interpreter.IsAlpha(infix[index]))
                {
                    infix = infix.Insert(index, Interpreter.LongOpMark0Str);
                    index = Interpreter.SkipString(infix, index + 2);
                    infix = infix.Insert(index, Interpreter.LongOpMark1Str);
                }
                else if (Interpreter.IsSpecial(infix[index]))
                {
                    infix = infix.Insert(index, Interpreter.LongOpMark0Str);
                    index = Interpreter.SkipSpecial(infix, index + 2);
                    infix = infix.Insert(index, Interpreter.LongOpMark1Str);
                }
            }

            // Add blank spaces where needed.
            for (int index = 0; index < infix.Length; ++index)
            {
                if (Interpreter.operators.ContainsKey(infix[index].ToString()) || infix[index] == Interpreter.VarPrefixChar || infix[index] == Interpreter.OpMarkChar ||
                    infix[index] == Interpreter.OpenBracketChar || infix[index] == Interpreter.ClosingBracketChar)
                {
                    // Ignore variable. It would be a mess to find an operator in the middle of a variable name...
                    if (infix[index] == Interpreter.VarPrefixChar)
                    {
                        index = Interpreter.SkipString(infix, index + 2);
                        //continue;
                    }

                    if (index != 0 && infix[index - 1] != Interpreter.WhiteSpaceChar)
                    {
                        infix = infix.Insert(index, Interpreter.WhiteSpaceStr);
                    }

                    // Handle long operators.
                    int jndex = index;
                    if (infix[index] == Interpreter.OpMarkChar)
                    {
                        jndex = infix.IndexOf(Interpreter.OpMarkChar, index + 1);
                    }

                    if (jndex != infix.Length - 1 && infix[jndex + 1] != Interpreter.OpMarkChar)
                    {
                        infix = infix.Insert(jndex + 1, Interpreter.WhiteSpaceStr);
                    }

                    index = jndex;
                }
            }

            // Trim long op mark and white spaces.
            infix = System.Text.RegularExpressions.Regex.Replace(infix.Replace(Interpreter.OpMarkStr, string.Empty), @"\s+", " ");
            infix = infix.TrimStart(WhiteSpaceChar);
            infix = infix.TrimEnd(WhiteSpaceChar);

            string[] tokens = infix.Split(Interpreter.WhiteSpaceChar);
            System.Collections.Generic.List <string>  list  = new System.Collections.Generic.List <string>();  //TODO: static
            System.Collections.Generic.Stack <string> stack = new System.Collections.Generic.Stack <string>(); //TODO: static

            for (int tokenIndex = 0; tokenIndex < tokens.Length; ++tokenIndex)
            {
                string token = tokens[tokenIndex];

                if (string.IsNullOrEmpty(token) || token == Interpreter.WhiteSpaceStr)
                {
                    continue;
                }

                if (Interpreter.operators.ContainsKey(token))
                {
                    while (stack.Count > 0 && Interpreter.operators.ContainsKey(stack.Peek()))
                    {
                        if (ComparePrecedence(token, stack.Peek()) < 0)
                        {
                            list.Add(stack.Pop());
                            continue;
                        }

                        break;
                    }

                    stack.Push(token);
                }
                else if (token == Interpreter.OpenBracketStr)
                {
                    stack.Push(token);
                }
                else if (token == Interpreter.ClosingBracketStr)
                {
                    while (stack.Count > 0 && stack.Peek() != Interpreter.OpenBracketStr)
                    {
                        list.Add(stack.Pop());
                    }

                    stack.Pop();
                }
                else
                {
                    list.Add(token);
                }
            }

            while (stack.Count > 0)
            {
                list.Add(stack.Pop());
            }

            string rpn = string.Join(Interpreter.WhiteSpaceStr, list.ToArray());

            return(rpn);
        }
Ejemplo n.º 16
0
    public void compute_expression(string expr)
    {
        System.Collections.Generic.Stack<char> myStack = new System.Collections.Generic.Stack<char>();
        string output = "";
        // Rewriting the string into Reverse Polish Notation(RPN) format
        foreach(char token in expr)
        {
             //Read a token.
            //If the token is a number, then add it to the output queue.
            if (Char.IsNumber(token) == true)
            {
                output = output + ' ' +token;
            }
            if(token == '+' || token == '-')
            {
                if (myStack.Count() != 0)
                {
                        while(myStack.Peek() == '*' || myStack.Peek() == '/' || myStack.Peek() == '-')
                        {
                            if (myStack.Count() != 0)
                            {
                                output = output + ' ' + myStack.Peek();
                                myStack.Pop();
                            }
                            if (myStack.Count() == 0)
                            {
                                break;
                            }
                        }
                }
                myStack.Push(token);
            }
            if(token == '(')
            {
                myStack.Push(token);
            }

            if (token == ')')
            {
                if (myStack.Count() != 0)
                {
                    while (myStack.Peek() != '(')
                    {
                        if (myStack.Count() != 0)
                        {
                            output = output + ' ' + myStack.Peek();
                            myStack.Pop();
                        }
                    }
                myStack.Pop();
                }
            }
        }
           while(myStack.Count() != 0)
           {
               output = output + " " + myStack.Peek();
               myStack.Pop();
           }
        //Done RPN
           //Now we need to Evaluate the RPN
           evalu(output);
    }
Ejemplo n.º 17
0
        /// <summary>
        /// Virtual. Plots a time graph with a filtered set of data.
        /// </summary>
        /// <param name="subSet">Filtered set of data.</param>
        /// <param name="panel">The panel.</param>
        protected override void DrawFilteredTimeGraph(IEnumerable subSet, PanelWrapper panel)
        {
            base.DrawFilteredTimeGraph(subSet, panel);

            // Maintain the previous and current point plotted for the virtual method call
            GraphPoint prevPoint = new GraphPoint();
            GraphPoint currPoint = new GraphPoint();

            System.Collections.Generic.Stack<FrameworkElement> dataPointStack =
                new System.Collections.Generic.Stack<FrameworkElement>();

            System.Collections.Generic.Stack<FrameworkElement> dataPointLabelStack =
                new System.Collections.Generic.Stack<FrameworkElement>();

            CollisionDetectionManager collisionManager = GraphBase.GetCollisionDetectionManager(this.DynamicPlotLayer);

            foreach (object o in subSet)
            {
                if (panel.AbortLayout)
                {
                    break;
                }

                GraphPoint gp = this.GetBoundGraphPoint(o);
                if (null == gp)
                {
                    return;
                }

                gp.X1Pixel = this.GetXForDate(gp.X1);
                gp.Y1Pixel = this.GetYForValue(gp.Y1);

                if (!Double.IsNaN(gp.Y2))
                {
                    gp.Y2Pixel = this.GetYForValue(gp.Y2);
                }

                currPoint = gp;

                // process the plotted data marker
                this.ProcessPlottedDataMarker(prevPoint, currPoint);

                if (!this.Minimized)
                {
                    if (!double.IsNaN(gp.Y1) && currPoint.X1Pixel >= 0 && currPoint.X1Pixel < this.DynamicMainLayerViewport.ActualWidth)
                    {
                        FrameworkElement marker = this.GetPlottedDataMarker(gp);
                        double left = Canvas.GetLeft(marker);
#if !SILVERLIGHT
                    // For WPF should snap to grid if requested
                    bool snap = GraphBase.GetSnapToPixels(marker);
                    if (marker.SnapsToDevicePixels != snap)
                    {
                        marker.SnapsToDevicePixels = snap;
                    }
#endif

                        if (left < 0 || (left + marker.Width) > this.DynamicMainLayerViewport.ActualWidth)
                        {
                            this.CurrentWorkingPanel.SeamedElementCollection.Add(marker);
                        }

                        this.DynamicPlotLayer.Children.Add(marker);
                        dataPointStack.Push(marker);

                        FrameworkElement labelElement = null;
                        if (null != this.LabelTemplate)
                        {
                            labelElement = this.LabelTemplate.LoadContent() as FrameworkElement;
                            labelElement.DataContext = gp;
                            dataPointLabelStack.Push(labelElement);
                        }

                        if (null != labelElement)
                        {
                            double offsetValueX = GraphBase.GetXOffset(labelElement);
                            double offsetValueY = GraphBase.GetYOffset(labelElement);

                            // define the label position
                            double labelY = currPoint.Y1Pixel;
                            if (!double.IsNaN(gp.Y2) && gp.Y1 < gp.Y2)
                            {
                                labelY = currPoint.Y2Pixel;
                            }

                            double markerOffset = Math.Abs(GraphBase.GetYOffset(marker)) + 2;
                            Canvas.SetTop(labelElement, (labelY - markerOffset) + offsetValueY);
                            Canvas.SetLeft(labelElement, currPoint.X1Pixel + offsetValueX);
                            labelElement.Visibility = this.ShowDataPointLabels;
                            this.DynamicPlotLayer.Children.Add(labelElement);
                            GraphBase.SetDataPointLabel(marker, labelElement);
                            panel.LabelElements.Add(labelElement);

                            marker.MouseEnter += new MouseEventHandler(this.DataPointMarker_MouseEnter);
                            marker.MouseLeave += new MouseEventHandler(this.DataPointMarker_MouseLeave);
                        }
                    }
                }

                prevPoint = currPoint;
            }

            if (!panel.AbortLayout && this.DetectCollisions)
            {
                Collision previousCollision = null;

                // get the last items in the collection for the data context
                object[] lastItems = this.GetLastDataPoints();
                object lastObject = lastItems[1];
                object secondLastObject = lastItems[0];

                byte lastItemsCheck = 0;

                while (dataPointStack.Count > 0)
                {
                    FrameworkElement ele = dataPointStack.Pop();
                    FrameworkElement labelEle = GraphBase.GetDataPointLabel(ele);

                    if (lastItemsCheck < 2 && null != labelEle && null != labelEle.DataContext)
                    {
                        // this is the last item on the page.
                        // we plot back to front to check if things overlap.
                        ++lastItemsCheck;
                        object gp = ((GraphPoint)labelEle.DataContext).DataContext;
                        if (lastObject == gp)
                        {
                            // this is the last item in the series.
                            GraphBase.SetLastItem(ele, true);
                            labelEle.Visibility = Visibility.Visible;
                            labelEle.RenderTransform = this.LabelTransform;
                        }

                        if (secondLastObject == gp)
                        {
                            // this is the second last item in the series.
                            GraphBase.SetSecondToLast(ele, true);
                            labelEle.Visibility = Visibility.Visible;
                        }
                    }

                    FrameworkElement clashElement = collisionManager.RegisterAndTestIfMarkerOverlaps(ele);

                    if (null != clashElement)
                    {
                        previousCollision = new Collision(clashElement, ele, true);
                        this.CurrentWorkingPanel.CollisionCollection.Add(previousCollision);

                        GraphBase.SetDataPointOverlapProperty(ele, true);
                        GraphBase.SetDataPointOverlapProperty(labelEle, true);
                        labelEle.Visibility = Visibility.Collapsed;

                        GraphBase.SetDataPointOverlapProperty(clashElement, true);
                        FrameworkElement clashElementLabel = GraphBase.GetDataPointLabel(clashElement);
                        GraphBase.SetDataPointOverlapProperty(clashElementLabel, true);
                        clashElementLabel.Visibility = Visibility.Collapsed;
                    }
                    else
                    {
                        // this marker does not overlap
                        previousCollision = null;
                    }
                }

                while (dataPointLabelStack.Count > 0)
                {
                    FrameworkElement ele2 = dataPointLabelStack.Pop();
                    if (collisionManager.RegisterAndTestIfLabelOverlaps(ele2))
                    {
                        GraphBase.SetDataPointOverlapProperty(ele2, true);
                        ele2.Visibility = Visibility.Collapsed;
                    }
                }

                PanelWrapper otherPanel = null;

                // we get panel 2 then panel 1 when getting both panels.
                double markerOffsetToUse = 0;

                // perform seam detection
                // panel1 is to the left of panel2
                if (this.CurrentWorkingPanel == this.Panel1)
                {
                    // panel2 markers must be incremented by the width of the layer.
                    otherPanel = this.Panel2;
                    markerOffsetToUse = this.Panel1.Width;
                }
                else
                {
                    // panel1 markers must be decremented by the width of the plot layer.
                    // if we are renewing both panels, then do not do collisions detections on seams for
                    if (true != this.RenewingBothPanels)
                    {
                        otherPanel = this.Panel1;
                        markerOffsetToUse = this.Panel2.Width * -1;
                    }
                }

                // this gets run if we are renewing a panel, but if renewing both, only for panel 1
                if (null != otherPanel)
                {
                    LookThroughAdjacentPanelForOverlap(this.CurrentWorkingPanel, otherPanel, markerOffsetToUse);
                }

                double lastCollisionPosition = -1;

                foreach (Collision collision in this.CurrentWorkingPanel.CollisionCollection)
                {
                    if (null != this.CollisionTemplate)
                    {
                        FrameworkElement collisionIcon = this.CollisionTemplate.LoadContent() as FrameworkElement;
                        double theXOffset = GraphBase.GetXOffset(collisionIcon);
                        double theYOffset = GraphBase.GetYOffset(collisionIcon);
                        if (null != collisionIcon)
                        {
                            double localxPosition = Canvas.GetLeft(collision.ClusterStartElement) + theXOffset;
                            double localyPosition = Canvas.GetTop(collision.ClusterStartElement) + theYOffset;

                            if (lastCollisionPosition == -1 || localxPosition < lastCollisionPosition - 46)
                            {
                                lastCollisionPosition = localxPosition;

                                Canvas.SetLeft(collisionIcon, localxPosition);
                                Canvas.SetTop(collisionIcon, localyPosition);

                                if (true == collision.ClusterShowingIcon)
                                {
                                    this.DynamicPlotLayer.Children.Add(collisionIcon);
                                }
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 18
0
 public void PopTypeContext(Schema.IDataType dataType)
 {
     Error.AssertFail(_typeStack.Count > 0, "Type stack underflow");
     _typeStack.Pop();
 }
Ejemplo n.º 19
0
        private void Stack_New_Click(object sender, EventArgs e)
        {
            var any = stackCollection.Pop(); // Issue Array/Collection Access

            MessageBox.Show(any.ToString());
        }
 internal void SetPositions(System.Collections.Generic.Stack <int> stack)
 {
     this.endChar   = stack.Pop();
     this.startChar = stack.Pop();
 }
Ejemplo n.º 21
0
        public void PrettyPrint(System.Text.StringBuilder input, System.Text.StringBuilder output)
        {
            if (input == null)
            {
                throw new System.ArgumentNullException("input");
            }
            if (output == null)
            {
                throw new  System.ArgumentNullException("output");
            }

            int  inputLength = input.Length;
            char c;

            for (int i = 0; i < inputLength; i++)
            {
                c = input[i];

                switch (c)
                {
                case '{':
                    if (!InString())
                    {
                        if (inVariableAssignment || (context.Count > 0 && context.Peek() != JsonContextType.Array))
                        {
                            output.Append(NewLine);
                            BuildIndents(context.Count, output);
                        }
                        output.Append(c);
                        context.Push(JsonContextType.Object);
                        output.Append(NewLine);
                        BuildIndents(context.Count, output);
                    }
                    else
                    {
                        output.Append(c);
                    }

                    break;

                case '}':
                    if (!InString())
                    {
                        output.Append(NewLine);
                        context.Pop();
                        BuildIndents(context.Count, output);
                        output.Append(c);
                    }
                    else
                    {
                        output.Append(c);
                    }

                    break;

                case '[':
                    output.Append(c);

                    if (!InString())
                    {
                        context.Push(JsonContextType.Array);
                    }

                    break;

                case ']':
                    if (!InString())
                    {
                        output.Append(c);
                        context.Pop();
                    }
                    else
                    {
                        output.Append(c);
                    }

                    break;

                case '=':
                    output.Append(c);
                    break;

                case ',':
                    output.Append(c);

                    if (!InString() && context.Peek() != JsonContextType.Array)
                    {
                        BuildIndents(context.Count, output);
                        output.Append(NewLine);
                        BuildIndents(context.Count, output);
                        inVariableAssignment = false;
                    }

                    break;

                case '\'':
                    if (!inDoubleString && prevChar != '\\')
                    {
                        inSingleString = !inSingleString;
                    }

                    output.Append(c);
                    break;

                case ':':
                    if (!InString())
                    {
                        inVariableAssignment = true;
                        output.Append(Space);
                        output.Append(c);
                        output.Append(Space);
                    }
                    else
                    {
                        output.Append(c);
                    }

                    break;

                case '"':
                    if (!inSingleString && prevChar != '\\')
                    {
                        inDoubleString = !inDoubleString;
                    }

                    output.Append(c);
                    break;

                default:
                    output.Append(c);
                    break;
                }
                prevChar = c;
            }
        }
Ejemplo n.º 22
0
        public static void interateBinaryTreeEx(TreeAndGraph.BinaryTreeNode head, Order o)
        {
            TreeAndGraph.BinaryTreeNode btn = head;
            if (o == Order.Post)
            {
                System.Collections.Generic.Stack<TreeAndGraph.BinaryTreeNode> s
                    = new System.Collections.Generic.Stack<TreeAndGraph.BinaryTreeNode>();
                s.Push(btn);
                TreeAndGraph.BinaryTreeNode cur = null;
                TreeAndGraph.BinaryTreeNode pre = null;
                while (s.Count != 0)
                {
                    cur = s.Peek();
                    if ((cur.LeftNode == null && cur.RightNode == null) || (pre != null && (pre == cur.LeftNode || pre == cur.RightNode)))
                    {
                        System.Console.WriteLine("XPost:"+cur.Data);
                        s.Pop();
                        pre = cur;
                    }
                    else
                    {
                        if (cur.RightNode != null)
                        {
                            s.Push(cur.RightNode);
                        }
                        if (cur.LeftNode != null)
                        {
                            s.Push(cur.LeftNode);
                        }
                    }
                }
            }
            if (o == Order.Pre)
            {
                System.Collections.Generic.Stack<TreeAndGraph.BinaryTreeNode> s
                    = new System.Collections.Generic.Stack<TreeAndGraph.BinaryTreeNode>();

                while (btn != null || s.Count != 0)
                {
                    while (btn != null)
                    {
                        s.Push(btn);
                        System.Console.WriteLine("XPre:" + btn.Data);
                        btn = btn.LeftNode;
                    }
                    if (s.Count != 0)
                    {
                        btn = s.Pop().RightNode;
                    }
                }
            }
            if (o == Order.Mid)
            {
                System.Collections.Generic.Stack<TreeAndGraph.BinaryTreeNode> s
                     = new System.Collections.Generic.Stack<TreeAndGraph.BinaryTreeNode>();
                while (btn != null || s.Count != 0)
                {
                    while (btn != null)
                    {
                        s.Push(btn);
                        btn = btn.LeftNode;
                    }
                    if (s.Count != 0)
                    {
                        btn = s.Pop();
                        System.Console.WriteLine("XMid:" + btn.Data);
                        btn = btn.RightNode;
                    }

                }
            }
        }
 private static long sp()
 {
     return((s.Count == 0)?0:s.Pop());
 }
Ejemplo n.º 24
0
        } // End Function FormatOutput

        public static string Process(string inputText)
        {
            bool escaped     = false;
            bool inquotes    = false;
            int  column      = 0;
            int  indentation = 0;

            System.Collections.Generic.Stack <int> indentations = new System.Collections.Generic.Stack <int>();
            int TABBING = 8;

            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            foreach (char x in inputText)
            {
                sb.Append(x);
                column++;
                if (escaped)
                {
                    escaped = false;
                }
                else
                {
                    if (x == '\\')
                    {
                        escaped = true;
                    }
                    else if (x == '\"')
                    {
                        inquotes = !inquotes;
                    }
                    else if (!inquotes)
                    {
                        if (x == ',')
                        {
                            // if we see a comma, go to next line, and indent to the same depth
                            sb.Append("\r\n");
                            column = 0;
                            for (int i = 0; i < indentation; i++)
                            {
                                sb.Append(" ");
                                column++;
                            }
                        }
                        else if (x == '[' || x == '{')
                        {
                            // if we open a bracket or brace, indent further (push on stack)
                            indentations.Push(indentation);
                            indentation = column;
                        }
                        else if (x == ']' || x == '}')
                        {
                            // if we close a bracket or brace, undo one level of indent (pop)
                            indentation = indentations.Pop();
                        }
                        else if (x == ':')
                        {
                            // if we see a colon, add spaces until we get to the next
                            // tab stop, but without using tab characters!
                            while ((column % TABBING) != 0)
                            {
                                sb.Append(' ');
                                column++;
                            }
                        }
                    }
                }
            } // Next x

            return(sb.ToString());
        } // End Function Process
Ejemplo n.º 25
0
        private static SelectionCriterion _ParseCriterion(String s)
        {
            if (s == null) return null;

            // inject spaces after open paren and before close paren
            string[][] prPairs =
                {
                    new string[] { @"\(\(", "( (" },
                    new string[] { @"\)\)", ") )" },
                    new string[] { @"\((\S)", "( $1" },
                    new string[] { @"(\S)\)", "$1 )" },
                    new string[] { @"(\S)\(", "$1 (" },
                    new string[] { @"\)(\S)", ") $1" },
                    new string[] { @"([^ ]+)>([^ ]+)", "$1 > $2" },
                    new string[] { @"([^ ]+)<([^ ]+)", "$1 < $2" },
                    new string[] { @"([^ ]+)!=([^ ]+)", "$1 != $2" },
                    new string[] { @"([^ ]+)=([^ ]+)", "$1 = $2" },
                };
            for (int i = 0; i < prPairs.Length; i++)
            {
                Regex rgx = new Regex(prPairs[i][0]);
                s = rgx.Replace(s, prPairs[i][1]);
            }

            // shorthand for filename glob
            if (s.IndexOf(" ") == -1)
                s = "name = " + s;

            // split the expression into tokens
            string[] tokens = s.Trim().Split(' ', '\t');

            if (tokens.Length < 3) throw new ArgumentException(s);

            SelectionCriterion current = null;

            LogicalConjunction pendingConjunction = LogicalConjunction.NONE;

            ParseState state;
            var stateStack = new System.Collections.Generic.Stack<ParseState>();
            var critStack = new System.Collections.Generic.Stack<SelectionCriterion>();
            stateStack.Push(ParseState.Start);

            for (int i = 0; i < tokens.Length; i++)
            {
                string tok1 = tokens[i].ToLower();
                switch (tok1)
                {
                    case "and":
                    case "xor":
                    case "or":
                        state = stateStack.Peek();
                        if (state != ParseState.CriterionDone)
                            throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));

                        if (tokens.Length <= i + 3)
                            throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));

                        pendingConjunction = (LogicalConjunction)Enum.Parse(typeof(LogicalConjunction), tokens[i].ToUpper(), true);
                        current = new CompoundCriterion { Left = current, Right = null, Conjunction = pendingConjunction };
                        stateStack.Push(state);
                        stateStack.Push(ParseState.ConjunctionPending);
                        critStack.Push(current);
                        break;

                    case "(":
                        state = stateStack.Peek();
                        if (state != ParseState.Start && state != ParseState.ConjunctionPending && state != ParseState.OpenParen)
                            throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));

                        if (tokens.Length <= i + 4)
                            throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));

                        stateStack.Push(ParseState.OpenParen);
                        break;

                    case ")":
                        state = stateStack.Pop();
                        if (stateStack.Peek() != ParseState.OpenParen)
                            throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));

                        stateStack.Pop();
                        stateStack.Push(ParseState.CriterionDone);
                        break;

                    case "atime":
                    case "ctime":
                    case "mtime":
                        if (tokens.Length <= i + 2)
                            throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));

                        DateTime t;
                        try
                        {
                            t = DateTime.ParseExact(tokens[i + 2], "yyyy-MM-dd-HH:mm:ss", null);
                        }
                        catch (FormatException)
                        {
                            try
                            {
                                t = DateTime.ParseExact(tokens[i + 2], "yyyy/MM/dd-HH:mm:ss", null);
                            }
                            catch (FormatException)
                            {
                                try
                                {
                                    t = DateTime.ParseExact(tokens[i + 2], "yyyy/MM/dd", null);
                                }
                                catch (FormatException)
                                {
                                    try
                                    {
                                        t = DateTime.ParseExact(tokens[i + 2], "MM/dd/yyyy", null);
                                    }
                                    catch (FormatException)
                                    {
                                        t = DateTime.ParseExact(tokens[i + 2], "yyyy-MM-dd", null);
                                    }
                                }
                            }
                        }
                        t= DateTime.SpecifyKind(t, DateTimeKind.Local).ToUniversalTime();
                        current = new TimeCriterion
                        {
                            Which = (WhichTime)Enum.Parse(typeof(WhichTime), tokens[i], true),
                            Operator = (ComparisonOperator)EnumUtil.Parse(typeof(ComparisonOperator), tokens[i + 1]),
                            Time = t
                        };
                        i += 2;
                        stateStack.Push(ParseState.CriterionDone);
                        break;


                    case "length":
                    case "size":
                        if (tokens.Length <= i + 2)
                            throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));

                        Int64 sz = 0;
                        string v = tokens[i + 2];
                        if (v.ToUpper().EndsWith("K"))
                            sz = Int64.Parse(v.Substring(0, v.Length - 1)) * 1024;
                        else if (v.ToUpper().EndsWith("KB"))
                            sz = Int64.Parse(v.Substring(0, v.Length - 2)) * 1024;
                        else if (v.ToUpper().EndsWith("M"))
                            sz = Int64.Parse(v.Substring(0, v.Length - 1)) * 1024 * 1024;
                        else if (v.ToUpper().EndsWith("MB"))
                            sz = Int64.Parse(v.Substring(0, v.Length - 2)) * 1024 * 1024;
                        else if (v.ToUpper().EndsWith("G"))
                            sz = Int64.Parse(v.Substring(0, v.Length - 1)) * 1024 * 1024 * 1024;
                        else if (v.ToUpper().EndsWith("GB"))
                            sz = Int64.Parse(v.Substring(0, v.Length - 2)) * 1024 * 1024 * 1024;
                        else sz = Int64.Parse(tokens[i + 2]);

                        current = new SizeCriterion
                        {
                            Size = sz,
                            Operator = (ComparisonOperator)EnumUtil.Parse(typeof(ComparisonOperator), tokens[i + 1])
                        };
                        i += 2;
                        stateStack.Push(ParseState.CriterionDone);
                        break;

                    case "filename":
                    case "name":
                        {
                            if (tokens.Length <= i + 2)
                                throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));

                            ComparisonOperator c =
                                (ComparisonOperator)EnumUtil.Parse(typeof(ComparisonOperator), tokens[i + 1]);

                            if (c != ComparisonOperator.NotEqualTo && c != ComparisonOperator.EqualTo)
                                throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));

                            string m = tokens[i + 2];
                            // handle single-quoted filespecs (used to include spaces in filename patterns)
                            if (m.StartsWith("'"))
                            {
                                int ix = i;
                                if (!m.EndsWith("'"))
                                {
                                    do
                                    {
                                        i++;
                                        if (tokens.Length <= i + 2)
                                            throw new ArgumentException(String.Join(" ", tokens, ix, tokens.Length - ix));
                                        m += " " + tokens[i + 2];
                                    } while (!tokens[i + 2].EndsWith("'"));
                                }
                                // trim off leading and trailing single quotes
                                m = m.Substring(1, m.Length - 2);
                            }

                            current = new NameCriterion
                            {
                                MatchingFileSpec = m,
                                Operator = c
                            };
                            i += 2;
                            stateStack.Push(ParseState.CriterionDone);
                        }
                        break;

                    case "attrs":
                    case "attributes":
                    case "type":
                        {
                            if (tokens.Length <= i + 2)
                                throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));

                            ComparisonOperator c =
                                (ComparisonOperator)EnumUtil.Parse(typeof(ComparisonOperator), tokens[i + 1]);

                            if (c != ComparisonOperator.NotEqualTo && c != ComparisonOperator.EqualTo)
                                throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));

                            current = (tok1 == "type")
                                ? (SelectionCriterion) new TypeCriterion
                                    {
                                        AttributeString = tokens[i + 2],
                                        Operator = c
                                    }
                                : (SelectionCriterion) new AttributesCriterion
                                    {
                                        AttributeString = tokens[i + 2],
                                        Operator = c
                                    };

                            i += 2;
                            stateStack.Push(ParseState.CriterionDone);
                        }
                        break;

                    case "":
                        // NOP
                        stateStack.Push(ParseState.Whitespace);
                        break;

                    default:
                        throw new ArgumentException("'" + tokens[i] + "'");
                }

                state = stateStack.Peek();
                if (state == ParseState.CriterionDone)
                {
                    stateStack.Pop();
                    if (stateStack.Peek() == ParseState.ConjunctionPending)
                    {
                        while (stateStack.Peek() == ParseState.ConjunctionPending)
                        {
                            var cc = critStack.Pop() as CompoundCriterion;
                            cc.Right = current;
                            current = cc; // mark the parent as current (walk up the tree)
                            stateStack.Pop();   // the conjunction is no longer pending

                            state = stateStack.Pop();
                            if (state != ParseState.CriterionDone)
                                throw new ArgumentException("??");
                        }
                    }
                    else stateStack.Push(ParseState.CriterionDone);  // not sure?
                }

                if (state == ParseState.Whitespace)
                    stateStack.Pop();
            }

            return current;
        }
Ejemplo n.º 26
0
 public T Pop()
 {
     return(innerStack.Pop());
 }
Ejemplo n.º 27
0
            internal void TarjanSearch(int w)
            {
                int min; // minimum z numeru prefiksowego wierzcholka w (w przeszukiwaniu DFS)

                // oraz wartosci low[u] dla wszystkich wierzcholkow u do ktorych prowadz krawedz z w
                visited[w] = true;
                s.Push(w);
                pref[w] = nr;
                low[w]  = nr;
                min     = nr;
                foreach (Edge e in g.OutEdges(w))
                {
                    if (!visited[e.To])
                    {
                        nr++;
                        TarjanSearch(e.To);
                    }
                    if (low[e.To] < min)
                    {
                        min = low[e.To];
                    }
                }

                if (min < low[w])
                {
                    low[w] = min;
                    return;
                }

                int v;

                do
                {
                    v      = s.Pop();
                    id[v]  = scc_nr;
                    low[v] = g.VerticesCount;
                } while (v != w);
                scc_nr++;

                // oznacz wierzcholek w jako odwiedzony
                // umiesc wierzcholek w na stosie s
                // przypisz zmiennym min, low[w], pref[w] numer prefiksowy zwiazany z przeszukiwaniem DFS
                // dla kazdej krawedzi <w,u> wychodzecej z w
                //     {
                //     jesli u jest nieodwiedzony wywolaj rekurencyjnie TarjanSearch(u)
                //     jesli trzeba zaktualizuj min (przy pomocy low[u])
                //     }
                // jesli min < low[w]
                //     {
                //     zaktualizuj low[w] (przy pomocy min)
                //     wyjdz z procedury
                //     }
                // powtarzaj
                //     {
                //     pobierz do v element ze stosu s
                //     przypisz id[v] = numer silnie spojnej skladowej
                //     przypisz low[v] duza wartosc (np. liczbe wierzcholkow grafu)
                //     }
                // dopoki v jest rozne od w;
                // zwieksz (o 1) numer silnie spojnej skladowej
            }
        private static int CalculateIndentation(string baseline, ITextSnapshotLine line, IEditorOptions options, IClassifier classifier, ITextView textView)
        {
            int indentation = GetIndentation(baseline, options.GetTabSize());
            int tabSize     = options.GetIndentSize();
            var tokens      = classifier.GetClassificationSpans(line.Extent);

            if (tokens.Count > 0 && !IsUnterminatedStringToken(tokens[tokens.Count - 1]))
            {
                int tokenIndex = tokens.Count - 1;

                while (tokenIndex >= 0 &&
                       (tokens[tokenIndex].ClassificationType.IsOfType(PredefinedClassificationTypeNames.Comment) ||
                        tokens[tokenIndex].ClassificationType.IsOfType(PredefinedClassificationTypeNames.WhiteSpace)))
                {
                    tokenIndex--;
                }

                if (tokenIndex < 0)
                {
                    return(indentation);
                }

                if (ReverseExpressionParser.IsExplicitLineJoin(tokens[tokenIndex]))
                {
                    // explicit line continuation, we indent 1 level for the continued line unless
                    // we're already indented because of multiple line continuation characters.

                    indentation = GetIndentation(line.GetText(), options.GetTabSize());
                    var joinedLine = tokens[tokenIndex].Span.Start.GetContainingLine();
                    if (joinedLine.LineNumber > 0)
                    {
                        var prevLineSpans = classifier.GetClassificationSpans(tokens[tokenIndex].Span.Snapshot.GetLineFromLineNumber(joinedLine.LineNumber - 1).Extent);
                        if (prevLineSpans.Count == 0 || !ReverseExpressionParser.IsExplicitLineJoin(prevLineSpans[prevLineSpans.Count - 1]))
                        {
                            indentation += tabSize;
                        }
                    }
                    else
                    {
                        indentation += tabSize;
                    }

                    return(indentation);
                }

                string sline    = tokens[tokenIndex].Span.GetText();
                var    lastChar = sline.Length == 0 ? '\0' : sline[sline.Length - 1];

                // use the expression parser to figure out if we're in a grouping...
                var spans = textView.BufferGraph.MapDownToFirstMatch(
                    tokens[tokenIndex].Span,
                    SpanTrackingMode.EdgePositive,
                    PythonContentTypePrediciate
                    );
                if (spans.Count == 0)
                {
                    return(indentation);
                }

                var revParser = new ReverseExpressionParser(
                    spans[0].Snapshot,
                    spans[0].Snapshot.TextBuffer,
                    spans[0].Snapshot.CreateTrackingSpan(
                        spans[0].Span,
                        SpanTrackingMode.EdgePositive
                        )
                    );

                var tokenStack = new System.Collections.Generic.Stack <ClassificationSpan>();
                tokenStack.Push(null);  // end with an implicit newline
                bool endAtNextNull = false;

                foreach (var token in revParser)
                {
                    tokenStack.Push(token);
                    if (token == null && endAtNextNull)
                    {
                        break;
                    }
                    else if (token != null &&
                             token.ClassificationType == revParser.Classifier.Provider.Keyword &&
                             PythonKeywords.IsOnlyStatementKeyword(token.Span.GetText()))
                    {
                        endAtNextNull = true;
                    }
                }

                var indentStack = new System.Collections.Generic.Stack <LineInfo>();
                var current     = LineInfo.Empty;

                while (tokenStack.Count > 0)
                {
                    var token = tokenStack.Pop();
                    if (token == null)
                    {
                        current.NeedsUpdate = true;
                    }
                    else if (token.IsOpenGrouping())
                    {
                        indentStack.Push(current);
                        var start = token.Span.Start;
                        var line2 = start.GetContainingLine();
                        var next  = tokenStack.Count > 0 ? tokenStack.Peek() : null;
                        if (next != null && next.Span.End <= line2.End)
                        {
                            current = new LineInfo {
                                Indentation = start.Position - line2.Start.Position + 1
                            };
                        }
                        else
                        {
                            current = new LineInfo {
                                Indentation = GetIndentation(line2.GetText(), tabSize) + tabSize
                            };
                        }
                    }
                    else if (token.IsCloseGrouping())
                    {
                        if (indentStack.Count > 0)
                        {
                            current = indentStack.Pop();
                        }
                        else
                        {
                            current.NeedsUpdate = true;
                        }
                    }
                    else if (ReverseExpressionParser.IsExplicitLineJoin(token))
                    {
                        while (token != null && tokenStack.Count > 0)
                        {
                            token = tokenStack.Pop();
                        }
                    }
                    else if (current.NeedsUpdate == true)
                    {
                        var line2 = token.Span.Start.GetContainingLine();
                        current = new LineInfo {
                            Indentation = GetIndentation(line2.GetText(), tabSize)
                        };
                    }

                    if (token != null && ShouldDedentAfterKeyword(token))       // dedent after some statements
                    {
                        current.ShouldDedentAfter = true;
                    }

                    if (token != null && token.Span.GetText() == ":" &&         // indent after a colon
                        indentStack.Count == 0)                                 // except in a grouping
                    {
                        current.ShouldIndentAfter = true;
                        // If the colon isn't at the end of the line, cancel it out.
                        // If the following is a ShouldDedentAfterKeyword, only one dedent will occur.
                        current.ShouldDedentAfter = (tokenStack.Count != 0 && tokenStack.Peek() != null);
                    }
                }

                indentation = current.Indentation +
                              (current.ShouldIndentAfter ? tabSize : 0) -
                              (current.ShouldDedentAfter ? tabSize : 0);
            }

            return(indentation);
        }
Ejemplo n.º 29
0
        private static int CalculateIndentation(string baseline, ITextSnapshotLine line, IEditorOptions options, IClassifier classifier, ITextView textView) {
            int indentation = GetIndentation(baseline, options.GetTabSize());
            int tabSize = options.GetIndentSize();
            var tokens = classifier.GetClassificationSpans(line.Extent);
            if (tokens.Count > 0 && !IsUnterminatedStringToken(tokens[tokens.Count - 1])) {
                int tokenIndex = tokens.Count - 1;

                while (tokenIndex >= 0 &&
                    (tokens[tokenIndex].ClassificationType.IsOfType(PredefinedClassificationTypeNames.Comment) ||
                    tokens[tokenIndex].ClassificationType.IsOfType(PredefinedClassificationTypeNames.WhiteSpace))) {
                    tokenIndex--;
                }

                if (tokenIndex < 0) {
                    return indentation;
                }

                if (ReverseExpressionParser.IsExplicitLineJoin(tokens[tokenIndex])) {
                    // explicit line continuation, we indent 1 level for the continued line unless
                    // we're already indented because of multiple line continuation characters.

                    indentation = GetIndentation(line.GetText(), options.GetTabSize());
                    var joinedLine = tokens[tokenIndex].Span.Start.GetContainingLine();
                    if (joinedLine.LineNumber > 0) {
                        var prevLineSpans = classifier.GetClassificationSpans(tokens[tokenIndex].Span.Snapshot.GetLineFromLineNumber(joinedLine.LineNumber - 1).Extent);
                        if (prevLineSpans.Count == 0 || !ReverseExpressionParser.IsExplicitLineJoin(prevLineSpans[prevLineSpans.Count - 1])) {
                            indentation += tabSize;
                        }
                    } else {
                        indentation += tabSize;
                    }

                    return indentation;
                }

                string sline = tokens[tokenIndex].Span.GetText();
                var lastChar = sline.Length == 0 ? '\0' : sline[sline.Length - 1];

                // use the expression parser to figure out if we're in a grouping...
                var spans = textView.BufferGraph.MapDownToFirstMatch(
                    tokens[tokenIndex].Span,
                    SpanTrackingMode.EdgePositive,
                    PythonContentTypePrediciate
                );
                if (spans.Count == 0) {
                    return indentation;
                }
                
                var revParser = new ReverseExpressionParser(
                        spans[0].Snapshot,
                        spans[0].Snapshot.TextBuffer,
                        spans[0].Snapshot.CreateTrackingSpan(
                            spans[0].Span,
                            SpanTrackingMode.EdgePositive
                        )
                    );

                var tokenStack = new System.Collections.Generic.Stack<ClassificationSpan>();
                tokenStack.Push(null);  // end with an implicit newline
                bool endAtNextNull = false;

                foreach (var token in revParser) {
                    tokenStack.Push(token);
                    if (token == null && endAtNextNull) {
                        break;
                    } else if (token != null &&
                       token.ClassificationType == revParser.Classifier.Provider.Keyword &&
                       PythonKeywords.IsOnlyStatementKeyword(token.Span.GetText())) {
                        endAtNextNull = true;
                    }
                }

                var indentStack = new System.Collections.Generic.Stack<LineInfo>();
                var current = LineInfo.Empty;

                while (tokenStack.Count > 0) {
                    var token = tokenStack.Pop();
                    if (token == null) {
                        current.NeedsUpdate = true;
                    } else if (token.IsOpenGrouping()) {
                        indentStack.Push(current);
                        var start = token.Span.Start;
                        var line2 = start.GetContainingLine();
                        var next = tokenStack.Count > 0 ? tokenStack.Peek() : null;
                        if (next != null && next.Span.End <= line2.End) {
                            current = new LineInfo {
                                Indentation = start.Position - line2.Start.Position + 1
                            };
                        } else {
                            current = new LineInfo {
                                Indentation = GetIndentation(line2.GetText(), tabSize) + tabSize
                            };
                        }
                    } else if (token.IsCloseGrouping()) {
                        if (indentStack.Count > 0) {
                            current = indentStack.Pop();
                        } else {
                            current.NeedsUpdate = true;
                        }
                    } else if (ReverseExpressionParser.IsExplicitLineJoin(token)) {
                        while (token != null && tokenStack.Count > 0) {
                            token = tokenStack.Pop();
                        }
                    } else if (current.NeedsUpdate == true) {
                        var line2 = token.Span.Start.GetContainingLine();
                        current = new LineInfo {
                            Indentation = GetIndentation(line2.GetText(), tabSize)
                        };
                    }

                    if (token != null && ShouldDedentAfterKeyword(token)) {     // dedent after some statements
                        current.ShouldDedentAfter = true;
                    }

                    if (token != null && token.Span.GetText() == ":" &&         // indent after a colon
                        indentStack.Count == 0) {                               // except in a grouping
                        current.ShouldIndentAfter = true;
                        // If the colon isn't at the end of the line, cancel it out.
                        // If the following is a ShouldDedentAfterKeyword, only one dedent will occur.
                        current.ShouldDedentAfter = (tokenStack.Count != 0 && tokenStack.Peek() != null);
                    }
                }

                indentation = current.Indentation +
                    (current.ShouldIndentAfter ? tabSize : 0) -
                    (current.ShouldDedentAfter ? tabSize : 0);
            }

            // Map indentation back to the view's text buffer.
            int offset = 0;
            var viewLineStart = textView.BufferGraph.MapUpToSnapshot(line.Start, PointTrackingMode.Positive, PositionAffinity.Successor, textView.TextSnapshot);
            if (viewLineStart.HasValue) {
                offset = viewLineStart.Value.Position - viewLineStart.Value.GetContainingLine().Start.Position;
            }

            return offset + indentation;
        }
        private static Node RpnToNode(string rpn)
        {
            string[] tokens = rpn.Split(Interpreter.WhiteSpaceChar);
            System.Collections.Generic.Stack <Node> values = new System.Collections.Generic.Stack <Node>();

            for (int tokenIndex = 0; tokenIndex < tokens.Length; ++tokenIndex)
            {
                string token = tokens[tokenIndex];

                if (Interpreter.operators.ContainsKey(token))
                {
                    OperatorDescriptor opeDesc = Interpreter.operators[token];

                    if (opeDesc.NodeType != null)
                    {
                        if (opeDesc.NodeType.IsSubclassOf(typeof(ZeroNode)))
                        {
                            System.Reflection.ConstructorInfo constructorInfo = opeDesc.NodeType.GetConstructor(new System.Type[0]);
                            if (constructorInfo != null)
                            {
                                Node node = (Node)constructorInfo.Invoke(new object[0]);
                                values.Push(node);
                            }
                        }

                        if (opeDesc.NodeType.IsSubclassOf(typeof(UnaryNode)))
                        {
                            System.Reflection.ConstructorInfo constructorInfo = opeDesc.NodeType.GetConstructor(new [] { typeof(Node) });
                            if (constructorInfo != null)
                            {
                                Node node = (Node)constructorInfo.Invoke(new object[] { values.Pop() });
                                values.Push(node);
                            }
                        }

                        if (opeDesc.NodeType.IsSubclassOf(typeof(BinaryNode)))
                        {
                            System.Reflection.ConstructorInfo constructorInfo = opeDesc.NodeType.GetConstructor(new [] { typeof(Node), typeof(Node) });
                            if (constructorInfo != null)
                            {
                                Node right = values.Pop();
                                Node left  = values.Pop();
                                Node node  = (Node)constructorInfo.Invoke(new object[] { left, right });
                                values.Push(node);
                            }
                        }
                    }
                }
                else
                {
                    double value;
                    if (double.TryParse(token, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture.NumberFormat, out value))
                    {
                        Node node = new ValueNode(value);
                        values.Push(node);
                    }
                    else
                    {
                        Node node = new VarNode(token);
                        values.Push(node);
                    }
                }
            }

            if (values.Count != 1)
            {
                throw new System.InvalidOperationException("Cannot calculate formula");
            }

            return(values.Pop());
        }