Example #1
0
    public static void bfs(Graph G, int startVert)
    {
        bool[] visited = new bool[G.Size];
        // NOTE: the namespace reference isn't required if you have this file on it's own, but if you download
        // all the files with this in the same folder, it will mistakenly reference
        // the local Queue implementation, and not the built in!
        System.Collections.Generic.Queue <int> q = new System.Collections.Generic.Queue <int>();

        visited[startVert] = true;

        q.Enqueue(startVert);

        while (q.Count > 0)
        {
            int v = q.Dequeue();
            foreach (int adjV in G.adj[v])
            {
                if (!visited[adjV])
                {
                    visited[adjV] = true;
                    q.Enqueue(adjV);
                }
            }
        }
    }
Example #2
0
        //Performs BFS to find node with value
        //returns node with given value
        //returns null if value was not found in graph
        public static GraphNode <T> Search <T>(GraphNode <T> begining, T value)
        {
            System.Collections.Generic.Queue <GraphNode <T> > q = new System.Collections.Generic.Queue <GraphNode <T> >();
            HashSet <GraphNode <T> > visited = new HashSet <GraphNode <T> >();

            q.Enqueue(begining);

            while (q.Count != 0)
            {
                GraphNode <T> node = q.Dequeue();

                if (node.Value.Equals(value))
                {
                    return(node);
                }


                if (!visited.Contains(node))
                {
                    visited.Add(node);
                    foreach (GraphNode <T> n in node.Neighbours)
                    {
                        q.Enqueue(n);
                    }
                }
            }
            return(null);
        }
Example #3
0
        public Queue(int lenght)
        {
            Container = new int[lenght];
            Lenght    = lenght;

            List = new System.Collections.Generic.Queue <Price>();
        }
Example #4
0
 public static void RecordProductViews(string bvin, MerchantTribeApplication app)
 {
     if (WebAppSettings.LastProductsViewedCookieName != string.Empty)
     {
         string SavedProductIDs = SessionManager.GetCookieString(WebAppSettings.LastProductsViewedCookieName, app.CurrentStore);
         if (SavedProductIDs != string.Empty)
         {
             string[] AllIDs = SavedProductIDs.Split(',');
             System.Collections.Generic.Queue <string> q = new System.Collections.Generic.Queue <string>();
             q.Enqueue(bvin);
             foreach (string id in AllIDs)
             {
                 if (q.Count < 10)
                 {
                     if (!q.Contains(id))
                     {
                         q.Enqueue(id);
                     }
                 }
             }
             SessionManager.SetCookieString(WebAppSettings.LastProductsViewedCookieName, string.Join(",", q.ToArray()), app.CurrentStore);
         }
         else
         {
             SessionManager.SetCookieString(WebAppSettings.LastProductsViewedCookieName, bvin, app.CurrentStore);
         }
     }
 }
Example #5
0
        private void IdleResume()
        {
            if (_Idle != null || !_Idling)
            {
                return;
            }

            var response = SendCommandGetResponse(GetTag() + "IDLE");

            response = response.Substring(response.IndexOf(" ")).Trim();
            if (!response.TrimStart().StartsWith("idling", StringComparison.OrdinalIgnoreCase))
            {
                throw new Exception(response);
            }

            if (_IdleEvents == null)
            {
                _IdleQueue     = new Queue <string>();
                _IdleEventsMre = new AutoResetEvent(false);
                _IdleEvents    = new Thread(WatchIdleQueue);
                _IdleEvents.Start();
            }
            _Idle = new Thread(ReceiveData);
            _Idle.Start();
        }
 public static void RecordProductViews(string bvin, MerchantTribeApplication app)
 {
     if (WebAppSettings.LastProductsViewedCookieName != string.Empty)
     {
         string SavedProductIDs = SessionManager.GetCookieString(WebAppSettings.LastProductsViewedCookieName, app.CurrentStore);
         if (SavedProductIDs != string.Empty)
         {
             string[] AllIDs = SavedProductIDs.Split(',');
             System.Collections.Generic.Queue<string> q = new System.Collections.Generic.Queue<string>();
             q.Enqueue(bvin);
             foreach (string id in AllIDs)
             {
                 if (q.Count < 10)
                 {
                     if (!q.Contains(id))
                     {
                         q.Enqueue(id);
                     }
                 }
             }
             SessionManager.SetCookieString(WebAppSettings.LastProductsViewedCookieName, string.Join(",", q.ToArray()), app.CurrentStore);
         }
         else
         {
             SessionManager.SetCookieString(WebAppSettings.LastProductsViewedCookieName, bvin, app.CurrentStore);
         }
     }
 }
        public void LineByLineLevelOrderTraversal(Bnode <int> head)
        {
            var q = new System.Collections.Generic.Queue <Bnode <int> >();

            q.Enqueue(head);
            int curlevel  = 1;
            int nextlevel = 0;

            while (q.Count > 0)
            {
                var node = q.Dequeue();
                curlevel--;

                if (node.left != null)
                {
                    q.Enqueue(node.left);
                    nextlevel++;
                }
                if (node.right != null)
                {
                    q.Enqueue(node.right);
                    nextlevel++;
                }

                if (curlevel == 0)
                {
                    curlevel = nextlevel;
                    curlevel = 0;
                    Console.Write("\n");
                }
            }
        }
Example #8
0
        public FileMessageQueue(string queueName, string path)
        {
            m_QueueName = queueName;
            m_Path      = path;
            m_Event     = new ManualResetEvent(false);
            m_Queue     = new Queue <string>(1000000);

            if (path.StartsWith("."))
            {
                var directory = System.IO.Path.GetDirectoryName(this.GetType().Assembly.Location);
                path = System.IO.Path.Combine(directory.TrimEnd('\\'), path.TrimStart('.').TrimStart('\\'));
                if (!System.IO.Directory.Exists(path))
                {
                    System.IO.Directory.CreateDirectory(path);
                }
            }

            m_FileWatcher              = new FileSystemWatcher();
            m_FileWatcher.Path         = path;
            m_FileWatcher.NotifyFilter = NotifyFilters.CreationTime;
            m_FileWatcher.Created     += (s, arg) =>
            {
                m_Queue.Enqueue(arg.FullPath);
                m_Event.Set();
            };
            m_FileWatcher.Filter = Filter;
            m_FileWatcher.EnableRaisingEvents = true;
        }
Example #9
0
        /// <summary>
        /// 文件夹遍历方法(广度优先算法)
        /// </summary>
        /// <param name="sPathName">起始文件夹</param>
        public static FileInfo[] TraversingAllFiles(string sPathName)
        {
            System.Collections.ArrayList al = new System.Collections.ArrayList();
            //创建一个队列用于保存子目录
            System.Collections.Generic.Queue <string> pathQueue = new System.Collections.Generic.Queue <string>();
            //首先把根目录排入队中
            pathQueue.Enqueue(sPathName);
            //开始循环查找文件,直到队列中无任何子目录
            string path = string.Empty;

            while (pathQueue.Count > 0)
            {
                //从队列中取出一个目录,把该目录下的所有子目录排入队中
                path = pathQueue.Dequeue();

                foreach (DirectoryInfo diChild in GetAllDirPath(path))
                {
                    pathQueue.Enqueue(diChild.FullName);
                }

                //查找该目录下的所有文件,依次处理
                foreach (FileInfo fi in GetAllFilePath(path))
                {
                    al.Add(fi);
                }
            }
            return((FileInfo[])al.ToArray(typeof(FileInfo)));
        }
        public PcapStreamReader(System.IO.Stream pcapStream, int packetQueueSize, StreamReadCompletedCallback streamReadCompletedCallback, bool startBackgroundWorkers, long streamMaxLength, int readTimeoutMilliseconds)
        {
            this.pcapStream              = pcapStream;
            this.streamLength            = streamMaxLength;
            this.readBytesEstimate       = 0;
            this.readTimeoutMilliseconds = readTimeoutMilliseconds;

            this.packetQueueSize             = packetQueueSize;
            this.streamReadCompletedCallback = streamReadCompletedCallback;


            //TODO: Figure out if it is a libpcap or pcapNG stream...
            this.pcapParser = PcapParserFactory.CreatePcapParser(this);// new PcapParser(pcapStream, this.AbortReadingPcapStream);

            /*
             * byte[] buffer4=new byte[4];//32 bits is suitable
             * byte[] buffer2=new byte[2];//16 bits is sometimes needed
             * uint wiresharkMagicNumber=0xa1b2c3d4;
             *
             * //Section Header Block (mandatory)
             *
             * this.pcapStream.Read(buffer4, 0, 4);
             *
             * if(wiresharkMagicNumber==this.ToUInt32(buffer4, false))
             *  this.littleEndian=false;
             * else if(wiresharkMagicNumber==this.ToUInt32(buffer4, true))
             *  this.littleEndian=true;
             * else
             *  throw new System.IO.InvalidDataException("The stream is not a PCAP file. Magic number is "+this.ToUInt32(buffer4, false).ToString("X2")+" or "+this.ToUInt32(buffer4, true).ToString("X2")+" but should be "+wiresharkMagicNumber.ToString("X2")+".");
             *
             *
             * this.pcapStream.Read(buffer2, 0, 2);
             * this.majorVersionNumber=ToUInt16(buffer2, this.littleEndian);
             *
             * this.pcapStream.Read(buffer2, 0, 2);
             * this.minorVersionNumber=ToUInt16(buffer2, this.littleEndian);
             *
             * this.pcapStream.Read(buffer4, 0, 4);
             * this.timezoneOffsetSeconds=(int)ToUInt32(buffer4, this.littleEndian);
             *
             * this.pcapStream.Read(buffer4, 0, 4);
             *
             * this.pcapStream.Read(buffer4, 0, 4);
             * this.maximumPacketSize=ToUInt32(buffer4, this.littleEndian);
             *
             * this.pcapStream.Read(buffer4, 0, 4); //offset = 20 = 0x14
             * this.dataLinkType=(DataLinkType)ToUInt32(buffer4, this.littleEndian);
             */
            //this.pcapHeaderSize = this.pcapStream.Position;

            this.backgroundStreamReader = new System.ComponentModel.BackgroundWorker();
            this.backgroundStreamReader.WorkerSupportsCancellation = true;
            this.packetQueue       = new Queue <PcapFrame>(this.packetQueueSize);
            this.enqueuedByteCount = 0;
            this.dequeuedByteCount = 0;
            if (startBackgroundWorkers)
            {
                this.StartBackgroundWorkers();
            }
        }
Example #11
0
        public static IEnumerable <(GraphNode node, int distance)> FindPaths(GraphNode startGraphNode)
        {
            var queue   = new System.Collections.Generic.Queue <GraphNode>();
            var visited = new HashSet <GraphNode>();
            var result  = new List <(GraphNode, int)>();

            queue.Enqueue(startGraphNode);
            var distance = 1;

            while (queue.Count != 0)
            {
                var nodes = queue.ToList();
                queue.Clear();
                foreach (var node in nodes)
                {
                    visited.Add(node);
                    foreach (var incidentNode in node.Edges.Where(x => !visited.Contains(x)))
                    {
                        queue.Enqueue(incidentNode);
                        result.Add((incidentNode, distance));
                    }
                }

                distance++;
            }

            return(result);
        }
Example #12
0
 public Kitchen(Cargo _cargo)
 {
     cargo  = _cargo;
     orders = new System.Collections.Generic.Queue <KitchenPizza>(32);
     staff  = new List <KitchenStaff>(6);
     cooked = new List <KitchenPizza>(staff.Capacity);
 }
        public MainForm()
        {
            InitializeComponent();

            this.MouseDown += MainForm_MouseDown;
            this.chart.MouseDown += MainForm_MouseDown;
            this.FormClosing += Form1_FormClosing;

            string[] availableComPorts = SerialPort.GetPortNames();

            comPortListBox.Items.AddRange(availableComPorts);

            #region Minimize/Close Button Behavior Callback Registration

            minBox.MouseEnter += minBox_MouseEnter;
            minBox.MouseLeave += minBox_MouseLeave;
            minBox.MouseDown += minBox_MouseDown;
            minBox.MouseUp += minBox_MouseUp;
            minBox.MouseClick += minBox_MouseClick;

            closeBox.MouseEnter += closeBox_MouseEnter;
            closeBox.MouseLeave += closeBox_MouseLeave;
            closeBox.MouseDown += closeBox_MouseDown;
            closeBox.MouseUp += closeBox_MouseUp;
            closeBox.MouseClick += closeBox_MouseClick;

            #endregion

            comPortDetectorThread = new Thread(new ThreadStart(pollComPorts));
            comPortDetectorThread.Start();

            commandQueue = new System.Collections.Generic.Queue<Tuple<Command,double>>();
        }
Example #14
0
        public IEnumerable <IEnumerable <int> > TraverseByLevel()
        {
            var nodesQueue = new System.Collections.Generic.Queue <Node>();

            nodesQueue.Enqueue(_root);

            while (nodesQueue.Count > 0)
            {
                var currentLevelNodes = nodesQueue.Count;
                var currentLevel      = new List <int>();
                for (var index = 0; index < currentLevelNodes; ++index)
                {
                    var node = nodesQueue.Dequeue();
                    currentLevel.Add(node.Value);
                    if (node.Left != null)
                    {
                        nodesQueue.Enqueue(node.Left);
                    }
                    if (node.Right != null)
                    {
                        nodesQueue.Enqueue(node.Right);
                    }
                }

                yield return(currentLevel);
            }
        }
Example #15
0
        // level order
        public string BreadthFirstSearch(int startValue)
        {
            bool[] visited = new bool[vertices];
            System.Collections.Generic.Queue <GraphNode> queue = new System.Collections.Generic.Queue <GraphNode>();
            StringBuilder sb = new StringBuilder();

            int index = startValue;

            queue.Enqueue(adjLists[index]);
            visited[index] = true;

            while (queue.Count > 0)
            {
                var graphNode = queue.Dequeue();
                sb.Append(graphNode.value + " ");

                // print value graphNode.value
                for (int i = 0; i < graphNode.Edges.Count; i++)
                {
                    int adjIndex = graphNode.Edges[i];
                    if (!visited[adjIndex])
                    {
                        visited[adjIndex] = true;
                        queue.Enqueue(adjLists[adjIndex]);
                    }
                }
            }

            return(sb.ToString());
        }
Example #16
0
 public CallCenter(int numberOfEmployees)
 {
     this.FreeDirectors   = new System.Collections.Generic.Queue <Director>();
     this.FreeManagers    = new System.Collections.Generic.Queue <Manager>();
     this.FreeRespondents = new System.Collections.Generic.Queue <Respondent>();
     this.OncallEmployee  = new Employee[numberOfEmployees];
 }
Example #17
0
        public SkeletonIDMap(int NumSkeletonBones)
        {
            this.NumSkeletonBones = NumSkeletonBones;

            // Enqueue all valid ids
            this.free_id_queue = new System.Collections.Generic.Queue <int>();
            this._skeletons    = new HashSet <int>();
        }
Example #18
0
        public Logger(int Sample)
        {
            m_Sample = Sample;

            m_Commands = new System.Collections.Generic.Queue <Command>();

            m_Lines = new List <Line>();
        }
Example #19
0
 public void Initialize()
 {
     m_dicAssetBundleDatas = new Dictionary <string, CMAssetBundle>();
     waitingABPath         = new Queue <string>();
     asynLoadingAbDic      = new Dictionary <string, AssetBundleCreateRequest>();
     InitAssetsDependenceData();
     InitManifest();
 }
Example #20
0
        private static void BstTest()
        {
            System.Collections.Generic.Queue <Context> q = new System.Collections.Generic.Queue <Context>();
            BstBinaryTree <Context> bst = new BstBinaryTree <Context>();
            Random random = new Random();

            for (int i = 0; i < 1000; i++)
            {
                bst.Add(new Context(random.Next(10000), random.Next(10000) + "tag"));
            }

            bst.Add(new Context(555, "icxl add"));
            bst.Add(new Context(687, "icxl add"));

            // bst.remove(new Context(555, "icxl add"));

            Console.WriteLine("-----------------------------------------");

            var b     = bst.contains(new Context(555, "icxl add"));
            int count = bst.GetSize();

            for (int i = 0; i < count; i++)
            {
                q.Enqueue(bst.removeMax());
            }

            int qCount = q.Count;

            for (int i = 0; i < qCount; i++)
            {
                var obj = q.Dequeue();
                Console.WriteLine(obj.Value);
            }


            Console.WriteLine("555是否存在:" + b);


            // BstBinaryTree<int> bst = new BstBinaryTree<int>();
            // // int[] number = {5,3,9,8,4,2,10};
            // int[] number = {5,3,6,2,4,8};
            // for (int i = 0; i < number.Length; i++)
            // {
            //     bst.Add(number[i]);
            // }
            //
            //
            // bst.levelOrder();
            // bst.preOrder();
            // Console.WriteLine("");
            // bst.preOrderNR();
            // Console.WriteLine("");
            // Console.WriteLine(bst);
            // Console.WriteLine("");
            // bst.inOrder();
            // Console.WriteLine("");
            // bst.postOrder();
        }
Example #21
0
 public WiringOperator(ISocketSendable SocketSendable, ISocketRecevieable SocketRecevieable, bool listener)
 {
     m_Logger            = new Logger(100);
     m_Lines             = new Dictionary <EndPoint, Line>();
     m_Exits             = new System.Collections.Generic.Queue <Line>();
     m_SocketSendable    = SocketSendable;
     m_SocketRecevieable = SocketRecevieable;
     _Listener           = listener;
 }
Example #22
0
        public PcapFileReader(string filename, int packetQueueSize, ReadCompletedCallback captureCompleteCallback)
        {
            this.filename   = filename;
            this.fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read, 262144, FileOptions.SequentialScan);

            this.packetQueueSize       = packetQueueSize;
            this.readCompletedCallback = captureCompleteCallback;

            byte[] buffer4 = new byte[4]; //32 bits is suitable
            byte[] buffer2 = new byte[2]; //16 bits is sometimes needed
            uint   wiresharkMagicNumber = 0xa1b2c3d4;

            //Section Header Block (mandatory)

            fileStream.Read(buffer4, 0, 4);

            if (wiresharkMagicNumber == this.ToUInt32(buffer4, false))
            {
                this.littleEndian = false;
            }
            else if (wiresharkMagicNumber == this.ToUInt32(buffer4, true))
            {
                this.littleEndian = true;
            }
            else
            {
                throw new System.IO.InvalidDataException("The file " + filename + " is not a PCAP file. Magic number is " + this.ToUInt32(buffer4, false).ToString("X2") + " or " + this.ToUInt32(buffer4, true).ToString("X2") + " but should be " + wiresharkMagicNumber.ToString("X2") + ".");
            }

            /* major version number */
            fileStream.Read(buffer2, 0, 2);
            this.majorVersionNumber = ToUInt16(buffer2, this.littleEndian);
            /* minor version number */
            fileStream.Read(buffer2, 0, 2);
            this.minorVersionNumber = ToUInt16(buffer2, this.littleEndian);
            /* GMT to local correction */
            fileStream.Read(buffer4, 0, 4);
            this.timezoneOffsetSeconds = (int)ToUInt32(buffer4, this.littleEndian);
            /* accuracy of timestamps */
            fileStream.Read(buffer4, 0, 4);
            /* max length of captured packets, in octets */
            fileStream.Read(buffer4, 0, 4);
            this.maximumPacketSize = ToUInt32(buffer4, this.littleEndian);
            /* data link type */
            fileStream.Read(buffer4, 0, 4);
            this.dataLinkType = (DataLinkType)ToUInt32(buffer4, this.littleEndian);

            this.pcapHeaderSize = fileStream.Position;

            this.backgroundFileReader = new System.ComponentModel.BackgroundWorker();
            this.packetQueue          = new Queue <PcapPacket>(this.packetQueueSize);
            this.enqueuedByteCount    = 0;
            this.dequeuedByteCount    = 0;

            this.StartBackgroundWorkers();
        }
Example #23
0
 public Peer(System.Net.Sockets.Socket client)
 {
     _Socket = client;
     _SoulProvider = new Remoting.Soul.SoulProvider(this, this);
     _Responses = new Queue<Remoting.Package>();
     _Requests = new Queue<Request>();
     _ReadMachine = new Game.StageMachine();
     _WriteMachine = new Game.StageMachine();
     _Enable = true;
 }
Example #24
0
 static Keyboard()
 {
     instance = null;
     thisLock = new Object();
     keymapLock = new Object();
     buffer = new Queue<Action>();
     iglock = new System.Object();
     sw = new System.Diagnostics.Stopwatch();
     isPressed = new Dictionary<System.Windows.Forms.Keys, bool>();
 }
Example #25
0
    void make_log_queue()
    {
        string path = System.IO.Path.Combine(System.IO.Path.GetFullPath("."), "run.log");

        Debug.Log("rezolve log is " + path);
        log_write = new System.IO.StreamWriter(
            path);
        log_queue = new System.Collections.Generic.Queue <string>();
        errorlock = new object();
    }
        public override void Watch(ref System.Collections.Generic.Queue <string> queue)
        {
            System.Collections.Generic.Queue <string> q = queue;
            Action action = () =>
            {
                Console.WriteLine($"Количество: {q.Count} ");
            };

            action();
        }
Example #27
0
        public void Dispose()
        {
            this.isDisposed = true;
            if (this.pool != null)
            {
                this.pool.Dispose();
            }

            this.queue = null;
            this.pool  = null;
        }
        public void Dispose()
        {
            _readThread.Abort();
            _readThread.Join();
            _readThread = null;

            ClearQueue();
            _queue = null;

            _frameConverter = null;
        }
        public override ValidationError ValidateActivityChange(Activity activity, ActivityChangeAction action)
        {
            if (activity == null)
            {
                throw new ArgumentNullException("activity");
            }

            if (action == null)
            {
                throw new ArgumentNullException("action");
            }

            AddedActivityAction addedAction = action as AddedActivityAction;

            if (addedAction != null)
            {
                //Check existence of nested PersistOnClose/ICompensatable/SupportsTransaction nested anywhere
                //in the added activity branch
                System.Collections.Generic.Queue <Activity> childrenQueue = new System.Collections.Generic.Queue <Activity>();
                childrenQueue.Enqueue(addedAction.AddedActivity);

                while (childrenQueue.Count != 0)
                {
                    Activity childActivity = childrenQueue.Dequeue();

                    if (childActivity.SupportsTransaction)
                    {
                        return(new ValidationError(SR.GetString(SR.Error_AtomicScopeNestedInNonLRT), ErrorNumbers.Error_AtomicScopeNestedInNonLRT));
                    }

                    if (childActivity.PersistOnClose)
                    {
                        return(new ValidationError(SR.GetString(SR.Error_NestedPersistOnClose, activity.QualifiedName), ErrorNumbers.Error_NestedPersistOnClose));
                    }

                    if (childActivity is ICompensatableActivity)
                    {
                        return(new ValidationError(SR.GetString(SR.Error_NestedCompensatableActivity, activity.QualifiedName), ErrorNumbers.Error_NestedCompensatableActivity));
                    }

                    CompositeActivity compositeActivity = childActivity as CompositeActivity;

                    if (compositeActivity != null)
                    {
                        foreach (Activity grandChild in compositeActivity.EnabledActivities)
                        {
                            childrenQueue.Enqueue(grandChild);
                        }
                    }
                }
            }
            return(base.ValidateActivityChange(activity, action));
        }
Example #30
0
 private void IdleStop()
 {
     _Idling = false;
     IdlePause();
     if (_IdleEvents != null)
     {
         _IdleEvents.Abort();
         _IdleEvents    = null;
         _IdleQueue     = null;
         _IdleEventsMre = null;
     }
 }
Example #31
0
        private void Form1_Load(object sender, EventArgs e)
        {
            m_logQueue = new Queue <string>();
            m_LogTimer = new System.Threading.Timer(WriteToLocal, null, 0, System.Threading.Timeout.Infinite);

            if (!System.IO.Directory.Exists(m_LogFolder))
            {
                System.IO.Directory.CreateDirectory(m_LogFolder);
            }


            mouseHook.MouseMove  += new MouseEventHandler(mouseHook_MouseMove);
            mouseHook.MouseDown  += new MouseEventHandler(mouseHook_MouseDown);
            mouseHook.MouseUp    += new MouseEventHandler(mouseHook_MouseUp);
            mouseHook.MouseWheel += new MouseEventHandler(mouseHook_MouseWheel);

            //keyboardHook.KeyDown += new KeyEventHandler(keyboardHook_KeyDown);
            keyboardHook.KeyUp += new KeyEventHandler(keyboardHook_KeyUp);
            //keyboardHook.KeyPress += new KeyPressEventHandler(keyboardHook_KeyPress);

            mouseHook.Start();
            keyboardHook.Start();

            SetXYLabel(MouseSimulator.X, MouseSimulator.Y);

            listView2.Columns.Add(new ColumnHeader()
            {
                Text = "A"
            });
            listView2.Columns.Add(new ColumnHeader()
            {
                Text = "B"
            });
            listView2.Columns.Add(new ColumnHeader()
            {
                Text = "C"
            });
            listView2.Columns.Add(new ColumnHeader()
            {
                Text = "D"
            });
            listView2.Columns.Add(new ColumnHeader()
            {
                Text = "E"
            });
            listView2.Columns.Add(new ColumnHeader()
            {
                Text = "F"
            });

            this.ShowInTaskbar = false;
        }
Example #32
0
        private void ReaddChildNodes(Node removedNode)
        {
            // Leaf Check
            if (removedNode.LeftChild == null && removedNode.RightChild == null)
            {
                return;
            }

            // The folllowing code might seem a little redundant but we're using
            // 2 queues so we can add the child nodes back in, in (more or less)
            // the same order they were added in the first place
            var nodesToReadd = new System.Collections.Generic.Queue <Node>();

            var nodesToReaddQueue = new System.Collections.Generic.Queue <Node>();

            if (removedNode.LeftChild != null)
            {
                nodesToReaddQueue.Enqueue(removedNode.LeftChild);
            }

            if (removedNode.RightChild != null)
            {
                nodesToReaddQueue.Enqueue(removedNode.RightChild);
            }

            while (nodesToReaddQueue.Count > 0)
            {
                Node nodeToReadd = nodesToReaddQueue.Dequeue();

                nodesToReadd.Enqueue(nodeToReadd);

                if (nodeToReadd.LeftChild != null)
                {
                    nodesToReaddQueue.Enqueue(nodeToReadd.LeftChild);
                    nodeToReadd.LeftChild = null;
                }

                if (nodeToReadd.RightChild != null)
                {
                    nodesToReaddQueue.Enqueue(nodeToReadd.RightChild);
                    nodeToReadd.RightChild = null;
                }
            }

            while (nodesToReadd.Count > 0)
            {
                var nodeToReadd = nodesToReadd.Dequeue();

                this._count--;
                Add(this._locate(nodeToReadd.Value), nodeToReadd.Value);
            }
        }
Example #33
0
            private async Task Spin()
            {
                var chars = new System.Collections.Generic.Queue <string>(new[] { "|", "/", "-", "\\" });

                while (true)
                {
                    var chr = chars.Dequeue();
                    chars.Enqueue(chr);
                    Console.Write("{" + chr + "}");
                    Console.SetCursorPosition(Console.CursorLeft - 3, Console.CursorTop);
                    await Task.Delay(100, _token);
                }
            }
Example #34
0
        public Levels(MapPrototype map_prototype, Squad squad)
        {
            _Position = 0.0f;
            _Id = Guid.NewGuid();
            this._MapPrototype = map_prototype;
            _Stations = new Queue<Station>(_MapPrototype.Stations);
            _StageMachine = new Regulus.Utility.StageMachine();

            _Platoon = new Platoon(squad);
            _Platoon.EmptyEvent += () => { ReleaseEvent(); };

            _Platoons = new Utility.Updater(); ;
        }
 /// <summary>
 /// return edges in mst
 /// </summary>
 /// <returns></returns>
 public System.Collections.Generic.Queue <Edge> Edges()
 {
     System.Collections.Generic.Queue <Edge> mst = new System.Collections.Generic.Queue <Edge>();
     for (int v = 0; v < edgeTo.Length; v++)
     {
         Edge e = edgeTo[v];
         if (e != null)
         {
             mst.Enqueue(e);
         }
     }
     return(mst);
 }
 public ProgressForm(UploadFile[] files, string url, string user, string password)
 {
     InitializeComponent();
     this.files = files;
     this.url = url;
     this.user = user;
     this.password = password;
     total = 0;
     currentBytes = 0;
     ques = new Queue<UploadFile>(files);
     uploader = UploaderFactory.CreateInstance();
     currentPercent = 0;
 }
Example #37
0
        /// <summary>
        /// Initializes a new instance of the Presenter class.
        /// </summary>
        /// <param name="screen"></param>
        /// <param name="uploadWatcher"></param>
        public Presenter(IImageScreen screen,
            ImageUploadWatcher uploadWatcher,
            IIconExtractor extractor)
        {
            this.screen = screen;
            this.uploadWatcher = uploadWatcher;
            this.extractor = extractor;

            this.screen.Observer = this;
            this.worker = new System.ComponentModel.BackgroundWorker();
            worker.WorkerReportsProgress = true;
            worker.RunWorkerCompleted += worker_RunWorkerCompleted;
            worker.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(worker_ProgressChanged);
            worker.DoWork += worker_DoWork;

            imgsQueue = new Queue<ImageDetail[]>();

            this.uploadWatcher.ImagesUploaded += uploadWatcher_ImagesUploaded;
        }
Example #38
0
        private void IdleResume()
        {
            if (_Idle != null || !_Idling) return;

              var response = SendCommandGetResponse(GetTag() + "IDLE");
              response = response.Substring(response.IndexOf(" ")).Trim();
              if (!response.TrimStart().StartsWith("idling", StringComparison.OrdinalIgnoreCase))
            throw new Exception(response);

              if (_IdleEvents == null) {
            _IdleQueue = new Queue<string>();
            _IdleEventsMre = new AutoResetEvent(false);
            _IdleEvents = new Thread(WatchIdleQueue);
            _IdleEvents.Start();
              }
              _Idle = new Thread(ReceiveData);
              _Idle.Start();
        }
		private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
		{
			BackgroundWorker bw = sender as BackgroundWorker;
			List<ListViewItem> items = new List<ListViewItem>(chunk);
			if (supportedInterface != Guid.Empty)
				guidsToValidate = new Queue<Guid>();
			loading = true;
			using (RegistryKey k = Registry.ClassesRoot.OpenSubKey("CLSID", false))
			{
				try
				{
					string[] l = k.GetSubKeyNames();
					for (int i = 0; i < l.Length; i++)
					{
						if (bw.CancellationPending)
						{
							e.Cancel = true;
							break;
						}
						int mod = i % chunk;
						if (i != 0 && mod == 0)
						{
							bw.ReportProgress(i * 100 / (l.Length - 1), items.ToArray());
							items.Clear();
						}

						if (l[i].Length == 38 && l[i][0] == '{')
						{
							try
							{
								ListViewItem lvi = null;
								using (RegistryKey k2 = k.OpenSubKey(l[i]))
								{
									if (ServerType == SupportedServers.OutOfProcess)
									{
										using (RegistryKey k3 = k2.OpenSubKey("LocalServer32", false))
											if (k3 != null)
												lvi = new ListViewItem(new string[] { l[i].ToLower(), k2.GetValue(null) as string, k3.GetValue(null) as string });
									}
									else
									{
										using (RegistryKey k3 = k2.OpenSubKey("InProcServer32", false))
											if (k3 != null)
												lvi = new ListViewItem(new string[] { l[i].ToLower(), k2.GetValue(null) as string, k3.GetValue(null) as string });
											else
												lvi = new ListViewItem(new string[] { l[i].ToLower(), k2.GetValue(null) as string, null });
									}
								}

								if (lvi != null)
								{
									lvi.Name = lvi.SubItems[0].Text;
									items.Add(lvi);
									if (guidsToValidate != null)
										guidsToValidate.Enqueue(new Guid(l[i]));
								}
							}
							catch { }
						}

						if (i == l.Length - 1)
						{
							bw.ReportProgress(i * 100 / (l.Length - 1), items.ToArray());
						}
					}
				}
				catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.ToString()); }
			}
		}
Example #40
0
 /// <summary>
 /// Swaps the <strong>orderedTouchEvents</strong> and the <strong>orderedTouchEventsBackbuffer</strong>.  This is thread-safe.
 /// </summary>
 private void Swap()
 {
     // Only lock long enough to swap the collections.
     lock (swapLock)
     {
         Queue<TouchTargetEvent> newFrontBuffer = this.orderedTouchEventsBackbuffer;
         orderedTouchEventsBackbuffer = this.orderedTouchEvents;
         this.orderedTouchEvents = newFrontBuffer;
     }
 }
Example #41
0
        bool InternalExecute(DateTime now) {
            Execution execution = null;
            bool finished = false;
            List<Execution> operated = new List<Execution>();
            Queue<Execution> suspended = new Queue<Execution>();
            List<Guid> actived = new List<Guid>();
            while ((execution = _actived.Dequeue()) != null) {
                #region 试图运行一个 execution
                #region 运行前检查状态
                //1在Proccess挂起期间,修改了执行状态,就不再执行了
                if (execution.Info.ExecutionState.IsInactive()) continue;
                if (execution.Info.ExecutionState == ExecutionStates.Suspended) {
                    #region 挂起状态,就看时间到了没有,没到执行时间就进去挂起队列
                    this.SyncObject.EnterWriteLock();
                    try
                    {
                        if (execution.Info.ResumeTime == null)
                        {
                        
                            execution.Info.ExecutionState = ExecutionStates.Inactive;
                            operated.Add(execution);
                            continue;
                        
                        
                        }
                        else if(execution.Info.ResumeTime.Value>now){
                            suspended.Enqueue(execution);
                            actived.Add(execution.Info.Id);
                            continue;
                        }
                    }
                    finally
                    {
                        this.SyncObject.ExitWriteLock();
                    }
                    #endregion 
                }
                #endregion 

                var result = execution.Execute(now);

                #region 运行后处理运行结果
                this.SyncObject.EnterWriteLock();
                try {
                    if (result.ResumeTime != null)
                    {
                        #region 结果表明该活动正在运行,或者挂起
                        if (result.ResumeTime.Value == DateTime.MinValue)
                        {
                            #region 正在运行,进入挂起队列
                            execution.Info.ExecutionState = ExecutionStates.Running;
                            execution.Info.ResumeTime = null;
                            suspended.Enqueue(execution);
                            actived.Add(execution.Info.Id);
                            operated.Add(execution);
                            continue;
                            #endregion
                        }
                        else
                        {
                            #region 挂起
                            execution.Info.ExecutionState = ExecutionStates.Suspended;
                            //指定了重执行时间,继续进去队列
                            if (result.ResumeTime.Value != DateTime.MaxValue)
                            {
                                execution.Info.ResumeTime = result.ResumeTime;
                                suspended.Enqueue(execution);
                                actived.Add(execution.Info.Id);
                            }
                            else
                            {
                                //没指定重执行时间,无期限挂起,不再进入队列
                                execution.Info.ExecutionState = ExecutionStates.Inactive;
                            }
                            operated.Add(execution);
                            #endregion
                        }
                        #endregion
                    }
                    else
                    {
                        #region 运行已经有了结果,不再执行,并推入nexts到执行队列中
                        execution.Info.Result = result.Result;
                        execution.Info.ExecutionState = ExecutionStates.Completed;
                        //如果是finishactivity完成了,该过程全部结束
                        if (execution.Info.Id != _finishActivityId)
                        {
                            EnqueueNexts(execution, this._actived, operated);
                        }
                        else
                        {
                            finished = true;
                        }
                        #endregion
                    }
                } finally {
                    this.SyncObject.ExitWriteLock();
                }
                #endregion
                #endregion
            }
            this.SyncObject.EnterWriteLock();
            try {
                _actived = suspended;
                this.Info.Actived = actived;
                this.Info.Finished = finished;
                this.InternalStore(operated);
            } finally {
                this.SyncObject.ExitWriteLock();
            }

            
            return finished;
        }
        private void _InitializePoolOfWorkItems()
        {
            _toWrite = new Queue<int>();
            _toFill = new Queue<int>();
            _pool = new System.Collections.Generic.List<WorkItem>();
            int nTasks = BufferPairsPerCore * Environment.ProcessorCount;
            nTasks = Math.Min(nTasks, _maxBufferPairs);
            for(int i=0; i < nTasks; i++)
            {
                _pool.Add(new WorkItem(_bufferSize, _compressLevel, Strategy, i));
                _toFill.Enqueue(i);
            }

            _newlyCompressedBlob = new AutoResetEvent(false);
            _runningCrc = new CRC32();
            _currentlyFilling = -1;
            _lastFilled = -1;
            _lastWritten = -1;
            _latestCompressed = -1;
        }
Example #43
0
 public Snake()
 {
     _Waits = new Queue<SnakeBody>();
     _Bodys = new LinkedList<SnakeBody>();
     _Bodys.AddLast(new SnakeBody());
 }
 public Queue(System.Collections.Generic.Queue<int> queue)
 {
     this.queue = queue;
 }
Example #45
0
        public Processor()
        {
            ClockRatekHz = 100; // 100 kHz
            _RAM = new ushort[RAMSize];
            _Register = new ushort[RegisterCount];
            _IntQueue = new Queue<ushort>();

              ClearMemory();
            Reset();
            _RAM[0] = 0x841a;
               // _RAM[1] = 0x8419;
            //_RAM[2] = 0x1026;

            Actions = new Dictionary<ushort, Operation>
                          {
                              {0x01, opSET},
                              {0x02, opADD},
                              {0x03, opSUB},
                              {0x04, opMUL},
                              {0x05, opMLI},
                              {0x06, opDIV},
                              {0x07, opDVI},
                              {0x08, opMOD},
                            //  {0x09, opMDI},
                              {0x0a, opAND},
                              {0x0b, opBOR},
                              {0x0c, opXOR},
                              {0x0d, opSHR},
                              {0x0e, opASR},
                              {0x0f, opSHL},
                               {0x10, opIFB},
                              {0x11, opIFC},
                              {0x12, opIFE},
                              {0x13, opIFN},
                              {0x14, opIFG},
                              {0x15, opIFA},
                              {0x16, opIFL},
                              {0x17, opIFU},
                              //{0x18, opREAD},
                              //{0x19, opRESERVED},

                              //{0x1a, opADX},
                              {0x1a, opREAD},

                              {0x1b, opSBX},
                              //{0x1c, opRESERVED},
                              //{0x1d, opRESERVED},
                              {0x1e, opSTI},
                              {0x1f, opSTD}

                          };
        }
        private void InitializePoolOfWorkItems()
        {
            this.toWrite = new Queue<int>();
            this.toFill = new Queue<int>();
            this.pool = new System.Collections.Generic.List<WorkItem>();
            int nWorkers = BufferPairsPerCore * Environment.ProcessorCount;
            nWorkers = Math.Min(nWorkers, this.MaxWorkers);
            for(int i=0; i < nWorkers; i++)
            {
                this.pool.Add(new WorkItem(i, this.blockSize100k));
                this.toFill.Enqueue(i);
            }

            this.newlyCompressedBlob = new AutoResetEvent(false);
            this.currentlyFilling = -1;
            this.lastFilled = -1;
            this.lastWritten = -1;
            this.latestCompressed = -1;
        }
        public override ValidationError ValidateActivityChange(Activity activity, ActivityChangeAction action)
        {
            if (activity == null)
                throw new ArgumentNullException("activity");

            if (action == null)
                throw new ArgumentNullException("action");

            AddedActivityAction addedAction = action as AddedActivityAction;

            if (addedAction != null)
            {
                //Check existence of nested PersistOnClose/ICompensatable/SupportsTransaction nested anywhere
                //in the added activity branch
                System.Collections.Generic.Queue<Activity> childrenQueue = new System.Collections.Generic.Queue<Activity>();
                childrenQueue.Enqueue(addedAction.AddedActivity);

                while (childrenQueue.Count != 0)
                {
                    Activity childActivity = childrenQueue.Dequeue();

                    if (childActivity.SupportsTransaction)
                        return new ValidationError(SR.GetString(SR.Error_AtomicScopeNestedInNonLRT), ErrorNumbers.Error_AtomicScopeNestedInNonLRT);

                    if (childActivity.PersistOnClose)
                        return new ValidationError(SR.GetString(SR.Error_NestedPersistOnClose, activity.QualifiedName), ErrorNumbers.Error_NestedPersistOnClose);

                    if (childActivity is ICompensatableActivity)
                        return new ValidationError(SR.GetString(SR.Error_NestedCompensatableActivity, activity.QualifiedName), ErrorNumbers.Error_NestedCompensatableActivity);

                    CompositeActivity compositeActivity = childActivity as CompositeActivity;

                    if (compositeActivity != null)
                    {
                        foreach (Activity grandChild in compositeActivity.EnabledActivities)
                        {
                            childrenQueue.Enqueue(grandChild);
                        }
                    }
                }
            }
            return base.ValidateActivityChange(activity, action);
        }
Example #48
0
 // Use this for initialization
 void Awake()
 {
     chatLines = new Queue<string>(maxChatLines);
     chatWindow = GetComponent<Text>();
 }
Example #49
0
 private void IdleStop()
 {
     _Idling = false;
       IdlePause();
       if (_IdleEvents != null) {
     _IdleEvents.Abort();
     _IdleEvents = null;
     _IdleQueue = null;
     _IdleEventsMre = null;
       }
 }
Example #50
0
 public e16vm()
 {
     ClockRatekHz = 100; // 100 kHz
     _RAM = new ushort[RAMSize];
     _Register = new ushort[RegisterCount];
     _IntQueue = new Queue<ushort>();
     _Hardware = new List<Ie16Hardware>();
     ClearMemory();
     Reset();
 }
 //default constructor
 public Queue()
 {
     this.queue = new System.Collections.Generic.Queue<int>();
 }