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 }
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; }
/// <summary> /// load rtf /// </summary> /// <param name="reader">RTF text reader</param> public void Load(RTFReader reader) { myNodes.Clear(); System.Collections.Stack groups = new System.Collections.Stack(); RTFNodeGroup NewGroup = null; RTFNode NewNode = null; while (reader.ReadToken() != null) { if (reader.TokenType == RTFTokenType.GroupStart) { // begin group if (NewGroup == null) { NewGroup = this; } else { NewGroup = new RTFNodeGroup(); NewGroup.OwnerDocument = this; } if (NewGroup != this) { RTFNodeGroup g = ( RTFNodeGroup )groups.Peek(); g.AppendChild(NewGroup); } groups.Push(NewGroup); } else if (reader.TokenType == RTFTokenType.GroupEnd) { // end group NewGroup = ( RTFNodeGroup )groups.Pop(); NewGroup.MergeText(); if (NewGroup.FirstNode is RTFNode) { switch (NewGroup.Keyword) { case RTFConsts._fonttbl: // read font table ReadFontTable(NewGroup); break; case RTFConsts._colortbl: // read color table ReadColorTable(NewGroup); break; case RTFConsts._info: // read document information ReadDocumentInfo(NewGroup); break; } } if (groups.Count > 0) { NewGroup = (RTFNodeGroup)groups.Peek(); } else { break; } //NewGroup.MergeText(); } else { // read content NewNode = new RTFNode(reader.CurrentToken); NewNode.OwnerDocument = this; NewGroup.AppendChild(NewNode); if (NewNode.Keyword == RTFConsts._f) { RTFFont font = this.FontTable[NewNode.Parameter]; if (font != null) { myFontChartset = font.Encoding; } else { myFontChartset = null; } //myFontChartset = RTFFont.GetRTFEncoding( NewNode.Parameter ); } else if (NewNode.Keyword == RTFConsts._af) { RTFFont font = this.FontTable[NewNode.Parameter]; if (font != null) { myAssociateFontChartset = font.Encoding; } else { myAssociateFontChartset = null; } } } } // while( reader.ReadToken() != null ) while (groups.Count > 0) { NewGroup = ( RTFNodeGroup )groups.Pop(); NewGroup.MergeText(); } //this.UpdateInformation(); }
static void Main(string[] args) { Console.Title = "Ejercicio 27"; Random r = new Random(); #region Pilas Console.WriteLine("Pilas"); System.Collections.Stack pila = new System.Collections.Stack(); for (int i = 0; i < 20; i++) { pila.Push(r.Next(100, 200)); } Console.WriteLine("Mostrar como se ingresó"); MostrarPila(pila); Console.WriteLine("\nMostrar de forma decreciente"); pila = SortStack(pila, false); MostrarPila(pila); Console.WriteLine("\nMostrar de forma creciente"); pila = SortStack(pila, true); MostrarPila(pila); Console.ReadLine(); #endregion Console.Clear(); #region Colas Console.WriteLine("Colas"); System.Collections.Queue cola = new System.Collections.Queue(); for (int i = 0; i < 20; i++) { cola.Enqueue(r.Next(100, 200)); } Console.WriteLine("Mostrar como se ingresó"); MostrarCola(cola); Console.WriteLine("\nMostrar de forma decreciente"); cola = SortQueue(cola, true); MostrarCola(cola); Console.WriteLine("\nMostrar de forma creciente"); cola = SortQueue(cola, false); MostrarCola(cola); Console.ReadLine(); #endregion Console.Clear(); #region Listas Console.WriteLine("Listas"); System.Collections.ArrayList lista = new System.Collections.ArrayList(); for (int i = 0; i < 20; i++) { lista.Add(r.Next(100, 200)); } Console.WriteLine("Mostrar como se ingresó"); MostrarLista(lista); Console.WriteLine("\nMostrar de forma decreciente"); lista.Sort(); lista.Reverse(); MostrarLista(lista); Console.WriteLine("\nMostrar de forma creciente"); lista.Reverse(); MostrarLista(lista); Console.ReadLine(); #endregion }
//private static double Momspct = 0.25; static void Main(string[] args) { // så kan man spørge på argumenter til programmet if (args.Length > 0) { foreach (var item in args) { System.Console.WriteLine(item); } ; } ; // Så kan man hente i konfigurationsfilen //modul+add+reference: system.coonfiguration string m = System.Configuration.ConfigurationManager.AppSettings["moms"]; double moms = 0; if (m != null) { moms = Convert.ToDouble(m); } //Eller bruge program properties + settings. //kan bruges som en mini dattabase. string x = Module11_Collections.Properties.Settings.Default.Xpos; System.Collections.ArrayList lst1 = new System.Collections.ArrayList(); lst1.Add(1); lst1.Add(2); lst1.Remove(1); System.Collections.ArrayList lst2 = new System.Collections.ArrayList(); lst2.Add(new Hund() { Navn = "a" }); lst2.Add(new Hund() { Navn = "b" }); lst2.Remove(1); System.Collections.Stack lst3 = new System.Collections.Stack(); lst3.Push(1); lst3.Push(2); lst3.Push(133); System.Collections.Queue lst4 = new System.Collections.Queue(); lst4.Enqueue(new Hund() { Navn = "A" }); lst4.Enqueue(new Hund() { Navn = "B" }); lst4.Enqueue(new Hund() { Navn = "C" }); Hund h = (Hund)lst4.Dequeue(); System.Collections.Hashtable lst5 = new System.Collections.Hashtable(); lst5.Add("a", "a"); lst5.Add("b", "a"); lst5.Add("c", "a"); string r = lst5["b"].ToString(); Kennel kennel = new Kennel(); kennel.TilføjHund(h); ////////////////// System.Collections.Generic.List <Hund> lst6 = new System.Collections.Generic.List <Hund>(); lst6.Add(new Hund() { Navn = "a" }); lst6.Add(new Hund() { Navn = "b" }); Hund hh = lst6[0]; Queue <int> lst7 = new Queue <int>(); lst7.Enqueue(5); int ii = lst7.Dequeue(); Dictionary <int, Hund> lst8 = new Dictionary <int, Hund>(); lst8.Add(4, new Hund() { Navn = "b" }); lst8.Add(22, new Hund() { Navn = "g" }); Hund hhh = lst8[4]; List <string> lst9 = new List <string>(); lst9.Add("A1"); lst9.Add("B1"); lst9.Add("E1"); lst9.Add("C1"); foreach (var item in lst9) { System.Console.WriteLine(item); } for (int i = 0; i < lst9.Count; i++) { System.Console.WriteLine(lst9[i].ToString()); } //Test<MinType> t1 = new Test<MinType>(); Kennel2 k2 = new Kennel2(); //k2.Add(new Hund); //k2.Add(Hund ); if (System.Diagnostics.Debugger.IsAttached) { System.Console.Write("Press any key to continue . . . "); System.Console.ReadKey(); } }
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; } }
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)); } } } }
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); } } }
internal bool IsValid(string s) { if (String.IsNullOrEmpty(s)) { return(false); } if (s.Length > 10000) { return(false); } Char lastChar = ' '; bool isValid = true; System.Collections.Stack charStack = new System.Collections.Stack(); foreach (Char currentChar in s) { switch (currentChar) { case '(': charStack.Push(currentChar); break; case ')': if (charStack.Count > 0) { lastChar = (Char)charStack.Pop(); if (lastChar != '(') { isValid = false; } } else { isValid = false; } break; case ']': if (charStack.Count > 0) { lastChar = (Char)charStack.Pop(); if (lastChar != '[') { isValid = false; } } else { isValid = false; } break; case '[': charStack.Push(currentChar); break; case '{': charStack.Push(currentChar); break; case '}': if (charStack.Count > 0) { lastChar = (Char)charStack.Pop(); if (lastChar != '{') { isValid = false; } } else { isValid = false; } break; default: isValid = false; break; } if (!isValid) { break; } } if (charStack.Count > 0) { return(false); } Console.WriteLine(isValid); if (!isValid) { return(false); } else { return(true); } }
/// <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; } } }
private string BuildingRPN(string s) { System.Text.StringBuilder sb = new System.Text.StringBuilder(s); System.Collections.Stack sk = new System.Collections.Stack(); System.Text.StringBuilder re = new System.Text.StringBuilder(); char c = ' '; //sb.Replace( " ","" ); //一开始,我只去掉了空格.后来我不想不支持函数和常量能滤掉的全OUT掉. for (int i = 0; i < sb.Length; i++) { c = sb[i]; //added c==',' for german culture if (char.IsDigit(c) || c == ',')//数字当然要了. { re.Append(c); } //if( char.IsWhiteSpace( c )|| char.IsLetter(c); //如果是空白,那么不要.现在字母也不要. //continue; switch (c) //如果是其它字符...列出的要,没有列出的不要. { case '+': case '-': case '*': case '/': case '%': case '^': case '!': case '(': case ')': case '.': re.Append(c); break; default: continue; } } sb = new System.Text.StringBuilder(re.ToString()); #region 对负号进行预转义处理.负号变单目运算符求反. for (int i = 0; i < sb.Length - 1; i++) { if (sb[i] == '-' && (i == 0 || sb[i - 1] == '(')) { sb[i] = '!'; } } //字符转义. #endregion #region 将中缀表达式变为后缀表达式. re = new System.Text.StringBuilder(); for (int i = 0; i < sb.Length; i++) { if (char.IsDigit(sb[i]) || sb[i] == '.')//如果是数值. { re.Append(sb[i]); //加入后缀式 } else if (sb[i] == '+' || sb[i] == '-' || sb[i] == '*' || sb[i] == '/' || sb[i] == '%' || sb[i] == '^' || sb[i] == '!')//. { #region 运算符处理 while (sk.Count > 0) //栈不为空时 { c = (char)sk.Pop(); //将栈中的操作符弹出. if (c == '(') //如果发现左括号.停. { sk.Push(c); //将弹出的左括号压回.因为还有右括号要和它匹配. break; //中断. } else { if (Power(c) < Power(sb[i]))//如果优先级比上次的高,则压栈. { sk.Push(c); break; } else { re.Append(' '); re.Append(c); } //如果不是左括号,那么将操作符加入后缀式中. } } sk.Push(sb[i]); //把新操作符入栈. re.Append(' '); #endregion } else if (sb[i] == '(')//基本优先级提升 { sk.Push('('); re.Append(' '); } else if (sb[i] == ')') //基本优先级下调 { while (sk.Count > 0) //栈不为空时 { c = (char)sk.Pop(); //pop Operator if (c != '(') { re.Append(' '); re.Append(c); //加入空格主要是为了防止不相干的数据相临产生解析错误. re.Append(' '); } else { break; } } } else { re.Append(sb[i]); } } while (sk.Count > 0)//这是最后一个弹栈啦. { re.Append(' '); re.Append(sk.Pop()); } #endregion re.Append(' '); return(FormatSpace(re.ToString())); //在这里进行一次表达式格式化.这里就是后缀式了. }
private object GetFormulaResult(string s) { if (s == "") { return(null); } 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]; //added c==',' for germany culture if (char.IsDigit(c) || 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(null); // } 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 '*': if (y == 0) { sk.Push(x * 1); } else { sk.Push(x * y); } break; case '/': if (y == 0) { sk.Push(x / 1); } else { sk.Push(x / y); } break; case '%': sk.Push(x % y); break; case '^': // if (x > 0) // { //我原本还想,如果被计算的数是负数,又要开真分数次方时如何处理的问题.后来我想还是算了吧. sk.Push(System.Math.Pow(x, y)); // } // else // { // double t = y; // string ts = ""; // t = 1 / (2 * t); // ts = t.ToString(); // if (ts.ToUpper().LastIndexOf('E') > 0) // { // ; // } // } break; } #endregion } else if (c == '!')//单目取反. ) { sk.Push(-((double)sk.Pop())); } } if (sk.Count > 1) { return(null);//; } if (sk.Count == 0) { return(null);//; } return(sk.Pop()); }
// MARK: - Quick Sort public T[][] QuickSort <T>(T[] input) where T : IComparable <T> { T[][] state = new T[input.Length - 1][]; state[0] = (T[])input.Clone(); var i = 1; System.Collections.Stack stack = new System.Collections.Stack(); T pivot; int pivotIndex = 0; int leftIndex = pivotIndex + 1; int rightIndex = input.Length - 1; stack.Push(pivotIndex);//Push always with left and right stack.Push(rightIndex); int leftIndexOfSubSet, rightIndexOfSubset; while (stack.Count > 0) { rightIndexOfSubset = (int)stack.Pop();//pop always with right and left leftIndexOfSubSet = (int)stack.Pop(); leftIndex = leftIndexOfSubSet + 1; pivotIndex = leftIndexOfSubSet; rightIndex = rightIndexOfSubset; pivot = input[pivotIndex]; if (leftIndex > rightIndex) { continue; } while (leftIndex < rightIndex) { while ((leftIndex <= rightIndex) && (input[leftIndex].CompareTo(pivot) <= 0)) { leftIndex++; //increment right to find the greater } //element than the pivot while ((leftIndex <= rightIndex) && (input[rightIndex].CompareTo(pivot) >= 0)) { rightIndex--;//decrement right to find the } //smaller element than the pivot if (rightIndex >= leftIndex) { //if right index is //greater then only swap SwapElement <T>(ref input, leftIndex, rightIndex); state[i++] = (T[])input.Clone(); } } if (pivotIndex <= rightIndex) { if (input[pivotIndex].CompareTo(input[rightIndex]) > 0) { SwapElement(ref input, pivotIndex, rightIndex); state[i++] = input; } } if (leftIndexOfSubSet < rightIndex) { stack.Push(leftIndexOfSubSet); stack.Push(rightIndex - 1); } if (rightIndexOfSubset > rightIndex) { stack.Push(rightIndex + 1); stack.Push(rightIndexOfSubset); } } return(state); }
static void Main(string[] args) { { Console.WriteLine("The program class initiates Interface'ISweepstakes'\nOther classes, 'MySweeps' and 'Your Sweeps', implement the ISweepstakes interface."); Console.WriteLine(); MySweeps mySweepstakeClass = new MySweeps(); // Create a MySweeps object mySweepstakeClass.InsertSweepstakes(); mySweepstakeClass.GetSweepstakes(); YourSweepstakes yourSweeps = new YourSweepstakes(); yourSweeps.NameOfSweeps(); yourSweeps.RegisterParticipantInSweeps(); Console.WriteLine("This is a stack in the Interface Class"); Console.WriteLine("List elements in stack"); System.Collections.Stack st2 = new System.Collections.Stack(); st2.Push("now"); st2.Push("programmer"); st2.Push("am a"); st2.Push("I"); foreach (Object obj in st2) { Console.WriteLine(obj); } Console.ReadKey(); Console.WriteLine("+++++++++++++++++++++++++++++++++++++++++++++++++"); Console.WriteLine(); Console.WriteLine("Pop element from the stack"); st2.Pop(); Console.WriteLine(); foreach (Object obj in st2) { Console.WriteLine(obj); } Console.ReadKey(); Console.WriteLine("+++++++++++++++++++++++++++++++++++++++++++++++++"); Console.WriteLine(); Console.WriteLine("Pop another element from the stack"); //Stack st3 = new Stack(); st2.Pop(); Console.WriteLine(); foreach (Object obj in st2) { Console.WriteLine(obj); } Console.ReadKey(); Console.WriteLine("+++++++++++++++++++++++++++++++++++++++++++++++++"); Console.WriteLine(); Console.WriteLine("Pop another element from the stack"); //Stack st3 = new Stack(); st2.Pop(); Console.WriteLine(); foreach (Object obj in st2) { Console.WriteLine(obj); } Console.ReadKey(); Console.WriteLine("+++++++++++++++++++++++++++++++++++++++++++++++++"); Console.WriteLine(); Console.WriteLine("Push elements one by one"); Console.WriteLine(); st2.Push("programmer"); st2.Push("am a"); st2.Push("I"); foreach (Object obj in st2) { Console.WriteLine(obj); Console.ReadLine(); } } }
internal bool LoadContent(ModernMenuItem item, out bool isLeft, out bool AnimationShown) { int previousIndex, currentIndex; currentIndex = item.Index; previousIndex = 0; if (recentActions.Count > 0) { ModernMenuItem previousItem = recentActions.Peek() as ModernMenuItem; previousIndex = previousItem.Index; } isLeft = currentIndex <= previousIndex; System.Diagnostics.Debug.WriteLine("IsLeft=" + isLeft); AnimationShown = false; if (item.Items != null && item.Items.Count > 0) { return(true); } if (this.Content is ModernContent currentContent && !suppressCanBeClosed && !currentContent.CanBeClosed()) { return(false); } recentActions.Push(item); if (item.ContentType != null && item.ContentType.IsSubclassOf(typeof(ModernContent))) { Storyboard story = isLeft ? ((Storyboard)FindResource("ContentLeftInStoryboard")).Clone() : ((Storyboard)FindResource("ContentRightInStoryboard")).Clone(); if (Cache.ContainsKey(item)) { //item has already in the Cache ModernContent content = Cache[item]; loadedMenu = item; if (LoadContentSub(content, out AnimationShown, story)) { return(true); } } else { ModernContent content = (ModernContent)Activator.CreateInstance(item.ContentType); Cache.Add(item, content); loadedMenu = item; if (LoadContentSub(content, out AnimationShown, story)) { return(true); } } } else { this.Content = null; this.CommandArea = null; this.IsContentDetachable = false; this.IsContentDetached = false; loadedMenu = item; nextStatusBar = DefaultStatusBar; if (this.StatusBar != nextStatusBar) { if (this.StatusBar != null) { this.StatusBar.BeginStoryboard(HideStatusbarStoryboard); System.Diagnostics.Debug.WriteLine("Hide StatueBar line 190"); } else { this.StatusBar = nextStatusBar; if (this.StatusBar != null) { this.StatusBar.BeginStoryboard(ShowStatusbarStoryboard); System.Diagnostics.Debug.WriteLine("Show StatusBar line 198"); } } } } return(true); }
/// <summary> /// Reverse Polish Notation /// �����沨�����ʽ.����. /// </summary> /// <param name="s"></param> /// <returns></returns> private static string BuildingRPN(string s) { System.Text.StringBuilder sb = new System.Text.StringBuilder(s); System.Collections.Stack sk = new System.Collections.Stack(); System.Text.StringBuilder re = new System.Text.StringBuilder(); char c = ' '; //sb.Replace(" ","");//һ��ʼ,��ֻȥ���˿ո�.�����Ҳ��벻֧�ֺ����ͳ������˵��ȫOUT��. for (int i = 0; i < sb.Length; i++) { c = sb[i]; if (char.IsDigit(c))//���ֵ�ȻҪ��. re.Append(c); //if(char.IsWhiteSpace(c)||char.IsLetter(c))//����ǿհ�,��ô��Ҫ.������ĸҲ��Ҫ. //continue; switch (c)//����������ַ�...�г���Ҫ,û���г��IJ�Ҫ. { case '+': case '-': case '*': case '/': case '%': case '^': case '!': case '(': case ')': case '.': re.Append(c); break; default: continue; } } sb = new System.Text.StringBuilder(re.ToString()); #region �Ը��Ž���Ԥת�崦��.���ű䵥Ŀ�������. for (int i = 0; i < sb.Length - 1; i++) if (sb[i] == '-' && (i == 0 || sb[i - 1] == '(')) sb[i] = '!';//�ַ�ת��. #endregion #region �������ʽ��Ϊ�����ʽ. re = new System.Text.StringBuilder(); for (int i = 0; i < sb.Length; i++) { if (char.IsDigit(sb[i]) || sb[i] == '.')//�������ֵ. { re.Append(sb[i]);//�����ʽ } else if (sb[i] == '+' || sb[i] == '-' || sb[i] == '*' || sb[i] == '/' || sb[i] == '%' || sb[i] == '^' || sb[i] == '!')//. { #region ��������� while (sk.Count > 0) //ջ��Ϊ��ʱ { c = (char)sk.Pop(); //��ջ�еIJ���������. if (c == '(') //�������������.ͣ. { sk.Push(c); //��������������ѹ��.��Ϊ����������Ҫ����ƥ��. break; //�ж�. } else { if (Power(c) < Power(sb[i]))//������ȼ����ϴεĸ�,��ѹջ. { sk.Push(c); break; } else { re.Append(' '); re.Append(c); } //�������������,��ô�������������ʽ��. } } sk.Push(sb[i]); //���²�������ջ. re.Append(' '); #endregion } else if (sb[i] == '(')//�������ȼ����� { sk.Push('('); re.Append(' '); } else if (sb[i] == ')')//�������ȼ��µ� { while (sk.Count > 0) //ջ��Ϊ��ʱ { c = (char)sk.Pop(); //pop Operator if (c != '(') { re.Append(' '); re.Append(c);//����ո���Ҫ��Ϊ�˷�ֹ����ɵ��������ٲ�����������. re.Append(' '); } else break; } } else re.Append(sb[i]); } while (sk.Count > 0)//�������һ����ջ��. { re.Append(' '); re.Append(sk.Pop()); } #endregion re.Append(' '); return FormatSpace(re.ToString());//���������һ�α��ʽ��ʽ��.������Ǻ�ʽ��. }
public static void Run() { // ExStart:ImageInformation // 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 Aspose.Pdf.Operators.GSave opSaveState = op as Aspose.Pdf.Operators.GSave; Aspose.Pdf.Operators.GRestore opRestoreState = op as Aspose.Pdf.Operators.GRestore; // Instantiate ConcatenateMatrix object as it defines current transformation matrix. Aspose.Pdf.Operators.ConcatenateMatrix opCtm = op as Aspose.Pdf.Operators.ConcatenateMatrix; // Create Do operator which draws objects from resources. It draws Form objects and Image objects Aspose.Pdf.Operators.Do opDo = op as Aspose.Pdf.Operators.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)); } } } // ExEnd:ImageInformation }
/// <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; }
/// <summary> /// Pushes the <see cref="ModelMatrix"/> in a stack. See also <see cref="PopMatrix"/>. /// A push must allways used with a popMatrix. /// </summary> public void PushMatrix() { S.Push(ModelMatrix); }
/// <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; } } }
public static void q_sort(ref int[] input) { System.Collections.Stack stack = new System.Collections.Stack(); int pivot; int pivotIndex = 0; int leftIndex = pivotIndex + 1; int rightIndex = input.Length - 1; stack.Push(pivotIndex);//Push always with left and right stack.Push(rightIndex); int leftIndexOfSubSet, rightIndexOfSubset; while (stack.Count > 0) { rightIndexOfSubset = (int)stack.Pop();//pop always with right and left leftIndexOfSubSet = (int)stack.Pop(); leftIndex = leftIndexOfSubSet + 1; pivotIndex = leftIndexOfSubSet; rightIndex = rightIndexOfSubset; pivot = input[pivotIndex]; if (leftIndex > rightIndex) { continue; } while (leftIndex < rightIndex) { while ((leftIndex <= rightIndex) && (input[leftIndex] <= pivot)) { leftIndex++; //increment right to find the greater } //element than the pivot while ((leftIndex <= rightIndex) && (input[rightIndex] >= pivot)) { rightIndex--;//decrement right to find the } //smaller element than the pivot if (rightIndex >= leftIndex) //if right index is //greater then only swap { SwapElement(ref input, leftIndex, rightIndex); } } if (pivotIndex <= rightIndex) { if (input[pivotIndex] > input[rightIndex]) { SwapElement(ref input, pivotIndex, rightIndex); } } if (leftIndexOfSubSet < rightIndex) { stack.Push(leftIndexOfSubSet); stack.Push(rightIndex - 1); } if (rightIndexOfSubset > rightIndex) { stack.Push(rightIndex + 1); stack.Push(rightIndexOfSubset); } } }
/// <summary> /// Создает массив, в котором располагаются операторы и символы представленные в обратной польской записи (безскобочной) /// На этом же этапе отлавливаются почти все остальные ошибки (см код). По сути - это компиляция. /// </summary> /// <returns>массив обратной польской записи</returns> public static System.Collections.ArrayList CreateStack() { //Собственно результирующий массив System.Collections.ArrayList strarr = new System.Collections.ArrayList(30); //Стек с операторами где они временно храняться System.Collections.Stack operators = new System.Collections.Stack(15); string expr = expression; //пооператорная обработка выражения while (expr != "") { string op = expr.Substring(0, expr.IndexOf(" ")); // берём кусок выражения обрамлённый пробелами expr = expr.Substring(expr.IndexOf(" ") + 1); // отсекаем от выражения взятый кусок switch (op) { case "(": //1 { //Кладем в стэк operators.Push(op); break; } case "m": //4 { //вытаскиваем из стека все операторы чей приоритет больше либо равен унарному минусу while (operators.Count != 0 && (operators.Peek().ToString() == "m" || operators.Peek().ToString() == "p")) { if (strarr.Capacity > strarr.Count) { strarr.Add(operators.Pop()); } else { // переполнгение стека - возвращем null return(null); } } operators.Push(op); break; } case "p": //4 { while (operators.Count != 0 && (operators.Peek().ToString() == "m" | operators.Peek().ToString() == "p")) { if (strarr.Capacity > strarr.Count) { strarr.Add(operators.Pop()); } else { return(null); } } operators.Push(op); break; } case "*": //3 { while (operators.Count != 0 && (operators.Peek().ToString() == "*" || operators.Peek().ToString() == "/" || operators.Peek().ToString() == "mod" || operators.Peek().ToString() == "m" || operators.Peek().ToString() == "p")) { if (strarr.Capacity > strarr.Count) { strarr.Add(operators.Pop()); } else { return(null); } } operators.Push(op); break; } case "/": //3 { while (operators.Count != 0 && (operators.Peek().ToString() == "*" || operators.Peek().ToString() == "/" || operators.Peek().ToString() == "mod" || operators.Peek().ToString() == "m" || operators.Peek().ToString() == "p")) { if (strarr.Capacity > strarr.Count) { strarr.Add(operators.Pop()); } else { return(null); } } operators.Push(op); break; } case "mod": //3 { while (operators.Count != 0 && (operators.Peek().ToString() == "*" || operators.Peek().ToString() == "/" || operators.Peek().ToString() == "mod" || operators.Peek().ToString() == "m" || operators.Peek().ToString() == "p")) { if (strarr.Capacity > strarr.Count) { strarr.Add(operators.Pop()); } else { return(null); } } operators.Push(op); break; } case "+": //2 { while (operators.Count != 0 && (operators.Peek().ToString() == "*" || operators.Peek().ToString() == "/" || operators.Peek().ToString() == "mod" || operators.Peek().ToString() == "+" || operators.Peek().ToString() == "-" || operators.Peek().ToString() == "m" || operators.Peek().ToString() == "p")) { if (strarr.Capacity > strarr.Count) { strarr.Add(operators.Pop()); } else { return(null); } } operators.Push(op); break; } case "-": //2 { while (operators.Count != 0 && (operators.Peek().ToString() == "*" | operators.Peek().ToString() == "/" | operators.Peek().ToString() == "mod" | operators.Peek().ToString() == "+" | operators.Peek().ToString() == "-" | operators.Peek().ToString() == "m" | operators.Peek().ToString() == "p")) { if (strarr.Capacity > strarr.Count) { strarr.Add(operators.Pop()); } else { return(null); } } operators.Push(op); break; } case ")": { while (operators.Peek().ToString() != "(") { if (strarr.Capacity > strarr.Count) { strarr.Add(operators.Pop()); } else { return(null); } } operators.Pop(); break; } default: { //на входе - число - помещаем в выходной массив if (strarr.Capacity > strarr.Count) { strarr.Add(op); } else { return(null); } break; } } } //записываем все что осталовь в стеке в выходной массив while (operators.Count != 0) { strarr.Add(operators.Pop()); } return(strarr); }
/*******************************/ /// <summary> /// Adds an element to the top end of a Stack instance. /// </summary> /// <param name="stack">The Stack instance</param> /// <param name="element">The element to add</param> /// <returns>The element added</returns> public static System.Object StackPush(System.Collections.Stack stack, System.Object element) { stack.Push(element); return(element); }
protected virtual ICommand ProcessReceiveBuffer(Byte[] data, ref Byte[] remainder, int depth) { /// TODO seriously clean this code up, break it up into smaller methods. /// TODO seriously clean this code up, break it up into smaller methods. /// TODO seriously clean this code up, break it up into smaller methods. /// TODO seriously clean this code up, break it up into smaller methods. Boolean hasPrevBuffer = (remainder != null && remainder.Length > 0); Int32 lengthPrevBuffer = hasPrevBuffer ? remainder.Length : 0; // TODO should support streams instead of creating byte arrays. Int32 cutpos = Array.IndexOf <Byte> (data, ((byte)'\0')); if (cutpos >= 0) { // append the previous buffer to the new data buffer, only append to cutpos of data buffer // essentially, it will prefix data buf with remainder, and append the data buffer up to cutpos byte[] b = MergeBuffer(remainder, data, cutpos); Object serial = null; if (CommandStack.Count == depth) { serial = CommandStack.Pop(); } else { serial = BufferCodec.DetermineSerial(b, this.BufferEncoding); } // TODO determine if the command exists???? ICommand command = BufferCodec.ToCommand(serial, b, this.BufferEncoding); if (command == null) { // TODO should dump this into a file? depending on the size? Debug.WriteLine(String.Format( "Unable to parse command using {0}: ", BufferEncoding.GetString(b) )); } else { // attempt to invoke the appropriate handler, if it exists, otherwise // call the generic OnReceive handler. Usually event handlers exist when // the usage is a client and not a server endpoint, the AbstractServer // will most likely handle all the event handling rather the actual client socket. if (!AttemptReceiveEventHandler(this, command, this.OnReceivedInvokeAsynchronously)) { if (OnReceivedInvokeAsynchronously) { this.OnReceived.BeginInvoke( this, command, BeginInvokeOnReceivedCallback, null ); } else { this.OnReceived(this, command); } } } /// copy the data buffer remainder, so from cutpos onward to the remainder reference. /// however, first, recursively walk the array, searching for command splits \0 if (data.Length > cutpos) { int length = data.Length - cutpos - 1; remainder = new byte[length]; Buffer.BlockCopy(data, cutpos + 1, remainder, 0, length); return(ProcessReceiveBuffer( remainder, ref remainder, depth + 1 )); } else { remainder = null; } // TODO return command (use appropriate deserializer) return(default(ICommand)); } // only if the data is not the same reference as the remainder. // this usually happens when the data buffer is split and there // are remaining bytes in the data stream that need to be returned // and available for the next socket receive buffer (prepending) if (data != remainder) { remainder = MergeBuffer(remainder, data); } // if there is enough data to determine the command type. if (depth > CommandStack.Count) { Object commandId = BufferCodec.DetermineSerial( remainder, this.BufferEncoding ); if (commandId != null) { CommandStack.Push(commandId); } } return(default(ICommand)); }
static void Main(string[] args) { //https://msdn.microsoft.com/es-es/library/ybcx56wz(v=vs.110).aspx // Lista de strings. List <string> sieteMares = new List <string>(); // Agrego items de a uno sieteMares.Add("Golfo Pérsico"); sieteMares.Add("Negro"); sieteMares.Add("Caspio"); sieteMares.Add("Rojo"); sieteMares.Add("Mediterráneo"); sieteMares.Add("Adriático"); sieteMares.Add("de Arabia"); // Itero la lista y muestro los 7 mares Console.WriteLine("Los 7 mares:"); for (int i = 0; i < sieteMares.Count; i++) { Console.Write(sieteMares[i] + ", "); } // Freno y luego limpio la pantalla Console.ReadKey(); Console.Clear(); // Ordeno la Lista y vuelvo a mostrarla Console.WriteLine("Orden Ascendente"); sieteMares.Sort(); // Itero la lista y muestro los mares foreach (var mar in sieteMares) { Console.Write(mar + ", "); } Console.WriteLine(""); Console.WriteLine("Orden Descendente"); // Ordeno la Lista inversa y vuelvo a mostrarla sieteMares.Sort(Program.OrdenarDescendente); // Itero la lista y muestro los mares foreach (var mar in sieteMares) { Console.Write(mar + ", "); } // Freno y luego limpio la pantalla Console.ReadKey(); Console.Clear(); // Creo una lista, utilizando el inicializador de Colecciones. List <string> oceanos = new List <string> { "Ártico", "Antártico", "Pacífico", "Atlántico", "Índico" }; // Itero la lista y muestro los oceanos foreach (var oceano in oceanos) { Console.Write(oceano); Console.Write((oceanos.IndexOf(oceano) == oceanos.Count - 1) ? "." : ", "); // (condición) ? true : false } // Shorthand IF https://msdn.microsoft.com/es-ar/library/ty67wk28.aspx // Freno y luego limpio la pantalla Console.ReadKey(); Console.Clear(); // Quito el primer elemento que coincida oceanos.Remove("Antártico"); // Itero la lista y muestro los oceanos que quedaron foreach (var oceano in oceanos) { Console.WriteLine("{1} {0}", oceano, oceanos.IndexOf(oceano) + 1); } // Freno y luego limpio la pantalla Console.ReadKey(); Console.Clear(); // Quito el elemento en una posición especifica oceanos.RemoveAt(2); //Atlántico // Itero la lista y muestro los oceanos que quedaron foreach (var oceano in oceanos) { Console.Write("{0}, ", oceano); } // Freno y luego limpio la pantalla Console.ReadKey(); Console.Clear(); //---------------OTRAS COLECCIONES GENERICAS--------------------------- // Diccionario Dictionary <string, string> miDiccionario = new Dictionary <string, string>(); miDiccionario.Add("1ra", "Boca Juniors"); miDiccionario.Add("2da", "Boca Unidos"); miDiccionario.Add("3ra", "Boca Río Gallegos"); miDiccionario.Add("4ta", "Huracán San Rafael"); miDiccionario.Add("5ta", "Leandro N. Alem"); // Itero y muestro el Diccionario foreach (KeyValuePair <string, string> entrada in miDiccionario) { Console.WriteLine("{0}. {1}", entrada.Key, entrada.Value); } // Pregundo si contiene cierta Clave if (miDiccionario.ContainsKey("2da")) { Console.WriteLine("El Key '2da' es {0}", miDiccionario["2da"]); } // Quito un ítem miDiccionario.Remove("3ra"); // Modifico un ítem miDiccionario["2da"] = "Newcastle United"; // Itero y muestro las claves foreach (string entrada in miDiccionario.Keys) { Console.WriteLine("Claves: {0}", entrada); } // Itero y muestro los valores foreach (string entrada in miDiccionario.Values) { Console.WriteLine("Valor: {0}", entrada); } // Freno y luego limpio la pantalla Console.ReadKey(); Console.Clear(); // Cola Console.WriteLine("COLA"); Queue <Cliente> clientesCola = new Queue <Cliente>(); clientesCola.Enqueue(new Cliente("Jorge")); clientesCola.Enqueue(new Cliente("Alberto")); clientesCola.Enqueue(new Cliente("Luis")); clientesCola.Enqueue(new Cliente("María")); Random r = new Random(); while (clientesCola.Count > 0) { Console.WriteLine("Atender a: {0}. Quedan {1} cliente/s en espera.", clientesCola.Dequeue(), clientesCola.Count); // Demoro la iteración entre 1 y 3 segundos System.Threading.Thread.Sleep(r.Next(1000, 3000)); } Console.WriteLine(""); // Pila Console.WriteLine("PILA"); Stack <Cliente> clientesPila = new Stack <Cliente>(); clientesPila.Push(new Cliente("Jorge")); clientesPila.Push(new Cliente("Alberto")); clientesPila.Push(new Cliente("Luis")); clientesPila.Push(new Cliente("María")); while (clientesPila.Count > 0) { Console.WriteLine("Atender a: {0}. Quedan {1} cliente/s en espera.", clientesPila.Pop(), clientesPila.Count); // Demoro la iteración entre 1 y 3 segundos System.Threading.Thread.Sleep(r.Next(1000, 3000)); } // Freno y luego limpio la pantalla Console.ReadKey(); Console.Clear(); SortedList <int, Cliente> listaOrdenada = new SortedList <int, Cliente>(); listaOrdenada.Add(3, new Cliente("Miguel")); listaOrdenada.Add(2, new Cliente("Alejandra")); listaOrdenada.Add(8, new Cliente("Agostina")); listaOrdenada.Add(1, new Cliente("Valentino")); foreach (KeyValuePair <int, Cliente> entrada in listaOrdenada) { Console.WriteLine("{0}. {1}", entrada.Key, entrada.Value); } // Freno y luego limpio la pantalla Console.ReadKey(); Console.Clear(); Console.WriteLine("PILA NO GENÉRICA"); System.Collections.Stack clientesPilaGenerica = new System.Collections.Stack(); clientesPilaGenerica.Push(new Cliente("Jorge")); clientesPilaGenerica.Push(new Cliente("Alberto")); clientesPilaGenerica.Push(new Cliente("Luis")); clientesPilaGenerica.Push(new Cliente("María")); clientesPilaGenerica.Push(1); while (clientesPilaGenerica.Count > 0) { // Debo castear el contenido de la pila, ya que es del tipo Object Object obj = clientesPilaGenerica.Pop(); if (obj is Cliente) { Cliente c = (Cliente)obj; Console.WriteLine("Atender a: {0}. Quedan {1} cliente/s en espera.", c, clientesPilaGenerica.Count); } else { Console.WriteLine(obj); } } // Freno y luego limpio la pantalla Console.ReadKey(); Console.Clear(); }
public override void BeforeScanningStarts() { ulli.Push(this); }
protected void Push(INode node) { _nodeStack.Push(node); }
public override void Push(int i) { stack.Push(i); }
public static void MostrarColeccionesNoGenerics() { Console.Clear(); Console.WriteLine("******************************"); Console.WriteLine("*****Pilas No Genéricas*******"); Console.WriteLine("******************************"); Console.ReadLine(); //DECLARO E INSTANCIO UNA COLECCION DE TIPO LIFO System.Collections.Stack pila = new System.Collections.Stack(); pila.Push(1); pila.Push(2); pila.Push(3); pila.Push(4); Console.WriteLine("Agrego elementos a la pila..."); Console.WriteLine("Utilizo pila.Push()"); Console.WriteLine("Orden de los elementos: 1 - 2 - 3 - 4"); Console.ReadLine(); Console.WriteLine("Muestro el primer elemento de la pila..."); Console.WriteLine("Utilizo pila.Peek()"); Console.ReadLine(); Console.WriteLine(pila.Peek()); Console.ReadLine(); Console.WriteLine("Muestro todos los elementos de la pila..."); Console.WriteLine("Recorro con un foreach. No saco los elementos de la pila."); Console.ReadLine(); foreach (int elemento in pila) { Console.WriteLine(elemento); } Console.ReadLine(); Console.WriteLine("Desapilo todos los elementos de la pila..."); Console.WriteLine("Utilizo pila.Pop(). Recorro con un for"); Console.ReadLine(); int cantidad = pila.Count; for (int i = 0; i < cantidad; i++) { Console.WriteLine("Elemento {0} = {1}", i, pila.Pop()); } Console.ReadLine(); Console.WriteLine("Cantidad de elementos en la pila = {0}", pila.Count); Console.ReadLine(); Console.Clear(); Console.WriteLine("******************************"); Console.WriteLine("****Colas No Genéricas********"); Console.WriteLine("******************************"); Console.ReadLine(); System.Collections.Queue cola = new System.Collections.Queue(); cola.Enqueue(1); cola.Enqueue(2); cola.Enqueue(3); cola.Enqueue(4); Console.WriteLine("Agrego elementos a la cola..."); Console.WriteLine("Utilizo pila.Enqueue()"); Console.WriteLine("Orden de los elementos: 1 - 2 - 3 - 4"); Console.ReadLine(); Console.WriteLine("Muestro el primer elemento de la cola..."); Console.WriteLine("Utilizo cola.Peek()"); Console.ReadLine(); Console.WriteLine(cola.Peek()); Console.ReadLine(); Console.WriteLine("Muestro todos los elementos de la cola..."); Console.WriteLine("Recorro con un foreach"); Console.ReadLine(); foreach (int elemento in cola) { Console.WriteLine(elemento); } Console.ReadLine(); Console.WriteLine("Saco todos los elementos de la cola..."); Console.WriteLine("Utilizo cola.Dequeue(). Recorro con un for"); Console.ReadLine(); cantidad = cola.Count; for (int i = 0; i < cantidad; i++) { Console.WriteLine("Elemento {0} = {1}", i, cola.Dequeue()); } Console.ReadLine(); Console.WriteLine("Cantidad de elementos en la cola = {0}", cola.Count); Console.ReadLine(); Console.Clear(); Console.WriteLine("******************************"); Console.WriteLine("******Listas Dinamicas********"); Console.WriteLine("******************************"); Console.ReadLine(); System.Collections.ArrayList vec = new System.Collections.ArrayList(); vec.Add(1); vec.Add(4); vec.Add(3); vec.Add(2); Console.WriteLine("Agrego elementos al ArrayList..."); Console.WriteLine("Utilizo vec.Add()"); Console.WriteLine("Orden de los elementos: 1 - 4 - 3 - 2"); Console.ReadLine(); Console.WriteLine("Muestro todos los elementos del ArrayList..."); Console.WriteLine("Recorro con un foreach"); Console.ReadLine(); foreach (int elemento in vec) { Console.WriteLine(elemento); } Console.ReadLine(); Console.WriteLine("Ordeno los elementos del ArrayList..."); Console.WriteLine("Utilizo vec.Sort(). Recorro con un for"); Console.ReadLine(); vec.Sort(); cantidad = vec.Count; for (int i = 0; i < cantidad; i++) { Console.WriteLine("Elemento {0} = {1}", i, vec[i]); } Console.ReadLine(); Console.WriteLine("Ordeno los elementos del ArrayList..."); Console.WriteLine("Utilizo vec.Reverse(). Recorro con un for"); Console.ReadLine(); vec.Reverse(); cantidad = vec.Count; for (int i = 0; i < cantidad; i++) { Console.WriteLine("Elemento {0} = {1}", i, vec[i]); } Console.ReadLine(); Console.Clear(); Console.WriteLine("******************************"); Console.WriteLine("*********HashTable************"); Console.WriteLine("******************************"); Console.ReadLine(); System.Collections.Hashtable ht = new System.Collections.Hashtable(); ht.Add(1, "valor 1"); ht.Add(4, "valor 4"); ht.Add(3, "valor 3"); ht.Add(2, "valor 2"); Console.WriteLine("Agrego elementos al HashTable..."); Console.WriteLine("Utilizo vec.Add()"); Console.WriteLine("Orden de los elementos: 1 - 4 - 3 - 2"); Console.ReadLine(); Console.WriteLine("Muestro todos los elementos del HashTable..."); Console.WriteLine("Recorro con un for"); Console.ReadLine(); cantidad = ht.Count; for (int i = 1; i <= cantidad; i++) { Console.WriteLine("Elemento {0} = {1}", i, ht[i]); } Console.ReadLine(); }
/* * public void YY() * { * System.Collections.Stack s = new System.Collections.Stack(); * s.Push(0); * goto thamer; * * suite: * Console.Write('X'); * Console.Write('\n'); * return; * thamer: * Console.Write('S'); * Console.Write('\n'); * int i = (int)s.Pop(); * switch (i) { * case 0: goto suite; * } * } */ public void XX() { System.Collections.Stack s = new System.Collections.Stack(); s.Push(42); Console.Write((int)s.Pop()); }
/// <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); }
/// <summary> /// load rtf /// </summary> /// <param name="reader">RTF text reader</param> public void Load( RTFReader reader ) { myNodes.Clear(); System.Collections.Stack groups = new System.Collections.Stack(); RTFNodeGroup NewGroup = null ; RTFNode NewNode = null; while( reader.ReadToken() != null ) { if( reader.TokenType == RTFTokenType.GroupStart ) { // begin group if( NewGroup == null) { NewGroup = this ; } else { NewGroup = new RTFNodeGroup(); NewGroup.OwnerDocument = this ; } if( NewGroup != this ) { RTFNodeGroup g = ( RTFNodeGroup ) groups.Peek(); g.AppendChild( NewGroup ); } groups.Push( NewGroup ); } else if( reader.TokenType == RTFTokenType.GroupEnd ) { // end group NewGroup = ( RTFNodeGroup ) groups.Pop(); NewGroup.MergeText(); if (NewGroup.FirstNode is RTFNode) { switch (NewGroup.Keyword) { case RTFConsts._fonttbl: // read font table ReadFontTable(NewGroup); break; case RTFConsts._colortbl: // read color table ReadColorTable(NewGroup); break; case RTFConsts._info : // read document information ReadDocumentInfo(NewGroup); break; } } if (groups.Count > 0) { NewGroup = (RTFNodeGroup)groups.Peek(); } else { break; } //NewGroup.MergeText(); } else { // read content NewNode = new RTFNode( reader.CurrentToken ); NewNode.OwnerDocument = this ; NewGroup.AppendChild( NewNode ); if (NewNode.Keyword == RTFConsts._f ) { RTFFont font = this.FontTable[NewNode.Parameter]; if (font != null) { myFontChartset = font.Encoding; } else { myFontChartset = null; } //myFontChartset = RTFFont.GetRTFEncoding( NewNode.Parameter ); } else if (NewNode.Keyword == RTFConsts._af) { RTFFont font = this.FontTable[NewNode.Parameter]; if (font != null) { myAssociateFontChartset = font.Encoding; } else { myAssociateFontChartset = null; } } } }// while( reader.ReadToken() != null ) while( groups.Count > 0 ) { NewGroup = ( RTFNodeGroup ) groups.Pop(); NewGroup.MergeText(); } //this.UpdateInformation(); }
/// <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); }
/// <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(); }
static void Main(string[] args) { Console.WriteLine("******************************"); Console.WriteLine("**Generics vs. No Generics****"); Console.WriteLine("******************************"); Console.ReadLine(); Console.WriteLine("Creo una Pila no genérica."); Console.WriteLine("System.Collections.Stack pilaNoGenerica = new System.Collections.Stack();"); Console.ReadLine(); Console.Clear(); //DECLARO E INSTANCIO UNA PILA NO GENERICA System.Collections.Stack pilaNoGenerica = new System.Collections.Stack(); Console.WriteLine("Agrego valores a la pila de distintos tipos."); Console.ReadLine(); pilaNoGenerica.Push(3); pilaNoGenerica.Push("Valor de tipo String"); pilaNoGenerica.Push(new Personas.Persona("Alfredo", "Lopez", 22555999)); Console.WriteLine("Desapilo con el método Pop()."); Console.ReadLine(); int cant = pilaNoGenerica.Count; for (int i = 0; i < cant; i++) { Console.WriteLine("Elementos en la pila no genérica {0}", pilaNoGenerica.Pop()); } Console.ReadLine(); Console.Clear(); Console.WriteLine("Agrego valores a la pila de tipo 'Persona'."); Console.WriteLine("Pero me equivoco e ingreso un elemento de otro tipo..."); Console.ReadLine(); pilaNoGenerica.Push(new Personas.Persona("Brian", "Jimenez", 23000666)); pilaNoGenerica.Push("Valor de tipo String"); pilaNoGenerica.Push(new Personas.Persona("Alfredo", "Lopez", 22555999)); Console.WriteLine("Recorro con un for each y utilizo el método MostrarPersonas()."); Console.ReadLine(); foreach (Personas.Persona item in pilaNoGenerica) { item.MostrarPersona(); } Console.WriteLine("Se produce un error en tiempo de ejecución."); Console.ReadLine(); Console.Clear(); Console.WriteLine("Creo una Pila genérica."); Console.WriteLine("System.Collections.Generic.Stack<Personas.Persona> pilaGenerica"); Console.ReadLine(); //DECLARO UN PILA GENERICA DE TIPO PERSONA System.Collections.Generic.Stack <Personas.Persona> pilaGenerica; //INSTANCIO LA PILA GENERICA DE TIPO PERSONA pilaGenerica = new System.Collections.Generic.Stack <Personas.Persona>(); Console.WriteLine("Agrego valores a la pila de tipo 'Persona'."); Console.WriteLine("Pero me equivoco e ingreso un elemento de otro tipo..."); Console.ReadLine(); pilaGenerica.Push(new Personas.Persona("Adrian", "Gonzalez", 32885410)); //pilaGenerica.Push("Adrian Gonzalez"); pilaGenerica.Push(new Personas.Persona("Marta", "Lopez", 18542330)); Console.WriteLine("Se produce un error en tiempo de compilación."); Console.ReadLine(); Console.Clear(); Console.WriteLine("Recorro con un for each y utilizo el método MostrarPersonas()."); Console.ReadLine(); foreach (Personas.Persona item in pilaGenerica) { item.MostrarPersona(); } Console.ReadLine(); }
/// <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; }
///<summary>将当前程序域压到堆栈备用。push和pop适用于保存域信息,当返回上级界面时可pop恢复上级域提示信息</summary> public void push() { stack.Push(curDomain); }
/// <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; } }
public void PushContext(FAMIX.Entity context) { stack.Push(context); }
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 }
public virtual void push(TokenStream stream) { streamStack.Push(input); // save current stream select(stream); }
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; }
public static void MostrarColeccionesNoGenerics() { Console.Clear(); Console.WriteLine("******************************"); Console.WriteLine("*****Pilas No Genéricas*******"); Console.WriteLine("******************************"); Console.ReadLine(); //DECLARO E INSTANCIO UNA COLECCION DE TIPO LIFO System.Collections.Stack pila = new System.Collections.Stack(); pila.Push(1); pila.Push(2); pila.Push(3); pila.Push(4); Console.WriteLine("Agrego elementos a la pila..."); Console.WriteLine("Utilizo pila.Push()"); Console.WriteLine("Orden de los elementos: 1 - 2 - 3 - 4"); Console.ReadLine(); Console.WriteLine("Muestro el primer elemento de la pila..."); Console.WriteLine("Utilizo pila.Peek()"); Console.ReadLine(); Console.WriteLine(pila.Peek()); Console.ReadLine(); Console.WriteLine("Muestro todos los elementos de la pila..."); Console.WriteLine("Recorro con un foreach. No saco los elementos de la pila."); Console.ReadLine(); foreach (int elemento in pila) { Console.WriteLine(elemento); } Console.ReadLine(); Console.WriteLine("Desapilo todos los elementos de la pila..."); Console.WriteLine("Utilizo pila.Pop(). Recorro con un for"); Console.ReadLine(); int cantidad = pila.Count; for (int i = 0; i < cantidad; i++) { Console.WriteLine("Elemento {0} = {1}", i, pila.Pop()); } Console.ReadLine(); Console.WriteLine("Cantidad de elementos en la pila = {0}", pila.Count); Console.ReadLine(); Console.Clear(); Console.WriteLine("******************************"); Console.WriteLine("****Colas No Genéricas********"); Console.WriteLine("******************************"); Console.ReadLine(); System.Collections.Queue cola = new System.Collections.Queue(); cola.Enqueue(1); cola.Enqueue(2); cola.Enqueue(3); cola.Enqueue(4); Console.WriteLine("Agrego elementos a la cola..."); Console.WriteLine("Utilizo pila.Enqueue()"); Console.WriteLine("Orden de los elementos: 1 - 2 - 3 - 4"); Console.ReadLine(); Console.WriteLine("Muestro el primer elemento de la cola..."); Console.WriteLine("Utilizo cola.Peek()"); Console.ReadLine(); Console.WriteLine(cola.Peek()); Console.ReadLine(); Console.WriteLine("Muestro todos los elementos de la cola..."); Console.WriteLine("Recorro con un foreach"); Console.ReadLine(); foreach (int elemento in cola) { Console.WriteLine(elemento); } Console.ReadLine(); Console.WriteLine("Saco todos los elementos de la cola..."); Console.WriteLine("Utilizo cola.Dequeue(). Recorro con un for"); Console.ReadLine(); cantidad = cola.Count; for (int i = 0; i < cantidad; i++) { Console.WriteLine("Elemento {0} = {1}", i, cola.Dequeue()); } Console.ReadLine(); Console.WriteLine("Cantidad de elementos en la cola = {0}", cola.Count); Console.ReadLine(); Console.Clear(); Console.WriteLine("******************************"); Console.WriteLine("******Listas Dinamicas********"); Console.WriteLine("******************************"); Console.ReadLine(); System.Collections.ArrayList vec = new System.Collections.ArrayList(); vec.Add(1); vec.Add(4); vec.Add(3); vec.Add(2); Console.WriteLine("Agrego elementos al ArrayList..."); Console.WriteLine("Utilizo vec.Add()"); Console.WriteLine("Orden de los elementos: 1 - 4 - 3 - 2"); Console.ReadLine(); Console.WriteLine("Muestro todos los elementos del ArrayList..."); Console.WriteLine("Recorro con un foreach"); Console.ReadLine(); foreach (int elemento in vec) { Console.WriteLine(elemento); } Console.ReadLine(); Console.WriteLine("Ordeno los elementos del ArrayList..."); Console.WriteLine("Utilizo vec.Sort(). Recorro con un for"); Console.ReadLine(); vec.Sort(); cantidad = vec.Count; for (int i = 0; i < cantidad; i++) { Console.WriteLine("Elemento {0} = {1}", i, vec[i]); } Console.ReadLine(); Console.WriteLine("Ordeno los elementos del ArrayList..."); Console.WriteLine("Utilizo vec.Reverse(). Recorro con un for"); Console.ReadLine(); vec.Reverse(); cantidad = vec.Count; for (int i = 0; i < cantidad; i++) { Console.WriteLine("Elemento {0} = {1}", i, vec[i]); } Console.ReadLine(); Console.Clear(); Console.WriteLine("******************************"); Console.WriteLine("*********HashTable************"); Console.WriteLine("******************************"); Console.ReadLine(); System.Collections.Hashtable ht = new System.Collections.Hashtable(); ht.Add(1, "valor 1"); ht.Add(4, "valor 4"); ht.Add(3, "valor 3"); ht.Add(2, "valor 2"); Console.WriteLine("Agrego elementos al HashTable..."); Console.WriteLine("Utilizo vec.Add()"); Console.WriteLine("Orden de los elementos: 1 - 4 - 3 - 2"); Console.ReadLine(); Console.WriteLine("Muestro todos los elementos del HashTable..."); Console.WriteLine("Recorro con un for"); Console.ReadLine(); cantidad = ht.Count; for (int i = 1; i <= cantidad; i++) { Console.WriteLine("Elemento {0} = {1}", i, ht[i]); } Console.ReadLine(); }
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); } } }
/// <summary> /// 过滤除特定标签和标签中的style /// 去除非DIV BR P A Table 等之外的标签,并自动填补这些标签的配对 /// 2009-5 By 宋光明 /// </summary> /// <param name="strHtml"></param> /// <returns></returns> public static string StripHtmlExceptTags(string strHtml, string[] keepTags) { #region Delete by 2009 11 17 //string exceptHtmlTags //if (string.IsNullOrEmpty(strHtml)) return strHtml; //string exceptTag = @"p|\/p|table|\/table|tr|\/tr|td|\/td|a|\/a|br"; //string exceptTags = @"p|table|tr|td|a|br"; //if (!string.IsNullOrEmpty(exceptHtmlTags)) //{ // string[] tags = exceptTags.Split('|'); // exceptTag = ""; // foreach(string etag in tags) // { // exceptTags += etag; // exceptTags += @"|\/"; // exceptTags += etag; // exceptTags += "|"; // } // exceptTag = exceptTags.Substring(0, exceptTags.Length - 1); // exceptTags = exceptHtmlTags; //} #endregion string expString = ""; string backString = ""; foreach (var aTag in keepTags) { var theTag = aTag.ToLower(); if (theTag != "br") { if (backString != "") { backString += "|"; } expString += theTag + @"|\/" + theTag + "|"; backString += theTag; } } //过滤脚本及其内容 System.Text.RegularExpressions.Regex regexScript = new System.Text.RegularExpressions.Regex(@"<[\s]*?script[^>]*?>[\s\S]*?<[\s]*?\/[\s]*?script[\s]*?>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); //过滤CSS样式及其内容 System.Text.RegularExpressions.Regex regexStyle = new System.Text.RegularExpressions.Regex(@"<[\s]*?style[^>]*?>[\s\S]*?<[\s]*?\/[\s]*?style[\s]*?>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); //过滤除指定标签外的<>内的内容 //System.Text.RegularExpressions.Regex regexExceptTag = new System.Text.RegularExpressions.Regex(@"<(?!" + exceptTag + @")[^>]*>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); // back System.Text.RegularExpressions.Regex regexExceptTag = new System.Text.RegularExpressions.Regex(@"<(?!p|\/p|table|\/table|tr|\/tr|td|\/td|a|\/a|br|div|\/div)[^>]*>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regexExceptTag = new System.Text.RegularExpressions.Regex(@"<(?!" + expString + "br)[^>]*>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); //查找现有的标签 System.Text.RegularExpressions.Regex regexTag = new System.Text.RegularExpressions.Regex(@"<[^>]*>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); //查找Style样式 System.Text.RegularExpressions.Regex regexTagStyle = new System.Text.RegularExpressions.Regex(@"style=['|""][^>]*?['|""]", System.Text.RegularExpressions.RegexOptions.IgnoreCase); strHtml = regexScript.Replace(strHtml, ""); strHtml = regexStyle.Replace(strHtml, ""); strHtml = regexExceptTag.Replace(strHtml, ""); MatchCollection matchs = regexTag.Matches(strHtml); StringBuilder retstr = new StringBuilder(); System.Collections.Stack myStack = new System.Collections.Stack(); int begindex = 0; //System.Text.RegularExpressions.Regex regexETagBegin = new System.Text.RegularExpressions.Regex(@"<("+exceptTags+")", System.Text.RegularExpressions.RegexOptions.IgnoreCase); //@"<(p|table|tr|td|a|br|div)" System.Text.RegularExpressions.Regex regexETagBegin = new System.Text.RegularExpressions.Regex(@"<(" + backString + (string.IsNullOrEmpty(backString) ? "" : "|") + "br)", System.Text.RegularExpressions.RegexOptions.IgnoreCase); //System.Text.RegularExpressions.Regex regexETagEnd = new System.Text.RegularExpressions.Regex(@"</(" + exceptTags + ")", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regexETagEnd = new System.Text.RegularExpressions.Regex(@"</(" + backString + ")", System.Text.RegularExpressions.RegexOptions.IgnoreCase); foreach (Match match in matchs) { bool writetag = true; string tmptag = regexTagStyle.Replace(match.Value, ""); if (regexETagBegin.Match(tmptag).Success) { string tagname = regexETagBegin.Match(tmptag).Groups[1].Value.ToLower(); if (tagname.Length != 0 && tmptag.Substring(tmptag.Length - 2, 1) != "/" && tagname != "br") { myStack.Push(tagname); } } else { string tagname = regexETagEnd.Match(tmptag).Groups[1].Value.ToLower(); if (myStack.Count > 0) { while (myStack.Peek().ToString() != tagname) { string popstack = myStack.Pop().ToString(); retstr.Append("</" + popstack + " >"); if (myStack.Count == 0) { break; } } if (myStack.Count > 0) { myStack.Pop(); } else { writetag = false; } } else { writetag = false; } } int matchbegin = match.Index; if (matchbegin > begindex) { retstr.Append(strHtml.Substring(begindex, matchbegin - begindex)); } begindex = matchbegin + match.Length; if (writetag) { retstr.Append(regexTagStyle.Replace(match.Value, "")); } } if (begindex < strHtml.Length) { retstr.Append(strHtml.Substring(begindex)); } while (myStack.Count > 0) { string tagname = myStack.Pop().ToString(); retstr.Append("</" + tagname + " >"); } return(retstr.ToString()); }