Example #1
0
        public void ReturnToPool(WebDriverItem webDriver)
        {
            CheckRunning();

            if (_webDriverList.Contains(webDriver))
            {
                _innerQueue.Enqueue(webDriver);
            }
        }
Example #2
0
        /// <summary>
        /// 지정된 키에 해당하는 값을 반환합니다.
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public override TValue GetValue(TKey key)
        {
            if (IsDebugEnabled)
            {
                log.Debug("Get Value... key=[{0}]", key);
            }

            if (_queue.Contains(key) == false)
            {
                _queue.Add(key);
            }

            return(base.GetValue(key));
        }
        public SubTypeConverter()
        {
            // todo limit to particular assemblies?

            // basic do-once
            if (TypesWithAttributes.Count != 0)
            {
                return;
            }

            // Find types with attributes added
            foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                foreach (var type in assembly.GetTypes())
                {
                    if (type.GetCustomAttributes(typeof(SubTypeAttribute), true).Length > 0)
                    {
                        TypesWithAttributes.Add(type);
                    }
                }
            }

            // Extract the SubTypeAttribute attributes
            foreach (var item in TypesWithAttributes)
            {
                foreach (var attribute in item.GetCustomAttributes(true).OfType <SubTypeAttribute>())
                {
                    var r = new Relationship(item, attribute.NewType, attribute.PropertyName, attribute.Value);
                    if (Relationships.Contains(r) == false)
                    {
                        Relationships.Add(r);
                    }
                }
            }
        }
        private IEnumerable <(MethodInfo, ICommunicationBase)> GetMethodsInner(string funcName, string toModule, Type messageType, Type resultType)
        {
            var modules = _comunications.Where(x => InModule(funcName, x.Name, toModule));

            foreach (var module in modules)
            {
                var @class = module.GetType().Name;
                var key    = $"{funcName}.{@class}.{messageType.Name}";

                if (_notFoundCache.Contains(key))
                {
                    continue;
                }

                if (!_cache.ContainsKey(key))
                {
                    var method = module.GetType().GetMethod(funcName, new[] { messageType, typeof(string) })
                                 ?? module.GetType().GetMethod(funcName, new [] { messageType });
                    if (method?.ReturnParameter != null && (method.ReturnParameter.ParameterType == resultType))
                    {
                        _cache[key] = new KeyValuePair <ICommunicationBase, MethodInfo>(module, method);
                    }
                    else
                    {
                        _notFoundCache.Add(key);
                        continue;
                    }
                }

                yield return(_cache[key].Value, _cache[key].Key);
            }
        }
Example #5
0
        /// <summary>
        /// Remove dupliate words from the word list.
        ///
        /// Note: this isn't used in the final product.
        /// </summary>
        public void executeStep()
        {
            if (ProcessingStarted != null)
            {
                ProcessingStarted(this, new EventArgs());
            }

            //Remove duplicate words...
            while (!_wordListIn.IsCompleted)
            {
                string nextItem = string.Empty;
                bool   hasNext  = _wordListIn.TryTake(out nextItem);
                if (hasNext)
                {
                    //Interal work may be more complex than just this....
                    bool NotInOutQueue = (!_wordListOut.Contains(nextItem));
                    if (NotInOutQueue)
                    {
                        _wordListOut.Add(nextItem);
                    }
                }
            }

            if (ProcessingCompleted != null)
            {
                ProcessingCompleted(this, new EventArgs());
            }
        }
Example #6
0
 public static void AddClient(GameClient client)
 {
     if (!ONLINE_CLIENTS.Contains(client))
     {
         ONLINE_CLIENTS.Add(client);
     }
 }
Example #7
0
        private void Parse(string html)
        {
            var strRef = @"(href|HREF)[]*=[]*[""'][^""'#>]+(jsp|html|aspx)[""']";

            var matches = new Regex(strRef).Matches(html);


            foreach (Match match in matches)
            {
                strRef = match.Value.Substring(match.Value.IndexOf('=') + 1)
                         .Trim('"', '\"', '#', '>');
                if (strRef.Length == 0)
                {
                    continue;
                }
                if (!strRef.StartsWith(startUrl))
                {
                    continue;
                }


                if (!downloadedUrls.Contains(strRef))
                {
                    queue.Enqueue(strRef);
                }
            }
        }
 public bool Contains(ILogMessage item)
 {
     lock (syncObj)
     {
         return(messageCollection.Contains(item));
     }
 }
Example #9
0
 public void Produce(T value)
 {
     if (!m_queue.Contains(value) && !InProgress.Contains(value))
     {
         m_queue.Add(value);
     }
 }
Example #10
0
        public override void Send(SendOrPostCallback continuation, object state)
        {
            var currentThreadId = Thread.CurrentThread.ManagedThreadId;

            if (currentThreadId == targetThreadId)
            {
                if (recursiveCount < 50)
                {
                    recursiveCount++;

                    continuation(state);

                    recursiveCount--;
                    return;
                }
            }

            var continuationinfo = new ContinuationInformation {
                Continuation = continuation, State = state
            };

            queue.Add(continuationinfo);
            while (queue.Contains(continuationinfo))
            {
                Thread.Sleep(1);
            }
        }
Example #11
0
        // Server side handler for the setPreferredSupplierForProduct RPC
        public override async Task <Empty> setPreferredSupplierForProduct(setPreferredSupplierForProductRequest request, ServerCallContext context)
        {
            //var scoped = _serviceProvider.CreateScope();
            //var supplierService = scoped.ServiceProvider.GetRequiredService<SupplierService>();
            //var supplier = supplierService.findById(request.PrefSupplier.Id);
            //var product = supplierService.findProductById(request.ProductReq.Id);
            //supplierService.setPreferredSupplierForProduct(supplier, product, request.ProductReq.Id);
            //return null;

            if (!products.Contains(request.ProductReq))
            {
                throw new UnknownProductException();
            }

            if (!suppliers.Contains(request.PrefSupplier))
            {
                throw new UnknownSupplierException();
            }

            foreach (var product in products)
            {
                if (product.Id == request.ProductReq.Id)
                {
                    lock (myLock)
                    {
                        Task.Run(() =>
                                 product.Preferredsupplier = request.PrefSupplier.Id);
                    }
                    return(await Task.FromResult(new Empty { Info = 1 }));
                }
            }

            return(await Task.FromResult(new Empty { Info = 0 }));
        }
Example #12
0
 public void AppendBuffer(byte[] buffer)
 {
     if (!this.taskAnswerIsRuning)
     {
         return;
     }
     if (reciveQueue.IsAddingCompleted)
     {
         return;
     }
     if (reciveQueue.Count > 4096)
     {
         return;
     }
     foreach (byte[] curBC in reciveQueue)
     {
         // 17位读写标识,不重复添加相同操作类型
         if (curBC[17] == buffer[17])
         {
             return;
         }
     }
     //不重复添加
     if (reciveQueue.Contains(buffer))
     {
         return;
     }
     reciveQueue.Add(buffer);
 }
 public static void addNotification(string message)
 {
     if (!notification.Contains(message))
     {
         notification.Add(message);
     }
 }
Example #14
0
 public void AddBannedIp(string ip)
 {
     if (!BannedIPs.Contains(ip))
     {
         BannedIPs.Add(ip);
     }
 }
        public FswatchFileSystemWatcher(string directory)
        {
            this.process = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName               = "/usr/local/bin/fswatch",
                    Arguments              = "-r .",
                    WorkingDirectory       = directory,
                    RedirectStandardOutput = true,
                    UseShellExecute        = false,
                    CreateNoWindow         = true,
                }
            };
            this.directory = directory;

            process.OutputDataReceived += (sender, e) =>
            {
                if (!string.IsNullOrEmpty(e.Data))
                {
                    lock (changedFiles)
                    {
                        if (!changedFiles.Contains(e.Data))
                        {
                            changedFiles.Add(e.Data);
                        }
                    }
                }
            };
            process.Start();
            process.BeginOutputReadLine();
        }
Example #16
0
 public void Add(T t)
 {
     if (LoadRatesQueue.Contains(t) || t.Equals(_activeItem))
     {
         return;
     }
     AddCore(t);
 }
Example #17
0
        public static bool IsValid(this string Token, int MaskID)
        {
            var    vals = new BlockingCollection <bool>();
            string s    = null;

            if (!TokenString.AvailableMasks.TryGetValue(MaskID, out s))
            {
                return(false);
            }
            if (Token.Length != s.Length)
            {
                return(false);
            }

            var maskbit = s[s.IndexOf('%')] >= 0 ? s[s.IndexOf('%')] : ' ';

            if (maskbit == ' ')
            {
                return(false);
            }

            var r = ' ';
            var f = Token.ToCharArray();

            Parallel.For(0, f.Length - 1, (i, state) => {
                var isvalid = false;

                char[] x = null;
                if (TokenString.Masking.TryGetValue(s[i], out x))
                {
                    isvalid = x.Contains(f[i]);
                }

                if (s[i] == '%')
                {
                    isvalid = f[i] == maskbit;
                    return;
                }

                if (s[i] == '~')
                {
                    r       = r == ' ' ? f[i] : r;
                    isvalid = (r == f[i]);
                }

                isvalid = isvalid ? true : (f[i] == s[i]);

                vals.Add(isvalid);
                if (!isvalid)
                {
                    state.Stop();
                }
            });

            return(vals.Contains(false) ? false : true);
        }
Example #18
0
 public void SortHelp(BlockingCollection <MyTask> tasksCollection)
 {
     while (tasksCollection != null)
     {
         if (tasksCollection.Contains(null))
         {
             break;
         }
         MyTask task = tasksCollection.Take();
         task.GoToSleep();
         writer.WriteLine(task.value);
     }
 }
Example #19
0
        private void DiscoverFiles(string fileName, string filePath)
        {
            lock (_lock)
            {
                if (!_inputQueue.Contains(filePath) && File.Exists(filePath))
                {
                    AddBreakLine();

                    _logger.LogInformation("Found file: {0}", fileName);
                    _inputQueue.Add(filePath);
                }
            }
            var consumer = Task.Run(() => ConsumeNewFile());
        }
Example #20
0
        public bool TryIncreaseCounterAndRequeue(string fileName)
        {
            bool returnvar = false;
            int  i         = 0;

            if (fileList.TryGetValue(fileName, out i))
            {
                returnvar = fileList.TryUpdate(fileName, i + 1, i);
                if (returnvar && !queue.Contains(fileName))
                {
                    queue.Add(fileName);
                }
            }
            return(returnvar);
        }
Example #21
0
 private void RemoveActive(PreparedDownload download)
 {
     lock (active)
     {
         PreparedDownload dl;
         while (active.Contains(download))
         {
             if (active.TryTake(out dl))
             {
                 break;
             }
         }
     }
     ProcessQueue();
 }
Example #22
0
        private void enumAllDevices(Device myDevice, int beforeEnum)
        {
            if (!alreadyHaveDevice.Contains(myDevice.UniqueDeviceName))
            {
                int      newServicesAdded = 0;
                Services myServices       = myDevice.Services;

                foreach (Service myService in myServices)
                {
                    BlockingCollection <Target> nextTargetsToAdd = new BlockingCollection <Target>();
                    nextTargetsToAdd = getServiceInfo(myService);
                    if (nextTargetsToAdd.Count > 0)
                    {
                        foreach (Target nextTargetToAdd in nextTargetsToAdd)
                        {
                            Targets.Add(nextTargetToAdd);
                            targetFoundCount++;
                        }
                        newServicesAdded++;
                    }
                }
                if ((beforeEnum == deviceDoneCount) && (newServicesAdded > 0))
                {
                    deviceDoneCount++;
                    treeUpdateRequired = true;
                }

                if (beforeEnum == deviceDoneCount)
                {
                    deviceTimedOut++;
                    timedOut = String.Format(" ({0} error)", deviceTimedOut);
                    devicesWithError.Add(myDevice.DocumentURL);
                    treeUpdateRequired = true;
                }



                if (myDevice.HasChildren)
                {
                    foreach (Device childDevice in myDevice.Children)
                    {
                        enumAllDevices(childDevice, beforeEnum);
                    }
                }
            }
            enumTextVar = "Enumeration complete";
            alreadyHaveDevice.Add(myDevice.UniqueDeviceName);
        }
Example #23
0
        private bool SendAndWaitForAck(HL7Request hl7Request, ref int ackRetries)
        {
            m_HL7Server.Logger.Info($"Sending {hl7Request.Request.ControlID}");
            GlobalWatch.Restart();

            m_EasyClient.Send(Encoding.ASCII.GetBytes(MLLP.CreateMLLPMessage(hl7Request.Request.Encode())));


            m_HL7Server.Logger.Info($"Sent {hl7Request.Request.ControlID}");

            string logMessage = string.Empty;

            logMessage = $"{hl7Request.Request.MessageID} sent (Ack RETRY) [{m_HL7Protocol.Config.MaxAckRetriesNumber}, {ackRetries}]";

            if (!Protocol.Config.IsAckRequired)
            {
                return(true);
            }

            if (!m_OutgoingRequests.Contains(hl7Request))
            {
                throw new OperationCanceledException("");
            }


            if (hl7Request.RequestCancellationToken.Token.IsCancellationRequested)
            {
                throw new OperationCanceledException(hl7Request.RequestCancellationToken.Token);
            }

            hl7Request.RequestCancellationToken.Token.ThrowIfCancellationRequested();

            m_HL7Server.Logger.Info($"Waiting for ack {hl7Request.Request.ControlID}");
            if (!hl7Request.AckReceivedEvent.Wait(Protocol.Config.AckTimeout, hl7Request.RequestCancellationToken.Token))
            {
                m_HL7Server.Logger.Info($"Ack received: {hl7Request.Request.ControlID}");
                if (ackRetries-- > 0)
                {
                    return(false);
                }
                else
                {
                    throw new HL7InterfaceException($"The message was not acknowledged after a total number of {m_HL7Protocol.Config.MaxAckRetriesNumber} retries");
                }
            }
            return(true);
        }
Example #24
0
 public static void AddRangeIfNotContains <T>(this BlockingCollection <T> collection, IEnumerable <T> items)
 {
     foreach (T t in items)
     {
         try
         {
             if (!collection.Contains(t))
             {
                 collection.Add(t);
             }
         }
         catch (InvalidOperationException)
         {
             break;
         }
     }
 }
Example #25
0
 /// <summary>
 /// 给规约增加任务
 /// </summary>
 /// <param name="task">要添加的任务。</param>
 internal void AddTask(ConnectionTask task)
 {
     if (task == null)
     {
         return;
     }
     lock (taskListBlocking)
     {
         if (!taskListBlocking.Contains(task))
         {
             if (task.GetRelatedProtocol() == null)
             {
                 task.SetRelatedProtocol(this.relatedProtocol);
             }
             taskListBlocking.Add(task, task.cancellationToken);
             //((EventWaitHandle)this.relatedProtocol.protocolEvents[(int)ProtocolEvents.TaskArrived]).Set();
             string LogMsg = string.Format("协议“{0}”增加了一个“{1}”任务。", "未定义协议名称", task.Name);
         }
     }
 }
Example #26
0
        /// <summary>
        /// Once the stop word list is 100% completes (thread is blocked until then) this
        /// will go through the wordlist and remove the stop word. They are removed by not
        /// being added to the 'out' list.
        ///
        /// Design: Consider removing the Suspending of the event since we have a blocking queue?
        /// </summary>
        public void executeStep()
        {
            if (ProcessingStarted != null)
            {
                ProcessingStarted(this, new EventArgs());
            }

            //First this MUST wait for _stopWordList to be complete. No choice there.

            if (_stopWordList.IsAddingCompleted)
            {
                while (!_wordListIn.IsCompleted)
                {
                    string nextItem = _wordListIn.Take();
                    if (!_stopWordList.Contains(nextItem))
                    {
                        _wordListOut.Add(nextItem);
                    }
                }

                if (ProcessingCompleted != null)
                {
                    ProcessingCompleted(this, new EventArgs());
                }
            }
            else
            {
                if (SuspendProcessing != null)
                {
                    SuspendRequestEventArgs arg = new SuspendRequestEventArgs();
                    arg.SuspendTimeMillaSeconds = 3600 / 16; //4 seconds
                    SuspendProcessing(this, arg);
                }
                else
                {
                    throw new Exception("Need to suspend but there is no method of restarting the thread");
                }
            }
        }
Example #27
0
        private async Task ProcessQueueAsync()
        {
            var tasks = new List <Task>();

            _ctsCancel = new CancellationTokenSource();
            _ctCancel  = _ctsCancel.Token;
            RaisePropertyChanged(nameof(this.IsBusy));

            while (!_ctCancel.IsCancellationRequested)
            {
                IQueueable item;
                if (!_queueList.TryTake(out item))
                {
                    break;
                }

                if (!item.IsQueued)
                {
                    continue;
                }
                _itemsProcessing.Add(item);
                Task t = Task.Run(async() =>
                {
                    try
                    {
                        await _semaphore.WaitAsync(_ctCancel);
                        if (item.IsQueued && !_ctCancel.IsCancellationRequested)
                        {
                            await item.StartAsync();
                        }
                        _semaphore.Release();
                    }
                    catch (OperationCanceledException)
                    {
                        return;
                    }
                });
                tasks.Add(t);
            }

            await Task.WhenAll(tasks.ToArray());

            if (_ctCancel.IsCancellationRequested)
            {
                var newList = new BlockingCollection <IQueueable>();
                foreach (var item in _itemsProcessing)
                {
                    if (!item.IsCompleted && !_queueList.Contains(item) && item.IsQueued)
                    {
                        newList.Add(item);
                    }
                }
                foreach (var item in _queueList)
                {
                    newList.Add(item);
                }
                _queueList.Dispose();
                _queueList = newList;
            }

            _itemsProcessing.Clear();
            _ctsCancel = null;
            _ctCancel  = default;
            RaisePropertyChanged(nameof(this.IsBusy));
        }
 public bool Contains(T item)
 {
     return(queue.Contains(item));
 }
Example #29
0
        void ComputeThread()
        {
            //Console.WriteLine("Start COMPUTE");

            var canceltoken = canceltokensource.Token;
            var computed    = new BlockingCollection <StarGrid>();

            this.computed = computed;

            while (WaitHandle.WaitAny(new WaitHandle[] { canceltoken.WaitHandle, ewh }) == 1)
            {
                while (!canceltoken.IsCancellationRequested)
                {
                    float    mindist = float.MaxValue;
                    float    maxdist = 0;
                    StarGrid selmin  = null;
                    StarGrid selmax  = null;

                    for (int i = grids.Count - 1; i >= 0; i--)              // go backwards thru the list, so the ones painted last gets considered first
                    {
                        StarGrid gcheck = grids[i];

                        //if (gcheck.Id == 2200)
                        //System.Diagnostics.Debug.WriteLine("Cell 2200 ");

                        if (gcheck.Id >= 0 && !gcheck.Working)                                      // if not a special grid
                        {
                            float dist = gcheck.DistanceFrom(curx, curz);
                            if (Math.Abs(dist - gcheck.CalculatedDistance) > MinRecalcDistance) // if its too small a change, ignore.. histerisis
                            {
                                int percentage = GetPercentage(dist);

                                if (percentage > gcheck.Percentage)                // if increase, it has priority..
                                {
                                    if (dist < mindist)                            // if best.. pick
                                    {
                                        mindist = dist;
                                        selmin  = gcheck;
                                        //Console.WriteLine("Select {0} incr perc {1} to {2} dist {3,8:0.0}", gcheck.Id, gcheck.Percentage, percentage, dist);
                                    }
                                }
                                else if (selmin == null && percentage < gcheck.Percentage)   // if not selected a min one, pick the further one to decrease
                                {
                                    if (dist > maxdist)
                                    {
                                        maxdist = dist;
                                        selmax  = gcheck;
                                        //Console.WriteLine("Select {0} decr perc {1} to {2} dist {3,8:0.0}", gcheck.Id, gcheck.Percentage, percentage, dist);
                                    }
                                }
                            }
                        }
                    }

                    if (selmin == null)
                    {
                        selmin = selmax;
                    }

                    if (selmin != null)
                    {
                        //System.Diagnostics.Debug.WriteLine("Repaint Grid -- " + selmin.Id + " dist from " + curx + "," + curz + " is " + selmin.DistanceFrom(curz,curz));
                        selmin.Working = true;                                          // stops another go by this thread, only cleared by UI when it has displayed
                        int   prevpercent = selmin.Percentage;
                        float prevdist    = selmin.CalculatedDistance;

                        selmin.CalculatedDistance = selmin.DistanceFrom(curx, curz);
                        selmin.Percentage         = GetPercentage(selmin.CalculatedDistance);
                        selmin.FillFromDB();

                        Thread.MemoryBarrier();                                         // finish above before trying to trigger another go..

                        Debug.Assert(Math.Abs(prevdist - selmin.CalculatedDistance) > MinRecalcDistance);

                        Debug.Assert(!computed.Contains(selmin));

                        //Tools.LogToFile(String.Format("Grid repaint {0} {1}%->{2}% dist {3,8:0.0}->{4,8:0.0} s{5}", selmin.Id, prevpercent, selmin.Percentage, prevdist, selmin.CalculatedDistance, selmin.CountJustMade));

                        computed.Add(selmin);
                    }
                    else
                    {
                        break;              // nothing to do, wait for kick
                    }
                }
            }

            Trace.WriteLine($"{Environment.TickCount} compute exit");
        }
Example #30
0
        void ComputeThread()
        {
            //Console.WriteLine("Start COMPUTE");

            while (true)
            {
                ewh.WaitOne();

                while (true)
                {
                    if (computeExit)
                    {
                        return;
                    }

                    double   mindist = double.MaxValue;
                    double   maxdist = 0;
                    StarGrid selmin  = null;
                    StarGrid selmax  = null;

                    foreach (StarGrid gcheck in grids)
                    {
                        if (gcheck.Id >= 0 && !gcheck.Working)                                     // if not a special grid
                        {
                            double dist = gcheck.DistanceFrom(curx, curz);

                            if (Math.Abs(dist - gcheck.CalculatedDistance) > MinRecalcDistance) // if its too small a change, ignore.. histerisis
                            {
                                int percentage = GetPercentage(dist);

                                if (percentage > gcheck.Percentage)                // if increase, it has priority..
                                {
                                    if (dist < mindist)                            // if best.. pick
                                    {
                                        mindist = dist;
                                        selmin  = gcheck;
                                        //Console.WriteLine("Select {0} incr perc {1} to {2} dist {3,8:0.0}", gcheck.Id, gcheck.Percentage, percentage, dist);
                                    }
                                }
                                else if (selmin == null && percentage < gcheck.Percentage)   // if not selected a min one, pick the further one to decrease
                                {
                                    if (dist > maxdist)
                                    {
                                        maxdist = dist;
                                        selmax  = gcheck;
                                        //Console.WriteLine("Select {0} decr perc {1} to {2} dist {3,8:0.0}", gcheck.Id, gcheck.Percentage, percentage, dist);
                                    }
                                }
                            }
                        }
                    }

                    if (selmin == null)
                    {
                        selmin = selmax;
                    }

                    if (selmin != null)
                    {
                        selmin.Working = true;                                          // stops another go by this thread, only cleared by UI when it has displayed
                        int    prevpercent = selmin.Percentage;
                        double prevdist    = selmin.CalculatedDistance;

                        selmin.CalculatedDistance = selmin.DistanceFrom(curx, curz);
                        selmin.Percentage         = GetPercentage(selmin.CalculatedDistance);
                        selmin.FillFromDB();

                        Thread.MemoryBarrier();                                         // finish above before trying to trigger another go..

                        Debug.Assert(Math.Abs(prevdist - selmin.CalculatedDistance) > MinRecalcDistance);

                        Debug.Assert(!computed.Contains(selmin));

                        //Console.WriteLine("Grid repaint {0} {1}%->{2}% dist {3,8:0.0}->{4,8:0.0} s{5}", selmin.Id, prevpercent, selmin.Percentage, prevdist, selmin.CalculatedDistance, selmin.CountJustMade);

                        computed.Add(selmin);
                    }
                    else
                    {
                        break;              // nothing to do, wait for kick
                    }
                }
            }
        }