Dequeue() public method

public Dequeue ( ) : Object
return Object
示例#1
1
        private static IEnumerable<Type> getTypes(Type sourceType)
        {
            Queue<Type> pending = new Queue<Type>();
            HashSet<Type> visited = new HashSet<Type>();
            pending.Enqueue(sourceType);

            while (pending.Count != 0)
            {
                Type type = pending.Dequeue();
                visited.Add(type);
                yield return type;

                if (type.BaseType != null)
                {
                    if (!visited.Contains(type.BaseType))
                    {
                        pending.Enqueue(type.BaseType);
                    }
                }

                foreach (Type interfaceType in type.GetInterfaces())
                {
                    if (!visited.Contains(interfaceType))
                    {
                        pending.Enqueue(interfaceType);
                    }
                }
            }
        }
示例#2
1
        private static void FillQueue(int firstX, int firstY, byte currColor, byte destColor)
        {
            Queue<Tuple<int, int>> q = new Queue<Tuple<int, int>>();
            q.Enqueue(Tuple.Create(firstX, firstY));

            var maxX = _data.GetLength(0);
                var maxY = _data.GetLength(1);
            while (q.Count > 0)
            {
                var point = q.Dequeue();
                var x = point.Item1;
                var y = point.Item2;

                if (_data[x, y] == destColor)
                    continue;
                if (_data[x, y] != currColor)
                    continue;

                _data[x, y] = destColor;

                if (x + 1 < maxX)
                    q.Enqueue(Tuple.Create(x + 1, y));
                if (x - 1 >= 0)
                    q.Enqueue(Tuple.Create(x - 1, y));

                if (y + 1 < maxY)
                    q.Enqueue(Tuple.Create(x, y + 1));
                if (y - 1 >= 0)
                    q.Enqueue(Tuple.Create(x, y - 1));

                Display(_data);
            }
        }
        public IEnumerator Start()
        {
            pool = new InventoryPool<InventoryUIItemWrapper>(wrapperPrefab, 8);
            queue = new Queue<ItemHolder>(8);
            destroyTimer = new WaitForSeconds(slideAnimation.length - 0.025f);
            offsetTimer = new WaitForSeconds(offsetTimerSeconds);

            foreach (var inv in InventoryManager.GetLootToCollections())
            {
                inv.OnAddedItem += (items, amount, cameFromCollection) =>
                {
                    if (cameFromCollection == false)
                    {
                        queue.Enqueue(new ItemHolder() { item = items.FirstOrDefault(), stackSize = amount});
                    }
                };
            }

            while (true)
            {
                if (queue.Count > 0)
                {
                    ShowItem(queue.Peek().item, queue.Peek().stackSize);
                    queue.Dequeue(); // Remove it
                }

                yield return offsetTimer;
            }
        }
		static void Run (Queue q)
		{
			MergeContext context = GetDefaultContext ();
			while (q.Count > 0) {
				string token = (string) q.Dequeue ();

				if (token.Length < 2)
					Usage ();

				if (token [0] == '-' && token [1] == '-') {
					if (token.Length < 3)
						Usage ();

					switch (token [2]) {
					case 'v':
						Version ();
						break;
					case 'a':
						About ();
						break;
					default:
						Usage ();
						break;
					}
				}

				if (token [0] == '-' || token [0] == '/') {
					token = token.Substring (1);

					if (token == "o" || token == "out")
						context.OutputPath = (string) q.Dequeue ();
					else if (token == "e" || token == "exe")
						context.OutputIsExecutable = true;
					else if (token == "d" || token == "dll")
						context.OutputIsExecutable = false;
					else if (token == "L")
						context.NativeLibraries.LibrariesSearchPaths.Add ((string) q.Dequeue ());
					else if (token == "l")
						context.NativeLibraries.Libraries.Add ((string) q.Dequeue ());
					else
						Usage ();
				} else {
					context.Assemblies.Add (token);
					while (q.Count > 0)
						context.Assemblies.Add ((string) q.Dequeue ());
				}
			}

			if (context.Assemblies.Count < 2)
				Error ("At least two assemblies needed");

			if (context.OutputPath == "")
				Error ("Please set output filename");

			context.NativeLibraries.Libraries.Add ("c");
			context.NativeLibraries.LibrariesSearchPaths.Add ("/lib");
			context.NativeLibraries.Initialize ();

			context.Link ();
		}
示例#5
1
        private static void Main()
        {
            string inputSentence = SampleSentence;
            string splitPattern = @"(\s+|\s*\,\s*|\s*\-\s*|\s*\!|\s*\.)";
            string[] elements = Regex.Split(inputSentence, splitPattern);

            Stack words = new Stack();
            Queue separators = new Queue();
            StringBuilder result = new StringBuilder();

            foreach (var element in elements)
            {
                if (Regex.IsMatch(element, splitPattern))
                {
                    separators.Enqueue(element);
                }
                else if (Regex.IsMatch(element, @"\S"))
                {
                    words.Push(element);
                }
            }

            while (words.Count > 0)
            {
                result.Append(words.Pop());
                result.Append(separators.Dequeue());
            }

            Console.WriteLine(result);
        }
        private void QueueTest()
        {
            Queue queue = new Queue();
             queue.Enqueue( CAR_BANK[0] );
             queue.Enqueue( CAR_BANK[1] );
             queue.Enqueue( CAR_BANK[2] );

             ((Car)queue.Peek()).Display();
             DeQueued( (Car)queue.Dequeue() );

             ((Car)queue.Peek()).Display();
             DeQueued( (Car)queue.Dequeue() );

             ((Car)queue.Peek()).Display();
             DeQueued( (Car)queue.Dequeue() );

             try
             {
            ((Car)queue.Peek()).Display();
            DeQueued( (Car)queue.Dequeue() );
             }
             catch (Exception e)
             {
            Console.WriteLine( "Error!:{0}", e.Message );
             }
        }
        public override bool Handle(object input, Queue<string> tokens)
        {
            var elementType = _property.PropertyType.GetGenericArguments().First();
            var list = typeof(List<>).CloseAndBuildAs<IList>(elementType);

            var wasHandled = false;

            var flag = "";
            if (tokens.NextIsFlagFor(_property))
            {
                flag = tokens.Dequeue();
                while (tokens.Count > 0 && !tokens.NextIsFlag())
                {
                    var value = _converter.FromString(tokens.Dequeue(), elementType);
                    list.Add(value);

                    wasHandled = true;
                }

                if(!wasHandled)
                {
                    throw new InvalidUsageException("No values specified for flag {0}.".ToFormat(flag));
                }

                _property.SetValue(input, list, null);
            }

            return wasHandled;
        }
示例#8
0
        static void Main(string[] args)
        {
            //ArrayList
            ArrayList arrayList = new ArrayList();
            arrayList.Add("First item");
            arrayList.Add(5);
            arrayList.Add('c');

            foreach (var item in arrayList) {
                Console.WriteLine("Element of arrayList: {0}", item);
            }

            //HashTable
            Hashtable hashtable = new Hashtable();
            hashtable.Add(0, "Zero item");
            hashtable[1] = "First item";
            hashtable["2"] = "Second item";
            hashtable[Guid.NewGuid()] = "Third item";

            ICollection keys = hashtable.Keys;
            foreach (var key in keys)
            {
                Console.WriteLine("Key: {0}, Value: {1}", key, hashtable[key]);
            }

            //SortedList
            SortedList sl = new SortedList();

            sl.Add("007", "Ritesh Saikia");
            sl.Add("001", "Zara Ali");
            sl.Add("002", "Abida Rehman");
            sl.Add("003", "Joe Holzner");
            sl.Add("004", "Mausam Benazir Nur");
            sl.Add("006", "M. Amlan");
            sl.Add("005", "M. Arif");

            ICollection slValues = sl.Values;
            foreach (var s in slValues) {
                Console.WriteLine("SortedList value: {0}", s);
            }
             //Queue is FIFO: First in First out
            Queue que = new Queue();
            que.Enqueue("Student_1");
            que.Enqueue(5);
            que.Enqueue("Student_2");
            que.Enqueue("Student_3");

            Console.WriteLine(que.Dequeue().ToString());
            Console.WriteLine(que.Dequeue().ToString());

            // Stack is FILO: First in Last out
            Stack StackPop = new Stack();
            StackPop.Push("Student_1");
            StackPop.Push("Student_2");
            StackPop.Push("Student_3");
            Console.WriteLine(StackPop.Pop().ToString());
            Console.WriteLine(StackPop.Pop().ToString());

            Console.ReadLine();
        }
示例#9
0
文件: p2.cs 项目: karunasagark/ps
        // times out for large values of x and y, since it is essentially scanning all the points on the coordinate space
        public int getDirections(int x, int y)
        {
            int curx, cury, dist;
            curx = cury = dist = 0;

            Queue q = new Queue();
            q.Enqueue(0); q.Enqueue(0); q.Enqueue(0);

            while (q.Count != 0)
            {
                curx = (int)q.Dequeue();
                cury = (int)q.Dequeue();
                dist = (int)q.Dequeue();

                if (curx == x && cury == y)
                {
                    return dist;
                }

                // -ve % 2 can result in -ve
                // -ve % 2 won't be -ve when remainder is zero
                // so checking for zero is safer
                int dy = ((curx+2) % 2 == 0) ? 1 : -1;
                int dx = ((cury+2) % 2 == 0) ? 1 : -1;

                q.Enqueue(curx); q.Enqueue(cury + dy); q.Enqueue(dist + 1);
                q.Enqueue(curx + dx); q.Enqueue(cury); q.Enqueue(dist + 1);
            }

            // path not found
            return -1;
        }
示例#10
0
        static void Mai(string[] args)
        {
            //4 algoritmos para almacenar informacion.
                //1.Colas (FIFO)
                //2.Pilas (LIFO)
                //3.Listas (Array dinamico, se accede a su informacion por el indice)
                //4.Diccionarios ()
                //5.Set()

            //Cola

            Queue q=new Queue();
            q.Enqueue("A");
            q.Enqueue(new Persona());//Enqueue para meter datos

            Console.WriteLine(q.Dequeue());//El dequeue para sacar datos
            Console.WriteLine(q.Dequeue());

            ArrayList l=new ArrayList();

            l.Add(new Persona());
            l.Add(new Persona());
            l.Add(new Persona());
            l.Add(new Persona());
            l.Add("Pepo");
            l.Add(23);
            l.Add(new Persona());
            l.Add(new Persona());
            Console.WriteLine(l[4]);

            Console.ReadLine();
        }
 public override bool Load(Queue<Token> tokens, Type tokenizerType,TemplateGroup group)
 {
     Token t = tokens.Dequeue();
     Match m;
     if (regAlternateFormat.IsMatch(t.Content))
     {
         m = regAlternateFormat.Match(t.Content);
         _variableName = m.Groups[1].Value;
         _entryName = m.Groups[2].Value;
         string tmp = t.Content.Substring(t.Content.IndexOf("|", m.Groups[2].Index) + 1);
         tmp = tmp.Substring(0, tmp.Length - 1);
         Tokenizer tok = (Tokenizer)tokenizerType.GetConstructor(new Type[] { typeof(string) }).Invoke(new object[] { tmp});
         _children = tok.TokenizeStream(group);
     }
     else
     {
         m = regVariableExtractor.Match(t.Content);
         _entryName = m.Groups[1].Value;
         _variableName = m.Groups[2].Value;
         if (regVarValueExtracor.IsMatch(_entryName))
             _entryName = regVarValueExtracor.Match(_entryName).Groups[2].Value;
         if (regListValueExtracor.IsMatch(_variableName))
             _variableName = regListValueExtracor.Match(_variableName).Groups[2].Value;
         while ((tokens.Count>0)&&!regEndFor.IsMatch(tokens.Peek().Content))
             _children.Add(ComponentExtractor.ExtractComponent(tokens, tokenizerType, group));
         if (tokens.Count > 0)
             tokens.Dequeue();
     }
     _entryName = _entryName.Trim();
     _variableName = _variableName.Trim();
     return true;
 }
示例#12
0
        static void Mai(string[] args)
        {
            //Cola.
            Queue q = new Queue();
            q.Enqueue("A");
            q.Enqueue(new Persona());

            Console.WriteLine(q.Dequeue());
            Console.WriteLine(q.Dequeue());

            //Es lo mas parecido a un array dinamico
            ArrayList p = new ArrayList();
            p.Add(new Persona());
            p.Add(new Persona());
            p.Add("Pepe");
            p.Add(new Persona());
            p.Add(new Persona());
            p.Add("");
            p.Add(new Persona());

            Console.WriteLine(p[2]);
            Console.ReadLine();

            //Diccionario. Estructura de datos que se almacena con claves.
            //Para usarlo llamaremos directamente a la clave.
        }
示例#13
0
		public void Write(string message) {
			string[] splitted = message.Split(new string[] {"\n"}, StringSplitOptions.None);
			Queue<string> queue = new Queue<string>(splitted);
			string first = queue.Dequeue();
			while (queue.Count > 0) {
				Strings.Add(new LineInfo(queue.Dequeue()));
			}
		}
示例#14
0
 public void TestQueue()
 {
     System.Collections.Queue target = new System.Collections.Queue();
     CollectionUtils.AddAll(target, new object[] { 4, "5", '6' });
     Assert.AreEqual(4, target.Dequeue());
     Assert.AreEqual("5", target.Dequeue());
     Assert.AreEqual('6', target.Dequeue());
 }
        public static void Main(string[] args)
        {
            var q1 = new System.Collections.Queue();

            q1.Enqueue(1);
            q1.Enqueue(2);
            q1.Enqueue(3);

            Console.WriteLine(q1.Dequeue() + "");
            Console.WriteLine(q1.Dequeue() + "");
            Console.WriteLine(q1.Dequeue());
        }
示例#16
0
 public static Bitmap ByteArrayToBitmap(byte[] rgbComponents, int width, int hight)
 {
     Queue<byte> rgbComponentQueue = new Queue<byte>(rgbComponents);
     Bitmap bitmap = new Bitmap(width, hight);
     for (int y = 0; y < hight; y++)
     {
         for (int x = 0; x < width; x++)
         {
             bitmap.SetPixel(x, y, Color.FromArgb(rgbComponentQueue.Dequeue(), rgbComponentQueue.Dequeue(), rgbComponentQueue.Dequeue()));
         }
     }
     return bitmap;
 }
示例#17
0
        static void Mai(string[] args)
        {
            /*En una coleccción se accede a sus elementos a traves de su indice,
            de la misma forma que sucede en un Array*/

            /*Tipos de colecciones: es "el que" queremos guardar*/
            /*Algoritmos de alamacenaje: es "como" lo queremos guardar*/

            /*Existen distintos algoritmos para almacenar y recuperar los objetos*/

            /*4 formas de gestion de información
            - Colas: no se accede deirectamente a la información FIFO. Ventajas, utiliza pocos
                     recursos de memoria, es facil y rapida de utilizar.

            - Pilas: funciona del mismo modo que una cola, pero la ultima información que introduce
                     es la primera que sale. LIFO last In first Out.

            - Listas: Es lo más similar a un Array. Es un array dinamico. Se accede a los elementos
                      por su indice. Un array de objetos es mucho más dinamico que uno convencional.

            - Diccionarios: es una estructura de datos que a cada objeto que almacena contiene s
                            propia clave.Ej. DNI.

            - Set: no se almacena el orden. Solo almacena la información. Sirve para guardar gran
                   cantidad en memoria de forma rapida y eficiente.
            */

            ArrayList l = new ArrayList();
            l.Add(new Persona());
            l.Add(new Persona());
            l.Add("Pepo");
            l.Add(new Persona());
            l.Add(new Persona());
            l.Add(23);
            l.Add(new Persona());

            Console.WriteLine(l[2]);

            /*Colas(Queue): FIFO first In first Out, se recupera la información en el mismo orden en el que se ha introducido*/

            Queue q = new Queue();
            q.Enqueue("A");
            q.Enqueue(new Persona());

            Console.WriteLine(q.Dequeue()); //recupera el primer objeto
            Console.WriteLine(q.Dequeue()); //recupero el segundo objeto

            Console.ReadLine();
        }
示例#18
0
        public static void Main()
        {
            const int multiplier = 2;
            const int firstAddend = 1;
            const int secondAddend = 2;

            int sequenceLength = 50;
            int currentNumber = int.Parse(Console.ReadLine());

            var sequence = new Queue<int>();
            var tempQueue = new Queue<int>();
            sequence.Enqueue(currentNumber);
            tempQueue.Enqueue(currentNumber);

            while (sequence.Count < sequenceLength)
            {
                currentNumber = tempQueue.Dequeue();

                sequence.Enqueue(currentNumber + firstAddend);
                sequence.Enqueue(multiplier * currentNumber + firstAddend);
                sequence.Enqueue(currentNumber + secondAddend);

                tempQueue.Enqueue(currentNumber + firstAddend);
                tempQueue.Enqueue(multiplier * currentNumber + firstAddend);
                tempQueue.Enqueue(currentNumber + secondAddend);
            }

            while (sequenceLength > 0)
            {
                Console.Write(sequence.Dequeue() + " ");
                sequenceLength--;
            }
        }
示例#19
0
    public static void ClearNoTouchZero(Dictionary <int, System.Collections.Queue> dic, Dictionary <int, PoolFlag_t> dicTouchZero)
    {
        if (dic != null)
        {
            if (dic.Count > 1)
            {
                foreach (KeyValuePair <int, System.Collections.Queue> data in dic)
                {
                    PoolFlag_t t_TouchZero = new PoolFlag_t();
                    t_TouchZero.Clear();
                    dicTouchZero.TryGetValue(data.Key, out t_TouchZero);
                    int cnt    = 0;
                    int delcnt = t_TouchZero.CanDel();
                    if (delcnt > 0)
                    {
                        System.Collections.Queue q = data.Value;
                        cnt = q.Count;
                        if (cnt > 1)
                        {
                            //清三分之一
                            for (int i = 0; i < delcnt; i++)
                            {
                                System.Object obj = q.Dequeue();
                                obj = null;
                            }
                        }
                    }
                    t_TouchZero.InPool -= delcnt;
                    t_TouchZero.total  -= delcnt;

                    dicTouchZero[data.Key] = t_TouchZero;
                }
            }
        }
    }
        /// <summary>
        /// returns true if path exists from startVertex to endVertex
        /// </summary>
        private bool breadthFirstSearch(object startVertex, object endVertex)
        {
            var queue = new Queue();
            var vertexQueue = new Queue();
            bool found = false;

            graph.clearMarks();
            queue.Enqueue(startVertex);

            do
            {
                object vertex = queue.Dequeue();

                if (vertex == endVertex)
                    found = true;
                else
                {
                    if (!graph.isMarked(vertex))
                    {
                        graph.markVertex(vertex);
                        vertexQueue = graph.getToVertices(vertex);

                        while (vertexQueue.Count > 0)
                        {
                            object item = vertexQueue.Dequeue();
                            if (!graph.isMarked(item))
                                queue.Enqueue(item);
                        }
                    }
                }
            } while (queue.Count > 0 & !found);

            return found;
        }
        /// <summary>
        /// returns true if path exists from startVertex to endVertex
        /// </summary>
        private bool depthFirstSearch(object startVertex, object endVertex)
        {
            var stack = new Stack();
            var vertextQueue = new Queue();
            bool found = false;

            graph.clearMarks();
            stack.Push(startVertex);
            do
            {
                object vertex = stack.Pop();

                if (vertex == endVertex) // general case when path is found
                    found = true;
                else
                {
                    if (!graph.isMarked(vertex)) // if not marked
                    {
                        graph.markVertex(vertex); // then mark that vertex
                        vertextQueue = graph.getToVertices(vertex); //get all adjecent vertexes

                        while (vertextQueue.Count > 0) // then for each of those adjecent vertexes
                        {
                            object item = vertextQueue.Dequeue();

                            if (!graph.isMarked(item))
                                stack.Push(item);
                        }
                    }
                }
            } while (stack.Count > 0 && !found);

            return found;
        }
示例#22
0
 public static string FromHashtableQueue(Queue<Hashtable> queue)
 {
     StringWriter textWriter = new StringWriter();
     JsonWriter jsonWriter = new JsonWriter(textWriter);
     jsonWriter.WriteStartArray();
     JsonSerializer serializer = new JsonSerializer();
     UUIDConverter UUID = new UUIDConverter();
     serializer.Converters.Add(UUID);
     while (queue.Count > 0)
     {
         try
         {
             Hashtable hashtable = queue.Dequeue();
             serializer.Serialize(jsonWriter, hashtable);
         }
         catch(Exception e)
         {
             AjaxLife.Debug("MakeJson.FromHashTable", e.Message);
         }
     }
     jsonWriter.WriteEndArray();
     jsonWriter.Flush();
     string text = textWriter.ToString();
     jsonWriter.Close();
     textWriter.Dispose();
     return text;
 }
示例#23
0
        public void BFS(VNode v)
        {
            /*使用队列来实现广度优先搜索

            */
            Queue<VNode> q = new Queue<VNode>();
            v.Visited = true;
            q.Enqueue(v);
            Console.WriteLine("Visit:{0}", v.Data);
            while (q.Count > 0)
            {
                var vnode = q.Dequeue();
                var enode = vnode.FirstEdge;
                while (null != enode)
                {
                    if (!enode.Adj.Visited)
                    {
                        enode.Adj.Visited = true;
                        Console.WriteLine("Visit:{0}", enode.Adj.Data);
                        q.Enqueue(enode.Adj);
                    }
                    enode = enode.Next;
                }
            }
        }
 private static Activity GetActivity(Activity containerActivity, string id)
 {
     if (containerActivity != null)
     {
         Queue queue = new Queue();
         queue.Enqueue(containerActivity);
         while (queue.Count > 0)
         {
             Activity activity = (Activity) queue.Dequeue();
             if (activity.Enabled)
             {
                 if (activity.QualifiedName == id)
                 {
                     return activity;
                 }
                 if (activity is CompositeActivity)
                 {
                     foreach (Activity activity2 in ((CompositeActivity) activity).Activities)
                     {
                         queue.Enqueue(activity2);
                     }
                 }
             }
         }
     }
     return null;
 }
示例#25
0
        public IList BreadthFirstSearch(BatteryStation s)
        {
            UnmarkAll();

            IList l = new ArrayList();
            Queue<BatteryStation> q = new Queue<BatteryStation>();

            q.Enqueue(s);
            l.Add(s);
            s.Mark = true;

            while (q.Count > 0)
            {
                BatteryStation n = q.Dequeue();
                BatteryStation c = null;

                while ((c = GetNextUnMarked(GetAdjacencies(n))) != null)
                {
                    c.Mark = true;
                    q.Enqueue(c);
                    l.Add(c);
                }
            }

            return l;
        }
        public IList<IList<int>> LevelOrderBottom(TreeNode root)
        {
            IList<IList<int>> result = new List<IList<int>>();
            if (root == null)
                return result;

            Stack<IList<int>> stack = new Stack<IList<int>>();
            Queue<TreeNode> queue = new Queue<TreeNode>();
            queue.Enqueue(root);
            while (queue.Count > 0)
            {
                IList<int> items = new List<int>();
                int num = queue.Count;
                for (int i = 0; i < num; i++)
                {
                    TreeNode node = queue.Dequeue();
                    items.Add(node.val);

                    if (node.left != null)
                        queue.Enqueue(node.left);
                    if (node.right != null)
                        queue.Enqueue(node.right);
                }
                stack.Push(items);
            }

            while (stack.Count > 0)
                result.Add(stack.Pop());

            return result;
        }
示例#27
0
        private void queueButton_Click(object sender, EventArgs e)
        {
            Queue fila = new Queue();

            //Adicionando itens
            fila.Enqueue("Gabriela");
            fila.Enqueue("Rafael");
            fila.Enqueue("Thiago");

            //Exibindo os itens da coleção
            foreach (string elemento in fila)
            {
                listBox1.Items.Add(elemento);
            }
            listBox1.Items.Add("--------------");

            //Exibindo o item primeiro da fila
            listBox1.Items.Add("primeiro da fila");
            listBox1.Items.Add(fila.Peek());
            listBox1.Items.Add("--------------");

            //Retirando um elemento da fila (primeiro da fila)
            fila.Dequeue();

            //Exibindo o item primeiro da fila
            listBox1.Items.Add("primeiro da fila");
            listBox1.Items.Add(fila.Peek());
        }
示例#28
0
        //绘制字段分组的头
        //返回 true 表示还没有结束
        private bool drawGroupHead(Graphics g)
        {
            if (_GroupHeads.Count > 0)
            {
                int count = _GroupHeads.Count;
                //_HasDrawDetailHeight
                for (int i = 0; i < count; i++)
                {
                    DIYReport.ReportModel.RptSection section = _GroupHeads.Dequeue() as DIYReport.ReportModel.RptSection;
                    if (section.Visibled)
                    {
                        int tempHeight = _HasDrawDetailHeight + section.Height;
                        if (tempHeight > REAL_DETAIL_HEIGHT)
                        {
                            return(true);
                        }
                        DrawGroupField groupField = _DrawDetailInfo.GetGroupFieldByName(section.GroupField.FieldName);

                        groupField.HasDrawGroupHead = true;
                        foreach (RptSingleObj obj in section.RptObjList)
                        {
                            DrawRptSimpleObj(g, obj, _Rows[_HasDrawRowCount]);
                        }
                        _HasDrawDetailHeight += section.Height;

                        if (count > 0 && i == count - 1)
                        {
                            DIYReport.Express.ExSpecial._RowOrderNO = 0;
                        }
                    }
                }
            }
            return(false);
        }
示例#29
0
        /*      private class EdgeCounter : FieldTraverser
                {
                    private int count = 0;
                    public override void DoTraversal(Object field)
                    {
                        throw new ApplicationException("EdgePrinter should never traverse non Ptrs");
                    }
                    public override void DoTraversal(Pointer ptr)
                    {
                        if(ptr == 0u) return;
                        count ++;
                    }
                    public void reset(){count = 0;}
                    public int edgeCount(){return count;}
                }

        */
        public static void TraverseHeap(StateImpl state, FieldTraverser edge, FieldTraverser node)
        {
            heapQueue = new Queue();
            seen = new Hashtable();

            ReferenceTraverser et = new ReferenceTraverser(state, edge);

            state.TraverseGlobalReferences(et);

            for (int i = 0; i < state.NumProcesses; i++)
            {
                Process p = state.GetProcess(i);
                for (ZingMethod m = p.TopOfStack; m != null; m = m.Caller)
                {
                    m.TraverseFields(et);
                }
            }

            while (heapQueue.Count > 0)
            {
                Pointer ptr = (Pointer)heapQueue.Dequeue();
                if (node != null) node.DoTraversal(ptr);
                HeapEntry he = (HeapEntry)state.Heap[ptr];
                he.heList.TraverseFields(et);
            }
        }
示例#30
0
文件: Queue.cs 项目: yaobos/NCache
        /* ------------------------------------- Private Methods ----------------------------------- */


        /// <summary> Removes the first element. Returns null if no elements in queue.
        /// Always called with add_mutex locked (we don't have to lock add_mutex ourselves)
        /// </summary>
        protected object removeInternal(System.Collections.Queue queue)
        {
            object obj = null;

            lock (mutex)
            {
                int count = queue.Count;
                if (count > 0)
                {
                    obj = queue.Dequeue();
                }
                else
                {
                    return(null);
                }

                size--;
                if (size < 0)
                {
                    size = 0;
                }

                if (peekInternal() == endMarker)
                {
                    closed = true;
                }
            }

            return(obj);
        }
 private void ApplyDynamicUpdateMode(Activity seedActivity)
 {
     Queue<Activity> queue = new Queue<Activity>();
     queue.Enqueue(seedActivity);
     while (queue.Count > 0)
     {
         Activity activity = queue.Dequeue();
         activity.Readonly = true;
         activity.DynamicUpdateMode = true;
         foreach (DependencyProperty property in activity.MetaDependencyProperties)
         {
             if (activity.IsBindingSet(property))
             {
                 ActivityBind binding = activity.GetBinding(property);
                 if (binding != null)
                 {
                     binding.DynamicUpdateMode = true;
                 }
             }
         }
         if (activity is CompositeActivity)
         {
             CompositeActivity activity2 = activity as CompositeActivity;
             activity2.Activities.ListChanged += new EventHandler<ActivityCollectionChangeEventArgs>(this.OnActivityListChanged);
             foreach (Activity activity3 in ((CompositeActivity) activity).Activities)
             {
                 queue.Enqueue(activity3);
             }
         }
     }
 }
示例#32
0
        internal PacketReceiver(string LocalAddress) : base (LocalAddress)
        {
            packetReceiver = new Queue();
            tokenSource = new CancellationTokenSource();
            readerWriterLock = new ReaderWriterLockSlim();

            tokenSource.Token.Register(() => { 
                // Clear on cancel
                packetReceiver.Clear(); 
            });


            var thReceiveQueue = Task.Factory.StartNew(() => {
                while (tokenSource.Token.IsCancellationRequested == false)
                {
                    readerWriterLock.EnterUpgradeableReadLock();
                    if (packetReceiver.Count > 0)
                    {
                        readerWriterLock.EnterWriteLock();

                        byte[] data = (byte[])packetReceiver.Dequeue();

                        readerWriterLock.ExitWriteLock();

                        if (OnNewPacketReceived != null)
                            OnNewPacketReceived(this, new NewPacketEventArgs(data));
                    }

                    readerWriterLock.ExitUpgradeableReadLock();
                }
            });

        }
示例#33
0
    void UpdateCloudActions()
    {
        // TODO action time out...
        if (ActiveAction != null)
        {
            try
            {
                ActiveAction.PPIManager_Update();

                if (ActiveAction.isDone == false)
                {
                    return;
                }

                ActiveAction = null;
            }
            catch (System.Exception e)
            {
                ActiveAction = null;
                throw e;
            }
        }

        if (PendingActions.Count > 0)
        {
            ActiveAction = PendingActions.Dequeue();
        }
    }
 private void addMemory(Block newOne)
 {
     Queue visitQ = new Queue();
     BTNode newTree = new BTNode(newOne);
     if (Free == null)
         Free = newTree;
     else
     {
         visitQ.Enqueue(Free);
         while (true)
         {
             BTNode curTree = (BTNode)visitQ.Dequeue();
             if (curTree.left() == null)
             {
                 curTree.setLeft(newTree);
                 return;
             }
             if (curTree.right() == null)
             {
                 curTree.setRight(newTree);
                 return;
             }
             visitQ.Enqueue(curTree.left());
             visitQ.Enqueue(curTree.right());
         }
     }
 }
        public static Type ExtractEnumerableElementType(this Type inputType)
        {
            var seenTypes = new Dictionary<Type, object>();
            var processingQueue = new Queue<Type>(new[] { inputType });

            while (processingQueue.Count > 0)
            {
                Type currentType = processingQueue.Dequeue();
                if (seenTypes.ContainsKey(currentType))
                {
                    continue;
                }

                if (currentType.IsGenericType)
                {
                    Type genericTypeDefinition = currentType.GetGenericTypeDefinition();
                    if (genericTypeDefinition == typeof(IEnumerable<>))
                    {
                        Type argumentType = currentType.GetGenericArguments().First();
                        return argumentType;
                    }
                }

                seenTypes.Add(currentType, null);
                foreach (Type nextType in inputType.GetInterfaces())
                {
                    processingQueue.Enqueue(nextType);
                }
            }

            return null;
        }
        public IList<Pair<Node>> GetMatch()
        {
            var openNodes = new Queue<Node>();
            List<Node> visitedNodes;
            IList<Pair<Node>> parent = new List<Pair<Node>>();

            foreach (var leftNode in _leftNodes)
            {
                visitedNodes = new List<Node>();
                openNodes.Enqueue(leftNode);
                parent.Clear();

                while (openNodes.Count > 0)
                {
                    Node openNode = openNodes.Dequeue();
                    visitedNodes.Add(openNode);
                    if (openNode.IsLeftNode)
                    {
                        UpdateRightNodes(openNode, visitedNodes,
                                         openNodes, parent);
                    }
                    else
                    {
                        UpdateLeftNodes(openNode, visitedNodes,
                                        openNodes, parent);
                    }
                }
            }
            return _matching;
        }
示例#37
0
        /// <summary>
        /// Evaluates all cacheItems associated with this cache item to determine if it
        /// should be considered expired. Evaluation stops as soon as any CacheItem is still valid.
        /// </summary>
        /// <returns>True if cache should be considered expired</returns>
        //public static bool HasExpired()
        //{
        //    foreach (KeyValuePair<string, CacheItem> keyValuePair in ItemDictionary)
        //    {
        //        if (keyValuePair.Value.expiryDate.CompareTo(DateTime.Now) > 0)
        //        {
        //            return true;
        //        }
        //    }
        //    return false;
        //}

        /// <summary>
        /// 每隔1分钟将minutes分钟以前添加的元素扫描一次
        /// </summary>
        /// <param name="minutes"></param>
        private static void Scavange()
        {
            //Only scavange every 1 minute
            TimeSpan difference = DateTime.Now - _lastScavangeTime;

            if (difference.Minutes < IntervalMinutes)
            {
                return;
            }

            _lastScavangeTime = DateTime.Now;

            //NOTE: There is already a lock from Add method, which calls this method.

            //Monitor.Enter(keyQueue);
            int keyQueueCount = keyQueue.Count;

            //try
            //{
            for (int i = 0; i < keyQueueCount; i++)
            {
                if (ItemDictionary.ContainsKey((string)keyQueue.Peek()))
                {
                    if (ItemDictionary[(string)keyQueue.Peek()].timestamp.CompareTo(
                            DateTime.Now.AddMinutes(ScavangeMinutes * -1)) < 0)
                    {
                        CacheItem cahceItem = ItemDictionary[(string)keyQueue.Peek()];
                        _Remove((string)keyQueue.Dequeue());
                        cahceItem.Dispose();
                    }
                    else
                    {
                        continue;
                    }
                }
                else
                {
                    keyQueue.Dequeue();
                }
            }
            //}
            //finally
            //{
            //    //Monitor.Exit(keyQueue);
            //}
            GCWrapper.Collect();
        }
示例#38
0
 public void Push(object msg)
 {
     m_logQueue.Enqueue(msg);
     for (; m_logQueue.Count >= m_capacity;)
     {
         m_logQueue.Dequeue();
     }
 }
 /// <summary>
 /// Verifies the specified expected events occurred and that they occurred in the specified order.
 /// </summary>
 /// <param name="expectedEvents">The expected events.</param>
 public static void Verify(params string[] expectedEvents)
 {
     foreach (string expected in expectedEvents)
     {
         string actual = _events.Count > 0 ? _events.Dequeue() as string : null;
         Assert.AreEqual(expected, actual);
     }
 }
示例#40
0
        public static void Main(string[] args)
        {
            System.Collections.Queue kö = new System.Collections.Queue(10);
            {
                kö.Enqueue(1);
                kö.Enqueue(2);
                kö.Enqueue(3);
                kö.Enqueue(15);
                kö.Enqueue(null);
                kö.Enqueue(20);
                kö.Enqueue("test string");
                kö.Enqueue(25);


                Console.WriteLine($"Totalt antal element = {kö.Count}"); //Räknar antal element i kön

                Console.WriteLine(kö.Peek());                            //Kollar elementen i kön enligt ordning
                kö.Dequeue();
                Console.WriteLine(kö.Peek());
                kö.Dequeue();
                Console.WriteLine(kö.Peek());
                kö.Dequeue();
                kö.Dequeue();
                Console.WriteLine(kö.Peek());
                kö.Dequeue();
                kö.Dequeue();
                Console.WriteLine(kö.Peek());
                kö.Dequeue();
                Console.WriteLine(kö.Peek());

                Console.WriteLine($"Antal element efter = {kö.Count}"); // Visar att elementen tagits bort

                kö.Clear();
            }
        }
示例#41
0
 /// <summary>
 /// called by the messaging engine until returned null, after disassemble has been called
 /// </summary>
 /// <param name="pc">the pipeline context</param>
 /// <returns>an IBaseMessage instance representing the message created</returns>
 public Microsoft.BizTalk.Message.Interop.IBaseMessage GetNext(Microsoft.BizTalk.Component.Interop.IPipelineContext pc)
 {
     // get the next message from the Queue and return it
     Microsoft.BizTalk.Message.Interop.IBaseMessage msg = null;
     if ((_msgs.Count > 0))
     {
         msg = ((Microsoft.BizTalk.Message.Interop.IBaseMessage)(_msgs.Dequeue()));
     }
     return(msg);
 }
示例#42
0
        public void runQueue()
        {
            // Create a queue
            // Using Queue class
            System.Collections.Queue my_queue = new System.Collections.Queue();

            // Adding elements in Queue
            // Using Enqueue() method
            my_queue.Enqueue("GFG");
            my_queue.Enqueue("Geeks");
            my_queue.Enqueue("GeeksforGeeks");
            my_queue.Enqueue("geeks");
            my_queue.Enqueue("Geeks123");

            Console.WriteLine("Total elements present in my_queue: {0}",
                              my_queue.Count);

            // Checking if the element is
            // present in the Queue or not
            if (my_queue.Contains("GeeksforGeeks") == true)
            {
                Console.WriteLine("Element available...!!");
            }
            else
            {
                Console.WriteLine("Element not available...!!");
            }

            // Obtain the topmost element of my_queue
            // Using Dequeue method
            Console.WriteLine("Topmost element of my_queue"
                              + " is: {0}", my_queue.Dequeue());


            Console.WriteLine("Total elements present in my_queue: {0}",
                              my_queue.Count);

            // Obtain the topmost element of my_queue
            // Using Peek method
            Console.WriteLine("Topmost element of my_queue is: {0}",
                              my_queue.Peek());
            // After Dequeue method
            Console.WriteLine("Total elements present in my_queue: {0}",
                              my_queue.Count);

            // Remove all the elements from the queue
            my_queue.Clear();

            // After Clear method
            Console.WriteLine("Total elements present in my_queue: {0}",
                              my_queue.Count);

            Console.ReadLine();
        }
示例#43
0
 IBaseMessage IDisassemblerComponent.GetNext(IPipelineContext pContext)
 {
     if (qOutputMsgs.Count > 0)
     {
         return((IBaseMessage)qOutputMsgs.Dequeue());
     }
     else
     {
         return(null);
     }
 }
示例#44
0
 public IBaseMessage GetNext(IPipelineContext pContext)
 {
     if (qOutputMsgs.Count > 0)
     {
         return((IBaseMessage)qOutputMsgs.Dequeue());
     }
     else
     {
         return(null);
     }
 }
示例#45
0
        public void Pop()
        {
            waitEvent.WaitOne();

            lock (((ICollection)queue).SyncRoot)
            {
                var item = queue.Dequeue();
                Count--;
                Console.WriteLine("pop value {0}", item);
            }
        }
示例#46
0
 IBaseMessage IAssemblerComponent.Assemble(IPipelineContext pContext)
 {
     if (qOutputMsgs.Count > 0)
     {
         IBaseMessage msg = (IBaseMessage)qOutputMsgs.Dequeue();
         return(msg);
     }
     else
     {
         return(null);
     }
 }
 static public int Dequeue(IntPtr l)
 {
     try {
         System.Collections.Queue self = (System.Collections.Queue)checkSelf(l);
         var ret = self.Dequeue();
         pushValue(l, true);
         pushValue(l, ret);
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
示例#48
0
 /// <summary>
 /// Called from CommandLineDialog in the context of the main / UI thread.
 /// </summary>
 public void Update(CommandLineDialog window)
 {
     if (textQueue.Count > 0)
     {
         List <string> textList = new List <string>();
         while (textQueue.Count > 0)
         {
             textList.Add((string)textQueue.Dequeue());
         }
         string bodyText = window.bodyText + String.Join("", textList.ToArray());
         // Really weak handling of carriage returns.  Truncates to the previous
         // line for each newline detected.
         while (true)
         {
             // Really weak handling carriage returns for progress style updates.
             int carriageReturn = bodyText.LastIndexOf("\r");
             if (carriageReturn < 0 || bodyText.Substring(carriageReturn, 1) == "\n")
             {
                 break;
             }
             string bodyTextHead    = "";
             int    previousNewline = bodyText.LastIndexOf("\n", carriageReturn,
                                                           carriageReturn);
             if (previousNewline >= 0)
             {
                 bodyTextHead = bodyText.Substring(0, previousNewline + 1);
             }
             bodyText = bodyTextHead + bodyText.Substring(carriageReturn + 1);
         }
         window.bodyText = bodyText;
         if (window.autoScrollToBottom)
         {
             window.scrollPosition.y = Mathf.Infinity;
         }
         window.Repaint();
     }
     if (maxProgressLines > 0)
     {
         window.progress = (float)linesReported / (float)maxProgressLines;
     }
     if (result != null)
     {
         window.progressTitle = "";
         if (Complete != null)
         {
             Complete(result);
             Complete = null;
         }
     }
 }
示例#49
0
 static int Dequeue(IntPtr L)
 {
     try
     {
         ToLua.CheckArgsCount(L, 1);
         System.Collections.Queue obj = (System.Collections.Queue)ToLua.CheckObject(L, 1, typeof(System.Collections.Queue));
         object o = obj.Dequeue();
         ToLua.Push(L, o);
         return(1);
     }
     catch (Exception e)
     {
         return(LuaDLL.toluaL_exception(L, e));
     }
 }
示例#50
0
        /// <summary>
        /// Whem we start a transaction we must redeliver any rolled back messages
        /// </summary>
        public void RedeliverRolledBackMessages()
        {
            lock (semaphore)
            {
                System.Collections.Queue replacement = new System.Collections.Queue(queue.Count + messagesToRedeliver.Count);
                foreach (Apache.NMS.IMessage element in messagesToRedeliver)
                {
                    replacement.Enqueue(element);
                }
                messagesToRedeliver.Clear();

                while (queue.Count > 0)
                {
                    Apache.NMS.IMessage element = (Apache.NMS.IMessage)queue.Dequeue();
                    replacement.Enqueue(element);
                }

                queue = replacement;
                if (queue.Count > 0)
                {
                    messageReceivedEventHandle.Set();
                }
            }
        }
示例#51
0
 private object ProvideData(IOutputPort op, object selector)
 {
     if (m_queue.Count > 0)
     {
         object data = m_queue.Dequeue();
         LevelChangedEvent(Count + 1, Count, this);
         // Commented out the following because this functionality is now provided
         // (as it was before, also) through OnPortDataAccepted. Since the Queue
         // functionality assumes that if ProvideData is called, the data will be
         // accepted, then these two avenues are equivalent.
         //if ( ObjectDequeued != null ) ObjectDequeued(this,data);
         return(data);
     }
     else
     {
         return(null);
     }
 }
示例#52
0
        public void AddPoint()
        {
            Quaternion q1 = new Quaternion(-vectDiagonal.X, -vectDiagonal.Y, -vectDiagonal.Z, 0);

            q1 = (Quaternion.Conjugate(quat) * q1) * quat;
            while (points.Count >= psize)
            {
                points.Dequeue();
            }
            points.Enqueue(new Vector3(q1.X, q1.Y, q1.Z));

            Quaternion q = new Quaternion(-Center.X, -Center.Y, -Center.Z, 0);

            q = (Quaternion.Conjugate(quat) * q) * quat;
            PotentialEnergy = (q.Y) * Mass * gravitation;                             // mgh centrum masy
            KineticEnergyW  = Vector3.Dot(mulv(ref InertiaTensor, omega), omega) / 2; // mv^2/2 + Iw^2 / 2 +  energia kinetyczna
            // 0.5f*(Mass/gravitation) * Vector3.Dot(omega,omega)
        }
示例#53
0
        public void GetSumOfSlindingWindow(int[] arr, int windowSize)
        {
            // queue to keep track of elements of the window
            var queue = new System.Collections.Queue();
            var sum   = 0;

            for (var i = 0; i < windowSize; i++)
            {
                queue.Enqueue(arr[i]);
                sum = sum + arr[i];
            }

            Console.Write(sum + ", ");

            for (var i = windowSize; i < arr.Length; i++)
            {
                var val = queue.Dequeue();
                sum = sum - (int)val;
                queue.Enqueue(arr[i]);
                sum = sum + arr[i];
                Console.Write(sum + ", ");
            }

            /*
             *  if (a == null || k == 0 || a.length == 0)
             *      return; // confirm with interviewer what to do for this case
             *  // LinkedList implements Queue interface in Java
             *  Queue<Integer> q = new LinkedList<>();
             *  int sum = 0;
             *  for (int i = 0; i < a.length; i++) {
             *      if (q.size() == k) {
             *          int last = q.remove();
             *          sum -= last;
             *      }
             *      q.add(a[i]);
             *      sum += a[i];
             *      if (q.size() == k) {
             *          System.out.println(sum);
             *      }
             *  }
             */
        }
示例#54
0
        public T Get <T>() where T : class
        {
            T res;

            if (queue.Count != 0)
            {
                res = queue.Dequeue() as T;
            }
            else
            {
                var o = GameObject.Instantiate(p.gameObject, p.transform.parent);
                var s = o.GetComponent <BasicPath>();
                o.GetComponent <MeshRenderer>().enabled = true;
                o.GetComponent <MeshCollider>().enabled = true;
                s.underControl  = o.transform;
                s.straight_pool = this;
                res             = o as T;
            }
            return(res);
        }
示例#55
0
        void PasteItems(bool asgossip)
        {
            int itemIndex = this.NextItemIndex(false);

            this.Cursor = Cursors.WaitCursor;
            System.Collections.Queue newq = new Queue();
            try
            {
                while (clipboard.Count > 0)
                {
                    NgbhItem item = clipboard.Dequeue() as NgbhItem;
                    newq.Enqueue(item);

                    if (item != null)
                    {
                        item = item.Clone(this.Slot);

                        if (item.IsMemory && item.OwnerInstance > 0 && !asgossip)
                        {
                            item.OwnerInstance = (ushort)items.Parent.SlotID;
                        }

                        if (asgossip)
                        {
                            item.Flags.IsVisible = false;
                        }

                        AddItemAfterSelected(item);
                    }
                }
            }
            catch (Exception exception1)
            {
                this.Cursor = Cursors.Default;
                Helper.ExceptionMessage(Localization.Manager.GetString("errconvert"), exception1);
            }

            clipboard.Clear();
            clipboard   = newq;
            this.Cursor = Cursors.Default;
        }
示例#56
0
            public override void execute3(RunTimeValueBase thisObj,FunctionDefine functionDefine,SLOT returnSlot,SourceToken token,StackFrame stackframe,out bool success)
            {
                System.Collections.Queue queue =
                    (System.Collections.Queue)((LinkObj <object>)((ASBinCode.rtData.rtObjectBase)thisObj).value).value;

                try
                {
                    object obj = queue.Dequeue();

                    stackframe.player.linktypemapper.storeLinkObject_ToSlot(obj,functionDefine.signature.returnType,returnSlot,bin,stackframe.player);
                    //returnSlot.setValue((int)array.GetValue(index));
                    success = true;
                }
                catch (RuntimeLinkTypeMapper.TypeLinkClassException tlc)
                {
                    success = false;
                    stackframe.throwAneException(token,tlc.Message);
                }
                catch (KeyNotFoundException)
                {
                    success = false;
                    stackframe.throwAneException(token,"Queue内的值没有链接到脚本");
                }
                catch (ArgumentException a)
                {
                    success = false;
                    stackframe.throwAneException(token,a.Message);
                }
                catch (IndexOutOfRangeException i)
                {
                    success = false;
                    stackframe.throwAneException(token,i.Message);
                }
                catch (InvalidOperationException io)
                {
                    success = false;
                    stackframe.throwAneException(token,io.Message);
                }
            }
示例#57
0
        /// <summary>
        /// Process Hl7 requests and responses.
        /// </summary>
        public void ProcessMessages()
        {
            _looping = true;
            while (_looping == true)
            {
                // Check if anything has been queued
                while (_triggerQueue.Count != 0)
                {
                    // Get the trigger
                    Hl7Trigger trigger = (Hl7Trigger)_triggerQueue.Dequeue();
                    if (trigger != null)
                    {
                        // Process the trigger
                        ProcessTrigger(trigger);

                        // Wait awhile before processing new Trigger
                        System.Threading.Thread.Sleep(1000);
                    }
                }

                System.Threading.Thread.Sleep(_loopDelay);
            }
        }
示例#58
0
    //private static int gcCount = 0;

    private static void ClearHalf(Dictionary <int, System.Collections.Queue> dic)
    {
        if (dic != null)
        {
            if (dic.Count > 1)
            {
                foreach (KeyValuePair <int, System.Collections.Queue> data in dic)
                {
                    System.Collections.Queue q = data.Value;
                    int cnt = q.Count;
                    if (cnt > 1)
                    {
                        //清一半
                        int delcnt = (int)(cnt / 2);
                        for (int i = 0; i < delcnt; i++)
                        {
                            System.Object obj = q.Dequeue();
                            obj = null;
                        }
                    }
                }
            }
        }
    }
示例#59
0
    // since inheritance of Window does not work, the eventhandler have to be static methods and added after generation of the Window object

    // keyboard is pressed
    private static void InkCanvas_KeyDown(object sender, KeyEventArgs e)
    {
        Key Taste = e.Key;
        // the sender object is the object that generated the event
        InkCanvas objInkCanvas = (InkCanvas)sender;

        if (Keyboard.IsKeyDown(Key.RightCtrl) || Keyboard.IsKeyDown(Key.LeftCtrl))
// the following line only works with .Net 4.x
//		if (Keyboard.Modifiers.HasFlag(ModifierKeys.Control))
        {         // if Ctrl is pressed
            switch (Taste)
            {
            case Key.C:                     // copy marked area
                objInkCanvas.CopySelection();
                break;

            case Key.O:                     // open ink drawing
                Microsoft.Win32.OpenFileDialog objOpenDialog = new Microsoft.Win32.OpenFileDialog();
                objOpenDialog.Filter = "isf files (*.isf)|*.isf";
                if ((bool)objOpenDialog.ShowDialog())
                {
                    FileStream objFileStream = new FileStream(objOpenDialog.FileName, FileMode.Open);
                    objInkCanvas.Strokes.Add(new StrokeCollection(objFileStream));
                    objFileStream.Dispose();
                }
                break;

            case Key.P:                     // save grafic as PNG file
                Microsoft.Win32.SaveFileDialog objPNGDialog = new Microsoft.Win32.SaveFileDialog();
                objPNGDialog.Filter = "png files (*.png)|*.png";
                if ((bool)objPNGDialog.ShowDialog())
                {
                    FileStream objFileStream = new FileStream(objPNGDialog.FileName, FileMode.Create);
                    System.Windows.Media.Imaging.RenderTargetBitmap objRenderBitmap = new System.Windows.Media.Imaging.RenderTargetBitmap((int)objInkCanvas.ActualWidth, (int)objInkCanvas.ActualHeight, 96.0, 96.0, System.Windows.Media.PixelFormats.Default);
                    objRenderBitmap.Render(objInkCanvas);
                    System.Windows.Media.Imaging.BitmapFrame      objBitmapFrame = System.Windows.Media.Imaging.BitmapFrame.Create(objRenderBitmap);
                    System.Windows.Media.Imaging.PngBitmapEncoder objImgEncoder  = new System.Windows.Media.Imaging.PngBitmapEncoder();
// alternative for JPG:								System.Windows.Media.Imaging.JpegBitmapEncoder objImgEncoder = new System.Windows.Media.Imaging.JpegBitmapEncoder();
                    objImgEncoder.Frames.Add(objBitmapFrame);
                    objImgEncoder.Save(objFileStream);
                    objFileStream.Dispose();
                }
                break;

            case Key.S:                             // save ink drawing
                Microsoft.Win32.SaveFileDialog objSaveDialog = new Microsoft.Win32.SaveFileDialog();
                objSaveDialog.Filter = "isf files (*.isf)|*.isf";
                if ((bool)objSaveDialog.ShowDialog())
                {
                    FileStream objFileStream = new FileStream(objSaveDialog.FileName, FileMode.Create);
                    objInkCanvas.Strokes.Save(objFileStream);
                    objFileStream.Dispose();
                }
                break;

            case Key.V:                     // paste marked area
                objInkCanvas.Paste();
                break;

            case Key.X:                     // cut marked area
                objInkCanvas.CutSelection();
                break;
            }
        }
        else
        {         // no Ctrl key is pressed
            if (Keyboard.Modifiers == ModifierKeys.None)
            {     // only when no other modifier keys are pressed
                switch (Taste)
                {
                case Key.B:                         // next background color
                    Brush ActualBackColor = (Brush)BrushQueue.Dequeue();
                    BrushQueue.Enqueue(ActualBackColor);
                    objInkCanvas.Background = ActualBackColor;
                    break;

                case Key.C:                         // clear window content
                    objInkCanvas.Strokes.Clear();
                    break;

                case Key.D:                         // switch to draw mode
                    if (objInkCanvas.DefaultDrawingAttributes.IsHighlighter)
                    {
                        StoreHighLightSizeWidth  = objInkCanvas.DefaultDrawingAttributes.Width;
                        StoreHighLightSizeHeight = objInkCanvas.DefaultDrawingAttributes.Height;
                        StoreHighLightColor      = objInkCanvas.DefaultDrawingAttributes.Color;
                        objInkCanvas.DefaultDrawingAttributes.StylusTip     = StylusTip.Ellipse;
                        objInkCanvas.DefaultDrawingAttributes.IsHighlighter = false;
                        objInkCanvas.DefaultDrawingAttributes.Color         = StoreInkColor;
                        objInkCanvas.DefaultDrawingAttributes.Height        = StoreInkSizeHeight;
                        objInkCanvas.DefaultDrawingAttributes.Width         = StoreInkSizeWidth;
                    }
                    objInkCanvas.EditingMode = InkCanvasEditingMode.Ink;
                    break;

                case Key.E:                         // // switch to erase mode (and toggle it)
                    switch (objInkCanvas.EditingMode)
                    {
                    case InkCanvasEditingMode.EraseByStroke:
                        objInkCanvas.EditingMode = InkCanvasEditingMode.EraseByPoint;
                        break;

                    case InkCanvasEditingMode.EraseByPoint:
                        objInkCanvas.EditingMode = InkCanvasEditingMode.EraseByStroke;
                        break;

                    case InkCanvasEditingMode.Ink:
                        objInkCanvas.EditingMode = InkCanvasEditingMode.EraseByPoint;
                        break;
                    }
                    break;

                case Key.H:                         // switch to highlight mode
                    if (!objInkCanvas.DefaultDrawingAttributes.IsHighlighter)
                    {
                        StoreInkSizeWidth  = objInkCanvas.DefaultDrawingAttributes.Width;
                        StoreInkSizeHeight = objInkCanvas.DefaultDrawingAttributes.Height;
                        StoreInkColor      = objInkCanvas.DefaultDrawingAttributes.Color;
                        objInkCanvas.DefaultDrawingAttributes.Color = StoreHighLightColor;
                    }
                    objInkCanvas.EditingMode = InkCanvasEditingMode.Ink;
                    objInkCanvas.DefaultDrawingAttributes.IsHighlighter = true;
                    objInkCanvas.DefaultDrawingAttributes.StylusTip     = StylusTip.Rectangle;
                    if (StoreHighLightSizeWidth > 0.0)
                    {
                        objInkCanvas.DefaultDrawingAttributes.Height = StoreHighLightSizeHeight;
                        objInkCanvas.DefaultDrawingAttributes.Width  = StoreHighLightSizeWidth;
                    }
                    break;

                case Key.N:                         // next foreground color
                    Color ActualFrontColor = (Color)ColorQueue.Dequeue();
                    ColorQueue.Enqueue(ActualFrontColor);
                    objInkCanvas.DefaultDrawingAttributes.Color = ActualFrontColor;
                    break;

                case Key.Q:                         // close window
                    // event is handled now
                    e.Handled = true;
                    // parent object is Window
                    ((Window)(objInkCanvas).Parent).Close();
                    break;

                case Key.S:                         // start marking
                    objInkCanvas.Select(new System.Windows.Ink.StrokeCollection());
                    break;

                case Key.OemMinus:                         // shrink brush
                    switch (objInkCanvas.EditingMode)
                    {
                    case InkCanvasEditingMode.EraseByPoint:
                        if (objInkCanvas.EraserShape.Width > 3.0)
                        {
                            objInkCanvas.EraserShape = new RectangleStylusShape(objInkCanvas.EraserShape.Width - 2.0, objInkCanvas.EraserShape.Height - 2.0);
                            // size change needs refresh to display
                            objInkCanvas.EditingMode = InkCanvasEditingMode.None;
                            objInkCanvas.EditingMode = InkCanvasEditingMode.EraseByPoint;
                        }
                        break;

                    case InkCanvasEditingMode.Ink:
                        if (objInkCanvas.DefaultDrawingAttributes.Height > 3.0)
                        {
                            objInkCanvas.DefaultDrawingAttributes.Height = objInkCanvas.DefaultDrawingAttributes.Height - 2.0;
                            objInkCanvas.DefaultDrawingAttributes.Width  = objInkCanvas.DefaultDrawingAttributes.Width - 2.0;
                        }
                        break;
                    }
                    break;

                case Key.OemPlus:                         // enlarge brush
                    switch (objInkCanvas.EditingMode)
                    {
                    case InkCanvasEditingMode.EraseByPoint:
                        if (objInkCanvas.EraserShape.Width < 50.0)
                        {
                            objInkCanvas.EraserShape = new RectangleStylusShape(objInkCanvas.EraserShape.Width + 2.0, objInkCanvas.EraserShape.Height + 2.0);
                            // size change needs refresh to display
                            objInkCanvas.EditingMode = InkCanvasEditingMode.None;
                            objInkCanvas.EditingMode = InkCanvasEditingMode.EraseByPoint;
                        }
                        break;

                    case InkCanvasEditingMode.Ink:
                        if (objInkCanvas.DefaultDrawingAttributes.Height < 50.0)
                        {
                            objInkCanvas.DefaultDrawingAttributes.Height = objInkCanvas.DefaultDrawingAttributes.Height + 2.0;
                            objInkCanvas.DefaultDrawingAttributes.Width  = objInkCanvas.DefaultDrawingAttributes.Width + 2.0;
                        }
                        break;
                    }
                    break;
                }
            }
        }
    }
示例#60
0
        private void method_7(SocketAsyncEventArgs e)
        {
            Form1.WriteLine(3, "LS客户正常进入");
            IoServer userToken = e.UserToken as IoServer;

            try
            {
                string   str;
                DateTime ljtime;
                if (World.int_6 != 1)
                {
                    goto Label_0486;
                }
                IPAddress item = ((IPEndPoint)e.AcceptSocket.RemoteEndPoint).Address;
                if (World.BipList.Contains(item))
                {
                    if (World.bool_1)
                    {
                        try
                        {
                            e.AcceptSocket.Shutdown(SocketShutdown.Both);
                        }
                        catch
                        {
                        }
                        try
                        {
                            e.AcceptSocket.Close();
                        }
                        catch
                        {
                        }
                    }
                    if (World.bool_3)
                    {
                        try
                        {
                            userToken.b();
                            return;
                        }
                        catch
                        {
                            return;
                        }
                    }
                    using (SocketAsyncEventArgs args = new SocketAsyncEventArgs())
                    {
                        args.UserToken  = this;
                        args.Completed += new EventHandler <SocketAsyncEventArgs>(this.method_6);
                        this.listenSocket.AcceptAsync(args);
                    }
                    return;
                }
                if (World.string_3 != "")
                {
                    str = RxjhClass.GetUserIpadds(item.ToString()).Replace(" ", "").Trim();
                    bool     flag     = false;
                    string[] strArray = World.string_3.Split(new char[] { ',' });
                    for (int i = 0; i < strArray.Length; i++)
                    {
                        if (str.IndexOf(strArray[i]) != -1)
                        {
                            string[] strArray2 = World.string_7.Split(new char[] { ',' });
                            for (int j = 0; j < strArray2.Length; j++)
                            {
                                if (str.IndexOf(strArray2[j]) != -1)
                                {
                                    flag = true;
                                }
                            }
                            if (!flag)
                            {
                                goto Label_01FC;
                            }
                        }
                    }
                }
                goto Label_0296;
Label_01FC:
                try
                {
                    e.AcceptSocket.Shutdown(SocketShutdown.Both);
                }
                catch
                {
                }
                try
                {
                    e.AcceptSocket.Close();
                }
                catch
                {
                }
                Form1.WriteLine(1, "用户登陆[" + item.ToString() + "]被封 " + str);
                using (SocketAsyncEventArgs args2 = new SocketAsyncEventArgs())
                {
                    args2.UserToken  = this;
                    args2.Completed += new EventHandler <SocketAsyncEventArgs>(this.method_6);
                    this.listenSocket.AcceptAsync(args2);
                }
                return;

Label_0296:
                ljtime = DateTime.Now;
                int num3 = 0;
                foreach (NetState state in World.list.Values)
                {
                    if (state.ToString() == item.ToString())
                    {
                        ljtime = state.Ljtime;
                        num3++;
                    }
                }
                if (num3 > World.int_4)
                {
                    int totalMilliseconds = (int)DateTime.Now.Subtract(ljtime).TotalMilliseconds;
                    if (totalMilliseconds >= World.int_5)
                    {
                        return;
                    }
                    Form1.WriteLine(1, "到达IP最大连接数" + item.ToString());
                    if (!(!World.bool_2 || World.BipList.Contains(item)))
                    {
                        World.BipList.Add(item);
                    }
                    try
                    {
                        e.AcceptSocket.Shutdown(SocketShutdown.Both);
                    }
                    catch
                    {
                    }
                    try
                    {
                        e.AcceptSocket.Close();
                    }
                    catch
                    {
                    }
                    try
                    {
                        System.Collections.Queue queue = System.Collections.Queue.Synchronized(new System.Collections.Queue());
                        foreach (NetState state2 in World.list.Values)
                        {
                            if (state2.ToString() == item.ToString())
                            {
                                queue.Enqueue(state2);
                            }
                        }
                        while (queue.Count > 0)
                        {
                            ((NetState)queue.Dequeue()).Dispose();
                        }
                        return;
                    }
                    catch
                    {
                        return;
                    }
                }
                if (e.AcceptSocket != null)
                {
                    new NetState(e.AcceptSocket).Start();
                }
                return;

Label_0486:
                if (e.AcceptSocket != null)
                {
                    new NetState(e.AcceptSocket).Start();
                }
            }
            catch (Exception)
            {
            }
            finally
            {
                try
                {
                    using (SocketAsyncEventArgs args3 = new SocketAsyncEventArgs())
                    {
                        args3.UserToken  = this;
                        args3.Completed += new EventHandler <SocketAsyncEventArgs>(this.method_6);
                        this.listenSocket.AcceptAsync(args3);
                    }
                }
                catch (Exception)
                {
                }
            }
        }