public PT()
 {
     NodesStack = new System.Collections.Stack();
     pascalABC_lambda_definitions = new List <function_lambda_definition>();
     pascalABC_var_statements     = new List <var_def_statement>();
     pascalABC_type_declarations  = new List <type_declaration>();
 }
Ejemplo n.º 2
0
        public int solution(String S)
        {
            // 100%

            if (S.Length % 2 != 0)
            {
                return(0);
            }

            System.Collections.Stack stack = new System.Collections.Stack();
            var array = S.ToArray();

            for (int i = 0; i < S.Length; i++)
            {
                if (array[i] == '(')
                {
                    stack.Push(array[i]);
                }
                else
                {
                    var compare = stack.Count == 0 ? '@' : (char)stack.Pop();
                    if (compare != '(')
                    {
                        return(0);
                    }
                }
            }

            return(stack.Count == 0 ? 1 : 0);
        }
Ejemplo n.º 3
0
 public static void MostrarPila(System.Collections.Stack pila)
 {
     foreach (int intA in pila)
     {
         Console.WriteLine(intA);
     }
 }
Ejemplo n.º 4
0
        static void Main(string[] args)
        {
            System.Collections.Stack stack = new System.Collections.Stack();

            // TickCount is less accurate property
            int start = Environment.TickCount;
            // Ticks are measuring in 100 nanoseconds intervals
            long startLong = DateTime.Now.Ticks;

            long ctr1 = 0, ctr2 = 0, freq = 0;

            if (QueryPerformanceCounter(ref ctr1) != 0)                 // Begin timing.
            {
                for (int i = 0; i < 800000; i++)
                {
                    stack.Push(i);
                }
                QueryPerformanceCounter(ref ctr2);                      // Finish timing.
                QueryPerformanceFrequency(ref freq);
                Console.WriteLine("QueryPerformanceCounter minimum resolution: 1/" + freq + " seconds.");
                Console.WriteLine("100 Increment time: " + (ctr2 - ctr1) * 1.0 / freq + " seconds.");
            }

            int  end     = Environment.TickCount;
            long endLong = DateTime.Now.Ticks;

            Console.WriteLine("TickCount property:" + (end - start));
            Console.WriteLine("Ticks property:" + (endLong - startLong));

            Console.ReadLine();
        }
Ejemplo n.º 5
0
        // LIFO (Last In, First Out)
        public Stack()
        {
            Console.WriteLine("=> Stack");

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

            foreach (int number in new int[] { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21 })
            {
                numbers.Push(number);
                Console.WriteLine("Number: {0} has been pushed on the stack.", number); // entra na pilha
            }

            Console.Write("Iterator: ");

            foreach (int number in numbers)
            {
                Console.Write("{0} ", number);
            }

            // Peek method reads without remove it

            // for (int i = 0; i < numbers.Count; i++)
            //     Console.Write("{0}:{1} ", i, (int)numbers.Peek());

            Console.WriteLine();

            while (numbers.Count > 0)
            {
                int number = (int)numbers.Pop();
                Console.WriteLine("Number: {0} has been popped of the stack.", number); // saiu da pilha
            }

            Console.WriteLine();
        }
Ejemplo n.º 6
0
        /// <summary>
        /// takes an string as an input and checks if the parenthesis are valid or not
        /// Result is displayed as text in console
        /// </summary>
        /// <param name="input">Input String</param>
        public static void ValidataParenthesis(string input)
        {
            System.Collections.Stack s = new System.Collections.Stack();
            Dictionary <char, char>  parenthesisPair = new Dictionary <char, char>();

            parenthesisPair.Add('}', '{');
            parenthesisPair.Add(')', '(');
            parenthesisPair.Add(']', '[');
            char temp;

            foreach (char x in input)
            {
                if (x == '(' || x == '{' || x == '[')
                {
                    s.Push(x);
                }
                else if (x == '}' || x == ')' || x == ']')
                {
                    temp = Convert.ToChar(s.Pop());
                    if (parenthesisPair[x] != temp)
                    {
                        Console.WriteLine("Doesn't Match");
                        return;
                    }
                }
            }
            if (s.Count > 0)
            {
                Console.WriteLine("Doesn't Match");
                return;
            }
            Console.WriteLine("Valid Parenthesis");
        }
Ejemplo n.º 7
0
        public void RemoveKey(string key)
        {
            if (!Exists(key))
            {
                return;
            }
            var route = new Stack <TrieNode>();
            var node  = Root;

            foreach (var letter in key)
            {
                route.Push(node);
                node = node.Next(letter);
            }
            node.IsTerminal = false;
            foreach (var letter in key)
            {
                var parentNode = route.Pop();
                if (parentNode.Next(key[route.Count]).IsTerminal ||
                    parentNode.Next(key[route.Count]).Edges.Count > 0)
                {
                    return;
                }
                parentNode.Edges.Remove(key[route.Count]);
            }
        }
Ejemplo n.º 8
0
 public TransportShip(string name, int size)
 {
     Name      = name;
     Size      = size;
     Storage   = new System.Collections.Stack();
     Available = Size;
 }
Ejemplo n.º 9
0
        //brute force 100% correct
        public int solution(int[] A, int[] B)
        {
            System.Collections.Stack st = new System.Collections.Stack();
            int count = 0;

            for (int i = 0; i < A.Length; i++)
            {
                if (B[i] == 1)
                {
                    st.Push(i);
                }
                else
                {
                    while (st.Count > 0)
                    {
                        if (A[(int)st.Peek()] < A[i])
                        {
                            st.Pop();
                        }
                        else
                        {
                            break;
                        }
                    }
                    if (st.Count == 0)
                    {
                        count++;
                    }
                }
            }


            return(count + st.Count);
        }
Ejemplo n.º 10
0
 internal JJTIDLParserState()
 {
     nodes = new System.Collections.Stack();
     marks = new System.Collections.Stack();
     sp    = 0;
     mk    = 0;
 }
Ejemplo n.º 11
0
        //Brute force solution 100% correct
        public int solution(int[] H)
        {
            System.Collections.Stack st = new System.Collections.Stack();

            int b;
            int counter    = 0;
            int wallHeight = 0;

            for (int i = 0; i < H.Length; i++)
            {
                while (wallHeight > H[i] && st.Count > 0)
                {
                    b           = (int)st.Pop();;
                    wallHeight -= b;
                }

                if (wallHeight < H[i])
                {
                    counter++;
                    b           = H[i] - wallHeight;
                    wallHeight += b;
                    st.Push(b);
                }
            }

            return(counter);
        }
    public static void Main()
    {
        Console.WriteLine("List<int>");
        new List <int> {
            1, 2, 3
        }.DoSomething();
        Console.WriteLine("List<string>");
        new List <string> {
            "a", "b", "c"
        }.DoSomething();
        Console.WriteLine("int[]");
        new int[] { 1, 2, 3 }.DoSomething();
        Console.WriteLine("string[]");
        new string[] { "a", "b", "c" }.DoSomething();
        Console.WriteLine("nongeneric collection with ints");
        var stack = new System.Collections.Stack();

        stack.Push(1);
        stack.Push(2);
        stack.Push(3);
        stack.DoSomething();
        Console.WriteLine("nongeneric collection with mixed items");
        new System.Collections.ArrayList {
            1, "a", null
        }.DoSomething();
        Console.WriteLine("nongeneric collection with .. bits");
        new System.Collections.BitArray(0x6D).DoSomething();
    }
Ejemplo n.º 13
0
 public AllObjectCollections(
     System.Collections.ArrayList prop0,
     System.Collections.IEnumerable prop1,
     System.Collections.ICollection prop2,
     System.Collections.IList prop3,
     System.Collections.Hashtable prop4,
     System.Collections.IDictionary prop5,
     System.Collections.Specialized.HybridDictionary prop6,
     System.Collections.Specialized.NameValueCollection prop7,
     System.Collections.BitArray prop8,
     System.Collections.Queue prop9,
     System.Collections.Stack prop10,
     System.Collections.SortedList prop11)
 {
     Prop0  = prop0;
     Prop1  = prop1;
     Prop2  = prop2;
     Prop3  = prop3;
     Prop4  = prop4;
     Prop5  = prop5;
     Prop6  = prop6;
     Prop7  = prop7;
     Prop8  = prop8;
     Prop9  = prop9;
     Prop10 = prop10;
     Prop11 = prop11;
 }
        public bool SyntaxError(lr_parser parser, Symbol curToken)
        {
            TypeCobolProgramParser tcpParser = parser as TypeCobolProgramParser;

            if (tcpParser.IsTrial)
            {
                return(true);
            }
            List <string> expected = ExpectedSymbols(parser, curToken);
            string        symName  = CodeElementTokenizer.CupTokenToString(curToken.sym);
            string        text     = (curToken.value as CodeElement).Text;
            string        msg      = string.Format("extraneous input '{0}' expecting {{{1}}}", text, string.Join(", ", expected));

            System.Diagnostics.Debug.WriteLine(msg);
            CupParserDiagnostic diagnostic = new CupParserDiagnostic(msg, curToken, null);

            AddDiagnostic(diagnostic);
            //Try to add the last encountered statement in the stack if it is not already entered.
            System.Collections.Stack stack = tcpParser.getParserStack();
            object[] items = stack.ToArray();
            foreach (var item in items)
            {
                Symbol symbol = item as Symbol;
                if (symbol.value is StatementElement)
                {
                    lr_parser stmtParser = CloneParser(parser, (int)TypeCobolProgramSymbols.StatementEntryPoint,
                                                       symbol.value as CodeElement, true);
                    stmtParser.parse();
                    break;
                }
            }
            return(true);
        }
        // <summary>
        /// 十进制转换为十六进制
        /// </summary>
        /// <param name="x"></param>
        /// <returns></returns>
        public static string toHexString(this string x)
        {
            if (string.IsNullOrEmpty(x))
            {
                return("0");
            }



            string z = null;
            int    X = Convert.ToInt32(x);

            System.Collections.Stack a = new System.Collections.Stack();
            int i = 0;

            while (X > 0)
            {
                a.Push(Convert.ToString(X % 16));
                X = X / 16;
                i++;
            }
            while (a.Count != 0)
            {
                z += ToHex(Convert.ToString(a.Pop()));
            }
            if (string.IsNullOrEmpty(z))
            {
                z = "0";
            }
            return(z);
        }
 protected void Page_Command(object sender, CommandEventArgs e)
 {
     try
     {
         if (e.CommandName == "Search")
         {
             // 10/13/2005 Paul.  Make sure to clear the page index prior to applying search.
             grdMain.CurrentPageIndex = 0;
             grdMain.ApplySort();
             grdMain.DataBind();
         }
         // 12/14/2007 Paul.  We need to capture the sort event from the SearchView.
         else if (e.CommandName == "SortGrid")
         {
             grdMain.SetSortFields(e.CommandArgument as string[]);
         }
         else if (e.CommandName == "MassDelete")
         {
             string[] arrID = Request.Form.GetValues("chkMain");
             if (arrID != null)
             {
                 // 10/26/2007 Paul.  Use a stack to run the update in blocks of under 200 IDs.
                 //string sIDs = Utils.ValidateIDs(arrID);
                 System.Collections.Stack stk = Utils.FilterByACL_Stack(m_sMODULE, "delete", arrID, "EMAIL_TEMPLATES");
                 if (stk.Count > 0)
                 {
                     DbProviderFactory dbf = DbProviderFactories.GetFactory();
                     using (IDbConnection con = dbf.CreateConnection())
                     {
                         con.Open();
                         using (IDbTransaction trn = con.BeginTransaction())
                         {
                             try
                             {
                                 while (stk.Count > 0)
                                 {
                                     string sIDs = Utils.BuildMassIDs(stk);
                                     SqlProcs.spEMAIL_TEMPLATES_MassDelete(sIDs, trn);
                                 }
                                 trn.Commit();
                             }
                             catch (Exception ex)
                             {
                                 trn.Rollback();
                                 throw(new Exception(ex.Message, ex.InnerException));
                             }
                         }
                     }
                     Response.Redirect("default.aspx");
                 }
             }
         }
     }
     catch (Exception ex)
     {
         SplendidError.SystemError(new StackTrace(true).GetFrame(0), ex);
         lblError.Text = ex.Message;
     }
 }
Ejemplo n.º 17
0
        static void Main(string[] args)
        {
            System.Collections.ArrayList lst1 = new System.Collections.ArrayList();
            lst1.Add("a");
            lst1.Add("b");
            lst1.Insert(1, "c");
            foreach (var item in lst1)
            {
                Console.WriteLine(item);
            }
            for (int i = 0; i < lst1.Count; i++)
            {
                Console.WriteLine(lst1[i]);
            }

            System.Collections.Hashtable lst2 = new System.Collections.Hashtable();
            lst2.Add("123", "anders");
            lst2.Add("124", "lene");
            Console.WriteLine(lst2["124"]);

            //System.Collections.Queue
            System.Collections.Stack s = new System.Collections.Stack();
            s.Push("1");
            s.Push("2");
            s.Push("3");
            var o = s.Pop();

            Garage g = new Garage();

            g.SætBilIGarage(new Bil()
            {
                Mærke = "Volvo"
            });
            g.SætBilIGarage(new Bil()
            {
                Mærke = "BMW"
            });


            System.Collections.Generic.List <string> lst3 = new List <string>();
            lst3.Add("1");
            string r = lst3[0];

            System.Collections.Generic.List <Bil> lst4 = new List <Bil>();
            lst4.Add(new Bil());

            System.Collections.Generic.Queue <int>              lst5 = new Queue <int>();
            System.Collections.Generic.Stack <string>           lst6 = new Stack <string>();
            System.Collections.Generic.Dictionary <string, int> lst7 = new Dictionary <string, int>();
            lst7.Add("123", 5);
            lst7.Add("125", 6);

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

            lst8.Add(3);
            lst8.Add(6);
            lst8.Add(6);
            Test2(lst8.ToArray());
        }
Ejemplo n.º 18
0
 public void CheckMethodSpecAdmissibility(Expression exp, Method method, bool reportWFonly, bool dontReport) {
   DeclaringMethod = method;
   ReportWFErrorOnly = reportWFonly; // true for Pure methods: we only want to enforce well-foundedness on them
   DontReportError = dontReport;     
   StateStack = new System.Collections.Stack();
   ResetCurrentState();
   this.VisitExpression(exp);
 }
Ejemplo n.º 19
0
 public NavigationService()
 {
     RegisteredTypes = (from assembly in AppDomain.CurrentDomain.GetAssemblies()
                        from type in assembly.GetTypes()
                        where Attribute.IsDefined(type, typeof(ActivityAttribute))
                        select type).ToList();
     _data       = new Stack <object>();
     _returnData = new Stack <object>();
 }
Ejemplo n.º 20
0
        public int solution(int[] A)
        {
            candidate dominator = new candidate()
            {
                dominator = -1, index = -1
            };
            candidate first;
            candidate second;

            int count = 0;

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

            for (int i = 0; i < A.Length; i++)
            {
                st.Push(new candidate()
                {
                    dominator = A[i], index = i
                });

                if (st.Count > 1)
                {
                    first  = (candidate)st.Pop();
                    second = (candidate)st.Pop();

                    if (first.dominator == second.dominator)
                    {
                        st.Push(second);
                        st.Push(first);
                    }
                }
            }

            if (st.Count > 0)
            {
                dominator = (candidate)st.Pop();
                for (int i = 0; i < A.Length; i++)
                {
                    if (A[i] == dominator.dominator)
                    {
                        count++;
                    }
                }

                if (count <= A.Length / 2)
                {
                    return(-1);
                }
            }
            else
            {
                return(-1);
            }

            return(dominator.index);
        }
Ejemplo n.º 21
0
 public ProbeController(IProbe probe, string name, Config.ProbeType probeType, int startingTargetTemp)
 {
     _probe = probe;
     Name = name;
     ProbeType = probeType;
     TargetTemp = startingTargetTemp;
     State = Config.ProbeState.Unavailable;
     TargetReachedTimes = new System.Collections.ArrayList();
     TargetReachedTimespans = new System.Collections.Stack();
 }
Ejemplo n.º 22
0
    public XmlDocumentSerializationInfo(XmlDocument doc)
    {
      m_Doc = doc;
      m_SurrogateSelector = new XmlSurrogateSelector();
      m_SurrogateSelector.TraceLoadedAssembliesForSurrogates();
      m_NodeStack = new System.Collections.Stack();

      if(m_Doc.ChildNodes.Count>0)
        m_CurrentNode = (XmlElement)m_Doc.FirstChild;
    }
Ejemplo n.º 23
0
 public ProbeController(IProbe probe, string name, Config.ProbeType probeType, int startingTargetTemp)
 {
     _probe                 = probe;
     Name                   = name;
     ProbeType              = probeType;
     TargetTemp             = startingTargetTemp;
     State                  = Config.ProbeState.Unavailable;
     TargetReachedTimes     = new System.Collections.ArrayList();
     TargetReachedTimespans = new System.Collections.Stack();
 }
Ejemplo n.º 24
0
        //-----------------------------------------------------------
        // Member functions.
        //

        public FSMContext(State state)
        {
            // There is no state until the application explicitly
            // sets the initial state.
            name_          = "FSMContext";
            state_         = state;
            transition_    = "";
            previousState_ = null;
            stateStack_    = new System.Collections.Stack();
        } // end of FSMContext()
Ejemplo n.º 25
0
        /// <summary>
        /// Muestra los Valores de un Stack
        /// </summary>
        /// <param name="Stack">Un Array Stack</param>
        /// <param name="algumento">Un Texto por delante</param>
        /// <param name="salto">El Tipo de Salto</param>
        public void Show
            (System.Collections.Stack Stack, string algumento, int salto = 1)
        {
            foreach (object fruta in Stack)
            {
                System.Console.Write("{1}-> {0}\n", fruta, algumento);
            }

            LineasEsp.Salto(salto);
        }
Ejemplo n.º 26
0
        protected PathVObject(string name)
        {
            base.Name       = name;
            _matrix         = new System.Drawing.Drawing2D.Matrix();
            _identityMatrix = new System.Drawing.Drawing2D.Matrix();

            _pen           = new System.Drawing.Pen(System.Drawing.Color.Black, 1.0f);
            _pen.LineJoin  = System.Drawing.Drawing2D.LineJoin.Bevel;
            _brush         = new System.Drawing.SolidBrush(System.Drawing.Color.White);
            _brushMatrices = new System.Collections.Stack();
        }
Ejemplo n.º 27
0
 public void CheckModelfieldAdmissibility(ModelfieldContract mfC) {
   this.DeclaringMfC = mfC;
   this.DeclaringMember = mfC.Modelfield;
   if (this.DeclaringMember is Property)
     this.DeclaringMember = (this.DeclaringMember as Property).Getter; //references to the modelfield have been resolved as bindings to this getter
   foreach (Expression satExpr in mfC.SatisfiesList) {
     StateStack = new System.Collections.Stack();
     ResetCurrentState();
     this.VisitExpression(satExpr);
   }
 }
        public void WhenNoItemsStoredStackIsEmpty()
        {
            // Arrange
            var t     = new System.Collections.Stack();
            var stack = new Stack <int>();

            // Act
            var result = stack.IsEmpty;

            // Assert
            True(result);
        }
        public XmlDocumentSerializationInfo(XmlDocument doc)
        {
            m_Doc = doc;
            m_SurrogateSelector = new XmlSurrogateSelector();
            m_SurrogateSelector.TraceLoadedAssembliesForSurrogates();
            m_NodeStack = new System.Collections.Stack();

            if (m_Doc.ChildNodes.Count > 0)
            {
                m_CurrentNode = (XmlElement)m_Doc.FirstChild;
            }
        }
Ejemplo n.º 30
0
        private result getLeader(int[] B, int sIndex, int eIndex)
        {
            int    candidate = 0;
            int    count     = 0;
            int    Length    = eIndex - sIndex + 1;
            int    first     = 0;
            int    second    = 0;
            result r         = new result()
            {
                hasLeader = false, leader = 0, count = 0
            };

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

            for (int i = sIndex; i <= eIndex; i++)
            {
                st.Push(B[i]);

                if (st.Count > 1)
                {
                    first  = (int)st.Pop();
                    second = (int)st.Pop();
                    if (first == second)
                    {
                        st.Push(second);
                        st.Push(first);
                    }
                }
            }

            if (st.Count > 0)
            {
                candidate = (int)st.Pop();

                for (int i = sIndex; i <= eIndex; i++)
                {
                    if (B[i] == candidate)
                    {
                        count++;
                    }
                }

                if (count > Length / 2)
                {
                    r.hasLeader = true;
                    r.leader    = candidate;
                    r.count     = count;
                }
            }

            return(r);
        }
Ejemplo n.º 31
0
        static void Main(string[] args)
        {
            int[]    a = { 1, 2, 3 };
            double[] b = { 1.1, 2.2, 3.3 };
            char[]   c = { 'a', 'b', 'c' };
            Display(a);                                                     //效果类似于Display(int[] arr)
            Display(b);                                                     //效果类似于Display(double[] arr)
            Display(c);                                                     //效果类似于Display(char[] arr)

            Stack <int> s = new Stack <int>(10);                            //通过泛型创建一个int型数组

            System.Collections.Stack s1 = new System.Collections.Stack(12); //非泛型的Stack,元素类型object
        }
Ejemplo n.º 32
0
        protected PathVObject(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
            : base(info, context)
        {
            if (info == null)
            {
                throw new System.ArgumentNullException("info");
            }

            _brushMatrices = new System.Collections.Stack();

            _matrix = BinarySerializer.DeserializeMatrix((byte[])info.GetValue(SerializationNames.Matrix, typeof(byte[])));
            _pen    = BinarySerializer.DeserializePen((byte[])info.GetValue(SerializationNames.Pen, typeof(byte[])));
            _brush  = BinarySerializer.DeserializeBrush((byte[])info.GetValue(SerializationNames.Brush, typeof(byte[])));
        }
Ejemplo n.º 33
0
 public Form1()
 {
     InitializeComponent();
     image                   = null;
     video                   = null;
     cut                     = null;
     cutx                    = 0;
     cuty                    = 0;
     curFrame                = 0;
     history                 = new System.Collections.Stack();
     this.KeyDown           += Form1_KeyDown;
     pictureBox2.MouseWheel += pictureBox2_onMouseWheelRolled;
     Response("Press 'c' to use command. Commands: openpicture, openvideo, size, position, jump, progress. help [command] to get tips.");
 }
Ejemplo n.º 34
0
        static void Main(string[] args)
        {
            System.Collections.Stack stack = new System.Collections.Stack();
            stack.Push(1);
            stack.Push(2);
            stack.Push(3);

            Console.WriteLine("1 in stack:{0}", stack.Contains(1));
            Console.WriteLine("Remove 1:{0}", stack.Pop());
            Console.WriteLine("Peek1:{0}", stack.Peek());

            object[] numArray = stack.ToArray();
            Console.WriteLine(string.Join(", ", numArray));
        }
Ejemplo n.º 35
0
        public override void execute(StackFrame frame)
        {
            Object obj = frame.popOperand();

            System.Collections.Stack temp = new System.Collections.Stack();
            for (int i = 0; i < depth; i++){
                temp.Push(frame.popOperand());
            }
            frame.pushOperand(obj); // insert at depth depth

            while (temp.Count > 0){
                frame.pushOperand(temp.Pop());
            }

            frame.pushOperand(obj); // put the duplicated one back on top
        }
Ejemplo n.º 36
0
        public void Rewind()
        {
            //EH.Put("Rewind called");
            MethodNode nodeToExecute = null;
            if (this.m_callStack != null)
            {
                //find first item in stack (i.e., the first called method)
                while (this.m_callStack.Count > 1)
                    this.m_callStack.Pop();
                nodeToExecute = (MethodNode)this.m_callStack.Pop();
            }

            this.m_callStack = new System.Collections.Stack();
            this.m_valueStack = new System.Collections.ArrayList();
            this.m_currentNode = null;
            if (nodeToExecute != null)
                this.m_callStack.Push(nodeToExecute);
        }
Ejemplo n.º 37
0
        public static bool verifyPopFromPush(double[] push, double[] pop)
        {
            int index_push = 0;
            int index_pop = 0;
            System.Collections.Stack s = new System.Collections.Stack();

            while (true)
            {
                while (s.Count == 0 || pop[index_pop] != (double)s.Peek())
                {
                    if (index_push > push.Length - 1)
                    {
                        break;
                    }
                    s.Push(push[index_push]);
                    index_push++;

                }

                if ((double)s.Pop() != pop[index_pop])
                {
                    break;
                }
                index_pop++;
                if (index_pop > pop.Length - 1)
                {
                    break;
                }

            }

            if (index_push == push.Length && index_pop == pop.Length && s.Count == 0)
            {
                return true;
            }

            return false;
        }
Ejemplo n.º 38
0
        private static void SnipVoidDir(DirectoryInfo dTarget)
        {
            try
            {
                System.Collections.Stack stackDirs = new System.Collections.Stack();

                //Sub-subdirs
                SnipVoidRound(dTarget, stackDirs);

                //SubDirs
                SnipVoidRound(dTarget, stackDirs);
            }
            catch (Exception)
            {

                throw;
            }
        }
Ejemplo n.º 39
0
		/// <summary>
		/// Insert the newKey into this B-tree, 
		/// </summary>
		/// <param name="newKey"></param>
		/// <returns></returns>
		public bool Insert(IKey newKey)
		{
			//find the leaf where the newKey should be in
			BNode n = m_top;
			System.Collections.Stack visited = new System.Collections.Stack();
			int pos = -1;
			while (!n.Leaf)
			{
				IKey temp = n.SearchKey(newKey, ref pos);
				if (temp == null)
				{
					uint nextNodeId = n.GetChildAt(pos);
					visited.Push(n);
					
					n = (BNode)m_sgManager.GetSegment(nextNodeId, m_nodeFactory, m_keyFactory);
				}
				else
					return false;
			}
			
			//now BNode n is the leaf where insert should happen
			IKey t_temp = n.SearchKey(newKey, ref pos);
			if (t_temp == null)
			{
				//not exists, go ahead to insert the new key
				if (!n.IsFull)
				{
					n.InsertAtLeaf(newKey, pos);

					return true;
				}
				else
				{
					//split needed for this node
					BNode right = new BNode();
					m_sgManager.GetNewSegment(right);
					IKey median = null;
					n.SplitAtLeaf(newKey, pos,  ref median, ref right); //this split is at leaf

					bool finished = false;					
					//now n holds the left half of the items, 
					//right holds the right half items, median is the middle key

					while (!finished)
					{			
						//parent is node middle key will be inserted
						BNode parent = (visited.Count >0 ? (BNode)visited.Pop() : null);

						if (parent == null)
						{
							//new top node is needed
							BNode new_top = new BNode();
							m_sgManager.GetNewSegment(new_top);
							new_top.SetOrder(m_top.Order);
							new_top.Leaf = false;
							new_top.InsertFirstKey(median, n.SegmentID, right.SegmentID);

							this.m_top_sid = new_top.SegmentID;

							return true;
						}
						else
						{
							IKey tt = parent.SearchKey(median, ref pos);
							if (tt != null)
								return false;

							if (!parent.IsFull)
							{
								parent.InsertAtInternal(median, pos, right.SegmentID);
								return true;
							}
							else
							{
								//parent is full again
								BNode newRight = new BNode();
								m_sgManager.GetNewSegment(newRight);
								newRight.SetOrder(parent.Order);
								newRight.Leaf = parent.Leaf;
								//this split will insert median into the parent, then split and new middle key is newMedian
								IKey newMedian;
								parent.SplitAtInternal(median, pos, right.SegmentID, out newMedian, newRight);

								n = parent;
								median = newMedian;
								right = newRight;
							}

						}

					}


				}
			}
			else
				return false;

			return false;
		}
Ejemplo n.º 40
0
 /// <summary> Constructs a Filter object that will be built up piece by piece.   </summary>
 public RfcFilter()
     : base(null)
 {
     filterStack = new System.Collections.Stack();
     //The choice value must be set later: setChoiceValue(rootFilterTag)
     return ;
 }
	private void  InitBlock() {
	    filenameStack = new System.Collections.Stack();
	}
Ejemplo n.º 42
0
 /* **********************************************************************
 *  The following methods aid in building filters sequentially,
 *  and is used by DSMLHandler:
 ***********************************************************************/
 /// <summary> Called by sequential filter building methods to add to a filter
 /// component.
 /// 
 /// Verifies that the specified Asn1Object can be added, then adds the
 /// object to the filter.
 /// </summary>
 /// <param name="current">  Filter component to be added to the filter
 /// @throws LdapLocalException Occurs when an invalid component is added, or
 /// when the component is out of sequence.
 /// </param>
 private void addObject(Asn1Object current)
 {
     if (filterStack == null)
     {
         filterStack = new System.Collections.Stack();
     }
     if (choiceValue() == null)
     {
         //ChoiceValue is the root Asn1 node
         ChoiceValue = current;
     }
     else
     {
         Asn1Tagged topOfStack = (Asn1Tagged) filterStack.Peek();
         Asn1Object value_Renamed = topOfStack.taggedValue();
         if (value_Renamed == null)
         {
             topOfStack.TaggedValue = current;
             filterStack.Push(current);
     //					filterStack.Add(current);
         }
         else if (value_Renamed is Asn1SetOf)
         {
             ((Asn1SetOf) value_Renamed).add(current);
             //don't add this to the stack:
         }
         else if (value_Renamed is Asn1Set)
         {
             ((Asn1Set) value_Renamed).add(current);
             //don't add this to the stack:
         }
         else if (value_Renamed.getIdentifier().Tag == LdapSearchRequest.NOT)
         {
             throw new LdapLocalException("Attemp to create more than one 'not' sub-filter", LdapException.FILTER_ERROR);
         }
     }
     int type = current.getIdentifier().Tag;
     if (type == AND || type == OR || type == NOT)
     {
     //				filterStack.Add(current);
         filterStack.Push(current);
     }
     return ;
 }
Ejemplo n.º 43
0
        private void ConvertFileNewID()
        {
            Application.UseWaitCursor = true;
            toolStripStatusLabel1.Text = "Creating IDs... Please Wait";
            this.Refresh();
            string strContent = "";

            string[] strLines;

            stkIDs = new System.Collections.Stack();
            stkIDs.Clear();

            strContent = rtbContent.Text;
            strLines = strContent.Split('\n');
            long i = strLines.Length;

            toolStripProgressBar1.Maximum = Convert.ToInt32(i);
            toolStripProgressBar1.Minimum = 1;
            toolStripProgressBar1.Value = 1;
            this.Refresh();

            string strID = "";

            #region First Loop

            //Creating IDs
            for (int j = 0; j < i; j++)
            {

                if (strLines[j].StartsWith("<preface") || strLines[j].StartsWith("<chapter") || strLines[j].StartsWith("<sect") || strLines[j].StartsWith("<figure") || strLines[j].StartsWith("<table") || strLines[j].StartsWith("<sidebar") || strLines[j].StartsWith("<example") || strLines[j].StartsWith("<appendix") || strLines[j].StartsWith("<part") || strLines[j].StartsWith("<glossary")) // || strLines[j].StartsWith("<preface")
                {
                    //MessageBox.Show(strLines[j]);
                    strLines[j] = Regex.Replace(strLines[j], "^(.*) id=\"([^\"]*)\"(.*)$", "$1$3");
                    //MessageBox.Show(strLines[j]);
                    strLines[j] = strLines[j].Insert(strLines[j].LastIndexOf(">"), " id=\"****\"");
                    //MessageBox.Show(strLines[j]);

                }

                toolStripProgressBar1.Increment(1);
                if (strLines[j].StartsWith("<title>"))
                {
                    strID = CreateID(Regex.Replace(strLines[j], "<title>(.*)</title>", "$1"));

                    if (strLines[j - 1].IndexOf("id=\"*") >= 0)
                    {

                        /*if (strLines[j - 1].StartsWith("<preface"))
                        {
                            strLines[j - 1] = strLines[j - 1].Insert(strLines[j - 1].IndexOf("id=") + 4, "preface").Replace("*", "");
                        }
                        else
                        {
                        */
                            strLines[j - 1] = strLines[j - 1].Insert(strLines[j - 1].IndexOf("id=") + 4, strID).Replace("*", "");
                        //}
                    }
                    else
                    {
                        if (strLines[j - 2].IndexOf("id=\"*") >= 0)
                        {
                            /*
                            if (strLines[j - 2].StartsWith("<preface"))
                            {
                                strLines[j - 2] = strLines[j - 2].Insert(strLines[j - 2].IndexOf("id=") + 4, "preface").Replace("*", "");
                            }
                            else
                            {
                             */
                                strLines[j - 2] = strLines[j - 2].Insert(strLines[j - 2].IndexOf("id=") + 4, strID).Replace("*", "");
                            //}
                        }
                    }

                }

            }

            #endregion

            this.Refresh();

            rtbContent.Text = string.Join("\n", strLines);
            toolStripStatusLabel1.Text = "Ready";
            Application.UseWaitCursor = false;
        }
Ejemplo n.º 44
0
    protected void Interpret(Graphics g)
    {
      this._isMeasureInSync = false; // if structure is changed, the measure is out of sync

      char[] searchchars = new Char[] { '\\', '\r', '\n', ')' };

      // Modification of StringFormat is necessary to avoid 
      // too big spaces between successive words
      StringFormat strfmt = (StringFormat)StringFormat.GenericTypographic.Clone();
      strfmt.FormatFlags |= StringFormatFlags.MeasureTrailingSpaces;

      strfmt.LineAlignment = StringAlignment.Far;
      strfmt.Alignment = StringAlignment.Near;

      // next statement is necessary to have a consistent string length both
      // on 0 degree rotated text and rotated text
      // without this statement, the text is fitted to the pixel grid, which
      // leads to "steps" during scaling
      g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;

      MeasureFont(g, _font, out _cyBaseLineSpace, out _cyBaseAscent, out _cyBaseDescent);

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

      Font currFont = (Font)_font.Clone();


      if(null!=_cachedTextLines)
        _cachedTextLines.Clear(); // delete old contents 
      else
        _cachedTextLines = new TextLine.TextLineCollection();


      TextLine currTextLine = new TextLine();
        
      // create a new text line first
      _cachedTextLines.Add(currTextLine);
      int currTxtIdx = 0;

      TextItem currTextItem = new TextItem(currFont);
      //      TextItem firstItem = currTextItem; // preserve the first item
      


      currTextLine.Add(currTextItem);


      while(currTxtIdx<_text.Length)
      {

        // search for the first occurence of a backslash
        int bi = _text.IndexOfAny(searchchars,currTxtIdx);

        if(bi<0) // nothing was found
        {
          // move the rest of the text to the current item
          currTextItem.Text += _text.Substring(currTxtIdx,_text.Length-currTxtIdx);
          currTxtIdx = _text.Length;
        }
        else // something was found
        {
          // first finish the current item by moving the text from
          // currTxtIdx to (bi-1) to the current text item
          currTextItem.Text += _text.Substring(currTxtIdx,bi-currTxtIdx);
          
          if('\r'==_text[bi]) // carriage return character : simply ignore it
          {
            // simply ignore this character, since we search for \n
            currTxtIdx=bi+1;
          }
          else if('\n'==_text[bi]) // newline character : create a new line
          {
            currTxtIdx = bi+1;
            // create a new line
            currTextLine = new TextLine();
            _cachedTextLines.Add(currTextLine);
            // create also a new text item
            currTextItem = new TextItem(currTextItem,null);
            currTextLine.Add(currTextItem);
          }
          else if('\\'==_text[bi]) // backslash : look what comes after
          {
            if(bi+1<_text.Length && (')'==_text[bi+1] || '\\'==_text[bi+1])) // if a closing brace or a backslash, take these as chars
            {
              currTextItem.Text += _text[bi+1];
              currTxtIdx = bi+2;
            }
              // if the backslash not followed by a symbol and than a (, 
            else if(bi+3<_text.Length && !char.IsSeparator(_text,bi+1) && '('==_text[bi+2])
            {
              switch(_text[bi+1])
              {
                case 'b':
                case 'B':
                {
                  itemstack.Push(currTextItem);
                  currTextItem = new TextItem(currTextItem, new Font(currTextItem.Font.FontFamily,currTextItem.Font.Size,currTextItem.Font.Style | FontStyle.Bold, GraphicsUnit.World));
                  currTextLine.Add(currTextItem);
                  currTxtIdx = bi+3;
                }
                  break; // bold
                case 'i':
                case 'I':
                {
                  itemstack.Push(currTextItem);
                  currTextItem = new TextItem(currTextItem, new Font(currTextItem.Font.FontFamily,currTextItem.Font.Size,currTextItem.Font.Style | FontStyle.Italic, GraphicsUnit.World));
                  currTextLine.Add(currTextItem);
                  currTxtIdx = bi+3;
                }
                  break; // italic
                case 'u':
                case 'U':
                {
                  itemstack.Push(currTextItem);
                  currTextItem = new TextItem(currTextItem, new Font(currTextItem.Font.FontFamily,currTextItem.Font.Size,currTextItem.Font.Style | FontStyle.Underline, GraphicsUnit.World));
                  currTextLine.Add(currTextItem);
                  currTxtIdx = bi+3;
                }
                  break; // underlined
                case 's':
                case 'S': // strikeout
                {
                  itemstack.Push(currTextItem);
                  currTextItem = new TextItem(currTextItem, new Font(currTextItem.Font.FontFamily,currTextItem.Font.Size,currTextItem.Font.Style | FontStyle.Strikeout, GraphicsUnit.World));
                  currTextLine.Add(currTextItem);
                  currTxtIdx = bi+3;
                }
                  break; // end strikeout
                case 'g':
                case 'G':
                {
                  itemstack.Push(currTextItem);
                  currTextItem = new TextItem(currTextItem, new Font("Symbol",currTextItem.Font.Size,currTextItem.Font.Style, GraphicsUnit.World));
                  currTextLine.Add(currTextItem);
                  currTxtIdx = bi+3;
                }
                  break; // underlined
                case '+':
                case '-':
                {
                  itemstack.Push(currTextItem);
                  // measure the current font size
                  float cyLineSpace,cyAscent,cyDescent;
                  MeasureFont(g,currTextItem.Font,out cyLineSpace, out cyAscent, out cyDescent);
                  
                  currTextItem = new TextItem(currTextItem, new Font(currTextItem.Font.FontFamily,0.65f*currTextItem.Font.Size,currTextItem.Font.Style, GraphicsUnit.World));
                  currTextLine.Add(currTextItem);
                  currTextItem.m_SubIndex += ('+'==_text[bi+1] ? 1 : -1);


                  if('-'==_text[bi+1]) 
                    currTextItem.m_yShift += 0.15f*cyAscent; // Carefull: plus (+) means shift down
                  else
                    currTextItem.m_yShift -= 0.35f*cyAscent; // be carefull: minus (-) means shift up
                  
                  currTxtIdx = bi+3;
                }
                  break; // underlined
                case 'l': // Plot Curve Symbol
                case 'L':
                {
                  // parse the arguments
                  // either in the Form 
                  // \L(PlotCurveNumber) or
                  // \L(LayerNumber, PlotCurveNumber) or
                  // \L(LayerNumber, PlotCurveNumber, DataPointNumber)


                  // find the corresponding closing brace
                  int closingbracepos = _text.IndexOf(")",bi+1);
                  if(closingbracepos<0) // no brace found, so threat this as normal text
                  {
                    currTextItem.Text += _text.Substring(bi,3);
                    currTxtIdx += 3;
                    continue;
                  }
                  // count the commas between here and the closing brace to get
                  // the number of arguments
                  int parsepos=bi+3;
                  int[] arg = new int[3];
                  int args;
                  for(args=0;args<3 && parsepos<closingbracepos;args++)
                  {
                    int commapos = _text.IndexOf(",",parsepos,closingbracepos-parsepos);
                    int endpos = commapos>0 ? commapos : closingbracepos; // the end of this argument
                    try { arg[args]=System.Convert.ToInt32(_text.Substring(parsepos,endpos-parsepos)); }
                    catch(Exception) { break; }
                    parsepos = endpos+1;
                  }
                  if(args==0) // if not successfully parsed at least one number
                  {
                    currTextItem.Text += _text.Substring(bi,3);
                    currTxtIdx += 3;
                    continue;   // handle it as if it where normal text
                  }

                  // itemstack.Push(currTextItem); // here we don't need to put the item on the stack, since we pared until the closing brace
                  currTextItem = new TextItem(currTextItem,null);
                  currTextLine.Add(currTextItem);
                  currTextItem.SetAsSymbol(args,arg);

                  currTextItem = new TextItem(currTextItem,null); // create a normal text item behind the symbol item
                  currTextLine.Add(currTextItem); // to have room for the following text
                  currTxtIdx = closingbracepos+1;
                }
                  break; // curve symbol
                case '%': // Plot Curve Name
                {
                  // parse the arguments
                  // either in the Form 
                  // \%(PlotCurveNumber) or
                  // \%(LayerNumber, PlotCurveNumber) or
                  Match match;
                  int layerNumber=-1;
                  int plotNumber=-1;
                  string plotLabelStyle=null;
                  bool   plotLabelStyleIsPropColName=false;
                  if((match = _regexIntArgument.Match(_text,bi+2)).Success)
                  {
                    plotNumber = int.Parse(match.Result("${argone}"));
                  }
                  else if((match = _regexIntIntArgument.Match(_text,bi+2)).Success)
                  {
                    layerNumber = int.Parse(match.Result("${argone}"));
                    plotNumber =  int.Parse(match.Result("${argtwo}"));
                  }
                  else if((match = _regexIntQstrgArgument.Match(_text,bi+2)).Success)
                  {
                    plotNumber     = int.Parse(match.Result("${argone}"));
                    plotLabelStyle =  match.Result("${argtwo}");
                    plotLabelStyleIsPropColName=true;
                  }
                  else if((match = _regexIntStrgArgument.Match(_text,bi+2)).Success)
                  {
                    plotNumber     = int.Parse(match.Result("${argone}"));
                    plotLabelStyle =  match.Result("${argtwo}");
                  }
                  else if((match = _regexIntIntStrgArgument.Match(_text,bi+2)).Success)
                  {
                    layerNumber = int.Parse(match.Result("${argone}"));
                    plotNumber =  int.Parse(match.Result("${argtwo}"));
                    plotLabelStyle = match.Result("${argthree}");
                  }
                  else if((match = _regexIntIntQstrgArgument.Match(_text,bi+2)).Success)
                  {
                    layerNumber = int.Parse(match.Result("${argone}"));
                    plotNumber =  int.Parse(match.Result("${argtwo}"));
                    plotLabelStyle = match.Result("${argthree}");
                    plotLabelStyleIsPropColName=true;
                  }
      
                  if(match.Success)
                  {
                    itemstack.Push(currTextItem);
                    currTextItem = new TextItem(currTextItem,null);
                    currTextLine.Add(currTextItem);
                    currTextItem.SetAsPlotCurveName(layerNumber,plotNumber,plotLabelStyle,plotLabelStyleIsPropColName);

                    currTextItem = new TextItem(currTextItem,null); // create a normal text item behind the symbol item
                    currTextLine.Add(currTextItem); // to have room for the following text
                    currTxtIdx = bi+2+match.Length;
                  }
                  else
                  {
                    currTextItem.Text += _text.Substring(bi,2);
                    currTxtIdx += 3;
                    continue;   // handle it as if it where normal text
                  }
                }
                  break; // percent symbol
                default:
                  // take the sequence as it is
                  currTextItem.Text += _text.Substring(bi,3);
                  currTxtIdx = bi+3;
                  break;
              } // end of switch
            }
            else // if no formatting and also no closing brace or backslash, take it as it is
            {
              currTextItem.Text += _text[bi];
              currTxtIdx = bi+1;
            }
          } // end if it was a backslash
          else if(')'==_text[bi]) // closing brace
          {
            // the formating is finished, we can return to the formating of the previous section
            if(itemstack.Count>0)
            {
              TextItem preservedprevious = (TextItem)itemstack.Pop();
              currTextItem = new TextItem(preservedprevious,null);
              currTextLine.Add(currTextItem);
              currTxtIdx = bi+1;
            }
            else // if the stack is empty, take the brace as it is, and use the default style
            {
              currTextItem.Text += _text[bi];
              currTxtIdx = bi+1;
            }

          }
        }

      } // end of while loop

      this._isStructureInSync=true; // now the text was interpreted
    }
Ejemplo n.º 45
0
        private void ConvertFootNote()
        {
            Application.UseWaitCursor = true;
            toolStripStatusLabel1.Text = "Converting Footnotes ... Please Wait";
            this.Refresh();
            string strContent = "";

            string[] strLines;

            stkIDs = new System.Collections.Stack();
            stkIDs.Clear();

            strContent = rtbContent.Text;
            strLines = strContent.Split('\n');
            long i = strLines.Length;

            toolStripProgressBar1.Maximum = Convert.ToInt32(i)+1;
            toolStripProgressBar1.Minimum = 1;
            toolStripProgressBar1.Value = 1;
            this.Refresh();

            bool blNoteStart = false;
            string strFn = "";
            long lnBibNo = 0;

            MatchCollection mc;

            #region First Loop

            //Creating IDs
            for (int j = 0; j < i; j++)
            {

                if (strLines[j].StartsWith("<note"))
                {

                    blNoteStart = true;
                    strLines[j] = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
                        "<!DOCTYPE noteGroup PUBLIC \"-//OXFORD//DTD OXCHAPML//EN\" \"OxChapML.dtd\">\n"+
                        "<!-- [DTD] OxChapML, v2.5 -->\n"+
                        "<!-- [TCI] Oxford Scholarship Online Text Capture Instructions, v1.2 -->\n" +
                        "<!-- [TCI] OUP Bibliographic reference capture, v1.15 -->\n"+
                        "<noteGroup>";

                }

                if (strLines[j].StartsWith("</note>"))
                {
                    blNoteStart = false;

                    strLines[j] = "</noteGroup>";
                }

                if (strLines[j].StartsWith("<fn"))
                {

                    strFn = Regex.Replace(strLines[j], "^<fn([0-9]+)>(.*)", "$1");

                    mc = Regex.Matches(strLines[j], "</bibn>", RegexOptions.RightToLeft);
                    int intFirstBibStart = 0;
                    int intFirstBibEnd = 0;
                    string strBIB = "";

                    foreach (Match singleMc in mc)
                    {
                        lnBibNo++;
                        intFirstBibStart = strLines[j].IndexOf("<bibn>");
                        intFirstBibEnd = strLines[j].IndexOf("</bibn>");
                        //MessageBox.Show(strLines[j]);
                        strBIB = strLines[j].Substring(intFirstBibStart, (intFirstBibEnd - intFirstBibStart) + 7);
                        //MessageBox.Show(strBIB);
                        strLines[j] = strLines[j].Remove(intFirstBibStart, (intFirstBibEnd - intFirstBibStart) + 7);
                        //MessageBox.Show(strLines[j]);
                        strLines[j] = strLines[j].Insert(intFirstBibStart, ConvertSingleBibn(strBIB, lnBibNo.ToString()));
                        //MessageBox.Show(strLines[j]);

                    }

                    strLines[j] = Regex.Replace(strLines[j], "^<fn([0-9]+)>(.*)</fn>$", "<note id=\"" + strIDPrefix + "-note-$1\" type=\"footnote\"><p><enumerator><sup>$1</sup></enumerator> $2</p></note>");

                }

                toolStripProgressBar1.Value = toolStripProgressBar1.Value + 1;

            }

            #endregion

            this.Refresh();

            rtbContent.Text = string.Join("\n", strLines);
            toolStripStatusLabel1.Text = "Ready";
            Application.UseWaitCursor = false;
        }
Ejemplo n.º 46
0
        private void ConvertFile2HTML()
        {
            Application.UseWaitCursor = true;
            toolStripStatusLabel1.Text = "Converting to HTML ... Please Wait";
            this.Refresh();
            string strContent = "";

            string[] strLines;

            stkIDs = new System.Collections.Stack();
            stkIDs.Clear();

            strContent = rtbContent.Text;
            strLines = strContent.Split('\n');
            long i = strLines.Length;

            toolStripProgressBar1.Maximum = Convert.ToInt32(i)+1;
            toolStripProgressBar1.Minimum = 1;
            toolStripProgressBar1.Value = 1;
            toolStripStatusLabel1.Text = "Creating TOC ... Please Wait";
            this.Refresh();

            //strIDPrefix

            //string strIDPrefix = "images/978-1-933988-54-2-text_img_";

            #region Variable Decl

            long lnPart = 0;
            long lnChapter = 0;
            long lnAppendix = 0;
            long lnPreface = 0;
            long lnSect1 = 0;
            long lnSect2 = 0;
            long lnSect3 = 0;
            long lnSidebar = 0;
            long lnFigure = 0;
            long lnTable = 0;
            long lnOrderedList = 0;
            long lnExample = 0;

            bool blAppendix = false;
            bool blSidebar = false;
            bool blitemizedlist = false;
            bool blorderedlist = false;
            bool blSectionStart = false;
            bool blblockquote = false;
            bool blCopyrightPage = false;
            bool blTable = false;
            bool blNote = false;
            bool blNoteStart = false;
            bool blProgramListingStart = false;
            bool blExampleStart = false;
            bool blTipStart = false;

            string strChapterNumber = "";
            string strCurrentFileName = "";
            string strTempID = "";
            string strTempID2 = "";
            string strTempID3 = "";
            string strTempID4 = "";
            string strTempID5 = "";
            string strTempID6 = "";
            string strTempID7 = "";
            #endregion

            #region Looping Through Lines

            #region Content

            strContent = rtbContent.Text;
            strLines = strContent.Split('\n');
            i = strLines.Length;
            string[] strContentsFile = new string[i];
            string[] strBrfContentsFile = new string[i];
            string strCtTitle = "";
            string strCtID = "";
            int intCtIndex = 0;
            int intBfCtIndex = 0;

            for (int j = 0; j < i; j++)
            {
                if (strLines[j].StartsWith("<chapter ") || strLines[j].StartsWith("<part ") || strLines[j].StartsWith("<preface ") || strLines[j].StartsWith("<sect1 ") || strLines[j].StartsWith("<sect2 ") || strLines[j].StartsWith("<appendix "))
                {
                    if (strLines[j].IndexOf("label=") >= 0)
                    {
                        strChapterNumber = Regex.Replace(strLines[j], "^(.*) label=\"([^\"]+)\"(.*)$", "$2") +" " ;
                    }
                    else
                    {
                        strChapterNumber = "";
                    }

                    if (strLines[j].IndexOf(" id=") > 0)
                    {
                        strTempID7 = Regex.Replace(strLines[j], "^(.*) id=\"([^\"]*)\"(.*)$", "$2");
                    }
                    else
                    {
                        strTempID7 = "";
                    }

                    j++;
                    if (strLines[j].StartsWith("<title>"))
                    {
                        strTempID6 = Regex.Replace(strLines[j], "^<title>(.*)</title>$", "$1");
                    }

                    j++;

                    if (strLines[j].StartsWith("<title>"))
                    {
                        strTempID6 = Regex.Replace(strLines[j], "^<title>(.*)</title>$", "$1");
                    }

                    strContentsFile[intCtIndex] = "<link linkend=\"" + strTempID7 + "\">" + strChapterNumber + strTempID6 + "</link><br/>";
                    intCtIndex++;
                }

                toolStripProgressBar1.Value = j + 1;

            }

            string strXML1 = "<split filename=\"toc.xhtml\">\n"+
                        "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n" +
                        "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n" +
                        "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n" +
                        "<head>\n" +
                        "<title>Contents</title>\n" +
                        "<link href=\"bv_ebook_style.css\" rel=\"stylesheet\" type=\"text/css\"/>\n" +
                        "<link rel=\"stylesheet\" type=\"application/vnd.adobe-page-template+xml\" href=\"page-template.xpgt\"/>\n" +
                        "</head>\n" +
                        "<body>\n" +
                        "<div>\n<a id=\"toc\"></a>\n";

            //rtbContent.Text = strXML1 + string.Join("\n", strContentsFile, 0, intCtIndex) + "\n</div>\n</body>\n</html>\n</split>\n" + rtbContent.Text;

            #endregion

            #region Breif_contents
            toolStripStatusLabel1.Text = "Creating Breif Contents ... Please Wait";
            toolStripProgressBar1.Value = 1;

            for (int j = 0; j < i; j++)
            {
                if (strLines[j].StartsWith("<chapter ")) //strLines[j].StartsWith("<part ") || strLines[j].StartsWith("<preface ") || strLines[j].StartsWith("<appendix ")
                {
                    if (strLines[j].IndexOf("label=") >= 0)
                    {
                        strChapterNumber = Regex.Replace(strLines[j], "^(.*) label=\"([^\"]+)\"(.*)$", "$2") + " " + "<img src=\"" + strIDPrefix + "015.jpg\" width=\"5\" height=\"5\" alt=\"icon014\"/> ";
                    }
                    else
                    {
                        strChapterNumber = "<img src=\"" + strIDPrefix + "015.jpg\" width=\"5\" height=\"5\" alt=\"icon014\"/> ";
                    }

                    if (strLines[j].IndexOf(" id=") > 0)
                    {
                        strTempID7 = Regex.Replace(strLines[j], "^(.*) id=\"([^\"]*)\"(.*)$", "$2");
                    }
                    else
                    {
                        strTempID7 = "";
                    }

                    j++;
                    if (strLines[j].StartsWith("<title>"))
                    {
                        strTempID6 = Regex.Replace(strLines[j], "^<title>(.*)</title>$", "$1");
                    }

                    j++;

                    if (strLines[j].StartsWith("<title>"))
                    {
                        strTempID6 = Regex.Replace(strLines[j], "^<title>(.*)</title>$", "$1");
                    }

                    strBrfContentsFile[intBfCtIndex] = "<link linkend=\"" + strTempID7 + "\">" + strChapterNumber + strTempID6 + "</link><br/>";
                    intBfCtIndex++;
                }

                if (strLines[j].StartsWith("<part "))
                {
                    if (strLines[j].IndexOf("label=") >= 0)
                    {
                        strChapterNumber = "<b>P<small>ART</small> " + Regex.Replace(strLines[j], "^(.*) label=\"([^\"]+)\"(.*)$", "$2") + " " + "<img src=\"" + strIDPrefix + "015.jpg\" width=\"5\" height=\"5\" alt=\"icon014\"/> ";
                    }
                    else
                    {
                        strChapterNumber = "<img src=\"" + strIDPrefix + "015.jpg\" width=\"5\" height=\"5\" alt=\"icon014\"/> ";
                    }

                    if (strLines[j].IndexOf(" id=") > 0)
                    {
                        strTempID7 = Regex.Replace(strLines[j], "^(.*) id=\"([^\"]*)\"(.*)$", "$2");
                    }
                    else
                    {
                        strTempID7 = "";
                    }

                    j++;
                    if (strLines[j].StartsWith("<title>"))
                    {
                        strTempID6 = Regex.Replace(strLines[j], "^<title>(.*)</title>$", "$1");
                    }

                    j++;

                    if (strLines[j].StartsWith("<title>"))
                    {
                        strTempID6 = Regex.Replace(strLines[j], "^<title>(.*)</title>$", "$1").ToUpper().Insert(1, "<small>") + "</small></b>";
                    }

                    strBrfContentsFile[intBfCtIndex] = "<br/>\n<link linkend=\"" + strTempID7 + "\">" + strChapterNumber + strTempID6 + "</link><br/><br/>";
                    intBfCtIndex++;
                }

                toolStripProgressBar1.Value = j + 1;

            }

            string strXML2 = "<split filename=\"brief_contents.xhtml\">\n" +
                        "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n" +
                        "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n" +
                        "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n" +
                        "<head>\n" +
                        "<title>Brief Contents</title>\n" +
                        "<link href=\"bv_ebook_style.css\" rel=\"stylesheet\" type=\"text/css\"/>\n" +
                        "<link rel=\"stylesheet\" type=\"application/vnd.adobe-page-template+xml\" href=\"page-template.xpgt\"/>\n" +
                        "</head>\n" +
                        "<body>\n" +
                        "<div>\n<a id=\"brief_contents\"></a>\n<h2 class=\"chaptertitle\">brief contents</h2>\n";

            rtbContent.Text = strXML1 + string.Join("\n", strContentsFile, 0, intCtIndex) + "\n</div>\n</body>\n</html>\n</split>\n" + strXML2 + string.Join("\n", strBrfContentsFile, 0, intBfCtIndex) + "\n</div>\n</body>\n</html>\n</split>\n" + rtbContent.Text;

            #endregion

            this.Refresh();

            strContent = rtbContent.Text;
            strLines = strContent.Split('\n');
            i = strLines.Length;
            toolStripStatusLabel1.Text = "Converting to HTML ... Please Wait";
            toolStripProgressBar1.Maximum = Convert.ToInt32(i) + 1;
            toolStripProgressBar1.Minimum = 1;
            toolStripProgressBar1.Value = 1;
            //Creating IDs
            for (int j = 0; j < i; j++)
            {

                #region Chapters

                if (strLines[j].StartsWith("<chapter ")) // || strLines[j].StartsWith("<appendix") || strLines[j].StartsWith("<part") || strLines[j].StartsWith("<glossary")) // || strLines[j].StartsWith("<preface")
                {
                    lnChapter++;
                    blSectionStart = true;
                    strChapterNumber = Regex.Replace(strLines[j], "^(.*) label=\"([^\"]*)\"(.*)$", "$2");

                    if (strLines[j].IndexOf(" id=") > 0)
                    {
                        strTempID7 = Regex.Replace(strLines[j], "^(.*) id=\"([^\"]*)\"(.*)$", "$2");
                    }
                    else
                    {
                        strTempID7 = "";
                    }

                    strCurrentFileName = "chap" + lnChapter.ToString("00") + ".xhtml";

                    strLines[j] = "<split filename=\"chap" + lnChapter.ToString("00") + ".xhtml\">\n" +
                            "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n" +
                            "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n" +
                            "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n" +
                            "<head>\n" +
                            "<title>Chapter " + strChapterNumber + "</title>\n" +
                            "<link href=\"bv_ebook_style.css\" rel=\"stylesheet\" type=\"text/css\"/>\n" +
                            "<link rel=\"stylesheet\" type=\"application/vnd.adobe-page-template+xml\" href=\"page-template.xpgt\"/>\n" +
                            "</head>\n" +
                            "<body>\n" +
                            "<div>\n" +
                            "<a id=\"" + strTempID7 + "\"></a>";

                    j++;

                    //MessageBox.Show(strLines[j]);

                    strLines[j] = GeneralReplace(strLines[j]);

                            //<a id=\"page_3\"></a><h2 class=\"chaptertitle\">1<br/>SOA essentials</h2>";

                    j++;
                    //MessageBox.Show(strLines[j]);
                    if (strLines[j].StartsWith("<title>")) // || strLines[j].StartsWith("<appendix") || strLines[j].StartsWith("<part") || strLines[j].StartsWith("<glossary")) // || strLines[j].StartsWith("<preface")
                    {
                        strLines[j] = Regex.Replace(strLines[j], "^<title>(.*)</title>$", "<h2 class=\"chaptertitle\">" + strChapterNumber + "<br/>$1</h2>");
                        //MessageBox.Show(strLines[j]);
                    }
                    //<title>SOA essentials</title>
                    //<h2 class="chaptertitle">1<br/>SOA essentials</h2>
                    //MessageBox.Show(strLines[j]);

                }

                #endregion

                #region Prefaces

                if (strLines[j].StartsWith("<preface ")) // || strLines[j].StartsWith("<appendix") || strLines[j].StartsWith("<part") || strLines[j].StartsWith("<glossary")) // || strLines[j].StartsWith("<preface")
                {
                    lnPreface++;
                    blSectionStart = true;
                    strChapterNumber = Regex.Replace(strLines[j], "^(.*) id=\"([^\"]*)\"(.*)$", "$2");

                    if (strLines[j].IndexOf(" id=") > 0)
                    {
                        strTempID7 = Regex.Replace(strLines[j], "^(.*) id=\"([^\"]*)\"(.*)$", "$2");
                    }
                    else
                    {
                        strTempID7 = "";
                    }

                    strCurrentFileName = "pref" + lnPreface.ToString("00") + ".xhtml";
                    strLines[j] = "<split filename=\"pref" + lnPreface.ToString("00") + ".xhtml\">\n" +
                            "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n" +
                            "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n" +
                            "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n" +
                            "<head>";

                    j=j+2;

                    if (strLines[j].StartsWith("<title>")) // || strLines[j].StartsWith("<appendix") || strLines[j].StartsWith("<part") || strLines[j].StartsWith("<glossary")) // || strLines[j].StartsWith("<preface")
                    {
                        strLines[j - 2] = strLines[j - 2] + strLines[j] + "\n<link href=\"bv_ebook_style.css\" rel=\"stylesheet\" type=\"text/css\"/>\n" +
                            "<link rel=\"stylesheet\" type=\"application/vnd.adobe-page-template+xml\" href=\"page-template.xpgt\"/>\n" +
                            "</head>\n" +
                            "<body>\n" +
                            "<div>\n" +
                            "<a id=\"" + strTempID7 + "\"></a>";
                        //MessageBox.Show(strLines[j]);
                        if (strLines[j].IndexOf("copyright", StringComparison.InvariantCultureIgnoreCase) > 0)
                        {
                            blCopyrightPage = true;
                        }

                    }
                    strLines[j] = "";
                    j = j - 1;

                    //MessageBox.Show(strLines[j]);

                    strLines[j-1] = strLines[j-1] + GeneralReplace(strLines[j]);
                    strLines[j] = "";

                    //<a id=\"page_3\"></a><h2 class=\"chaptertitle\">1<br/>SOA essentials</h2>";

                    j = j + 2;
                    //MessageBox.Show(strLines[j]);

                    //<title>SOA essentials</title>
                    //<h2 class="chaptertitle">1<br/>SOA essentials</h2>
                    //MessageBox.Show(strLines[j]);

                }

                #endregion

                #region Closing Chapter, Part and Preface etc..

                if (strLines[j].StartsWith("</chapter>") || strLines[j].StartsWith("</partintro>") || strLines[j].StartsWith("</preface>") || strLines[j].StartsWith("</appendix>"))
                {
                    blCopyrightPage = false;
                    strLines[j] = "</div>\n</body>\n</html>\n</split>";

                    if (strLines[j].StartsWith("</appendix>"))
                    {
                        blAppendix = false;
                    }

                }

                if (strLines[j].StartsWith("<partintro>"))
                {
                    strLines[j] = "";
                }

                #endregion

                #region Part

                if (strLines[j].StartsWith("<part ")) // || strLines[j].StartsWith("<appendix") || strLines[j].StartsWith("<part") || strLines[j].StartsWith("<glossary")) // || strLines[j].StartsWith("<preface")
                {
                    lnPart++;
                    blSectionStart = true;
                    //MessageBox.Show(strLines[j]);
                    strChapterNumber = Regex.Replace(strLines[j], "^(.*) label=\"([^\"]*)\"(.*)$", "$2");

                    if (strLines[j].IndexOf(" id=") > 0)
                    {
                        strTempID7 = Regex.Replace(strLines[j], "^(.*) id=\"([^\"]*)\"(.*)$", "$2");
                    }
                    else
                    {
                        strTempID7 = "";
                    }

                    //MessageBox.Show(strChapterNumber);
                    strCurrentFileName = "part" + lnPart.ToString("00") + ".xhtml";
                    strLines[j] = "<split filename=\"part" + lnPart.ToString("00") + ".xhtml\">\n" +
                            "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n" +
                            "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n" +
                            "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n" +
                            "<head>\n" +
                            "<title>Part " + strChapterNumber + "</title>\n" +
                            "<link href=\"bv_ebook_style.css\" rel=\"stylesheet\" type=\"text/css\"/>\n" +
                            "<link rel=\"stylesheet\" type=\"application/vnd.adobe-page-template+xml\" href=\"page-template.xpgt\"/>\n" +
                            "</head>\n" +
                            "<body>\n" +
                            "<div>\n" +
                            "<a id=\"" + strTempID7 + "\"></a>";

                    //MessageBox.Show(strLines[j]);
                    j++;

                    //MessageBox.Show(strLines[j]);

                    strLines[j] = GeneralReplace(strLines[j]);

                    //<a id=\"page_3\"></a><h2 class=\"chaptertitle\">1<br/>SOA essentials</h2>";
                    //MessageBox.Show(strLines[j]);
                    j++;
                    //MessageBox.Show(strLines[j]);
                    if (strLines[j].StartsWith("<title>")) // || strLines[j].StartsWith("<appendix") || strLines[j].StartsWith("<part") || strLines[j].StartsWith("<glossary")) // || strLines[j].StartsWith("<preface")
                    {
                        strLines[j] = Regex.Replace(strLines[j], "^<title>(.*)</title>$", "<h2 class=\"chaptertitle\">Part " + strChapterNumber + "<br/>$1</h2>");
                        //MessageBox.Show(strLines[j]);
                    }
                    //<title>SOA essentials</title>
                    //<h2 class="chaptertitle">1<br/>SOA essentials</h2>
                    //MessageBox.Show(strLines[j]);

                }
                #endregion

                #region Appendix

                if (strLines[j].StartsWith("<appendix "))
                {
                    lnAppendix++;
                    blAppendix = true;
                    blSectionStart = true;
                    if (strLines[j].IndexOf(" label=") > 0)
                    {
                        strChapterNumber = Regex.Replace(strLines[j], "^(.*) label=\"([^\"]*)\"(.*)$", "$2");
                    }
                    else
                    {
                        strChapterNumber = "";
                    }

                    if (strLines[j].IndexOf(" id=") > 0)
                    {
                        strTempID7 = Regex.Replace(strLines[j], "^(.*) id=\"([^\"]*)\"(.*)$", "$2");
                    }
                    else
                    {
                        strTempID7 = "";
                    }

                    strCurrentFileName = "appe" + lnAppendix.ToString("00") + ".xhtml";
                    strLines[j] = "<split filename=\"appe" + lnAppendix.ToString("00") + ".xhtml\">\n" +
                            "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n" +
                            "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n" +
                            "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n" +
                            "<head>";

                    j = j + 2;

                    if (strLines[j].StartsWith("<title>")) // || strLines[j].StartsWith("<appendix") || strLines[j].StartsWith("<part") || strLines[j].StartsWith("<glossary")) // || strLines[j].StartsWith("<preface")
                    {
                        strLines[j - 2] = strLines[j - 2] + strLines[j] + "\n<link href=\"bv_ebook_style.css\" rel=\"stylesheet\" type=\"text/css\"/>\n" +
                            "<link rel=\"stylesheet\" type=\"application/vnd.adobe-page-template+xml\" href=\"page-template.xpgt\"/>\n" +
                            "</head>\n" +
                            "<body>\n" +
                            "<div>\n" +
                            "<a id=\"" + strTempID7 + "\"></a>";

                    }
                    //strLines[j] = "";
                    j = j - 1;

                    strLines[j] = strLines[j] + GeneralReplace(strLines[j]);
                    //strLines[j] = "";
                    j++;
                    if (strLines[j].StartsWith("<title>")) // || strLines[j].StartsWith("<appendix") || strLines[j].StartsWith("<part") || strLines[j].StartsWith("<glossary")) // || strLines[j].StartsWith("<preface")
                    {
                        strLines[j] = Regex.Replace(strLines[j], "^<title>(.*)</title>$", "<h2 class=\"chaptertitle\">" + strChapterNumber + "<br/>$1</h2>");
                        //MessageBox.Show(strLines[j]);
                    }
                    else
                    {
                        strLines[j] = "";
                    }

                    j++;
                    //j = j + 2;

                }

                #endregion

                #region Sect1

                if (strLines[j].StartsWith("<sect1 "))
                {
                    lnSect1++;
                    blSectionStart = true;
                    //MessageBox.Show(strLines[j]);
                    if (strLines[j].IndexOf(" label=") > 0)
                    {
                        strChapterNumber = Regex.Replace(strLines[j], "^(.*) label=\"([^\"]*)\"(.*)$", "$2") + "&#x00A0;&#x00A0;&#x00A0; ";
                    }
                    else
                    {
                        strChapterNumber = "";
                    }

                    if (strLines[j].IndexOf(" id=") > 0)
                    {
                        strTempID = " id=\"" + Regex.Replace(strLines[j], "^(.*) id=\"([^\"]*)\"(.*)$", "$2") + "\"";
                    }
                    else
                    {
                        strTempID = "";
                    }

                    //MessageBox.Show(strChapterNumber);

                    strLines[j] = ""; //"<a id=\"chapter_" + lnChapter.ToString() + "\"></a>";

                    j++;

                    strLines[j] = GeneralReplace(strLines[j]);
                    //MessageBox.Show(strLines[j]);

                    j++;
                    //MessageBox.Show(strLines[j]);
                    if (strLines[j].StartsWith("<title>")) // || strLines[j].StartsWith("<appendix") || strLines[j].StartsWith("<part") || strLines[j].StartsWith("<glossary")) // || strLines[j].StartsWith("<preface")
                    {
                        strLines[j] = Regex.Replace(strLines[j], "^<title>(.*)</title>$", "<p class=\"subhead\"" + strTempID + ">" + strChapterNumber + "$1</p>");
                        //MessageBox.Show(strLines[j]);
                    }

                }
                #endregion

                #region Sect2

                if (strLines[j].StartsWith("<sect2 ")) // || strLines[j].StartsWith("<appendix") || strLines[j].StartsWith("<part") || strLines[j].StartsWith("<glossary")) // || strLines[j].StartsWith("<preface")
                {
                    lnSect2++;
                    blSectionStart = true;
                    //MessageBox.Show(strLines[j]);
                    if (strLines[j].IndexOf(" label=") > 0)
                    {
                        strChapterNumber = Regex.Replace(strLines[j], "^(.*) label=\"([^\"]*)\"(.*)$", "$2") + "&#x00A0;&#x00A0;&#x00A0; ";
                    }
                    else
                    {
                        strChapterNumber = "";
                    }
                    //MessageBox.Show(strChapterNumber);
                    if (strLines[j].IndexOf(" id=") > 0)
                    {
                        strTempID = " id=\"" + Regex.Replace(strLines[j], "^(.*) id=\"([^\"]*)\"(.*)$", "$2") + "\"";
                    }
                    else
                    {
                        strTempID = "";
                    }

                    strLines[j] = ""; //"<a id=\"chapter_" + lnChapter.ToString() + "\"></a>";

                    j++;

                    strLines[j] = GeneralReplace(strLines[j]);
                    //MessageBox.Show(strLines[j]);

                    j++;
                    //MessageBox.Show(strLines[j]);
                    if (strLines[j].StartsWith("<title>")) // || strLines[j].StartsWith("<appendix") || strLines[j].StartsWith("<part") || strLines[j].StartsWith("<glossary")) // || strLines[j].StartsWith("<preface")
                    {
                        strLines[j] = Regex.Replace(strLines[j], "^<title>(.*)</title>$", "<p class=\"subhead1\"" + strTempID + ">" + strChapterNumber + "$1</p>");
                        //MessageBox.Show(strLines[j]);
                    }

                }

                #endregion

                #region Sect3

                if (strLines[j].StartsWith("<sect3 ")) // || strLines[j].StartsWith("<appendix") || strLines[j].StartsWith("<part") || strLines[j].StartsWith("<glossary")) // || strLines[j].StartsWith("<preface")
                {
                    lnSect3++;
                    blSectionStart = true;
                    //MessageBox.Show(strLines[j]);
                    if (strLines[j].IndexOf(" label=") > 0)
                    {
                        strChapterNumber = Regex.Replace(strLines[j], "^(.*) label=\"([^\"]*)\"(.*)$", "$2") + "&#x00A0;&#x00A0;&#x00A0; ";
                    }
                    else
                    {
                        strChapterNumber = "";
                    }
                    //MessageBox.Show(strChapterNumber);
                    if (strLines[j].IndexOf(" id=") > 0)
                    {
                        strTempID = " id=\"" + Regex.Replace(strLines[j], "^(.*) id=\"([^\"]*)\"(.*)$", "$2") + "\"";
                    }
                    else
                    {
                        strTempID = "";
                    }

                    strLines[j] = ""; //"<a id=\"chapter_" + lnChapter.ToString() + "\"></a>";

                    j++;

                    strLines[j] = GeneralReplace(strLines[j]);
                    //MessageBox.Show(strLines[j]);

                    j++;
                    //MessageBox.Show(strLines[j]);
                    if (strLines[j].StartsWith("<title>")) // || strLines[j].StartsWith("<appendix") || strLines[j].StartsWith("<part") || strLines[j].StartsWith("<glossary")) // || strLines[j].StartsWith("<preface")
                    {
                        strLines[j] = Regex.Replace(strLines[j], "^<title>(.*)</title>$", "<p class=\"subhead1\"" + strTempID + ">" + strChapterNumber + "$1</p>");
                        //MessageBox.Show(strLines[j]);
                    }

                }

                #endregion

                #region Sidebar

                if (strLines[j].StartsWith("<sidebar "))
                {
                    lnSidebar++;
                    blSidebar = true;
                    strLines[j] = "";
                    if (strLines[j].IndexOf(" id=") > 0)
                    {
                        strTempID = " id=\"" + Regex.Replace(strLines[j], "^(.*) id=\"([^\"]*)\"(.*)$", "$2") + "\"";
                    }
                    else
                    {
                        strTempID = "";
                    }
                    j++;

                    if (strLines[j].StartsWith("<title>"))
                    {
                        strLines[j] = Regex.Replace(strLines[j], "^<title>(.*)</title>$", "<p class=\"box-title\"" + strTempID + ">$1</p>");

                    }

                }

                if (strLines[j].StartsWith("</sidebar>"))
                {
                    strLines[j] = "";
                    blSidebar = false;
                    blSectionStart = true;
                }

                #endregion

                #region Note

                if (strLines[j].StartsWith("<note>"))
                {
                    strLines[j] = "";
                    blNote = true;
                    blNoteStart = true;
                }

                if (strLines[j].StartsWith("</note>"))
                {
                    strLines[j] = "";
                    blNote = false;
                    blSectionStart = true;
                }

                #endregion

                #region Programlisting

                if (strLines[j].StartsWith("<programlisting>"))
                {
                    blProgramListingStart = true;
                    strLines[j] = strLines[j].Replace("<programlisting>", "<p class=\"script\"><code>");
                    if (strLines[j].EndsWith(">") == false)
                    {
                        strLines[j] = strLines[j] + "<br/>";
                    }

                }

                //<programlisting>
                if (strLines[j].EndsWith("</programlisting>"))
                {
                    blProgramListingStart = false;
                    strLines[j] = strLines[j].Replace("</programlisting>", "</code></p>");
                    blSectionStart = true;
                }

                if (strLines[j].StartsWith("<")==false)
                {
                    if (blProgramListingStart == true)
                    {
                        strLines[j] = strLines[j] + "<br/>";

                        if (strLines[j].StartsWith(" ") == true)
                        {
                           // MessageBox.Show("[" + strLines[j].ToString() + "]");
                            strLines[j] = Regex.Replace(strLines[j], "([ ][ ])", "&#x00A0;&#x00A0;");
                            strLines[j] = Regex.Replace(strLines[j], "(&#x00A0;[ ])", "&#x00A0;&#x00A0;");
                            strLines[j] = Regex.Replace(strLines[j], "^([ ])(.*)$", "&#x00A0;$2");
                           // MessageBox.Show("[" + strLines[j].ToString() + "]");
                        }
                    }
                }

                #endregion

                #region Para

                if (strLines[j].StartsWith("<para>"))
                {
                    //Table
                    strLines[j] = Regex.Replace(strLines[j], "^<para>(.*)</para></entry>$", "<p class=\"body-text\">$1</p></td>");

                    if (strLines[j].IndexOf("<emphasis role=\"strong\">") > 0)
                    {

                        strLines[j] = Regex.Replace(strLines[j], "^<para>(.*)<emphasis role=\"strong\">(.*)</emphasis></para>$", "<p class=\"subhead2\">$1$2</p>");
                    }

                    if (blSidebar == true)
                    {
                        strLines[j] = Regex.Replace(strLines[j], "^<para>(.*)$", "<p class=\"box-para\">$1");
                    }
                    else
                    {
                        if (blblockquote == true)
                        {
                            strLines[j] = Regex.Replace(strLines[j], "^<para>(.*)$", "<p class=\"blockquote\">$1");
                        }
                        else
                        {

                            if (blNote == true)
                            {
                                if (blNoteStart == true)
                                {
                                    strLines[j] = Regex.Replace(strLines[j], "^<para>(.*)$", "<p class=\"hanging-note\"><small><b>NOTE</b></small> $1");
                                    blNoteStart = false;
                                }
                                else
                                {
                                    strLines[j] = Regex.Replace(strLines[j], "^<para>(.*)$", "<p class=\"hanging-note\">$1");
                                }

                            }
                            else
                            {

                                if (blCopyrightPage == true)
                                {

                                    strLines[j] = Regex.Replace(strLines[j], "^<para>(.*)$", "<p class=\"copyright\">$1");

                                }
                                else
                                {
                                    if (blTipStart == true)
                                    {

                                        strLines[j] = Regex.Replace(strLines[j], "^<para>(.*)$", "<p class=\"hanging-tip\"><small><b>TIP</b></small>&#x00A0;&#x00A0;&#x00A0;&#x00A0;&#x00A0;&#x00A0;$1");

                                    }
                                    else
                                    {

                                        if (blAppendix == true)
                                        {
                                            strLines[j] = Regex.Replace(strLines[j], "^<para>(.*)$", "<p class=\"hanging-indent\">$1");
                                        }
                                        else
                                        {
                                            if (blSectionStart == true)
                                            {

                                                strLines[j] = Regex.Replace(strLines[j], "^<para>(.*)$", "<p class=\"body-text\">$1");
                                            }
                                            else
                                            {

                                                strLines[j] = Regex.Replace(strLines[j], "^<para>(.*)$", "<p class=\"indent\">$1");

                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    blSectionStart = false;
                }

                #endregion

                #region Itemizedlist

                if (strLines[j].StartsWith("<itemizedlist mark=\"squf\">"))
                {
                    //strLines[j] = "";
                    strLines[j] = "<ul>";
                    blitemizedlist = true;
                }

                if (strLines[j].StartsWith("</itemizedlist>"))
                {
                    //strLines[j] = "";
                    strLines[j] = "</ul>";
                    blitemizedlist = false;
                    blSectionStart = true;
                }
                #endregion

                #region Orderedlist

                if (strLines[j].StartsWith("<orderedlist numeration=\"arabic\">"))
                {
                    //strLines[j] = "";
                    strLines[j] = "<ol>";
                    lnOrderedList = 0;
                    blorderedlist = true;
                }

                if (strLines[j].StartsWith("</orderedlist>"))
                {
                    //strLines[j] = "";
                    strLines[j] = "</ol>";
                    lnOrderedList = 0;
                    blorderedlist = false;
                    blSectionStart = true;
                }
                #endregion

                #region Blockquote

                if (strLines[j].StartsWith("<blockquote>"))
                {
                    strLines[j] = "";
                    blblockquote = true;
                }

                if (strLines[j].IndexOf("</blockquote>") > 0)
                {
                    strLines[j] = strLines[j].Replace("</blockquote>","");
                    blblockquote = false;
                    blSectionStart = true;

                }

                if (strLines[j].StartsWith("</blockquote>"))
                {
                    strLines[j] = "";
                    blblockquote = false;
                    blSectionStart = true;
                }

                #endregion

                #region Closing Sect, Figure
                //</example>

                if (strLines[j].StartsWith("</sect") || strLines[j].StartsWith("</figure>"))
                {
                    strLines[j] = "";
                    blSectionStart = true;
                }

                #endregion

                #region Closing example
                //</example>

                if (strLines[j].StartsWith("</example>"))
                {
                    strLines[j] = "";
                    blExampleStart  = false;
                    blSectionStart = true;
                }

                #endregion

                #region ListItem

                if (strLines[j].StartsWith("<listitem><para>"))
                {

                    if (blitemizedlist == true)
                    {
                        //Old
                        //strLines[j] = Regex.Replace(strLines[j], "^<listitem><para>(.*)</para></listitem>$", "<p class=\"hanging-list\"><img src=\"" + strIDPrefix + "015.jpg\" width=\"5\" height=\"5\" alt=\"icon014\"/> $1</p>");
                        strLines[j] = Regex.Replace(strLines[j], "^<listitem><para>(.*)</para></listitem>$", "<li><p>$1</p></li>");

                    }
                    else
                    {
                        if (blorderedlist == true)
                        {
                            lnOrderedList++;
                            //Old
                            //strLines[j] = Regex.Replace(strLines[j], "^<listitem><para>(.*)</para></listitem>$", "<p class=\"hanging-numberlist\">" + lnOrderedList.ToString() + " $1</p>");
                            strLines[j] = Regex.Replace(strLines[j], "^<listitem><para>(.*)</para></listitem>$", "<li><p>$1</p></li>");

                        }
                    }

                }

                #endregion

                #region Figure

                if (strLines[j].StartsWith("<figure "))
                {
                    lnFigure++;
                    if (strLines[j].IndexOf(" label=") > 0)
                    {
                        strChapterNumber = "Figure " + Regex.Replace(strLines[j], "^(.*) label=\"([^\"]*)\"(.*)$", "$2") + "&#x00A0;&#x00A0;&#x00A0; ";
                    }
                    else
                    {
                        strChapterNumber = "";
                    }

                    if (strLines[j].IndexOf(" id=") > 0)
                    {
                        strTempID = Regex.Replace(strLines[j], "^(.*) id=\"([^\"]*)\"(.*)$", "$2");
                    }
                    else
                    {
                        strTempID = "";
                    }

                    strLines[j] = "";

                    j++;
                    strTempID2 = "";
                    if (strLines[j].StartsWith("<title>"))
                    {
                        strTempID2 = Regex.Replace(strLines[j], "^<title>(.*)</title>$", "<p class=\"figure-caption\"><b>" + strChapterNumber + "$1</b></p>");
                        strLines[j] = "";
                    }

                    j++;

                    if (strLines[j].StartsWith("<graphic"))
                    {
                        //File Name
                        strTempID3 = Regex.Replace(strLines[j], "^(.*) fileref=\"([^\"]*)\"(.*)$", "$2");
                        //Width
                        strTempID4 = Regex.Replace(strLines[j], "^(.*) width=\"([^\"]*)\"(.*)$", "$2");
                        //height
                        strTempID5 = Regex.Replace(strLines[j], "^(.*) depth=\"([^\"]*)\"(.*)$", "$2");

                        //strLines[j] = "<p class=\"figure-image\" id=\"" + strTempID + "\"><img src=\"" + strIDPrefix + strTempID3 + ".jpg\" width=\"" + strTempID4 + "\" height=\"" + strTempID5 + "\" alt=\"fig" + lnFigure.ToString("000") + "\"/></p>\n" + strTempID2;
                        strLines[j] = "<p class=\"figure-image\" id=\"" + strTempID + "\"><img src=\"" + strTempID3 + "\" width=\"" + strTempID4 + "\" height=\"" + strTempID5 + "\" alt=\"" + strTempID3 + "\"/></p>\n" + strTempID2;

                    }

                }
                #endregion

                #region Example

                if (strLines[j].StartsWith("<example "))
                {
                    lnExample++;
                    blExampleStart = true;
                    if (strLines[j].IndexOf(" label=") > 0 && strLines[j].IndexOf(" role=") > 0)
                    {
                        strTempID6 = Regex.Replace(strLines[j], "^(.*) role=\"([^\"]*)\"(.*)$", "$2");
                        strChapterNumber = strTempID6 + " " + Regex.Replace(strLines[j], "^(.*) label=\"([^\"]*)\"(.*)$", "$2") + "&#x00A0;&#x00A0;&#x00A0; ";
                    }
                    else
                    {
                        strChapterNumber = "";
                    }

                    if (strLines[j].IndexOf(" id=") > 0)
                    {
                        strTempID = " id=\"" + Regex.Replace(strLines[j], "^(.*) id=\"([^\"]*)\"(.*)$", "$2") + "\"";
                    }
                    else
                    {
                        strTempID = "";
                    }

                    strLines[j] = "";

                    j++;
                    strTempID2 = "";
                    if (strLines[j].StartsWith("<title>"))
                    {
                        strLines[j] = Regex.Replace(strLines[j], "^<title>(.*)</title>$", "<p class=\"listing-script\"" + strTempID + "><b>" + strChapterNumber + "$1</b></p>");
                        //strLines[j] = "";
                    }

                    j++;

                }

                if (blExampleStart == true)
                {
                    if (strLines[j].StartsWith("<programlisting") == false && strLines[j].StartsWith("<") == true)
                    {
                        //strLines[j] = "<p class=\"script\">" + strLines[j] + "</p>";

                    }
                    else
                    {
                        strLines[j] = strLines[j].Replace("<programlisting>", "<p class=\"script\"><code>");
                        blProgramListingStart = true;
                    }
                }

                #endregion

                #region Tip

                if (strLines[j].StartsWith("<tip>"))
                {
                    blTipStart = true;
                    strLines[j] = "";

                }

                if (strLines[j].StartsWith("</tip>"))
                {
                    blTipStart = false ;
                    strLines[j] = "";

                }

                #endregion

                #region Table

                if (strLines[j].StartsWith("<table "))
                {
                    lnTable++;
                    strChapterNumber = "";
                    if (strLines[j].IndexOf(" label=") > 0)
                    {
                        strChapterNumber = "Table " + Regex.Replace(strLines[j], "^(.*) label=\"([^\"]*)\"(.*)$", "$2") + "&#x00A0;&#x00A0;&#x00A0; ";
                    }
                    else
                    {
                        strChapterNumber = "";
                    }

                    if (strLines[j].IndexOf(" id=") > 0)
                    {
                        strTempID = Regex.Replace(strLines[j], "^(.*) id=\"([^\"]*)\"(.*)$", "$2");
                    }
                    else
                    {
                        strTempID = "";
                    }

                    strLines[j] = "";

                    j++;
                    strTempID2 = "";
                    if (strLines[j].StartsWith("<title>"))
                    {
                        strTempID2 = Regex.Replace(strLines[j], "^<title>(.*)</title>$", "$1");
                        strLines[j] = "<table id=\"" + strTempID + "\" cellpadding=\"2\" cellspacing=\"0\">\n<p class=\"table-caption\"><b>" + strChapterNumber + strTempID2 + "</b></p>";
                    }
                    else
                    {
                        j--;
                        strLines[j] = "<table id=\"" + strTempID + "\" cellpadding=\"2\" cellspacing=\"0\">";

                    }

                }

                if (strLines[j].StartsWith("<row>"))
                {
                    strLines[j] = "<tr>";
                }
                if (strLines[j].StartsWith("</row>"))
                {
                    strLines[j] = "</tr>";
                }

                if (strLines[j].StartsWith("<entry"))
                {
                    strLines[j] = Regex.Replace(strLines[j], "^<entry(.*)><para>(.*)</para></entry>$", "<td$1>$2</td>");
                    strLines[j] = Regex.Replace(strLines[j], "^<entry(.*)><para>(.*)</para>$", "<td$1><p>$2</p>");
                    strLines[j] = Regex.Replace(strLines[j], "^<entry(.*)><para>(.*)$", "<td$1>$2");

                    //MessageBox.Show(strLines[j]);
                }

                if (strLines[j].StartsWith("<tgroup") || strLines[j].StartsWith("<colspec") || strLines[j].StartsWith("<thead>") || strLines[j].StartsWith("</thead>") || strLines[j].StartsWith("<tbody>") || strLines[j].StartsWith("</tbody>") || strLines[j].StartsWith("</tgroup>"))
                {
                    strLines[j] = "";
                    blSectionStart = true;
                }

                #endregion

                #region Remove Index

                if (strLines[j].IndexOf("<indexterm ") > 0 && strLines[j].LastIndexOf("</indexterm>") > 0)
                {
                    //MessageBox.Show(strLines[j] + strLines[j].IndexOf("<indexterm ").ToString());
                        strLines[j] = strLines[j].Remove(strLines[j].IndexOf("<indexterm "), (strLines[j].LastIndexOf("</indexterm>") - strLines[j].IndexOf("<indexterm ") + 12));
                    //MessageBox.Show(strLines[j]);
                }

                #endregion

                #region Some General Replacings
                //</para></entry>

                strLines[j] = strLines[j].Replace("</para></entry>", "</td>");
                strLines[j] = strLines[j].Replace("</programlisting>", "</code></p>");
                strLines[j] = strLines[j].Replace("<programlisting>", "<p class=\"script\"><code>");
                strLines[j] = strLines[j].Replace("</entry>", "</td>");
                strLines[j] = strLines[j].Replace("<p class=\"script\"><br/></p>", "<br/>");
                //Replace all general things
                strLines[j] = strLines[j].Replace("</para>", "</p>");
                //strLines[j] = strLines[j].Replace("<p class=\"script\"><p class=\"script\"><code>",
                strLines[j] = strLines[j].Replace("<listitem><para>", "<li><p>");
                strLines[j] = strLines[j].Replace("</para></listitem>", "</p></li>");
                strLines[j] = strLines[j].Replace("<listitem>", "<li>");
                strLines[j] = strLines[j].Replace("</listitem>", "</li>");
                strLines[j] = strLines[j].Replace("<entry", "<td");
                strLines[j] = strLines[j].Replace("<td align=\"center\" valign=\"bottom\">", "<td>");
                //
                if (strLines[j].IndexOf("<literal>") > 0)
                {
                    //MessageBox.Show(strLines[j]);
                    strLines[j] = Regex.Replace(strLines[j], "<literal>([^<]+)</literal>", "<code>$1</code>", RegexOptions.RightToLeft );
                    //MessageBox.Show(strLines[j]);
                }

                if (strLines[j].IndexOf("<emphasis>") > 0)
                {
                    //MessageBox.Show(strLines[j]);
                    strLines[j] = Regex.Replace(strLines[j], "<emphasis>([^<]+)</emphasis>", "<i>$1</i>", RegexOptions.RightToLeft);
                    //MessageBox.Show(strLines[j]);
                }

                if (strLines[j].IndexOf("<informalfigure>") >= 0)
                {
                    //MessageBox.Show(strLines[j]);
                    //strLines[j] = Regex.Replace(strLines[j], "<informalfigure><graphic fileref=\"figs/([^<> ]+).png\"/></informalfigure>", "<img src=\"images/$1.png\" alt=\"$1\"/>", RegexOptions.RightToLeft);
                    strLines[j] = Regex.Replace(strLines[j], "<informalfigure><graphic fileref=\"([^<> ]+)\"/></informalfigure>", "<img src=\"$1\" alt=\"$1\"/>", RegexOptions.RightToLeft);
                    //MessageBox.Show(strLines[j]);
                }

                if (strLines[j].IndexOf("<informalfigure>") < 0 && strLines[j].IndexOf("<graphic") >=0)
                {
                    //MessageBox.Show(strLines[j]);
                    //strLines[j] = Regex.Replace(strLines[j], "<graphic fileref=\"figs/([^<> ]+).png\"/>", "<img src=\"" + strIDPrefix + "/$1.png\" alt=\"$1\"/>", RegexOptions.RightToLeft);
                    strLines[j] = Regex.Replace(strLines[j], "<graphic fileref=\"([^<> ]+)\"/>", "<img src=\"$1\" alt=\"$1\"/>", RegexOptions.RightToLeft);
                    //MessageBox.Show(strLines[j]);
                }

                if (strLines[j].IndexOf("<systemitem role=\"url\">") >= 0)
                {
                    //MessageBox.Show(strLines[j]);
                    strLines[j] = Regex.Replace(strLines[j], "<systemitem role=\"url\">([^<>]+)</systemitem>", "<a href=\"$1\">$1</a>", RegexOptions.RightToLeft);
                    //MessageBox.Show(strLines[j]);
                }

                if (strLines[j].IndexOf("<systemitem role=\"httpurl\">") >= 0)
                {
                    //MessageBox.Show(strLines[j]);
                    strLines[j] = Regex.Replace(strLines[j], "<systemitem role=\"httpurl\">([^<>]+)</systemitem>", "<a href=\"http://$1\">$1</a>", RegexOptions.RightToLeft);
                    //MessageBox.Show(strLines[j]);
                }

                #endregion

                toolStripProgressBar1.Value = j+1;

            }

            #endregion

            this.Refresh();

            rtbContent.Text = string.Join("\n", strLines);
            toolStripProgressBar1.Value = toolStripProgressBar1.Maximum;
            //toolStripStatusLabel1.Text = "Ready";
            Application.UseWaitCursor = false;

            //IDLinking();
            IDLinkingVer2();
        }
Ejemplo n.º 47
0
		/// <summary>
		/// Remove the key from the tree.
		/// </summary>
		/// <param name="key"></param>
		/// <returns></returns>
		public bool Delete(IKey key)
		{
			int pos = -1;
			System.Collections.Stack visited = new System.Collections.Stack();
			System.Collections.Stack viaLinks = new System.Collections.Stack();
			
			//find the node which contains the key
			BNode n = FindNode(m_top, key, ref pos, visited, viaLinks);
			if (n == null)
			{
				return false;
			}
			else
			{
				if (n.Leaf)
				{
					n.RemoveAtLeaf(key, pos);
				}
				else
				{
					visited.Push(n);
					uint nextNodeId = n.GetChildAt(pos+1);
					viaLinks.Push(pos+1);
					BNode t_node = (BNode)m_sgManager.GetSegment(nextNodeId, m_nodeFactory, m_keyFactory);
					//find the leaf most leaf in its right sub-tree
					while (!t_node.Leaf)
					{
						visited.Push(t_node);
						nextNodeId = t_node.GetChildAt(0);
						viaLinks.Push(0);
						t_node = (BNode)m_sgManager.GetSegment(nextNodeId, m_nodeFactory, m_keyFactory);
					}
					Debug.Assert(t_node.Leaf);

					IKey successor = t_node.GetKeyAt(0);
                    
					//replace the key&data in n with the successor
					n.ReplaceKeyDataWSuccessor(key, successor, pos);

					//remove successor from the leaf node
					t_node.RemoveAtLeaf(successor, 0);

					n = t_node;
				}
			}

			//now n is the leaf node where the real deletion happens
			//visited keep all the parents visited so far, viaLinks keeps which links we followed
			while (n.IsUnderflow && n.SegmentID != m_top_sid)
			{

				BNode parent = (BNode)visited.Pop();
				//get left/right brother
				int followed = (int)viaLinks.Pop();
				BNode left = (followed>0? (BNode)m_sgManager.GetSegment(parent.GetChildAt(followed-1), m_nodeFactory, m_keyFactory) : null);
				BNode right = (followed<parent.KeyNums ? (BNode)m_sgManager.GetSegment(parent.GetChildAt(followed+1), m_nodeFactory, m_keyFactory) : null);

				Debug.Assert(left != null || right != null);

				bool combined = false;
				//try combin with right first
				if (right != null && right.KeyNums == right.ReqMinimum)
				{
					//combine with the right
					parent.CombineChildren(followed, n, right);
					Debug.Assert(right.KeyNums == 0);
					Debug.Assert(n.KeyNums > n.ReqMinimum);
					m_sgManager.FreeSegment(right);

					combined = true;

					if (parent.KeyNums == 0)
					{
						Debug.Assert(parent.Leaf == false);
						Debug.Assert(parent.SegmentID == this.m_top_sid);
						//tree will shrink
						this.m_top_sid = n.SegmentID;
						m_sgManager.FreeSegment(parent);
						break;
					}

				}
				else if (left != null && left.KeyNums == left.ReqMinimum)
				{
					//combine with the left
					parent.CombineChildren(followed-1, left, n);
					Debug.Assert(n.KeyNums == 0);
					Debug.Assert(left.KeyNums > left.ReqMinimum);
					m_sgManager.FreeSegment(n);

					combined = true;

					if (parent.KeyNums == 0)
					{
						Debug.Assert(parent.Leaf == false);
						Debug.Assert(parent.SegmentID == this.m_top_sid);
						//tree will shrink
						this.m_top_sid = left.SegmentID;
						m_sgManager.FreeSegment(parent);
						break;
					}

				}
				if (!combined)
				{
					//try redistrubute if combine is not possible
					if (right != null && right.KeyNums > right.ReqMinimum)
					{
						//redistribute one entry from right node
						parent.RedistributeRight2Left(followed, n, right);

					}
					else if (left != null &&  left.KeyNums > left.ReqMinimum)
					{
						//redistribute with left
						parent.RedistributeLeft2Right(followed-1, left, n);
					}

				}

				else
					n = parent;

			}

			return true;
		}
Ejemplo n.º 48
0
 public void CheckInvariantAdmissibility(Invariant inv) {
   DeclaringMember = inv;
   StateStack = new System.Collections.Stack();
   ResetCurrentState();
   this.VisitExpression(inv.Condition);
 }
Ejemplo n.º 49
0
        private void createOPFAuto(string strPath)
        {
            //fbdSplit.ShowDialog();
            string strSavePath = strPath;
            System.Collections.Stack stkImgs;
            stkImgs = new System.Collections.Stack();
            stkImgs.Clear();
            MatchCollection mc;

            if (strSavePath.Length > 2)
            {

                try
                {

                    Application.UseWaitCursor = true;
                    toolStripStatusLabel1.Text = "Creating .OPF File... Please Wait";
                    this.Refresh();
                    string strContent = "";

                    string[] strLines;

                    strContent = rtbContent.Text;
                    strLines = strContent.Split('\n');
                    long i = strLines.Length;

                    toolStripProgressBar1.Maximum = Convert.ToInt32(i) + 1;
                    toolStripProgressBar1.Minimum = 1;
                    toolStripProgressBar1.Value = 1;
                    this.Refresh();

                    StreamWriter swFiles;
                    string strFileNames = "";
                    string strChapterTitle = "";
                    bool blSplitStart = false;
                    bool blIdFound = false;
                    bool blSrcFound = false;
                    bool blTitleFound = false;
                    bool blATitleFound = false;
                    string strWrite = "";

                    string strIdFound = "";
                    string strSrcFound = "";
                    string strTitleFound = "";
                    string strATitleFound = "";
                    long lnImgIDCount = 1;

                    swFiles = new StreamWriter(strSavePath + "\\content.opf");

                    swFiles.WriteLine("<?xml version=\"1.0\"?>\n" +
                        "<package version=\"2.0\" xmlns=\"http://www.idpf.org/2007/opf\"\n" +
                        "         unique-identifier=\"isbn\">\n" +
                        " <metadata xmlns:dc=\"http://purl.org/dc/elements/1.1/\"\n" +
                        "           xmlns:opf=\"http://www.idpf.org/2007/opf\">\n" +
                        "   <dc:title>***Book Name***</dc:title> \n" +
                        "   <dc:creator>***Author Name***</dc:creator>\n" +
                        "   <dc:language>en-US</dc:language> \n" +
                        "   <dc:rights>***Copyright***</dc:rights>\n" +
                        "   <dc:publisher>***Publisher***</dc:publisher>\n" +
                        "   <dc:identifier id=\"isbn\">****</dc:identifier>\n" +
                        "   <meta name=\"cover\" content=\"cover-image\"/>  \n" +
                        " </metadata>\n" +
                        " <manifest>\n" +
                        "\n" +
                        "<!-- Images -->\n");

                    for (int j = 0; j < i; j++)
                    {

                        mc = Regex.Matches(strLines[j], "<img src=\"([^\"]+)\"");

                        foreach (Match singleMc in mc)
                        {

                            if (stkImgs.Contains(singleMc.Result("$1")) == false)
                            {
                                stkImgs.Push(singleMc.Result("$1"));
                                swFiles.WriteLine("  <item href=\"" + singleMc.Result("$1") + "\" id=\"img_" + lnImgIDCount.ToString() + "\" media-type=\"image/jpeg\"/>");
                                lnImgIDCount++;
                            }

                        }

                        toolStripProgressBar1.Value = j + 1;

                    }

                    swFiles.WriteLine("<!-- NCX -->\n" +
                        "\n" +
                        "<item id=\"ncx\" href=\"toc.ncx\" media-type=\"application/x-dtbncx+xml\"/>\n" +
                        "\n" +
                        " <!-- CSS Style Sheets -->\n" +
                        "\n" +
                        "<item id=\"style_bv\" href=\"bv_ebook_style.css\" media-type=\"text/css\"/>\n" +
                        "<item id=\"style_basic\" href=\"stylesheet.css\" media-type=\"text/css\"/>\n" +
                        "<item id=\"pagetemplate\" href=\"page-template.xpgt\" media-type=\"application/vnd.adobe-page-template+xml\"/>\n" +
                        "<!-- Content Documents -->\n" +
                        "\n");

                    string strIDRef = " <spine toc=\"ncx\">";

                    for (int j = 0; j < i; j++)
                    {

                        if (strLines[j].StartsWith("<split"))
                        {
                            strFileNames = Regex.Replace(strLines[j], "^<split filename=\"([^<>]+)\">$", "$1");
                            blSplitStart = true;
                            //swFiles.WriteLine("      <content src=\"" + strFileNames + "\"/>");
                            blSrcFound = true;
                            strSrcFound = strFileNames;

                        }

                        if (strLines[j].StartsWith("<div>") == true)
                        {
                            j++;
                            if (strLines[j].StartsWith("<a id=") == true)
                            {
                                strChapterTitle = Regex.Replace(strLines[j], "^<a id=\"([^<]*)\"></a>(.*)$", "$1");
                                //swFiles.WriteLine("    <navPoint class=\"chapter\" id=\"" + strChapterTitle + "\" playOrder=\"1\">");
                                blIdFound = true;
                                strIdFound = strChapterTitle;

                            }

                        }

                        if (strLines[j].StartsWith("</split"))
                        {
                            strWrite = "";
                            if (blIdFound == true)
                            {

                                if (blSrcFound == true)
                                {
                                    strWrite = "  <item id=\"" + strIdFound + "\" href=\"" + strSrcFound + "\" media-type=\"application/xhtml+xml\"/>";
                                    swFiles.WriteLine(strWrite);

                                    strIDRef = strIDRef + "\n" + "  <itemref idref=\"" + strIdFound + "\" linear=\"yes\" />";

                                }

                            }

                            blIdFound = false;
                            blSrcFound = false;
                            blTitleFound = false;
                            blATitleFound = false;

                            strIdFound = "";
                            strSrcFound = "";
                            strTitleFound = "";
                            strATitleFound = "";

                            blSplitStart = false;
                        }

                        toolStripProgressBar1.Value = j + 1;

                    }

                    swFiles.WriteLine("  </manifest>\n");

                    swFiles.WriteLine(strIDRef);

                    swFiles.WriteLine("<guide>");

                    for (int j = 0; j < i; j++)
                    {

                        if (strLines[j].StartsWith("<split"))
                        {
                            strFileNames = Regex.Replace(strLines[j], "^<split filename=\"([^<>]+)\">$", "$1");
                            blSplitStart = true;
                            //swFiles.WriteLine("      <content src=\"" + strFileNames + "\"/>");
                            blSrcFound = true;
                            strSrcFound = strFileNames;

                        }

                        if (strLines[j].StartsWith("<head>") == true)
                        {
                            j++;
                            if (strLines[j].StartsWith("<title>") == true)
                            {
                                strChapterTitle = Regex.Replace(strLines[j], "^<title>(.*)</title>$", "$1");
                                //swFiles.WriteLine("        <text>" + strChapterTitle + "</text>");
                                blTitleFound = true;
                                strTitleFound = strChapterTitle;
                            }

                        }

                        if (strLines[j].StartsWith("<h2 class=\"chaptertitle\">") == true)
                        {

                            strChapterTitle = Regex.Replace(strLines[j], "^<h2 class=\"chaptertitle\">(.*)</h2>$", "$1");
                            strChapterTitle = RemoveTag(strChapterTitle);
                            blATitleFound = true;
                            strATitleFound = strChapterTitle;

                        }

                        if (strLines[j].StartsWith("<div>") == true)
                        {
                            j++;
                            if (strLines[j].StartsWith("<a id=") == true)
                            {
                                strChapterTitle = Regex.Replace(strLines[j], "^<a id=\"([^<]*)\"></a>(.*)$", "$1");
                                //swFiles.WriteLine("    <navPoint class=\"chapter\" id=\"" + strChapterTitle + "\" playOrder=\"1\">");
                                blIdFound = true;
                                strIdFound = strChapterTitle;

                            }

                        }

                        if (strLines[j].StartsWith("</split"))
                        {
                            strWrite = "";
                            if (blIdFound == true)
                            {
                                strWrite = strIdFound;
                                if (blATitleFound == true)
                                {
                                    //strATitleFound
                                }
                                else
                                {
                                    if (blTitleFound == true)
                                    {
                                        strATitleFound = strTitleFound;
                                    }

                                }

                                strWrite = "<reference type=\"text\"\n" +
                                "		   title=\"" + strATitleFound + "\"\n" +
                                "          href=\"" + strSrcFound + "\"/>";

                                swFiles.WriteLine(strWrite);
                            }

                            blIdFound = false;
                            blSrcFound = false;
                            blTitleFound = false;
                            blATitleFound = false;

                            strIdFound = "";
                            strSrcFound = "";
                            strTitleFound = "";
                            strATitleFound = "";

                            blSplitStart = false;
                        }

                        toolStripProgressBar1.Value = j + 1;

                    }

                    swFiles.WriteLine("</guide>\n</package>");

                    swFiles.Flush();
                    swFiles.Close();

                    this.Refresh();

                    rtbContent.Text = string.Join("\n", strLines);
                    toolStripProgressBar1.Value = toolStripProgressBar1.Maximum;

                    toolStripStatusLabel1.Text = "Ready";
                    Application.UseWaitCursor = false;
                }
                catch
                {
                    MessageBox.Show("Unexpected Error", "ERR", MessageBoxButtons.OK);

                }
            }
        }
Ejemplo n.º 50
0
 //-----------------------------------------------------------
 // Member functions.
 //
 public FSMContext(State state)
 {
     // There is no state until the application explicitly
     // sets the initial state.
     name_ = "FSMContext";
     state_ = state;
     transition_ = "";
     previousState_ = null;
     stateStack_ = new System.Collections.Stack();
     debugFlag_ = false;
     debugStream_ = null;
 }
Ejemplo n.º 51
0
 public PT()
 {
     NodesStack = new System.Collections.Stack();
     pascalABC_lambda_definitions = new List<function_lambda_definition>();
     pascalABC_var_statements = new List<var_def_statement>();
     pascalABC_type_declarations = new List<type_declaration>();
 }
Ejemplo n.º 52
0
        /// <summary>
        /// Emulates the behavior of a SAX parser, it realizes the callback events of the parser.
        /// </summary>
        private void DoParsing()
        {
            System.Collections.Hashtable prefixes = new System.Collections.Hashtable();
            System.Collections.Stack stackNameSpace = new System.Collections.Stack();
            locator = new XmlSaxLocatorImpl();
            try
            {
                UpdateLocatorData(this.locator, (System.Xml.XmlTextReader)(this.reader));
                if (this.callBackHandler != null)
                    this.callBackHandler.setDocumentLocator(locator);
                if (this.callBackHandler != null)
                    this.callBackHandler.startDocument();
                while (this.reader.Read())
                {
                    UpdateLocatorData(this.locator, (System.Xml.XmlTextReader)(this.reader));
                    switch (this.reader.NodeType)
                    {
                        case System.Xml.XmlNodeType.Element:
                            bool Empty = reader.IsEmptyElement;
                            System.String namespaceURI = "";
                            System.String localName = "";
                            if (this.namespaceAllowed)
                            {
                                namespaceURI = reader.NamespaceURI;
                                localName = reader.LocalName;
                            }
                            System.String name = reader.Name;
                            SaxAttributesSupport attributes = new SaxAttributesSupport();
                            if (reader.HasAttributes)
                            {
                                for (int i = 0; i < reader.AttributeCount; i++)
                                {
                                    reader.MoveToAttribute(i);
                                    System.String prefixName = (reader.Name.IndexOf(":") > 0) ? reader.Name.Substring(reader.Name.IndexOf(":") + 1, reader.Name.Length - reader.Name.IndexOf(":") - 1) : "";
                                    System.String prefix = (reader.Name.IndexOf(":") > 0) ? reader.Name.Substring(0, reader.Name.IndexOf(":")) : reader.Name;
                                    bool IsXmlns = prefix.ToLower().Equals("xmlns");
                                    if (this.namespaceAllowed)
                                    {
                                        if (!IsXmlns)
                                            attributes.Add(reader.NamespaceURI, reader.LocalName, reader.Name, "" + reader.NodeType, reader.Value);
                                    }
                                    else
                                        attributes.Add("", "", reader.Name, "" + reader.NodeType, reader.Value);
                                    if (IsXmlns)
                                    {
                                        System.String namespaceTemp = "";
                                        namespaceTemp = (namespaceURI.Length == 0) ? reader.Value : namespaceURI;
                                        if (this.namespaceAllowed && !prefixes.ContainsKey(namespaceTemp) && namespaceTemp.Length > 0)
                                        {
                                            stackNameSpace.Push(name);
                                            System.Collections.Stack namespaceStack = new System.Collections.Stack();
                                            namespaceStack.Push(prefixName);
                                            prefixes.Add(namespaceURI, namespaceStack);
                                            if (this.callBackHandler != null)
                                                ((IXmlSaxContentHandler)this.callBackHandler).startPrefixMapping(prefixName, namespaceTemp);
                                        }
                                        else
                                        {
                                            if (this.namespaceAllowed && namespaceTemp.Length > 0 && !((System.Collections.Stack)prefixes[namespaceTemp]).Contains(reader.Name))
                                            {
                                                ((System.Collections.Stack)prefixes[namespaceURI]).Push(prefixName);
                                                if (this.callBackHandler != null)
                                                    ((IXmlSaxContentHandler)this.callBackHandler).startPrefixMapping(prefixName, reader.Value);
                                            }
                                        }
                                    }
                                }
                            }
                            if (this.callBackHandler != null)
                                this.callBackHandler.startElement(namespaceURI, localName, name, attributes);
                            if (Empty)
                            {
                                if (this.NamespaceAllowed)
                                {
                                    if (this.callBackHandler != null)
                                        this.callBackHandler.endElement(namespaceURI, localName, name);
                                }
                                else
                                    if (this.callBackHandler != null)
                                        this.callBackHandler.endElement("", "", name);
                            }
                            break;

                        case System.Xml.XmlNodeType.EndElement:
                            if (this.namespaceAllowed)
                            {
                                if (this.callBackHandler != null)
                                    this.callBackHandler.endElement(reader.NamespaceURI, reader.LocalName, reader.Name);
                            }
                            else
                                if (this.callBackHandler != null)
                                    this.callBackHandler.endElement("", "", reader.Name);
                            if (this.namespaceAllowed && prefixes.ContainsKey(reader.NamespaceURI) && ((System.Collections.Stack)stackNameSpace).Contains(reader.Name))
                            {
                                stackNameSpace.Pop();
                                System.Collections.Stack namespaceStack = (System.Collections.Stack)prefixes[reader.NamespaceURI];
                                while (namespaceStack.Count > 0)
                                {
                                    System.String tempString = (System.String)namespaceStack.Pop();
                                    if (this.callBackHandler != null)
                                        ((IXmlSaxContentHandler)this.callBackHandler).endPrefixMapping(tempString);
                                }
                                prefixes.Remove(reader.NamespaceURI);
                            }
                            break;

                        case System.Xml.XmlNodeType.Text:
                            if (this.callBackHandler != null)
                                this.callBackHandler.characters(reader.Value.ToCharArray(), 0, reader.Value.Length);
                            break;

                        case System.Xml.XmlNodeType.Whitespace:
                            if (this.callBackHandler != null)
                                this.callBackHandler.ignorableWhitespace(reader.Value.ToCharArray(), 0, reader.Value.Length);
                            break;

                        case System.Xml.XmlNodeType.ProcessingInstruction:
                            if (this.callBackHandler != null)
                                this.callBackHandler.processingInstruction(reader.Name, reader.Value);
                            break;

                        case System.Xml.XmlNodeType.Comment:
                            if (this.lexical != null)
                                this.lexical.comment(reader.Value.ToCharArray(), 0, reader.Value.Length);
                            break;

                        case System.Xml.XmlNodeType.CDATA:
                            if (this.lexical != null)
                            {
                                lexical.startCDATA();
                                if (this.callBackHandler != null)
                                    this.callBackHandler.characters(this.reader.Value.ToCharArray(), 0, this.reader.Value.ToCharArray().Length);
                                lexical.endCDATA();
                            }
                            break;

                        case System.Xml.XmlNodeType.DocumentType:
                            if (this.lexical != null)
                            {
                                System.String lname = this.reader.Name;
                                System.String systemId = null;
                                if (this.reader.AttributeCount > 0)
                                    systemId = this.reader.GetAttribute(0);
                                this.lexical.startDTD(lname, null, systemId);
                                this.lexical.startEntity("[dtd]");
                                this.lexical.endEntity("[dtd]");
                                this.lexical.endDTD();
                            }
                            break;
                    }
                }
                if (this.callBackHandler != null)
                    this.callBackHandler.endDocument();
            }
            catch (System.Xml.XmlException e)
            {
                throw e;
            }
        }
Ejemplo n.º 53
0
	internal JJTParserState() {
	    nodes = new System.Collections.Stack();
	    marks = new System.Collections.Stack();
	    sp = 0;
	    mk = 0;
	}
Ejemplo n.º 54
0
 /// <summary>
 /// �����沨�����ʽ����.
 /// </summary>
 /// <param name="s"></param>
 /// <returns></returns>
 public static string ComputeRPN(string s)
 {
     string S = BuildingRPN(s);
     string tmp = "";
     System.Collections.Stack sk = new System.Collections.Stack();
     char c = ' ';
     System.Text.StringBuilder Operand = new System.Text.StringBuilder();
     double x, y;
     for (int i = 0; i < S.Length; i++)
     {
         c = S[i];
         if (char.IsDigit(c) || c == '.')
         {//����ֵ�ռ�.
             Operand.Append(c);
         }
         else if (c == ' ' && Operand.Length > 0)
         {
             #region ������ת��
             try
             {
                 tmp = Operand.ToString();
                 if (tmp.StartsWith("-"))//������ת��һ��ҪС��...������ֱ��֧��.
                 {//�����ҵ��㷨�������֧������Զ���ᱻִ��.
                     sk.Push(-((double)Convert.ToDouble(tmp.Substring(1, tmp.Length - 1))));
                 }
                 else
                 {
                     sk.Push(Convert.ToDouble(tmp));
                 }
             }
             catch
             {
                 return "�����쳣����ֵ.";
             }
             Operand = new System.Text.StringBuilder();
             #endregion
         }
         else if (c == '+'//���������.˫Ŀ���㴦��.
          || c == '-'
          || c == '*'
          || c == '/'
          || c == '%'
          || c == '^')
         {
             #region ˫Ŀ����
             if (sk.Count > 0)/*�������ı��ʽ����û�а��������.���Ǹ������ǿմ�.������߼�����������.*/
             {
                 y = (double)sk.Pop();
             }
             else
             {
                 sk.Push(0);
                 break;
             }
             if (sk.Count > 0)
                 x = (double)sk.Pop();
             else
             {
                 sk.Push(y);
                 break;
             }
             switch (c)
             {
                 case '+':
                     sk.Push(x + y);
                     break;
                 case '-':
                     sk.Push(x - y);
                     break;
                 case '*':
                     sk.Push(x * y);
                     break;
                 case '/':
                     sk.Push(x / y);
                     break;
                 case '%':
                     sk.Push(x % y);
                     break;
                 case '^':
                     sk.Push(System.Math.Pow(x, y));
                     break;
             }
             #endregion
         }
         else if (c == '!')//��Ŀȡ��.)
         {
             sk.Push(-((double)sk.Pop()));
         }
     }
     if (sk.Count != 1)
         throw new Exception(String.Format("����ʧ��(sk.Count={0}): {1}", sk.Count, s));
     return sk.Pop().ToString();
 }
Ejemplo n.º 55
0
		/// <param name="isIndirectionOperatorAllowed">whether the fdb indirection operators are allowed, e.g.
		/// asterisk (*x) or trailing dot (x.)
		/// </param>
		public ASTBuilder(bool isIndirectionOperatorAllowed)
		{
			m_expStack = new System.Collections.Stack();
            m_opStack = new System.Collections.Stack();
			m_isIndirectionOperatorAllowed = isIndirectionOperatorAllowed;
		}
Ejemplo n.º 56
0
        private DateTime AddMissedEvents(DateTime latestTimeStamp)
        {
            DateTime retDateTime = DateTime.MinValue;
            string dateTimeWMI = convertToWMIDateTime(latestTimeStamp);
            CLogger.WriteLog(ELogLevel.DEBUG, "Querying Win32_NTLogEvent");

            string queryStr = @"SELECT * from Win32_NTLogEvent where LogFile = 'Security' and Category =" +
                            EVENT_CATEGORY.ToString() +
                            "and (EventCode=" + OBJ_OPEN_EVENT.ToString() + " OR EventCode= " + OBJ_DELETE_EVENT.ToString() +
                            " OR EventCode=" + OBJ_ACCESS_EVENT.ToString() +") and TimeGenerated > '" + dateTimeWMI + "'";

            SelectQuery query = new SelectQuery(queryStr);

            ManagementObjectSearcher eventLogSearcher = new ManagementObjectSearcher(query);
            CLogger.WriteLog(ELogLevel.DEBUG, "Created new MgmtObjSearcher");

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

            foreach (ManagementObject eventLogEntry in eventLogSearcher.Get())
            {
                /* On Win Server 2008, the items are provided by WMI in desc order of timestamps
                 * Hence we add the events to a stack and process it later by popping off elements
                 */
                if (osInfo.Version.Major == OS_VER_WIN_SERVER_2008)
                {
                    stack.Push(eventLogEntry);
                }
                else
                {
                    //CLogger.WriteLog(ELogLevel.DEBUG, "Looping through entries in eventLog");
                    EventEntry e = processManagementObject(eventLogEntry);
                    if (e != null)
                    {
                        CLogger.WriteLog(ELogLevel.DEBUG, "Looping through entries in eventLog , timestamp : "
                                    + e.timestamp.ToString());
                        retDateTime = e.timestamp;  // should not we compare timestamp
                        ProcessEventLogEventEntry(e);
                    }
                }
            }
            while (stack.Count != 0)
            {
                ManagementObject eventLogEntry = (ManagementObject)stack.Pop();
                EventEntry e = processManagementObject(eventLogEntry);
                if (e != null)
                {
                    CLogger.WriteLog(ELogLevel.DEBUG, "Looping through entries in eventLog , timestamp : "
                                + e.timestamp.ToString());
                    retDateTime = e.timestamp;  // should not we compare timestamp
                    ProcessEventLogEventEntry(e);
                }
            }

            CLogger.WriteLog(ELogLevel.DEBUG, "Returning from Missed events");
            return retDateTime;
        }
Ejemplo n.º 57
0
        void NotifyWork()
        {
            NotifyEventObject notifyObj;
             System.Collections.Stack stack = new System.Collections.Stack();
             while (true)
             {

             try
             {

                         if (notifyQueue.Count == 0)
                         {
                             lock (notifyQueue)
                             {
                                 System.Threading.Monitor.Wait(notifyQueue);
                             }
                         }
                         else
                         {
                             stack.Clear();
                             notifyObj = (NotifyEventObject)notifyQueue.Dequeue();
                             foreach (ClientConnection cn in clientStreamArray)
                             {
                                 try
                                 {

                                     if (cn.IsConnected)
                                     {
                                         cn.DoNotify((NotifyEventObject)notifyObj);
                                         // cnt++;
                                     }
                                     else
                                     {
                                         Console.WriteLine("client dead");
                                         stack.Push(cn);
                                     }

                                 }
                                 catch (Exception ex)
                                 {
                                     Console.WriteLine("client dead" + ex.Message);
                                     stack.Push(cn);

                                     //clientStreamArray.Remove(stream);
                                 }
                             }
                             while (stack.Count > 0)
                             {
                                 ClientConnection cc = (ClientConnection)stack.Pop();
                                 clientStreamArray.Remove(cc);
                                 cc.Dispose();
                             }

                     }

                 //lock (clientStreamArray)
                 //{

                 //}
             }
             catch (Exception ex)
             {
                 Console.WriteLine(ex.Message + ex.StackTrace);
             }

             }
        }
Ejemplo n.º 58
0
        private static long SearchForInterestFiles(DirectoryInfo dSrcDir, Dictionary<string, FileInfo> src, string stExtensions)
        {
            try
            {
                DateTime cacheDate = DateTime.MinValue;

                Dictionary<string, string> srcCache = new Dictionary<string, string>();

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

                string stCachePath = Path.Combine(@".\", dSrcDir.FullName.Replace('\\', '_').Replace(':', '_'));

                int cursorLeft = 0;
                if (File.Exists(stCachePath))
                {
                    Console.Write(String.Format(Resources.readCache, dSrcDir.FullName) + " ");
                    cursorLeft = Console.CursorLeft;

                    FileInfo f = new FileInfo(stCachePath);

                    StreamReader inputlist = File.OpenText(stCachePath);

                    string line = null;

                    while ((line = inputlist.ReadLine()) != null)
                    {
                        if (line.Contains("|"))
                        {
                            string[] split = line.Split('|');
                            srcCache.Add(split[1], split[0]);
                        }
                    }

                    inputlist.Close();

                    if (srcCache.Count > 0)
                        cacheDate = f.LastWriteTimeUtc;
                }
                else
                    Console.WriteLine(String.Format(Resources.warnNocache, dSrcDir.FullName));

                StreamWriter sw = new StreamWriter(stCachePath);

                long TotalInterestSize = 0;

                stackDirs.Push(dSrcDir);
                int schonIndex = 0;

                Stack<FileInfo> staHashToCompute = new Stack<FileInfo>();
                while (stackDirs.Count > 0)
                {
                    DirectoryInfo currentDir = (DirectoryInfo)stackDirs.Pop();

                    //Process .\files
                    foreach (FileInfo fileInfo in currentDir.GetFiles())
                    {
                        if (stExtensions.Contains(fileInfo.Extension))
                        {
                            string hash;
                            if ((fileInfo.LastWriteTimeUtc < cacheDate) && srcCache.ContainsKey(fileInfo.FullName))
                            {
                                hash = srcCache[fileInfo.FullName];
                                AddInSrc(src, fileInfo, hash, sw);
                            }
                            else
                                staHashToCompute.Push(fileInfo);

                            TotalInterestSize += fileInfo.Length;

                            {
                                ++schonIndex;
                                Console.CursorLeft = cursorLeft;
                                Console.Write(_stSchon[schonIndex % _stSchon.Length].ToString());
                            }
                        }
                    }

                    //Process Subdirectories
                    foreach (DirectoryInfo diNext in currentDir.GetDirectories())
                        stackDirs.Push(diNext);
                }

                //Process not cached hashs
                Console.WriteLine();
                if (staHashToCompute.Count > 10)
                    Console.Write(String.Format(Resources.hashToDo, staHashToCompute.Count) + " ");
                cursorLeft = Console.CursorLeft;

                int done = 0;
                foreach (FileInfo fi in staHashToCompute)
                {
                    ++done;
                    Console.CursorLeft = cursorLeft;
                    Console.Write(_stSchon[done % _stSchon.Length].ToString());
                    if (staHashToCompute.Count > 10)
                        if (done % (staHashToCompute.Count / 10) == 0)
                            Console.Write(" " + String.Format(Resources.hashWIP, done, staHashToCompute.Count));

                    string hash = Hash.GetSAH1HashFromFile(fi.FullName);
                    AddInSrc(src, fi, hash, sw);
                }
                sw.Close();

                Console.WriteLine();
                return TotalInterestSize;
            }
            catch (Exception)
            {
                throw;
            }
        }
Ejemplo n.º 59
0
		/// <summary> Walk the actions filling in the names of functions as we go.
		/// This is done by looking for DefineFunction's actions and then
		/// examining the content of the stack for a name.
		/// 
		/// </summary>
		/// <param name="c">list of actions to be traversed
		/// </param>
		/// <param name="swfVersion">version of swf file that housed the ActionList (just use 7 if you don't know)
		/// </param>
		/// <param name="pool">optional; constant pool for the list of actions
		/// </param>
		/// <param name="className">optional; used to locate a constructor function (i.e if funcName == className)
		/// </param>
		/// <param name="profileOffsets">optional; is filled with offsets if a call to a 
		/// function named 'profile' is encountered.  Can be null if caller is not
		/// interested in obtaining this information.
		/// </param>
		public static void walkActions(ActionList c, int swfVersion, String[] pool, String className, System.Collections.IList profileOffsets)
		{
			// assumption: ActionContext c is always not null! try-catch-finally may be busted.
			if (c == null)
				return ;
			
			System.Collections.Stack evalStack = new System.Collections.Stack();
			System.Collections.Hashtable variables = new System.Collections.Hashtable();
			
			// loop again, this time, we register all the actions...
			int offset;
			Action a;
			
			for (int i = 0; i < c.size(); i++)
			{
				offset = c.getOffset(i);
				a = c.getAction(i);
				
				switch (a.code)
				{
					
					// Flash 1 and 2 actions
					case ActionConstants.sactionHasLength: 
					case ActionConstants.sactionNone: 
					case ActionConstants.sactionGotoFrame: 
					case ActionConstants.sactionGetURL: 
					case ActionConstants.sactionNextFrame: 
					case ActionConstants.sactionPrevFrame: 
					case ActionConstants.sactionPlay: 
					case ActionConstants.sactionStop: 
					case ActionConstants.sactionToggleQuality: 
					case ActionConstants.sactionStopSounds: 
					case ActionConstants.sactionWaitForFrame: 
					// Flash 3 Actions
					case ActionConstants.sactionSetTarget: 
					case ActionConstants.sactionGotoLabel: 
						// no action
						break;
						
						// Flash 4 Actions
					
					case ActionConstants.sactionAdd: 
					case ActionConstants.sactionSubtract: 
					case ActionConstants.sactionMultiply: 
					case ActionConstants.sactionDivide: 
					case ActionConstants.sactionEquals: 
					case ActionConstants.sactionLess: 
					case ActionConstants.sactionAnd: 
					case ActionConstants.sactionOr: 
					case ActionConstants.sactionStringEquals: 
					case ActionConstants.sactionStringAdd: 
					case ActionConstants.sactionStringLess: 
					case ActionConstants.sactionMBStringLength: 
					case ActionConstants.sactionGetProperty: 
						// pop, pop, push
						pop(evalStack);
						break;
					
					case ActionConstants.sactionNot: 
					case ActionConstants.sactionStringLength: 
					case ActionConstants.sactionToInteger: 
					case ActionConstants.sactionCharToAscii: 
					case ActionConstants.sactionAsciiToChar: 
					case ActionConstants.sactionMBCharToAscii: 
					case ActionConstants.sactionMBAsciiToChar: 
					case ActionConstants.sactionRandomNumber: 
						// pop, push
						break;
					
					case ActionConstants.sactionGetVariable: 
						Object key = pop(evalStack);
						if (variables[key] == null)
						{
							evalStack.Push(key);
						}
						else
						{
							evalStack.Push(variables[key]);
						}
						break;
					
					case ActionConstants.sactionStringExtract: 
					case ActionConstants.sactionMBStringExtract: 
						// pop, pop, pop, push
						pop(evalStack);
						pop(evalStack);
						break;
					
					case ActionConstants.sactionPush: 
						Push p = (Push) a;
						System.Object o = p.value;
						int type = Push.getTypeCode(o);
						switch (type)
						{
							
							case ActionConstants.kPushStringType: 
								evalStack.Push(o);
								break;
							
							case ActionConstants.kPushNullType: 
								evalStack.Push("null");
								break;
							
							case ActionConstants.kPushUndefinedType: 
								evalStack.Push("undefined");
								break;
							
							case ActionConstants.kPushRegisterType: 
								evalStack.Push(registers[(int) ((SByte) o) & 0xFF]);
								break;
							
							case ActionConstants.kPushConstant8Type: 
							case ActionConstants.kPushConstant16Type: 
								evalStack.Push(pool[Convert.ToInt32(((ValueType) o)) & 0xFFFF]);
								break;
							
							case ActionConstants.kPushFloatType: 
								evalStack.Push(o + "F");
								break;
							
							case ActionConstants.kPushBooleanType: 
							case ActionConstants.kPushDoubleType: 
							case ActionConstants.kPushIntegerType: 
								evalStack.Push(o);
								break;
							
							default: 
								evalStack.Push("type" + type);
								break;
							
						}
						break;
					
					case ActionConstants.sactionIf: 
						pop(evalStack);
						break;
					
					case ActionConstants.sactionPop: 
					case ActionConstants.sactionCall: 
					case ActionConstants.sactionGotoFrame2: 
					case ActionConstants.sactionSetTarget2: 
					case ActionConstants.sactionRemoveSprite: 
					case ActionConstants.sactionWaitForFrame2: 
					case ActionConstants.sactionTrace: 
						// pop
						pop(evalStack);
						break;
					
					case ActionConstants.sactionJump: 
					case ActionConstants.sactionEndDrag: 
						// no action
						break;
					
					case ActionConstants.sactionSetVariable: 
						key = pop(evalStack);
						Object val = pop(evalStack);
						variables[key] = val;
						break;
					
					case ActionConstants.sactionGetURL2: 
						// pop, pop
						pop(evalStack);
						pop(evalStack);
						break;
					
					case ActionConstants.sactionSetProperty: 
					case ActionConstants.sactionCloneSprite: 
						// pop, pop, pop
						pop(evalStack);
						pop(evalStack);
						pop(evalStack);
						break;
					
					case ActionConstants.sactionStartDrag: 
						// pop, pop, pop, if the 3rd pop is non-zero, pop, pop, pop, pop
						pop(evalStack);
						pop(evalStack);
						Object obj = pop(evalStack);
						if (Int32.Parse(obj.ToString()) != 0)
						{
							pop(evalStack);
							pop(evalStack);
							pop(evalStack);
							pop(evalStack);
						}
						break;
					
					case ActionConstants.sactionGetTime: 
						// push
						evalStack.Push(dummy);
						break;
						
						// Flash 5 actions
					
					case ActionConstants.sactionDelete: 
						pop(evalStack);
						break;
					
					case ActionConstants.sactionDefineLocal: 
						// pop, pop
						val = pop(evalStack);
						key = pop(evalStack);
						variables[key] = val;
						break;
					
					case ActionConstants.sactionDefineFunction: 
					case ActionConstants.sactionDefineFunction2: 
						DefineFunction f = (DefineFunction) a;
						
						if (swfVersion > 6 && className != null)
						{
							if (f.name == null || f.name.Length == 0)
							{
								int depth = evalStack.Count;
								if (depth != 0)
								{
									o = evalStack.Peek();
									if (o == dummy)
									{
										f.name = "";
									}
									else if (o != null)
									{
										f.name = o.ToString();
									}
								}
								evalStack.Push(dummy);
							}
							
							if (f.name == "null")
							{
								f.name = "";
							}
							
							if (f.name == null || f.name.Length == 0)
							{
								// do nothing... it's an anonymous function!
							}
							else if (!className.EndsWith(f.name))
							{
								f.name = className + "." + f.name;
							}
							else
							{
								f.name = className + ".[constructor]";
							}
						}
						else
						{
							if (f.name == null || f.name.Length == 0)
							{
                                System.Text.StringBuilder buffer = new System.Text.StringBuilder();

                                Boolean bFirst = true;

								foreach (Object ob in evalStack)
								{
									if (ob == dummy)
									{
										break;
									}
									else if (bFirst)
									{
										buffer.Append(ob);
                                        bFirst = false;
									}
									else
									{
										buffer.Insert(0, '.');
										buffer.Insert(0, ob);
									}
								}
								f.name = buffer.ToString();
								
								if (f.name != null && f.name.IndexOf(".prototype.") == - 1)
								{
									f.name = "";
								}
								evalStack.Push(dummy);
							}
						}
						// evalActions(f.actions);
						break;
					
					case ActionConstants.sactionCallFunction: 
						Object function = pop(evalStack);
						if (profileOffsets != null && "profile".Equals(function))
						{
							profileOffsets.Add((Int32) (offset - 13)); // Push 1
							profileOffsets.Add((Int32) (offset - 5)); // Push 'profile'
							profileOffsets.Add((Int32) offset); // CallFunction
							profileOffsets.Add((Int32) (offset + 1)); // Pop
						}
						int n = Convert.ToInt32(((System.ValueType) pop(evalStack)));
						for (int k = 0; k < n; k++)
						{
							pop(evalStack);
						}
						evalStack.Push(dummy);
						break;
					
					case ActionConstants.sactionReturn: 
						// return function() { ... } doesn't push...
						pop(evalStack);
						break;
					
					case ActionConstants.sactionModulo: 
						// pop, push
						break;
					
					case ActionConstants.sactionNewObject: 
						pop(evalStack);
						int num = Convert.ToInt32(((ValueType) pop(evalStack)));
						for (int k = 0; k < num; k++)
						{
							pop(evalStack);
						}
						evalStack.Push(dummy);
						break;
					
					case ActionConstants.sactionDefineLocal2: 
					case ActionConstants.sactionDelete2: 
					case ActionConstants.sactionAdd2: 
					case ActionConstants.sactionLess2: 
						// pop
						pop(evalStack);
						break;
					
					case ActionConstants.sactionInitArray: 
						// pop, if the first pop is non-zero, keep popping
						num = Convert.ToInt32(((ValueType) pop(evalStack)));
						for (int k = 0; k < num; k++)
						{
							pop(evalStack);
						}
						evalStack.Push(dummy);
						break;
					
					case ActionConstants.sactionInitObject: 
						num = Convert.ToInt32(((ValueType) pop(evalStack))) * 2;
						for (int k = 0; k < num; k++)
						{
							pop(evalStack);
						}
						evalStack.Push(dummy);
						break;
					
					case ActionConstants.sactionTargetPath: 
					case ActionConstants.sactionEnumerate: 
					case ActionConstants.sactionToNumber: 
					case ActionConstants.sactionToString: 
					case ActionConstants.sactionTypeOf: 
						// no action
						break;
					
					case ActionConstants.sactionStoreRegister: 
						StoreRegister r = (StoreRegister) a;
						registers[r.register] = evalStack.Peek();
						break;
					
					case ActionConstants.sactionEquals2: 
						// pop, pop, push
						// if (evalStack.size() >= 2)
						{
							pop(evalStack);
						}
						break;
					
					case ActionConstants.sactionPushDuplicate: 
						evalStack.Push(dummy);
						break;
					
					case ActionConstants.sactionStackSwap: 
						// pop, pop, push, push
						break;
					
					case ActionConstants.sactionGetMember: 
						// pop, pop, concat, push
						Object o1 = pop(evalStack);
						Object o2 = pop(evalStack);
						if (pool != null)
						{
							try
							{
								evalStack.Push(pool[Int32.Parse(o2.ToString())] + "." + pool[Int32.Parse(o1.ToString())]);
							}
							catch (Exception)
							{
								if (o1 == dummy || o2 == dummy)
								{
									evalStack.Push(dummy);
								}
								else
								{
                                    evalStack.Push(o2 + "." + o1);
								}
							}
						}
						else
						{
							evalStack.Push(o2 + "." + o1);
						}
						break;
					
					case ActionConstants.sactionSetMember: 
						// pop, pop, pop
						pop(evalStack);
						pop(evalStack);
						pop(evalStack);
						break;
					
					case ActionConstants.sactionIncrement: 
					case ActionConstants.sactionDecrement: 
						break;
					
					case ActionConstants.sactionCallMethod: 
						pop(evalStack);
						pop(evalStack);
						Object obj2 = pop(evalStack);
						if (obj2 is String)
						{
							try
							{
								n = Int32.Parse((String) obj2);
							}
							catch (FormatException)
							{
								n = 1;
							}
						}
						else
						{
							n = Convert.ToInt32(((ValueType) obj2));
						}
						for (int k = 0; k < n; k++)
						{
							pop(evalStack);
						}
						evalStack.Push(dummy);
						break;
					
					case ActionConstants.sactionNewMethod: 
						/*Object meth =*/ pop(evalStack);
						/*Object cls =*/ pop(evalStack);
						num = Convert.ToInt32(((ValueType) pop(evalStack)));
						for (int k = 0; k < num; k++)
						{
							pop(evalStack);
						}
						evalStack.Push(dummy);
						break;
					
					case ActionConstants.sactionWith: 
						// pop
						pop(evalStack);
						break;
					
					case ActionConstants.sactionConstantPool: 
						pool = ((ConstantPool) a).pool;
						// no action
						break;
					
					case ActionConstants.sactionStrictMode: 
						break;
					
					
					case ActionConstants.sactionBitAnd: 
					case ActionConstants.sactionBitOr: 
					case ActionConstants.sactionBitLShift: 
						// pop, push
						break;
					
					case ActionConstants.sactionBitXor: 
					case ActionConstants.sactionBitRShift: 
					case ActionConstants.sactionBitURShift: 
						pop(evalStack);
						break;
						
						// Flash 6 actions
					
					case ActionConstants.sactionInstanceOf: 
						pop(evalStack);
						break;
					
					case ActionConstants.sactionEnumerate2: 
						// pop, push, more pushes?
						break;
					
					case ActionConstants.sactionStrictEquals: 
					case ActionConstants.sactionGreater: 
					case ActionConstants.sactionStringGreater: 
						pop(evalStack);
						break;
						
						// FEATURE_EXCEPTIONS
					
					case ActionConstants.sactionTry: 
						// do nothing
						break;
					
					case ActionConstants.sactionThrow: 
						pop(evalStack);
						break;
						
						// FEATURE_AS2_INTERFACES
					
					case ActionConstants.sactionCastOp: 
						break;
					
					case ActionConstants.sactionImplementsOp: 
						break;
						
						// Reserved for Quicktime
					
					case ActionConstants.sactionQuickTime: 
						break;
					
					default: 
						break;
					
				}
			}
		}
Ejemplo n.º 60
0
        public static void Run()
        {
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_Images();

            // Load the source PDF file
            Document doc = new Document(dataDir+ "ImageInformation.pdf");

            // Define the default resolution for image
            int defaultResolution = 72;
            System.Collections.Stack graphicsState = new System.Collections.Stack();
            // Define array list object which will hold image names
            System.Collections.ArrayList imageNames = new System.Collections.ArrayList(doc.Pages[1].Resources.Images.Names);
            // Insert an object to stack
            graphicsState.Push(new System.Drawing.Drawing2D.Matrix(1, 0, 0, 1, 0, 0));

            // Get all the operators on first page of document
            foreach (Operator op in doc.Pages[1].Contents)
            {
                // Use GSave/GRestore operators to revert the transformations back to previously set
                Operator.GSave opSaveState = op as Operator.GSave;
                Operator.GRestore opRestoreState = op as Operator.GRestore;
                // Instantiate ConcatenateMatrix object as it defines current transformation matrix.
                Operator.ConcatenateMatrix opCtm = op as Operator.ConcatenateMatrix;
                // Create Do operator which draws objects from resources. It draws Form objects and Image objects
                Operator.Do opDo = op as Operator.Do;

                if (opSaveState != null)
                {
                    // Save previous state and push current state to the top of the stack
                    graphicsState.Push(((System.Drawing.Drawing2D.Matrix)graphicsState.Peek()).Clone());
                }
                else if (opRestoreState != null)
                {
                    // Throw away current state and restore previous one
                    graphicsState.Pop();
                }
                else if (opCtm != null)
                {
                    System.Drawing.Drawing2D.Matrix cm = new System.Drawing.Drawing2D.Matrix(
                       (float)opCtm.Matrix.A,
                       (float)opCtm.Matrix.B,
                       (float)opCtm.Matrix.C,
                       (float)opCtm.Matrix.D,
                       (float)opCtm.Matrix.E,
                       (float)opCtm.Matrix.F);

                    // Multiply current matrix with the state matrix
                    ((System.Drawing.Drawing2D.Matrix)graphicsState.Peek()).Multiply(cm);

                    continue;
                }
                else if (opDo != null)
                {
                    // In case this is an image drawing operator
                    if (imageNames.Contains(opDo.Name))
                    {
                        System.Drawing.Drawing2D.Matrix lastCTM = (System.Drawing.Drawing2D.Matrix)graphicsState.Peek();
                        // Create XImage object to hold images of first pdf page
                        XImage image = doc.Pages[1].Resources.Images[opDo.Name];

                        // Get image dimensions
                        double scaledWidth = Math.Sqrt(Math.Pow(lastCTM.Elements[0], 2) + Math.Pow(lastCTM.Elements[1], 2));
                        double scaledHeight = Math.Sqrt(Math.Pow(lastCTM.Elements[2], 2) + Math.Pow(lastCTM.Elements[3], 2));
                        // Get Height and Width information of image
                        double originalWidth = image.Width;
                        double originalHeight = image.Height;

                        // Compute resolution based on above information
                        double resHorizontal = originalWidth * defaultResolution / scaledWidth;
                        double resVertical = originalHeight * defaultResolution / scaledHeight;

                        // Display Dimension and Resolution information of each image
                        Console.Out.WriteLine(
                                string.Format(dataDir + "image {0} ({1:.##}:{2:.##}): res {3:.##} x {4:.##}",
                                             opDo.Name, scaledWidth, scaledHeight, resHorizontal,
                                             resVertical));
                    }
                }
            }
            
            
        }