Esempio n. 1
0
        public MeCabNode Next()
        {
            while (this.agenda.Count != 0)
            {
                QueueElement top   = this.agenda.Pop();
                MeCabNode    rNode = top.Node;

                if (rNode.Stat == MeCabNodeStat.Bos)
                {
                    for (QueueElement n = top; n.Next != null; n = n.Next)
                    {
                        n.Node.Next      = n.Next.Node; // change next & prev
                        n.Next.Node.Prev = n.Node;
                    }
                    return(rNode);
                }

                for (MeCabPath path = rNode.LPath; path != null; path = path.LNext)
                {
                    QueueElement n = new QueueElement()
                    {
                        Node = path.LNode,
                        Gx   = path.Cost + top.Gx,
                        Fx   = path.LNode.Cost + path.Cost + top.Gx,
                        Next = top
                    };
                    this.agenda.Push(n);
                }
            }
            return(null);
        }
Esempio n. 2
0
 public MeCabNode Next()
 {
     while (this.agenda.Count != 0)
     {
         QueueElement queueElement = this.agenda.Pop();
         MeCabNode    node         = queueElement.Node;
         if (node.Stat == MeCabNodeStat.Bos)
         {
             QueueElement queueElement2 = queueElement;
             while (queueElement2.Next != null)
             {
                 queueElement2.Node.Next      = queueElement2.Next.Node;
                 queueElement2.Next.Node.Prev = queueElement2.Node;
                 queueElement2 = queueElement2.Next;
             }
             return(node);
         }
         for (MeCabPath meCabPath = node.LPath; meCabPath != null; meCabPath = meCabPath.LNext)
         {
             QueueElement queueElement3 = new QueueElement();
             queueElement3.Node = meCabPath.LNode;
             queueElement3.Gx   = meCabPath.Cost + queueElement.Gx;
             queueElement3.Fx   = meCabPath.LNode.Cost + meCabPath.Cost + queueElement.Gx;
             queueElement3.Next = queueElement;
             QueueElement item = queueElement3;
             this.agenda.Push(item);
         }
     }
     return(null);
 }
Esempio n. 3
0
        /// <summary>
        /// Return the oldest value of the queue and remove it.
        /// </summary>
        public async Task <T> Pop()
        {
            QueueElement Oldest    = _FirstQueueElement;
            QueueElement PreOldest = null;

            while (Oldest.Next != null)
            {
                PreOldest = Oldest;
                Oldest    = Oldest.Next;
            }

            if (PreOldest != null)
            {
                PreOldest.Next = null;
                Interlocked.Decrement(ref _Count);
            }

            var OnRemovedLocal = OnRemoved;

            if (OnRemovedLocal != null)
            {
                await Task.WhenAll(OnRemovedLocal.GetInvocationList().
                                   Cast <QueueDelegate>().
                                   Select(e => e(this,
                                                 _FirstQueueElement.Value)));
            }

            return(Oldest.Value);
        }
Esempio n. 4
0
        private void ProcessEvaluation(object obj)
        {
            _parameters.Logger.LogMethodInfo($"{Thread.CurrentThread.Name} {Thread.CurrentThread.ManagedThreadId} thread started.");

            CancellationToken token;

            try
            {
                token = (CancellationToken)obj;
            }
            catch (Exception ex)
            {
                _parameters.Logger.LogMethodError($"Arrived parameter is not {nameof(CancellationToken)}. Exception: {ex}");
                return;
            }

            WaitHandle[] handles = new WaitHandle[] { _queueHandle, token.WaitHandle };

            while (true)
            {
                WaitHandle.WaitAny(handles);

                if (token.IsCancellationRequested)
                {
                    _parameters.Logger.LogMethodInfo($"{Thread.CurrentThread.Name} (ID:{Thread.CurrentThread.ManagedThreadId}) thread cancelled.");
                    break;
                }

                while (true)
                {
                    if (token.IsCancellationRequested)
                    {
                        _parameters.Logger.LogMethodInfo($"{Thread.CurrentThread.Name} (ID:{Thread.CurrentThread.ManagedThreadId}) thread cancelled.");
                        break;
                    }

                    QueueElement item = null;
                    lock (_queueLockObj)
                    {
                        if (_processorQueue.Count > 0)
                        {
                            _parameters.Logger.LogTrace("New queue element arrived!");
                            item = _processorQueue.Dequeue();
                        }
                        else
                        {
                            break;
                        }
                    }

                    if (item == null)
                    {
                        _parameters.Logger.LogMethodError("Started to process item, but it is null");
                        continue;
                    }

                    Evaluate(item);
                }
            }
        }
Esempio n. 5
0
        /// <summary>
        /// Push a new value into the queue.
        /// </summary>
        /// <param name="Value">The value.</param>
        public async Task <QueueElement> Push(T Value)
        {
            var NewQueueElement = new QueueElement(Value);

            QueueElement OldFirst;

            do
            {
                OldFirst             = First;
                NewQueueElement.Next = OldFirst;
            }while (Interlocked.CompareExchange(ref _FirstQueueElement, NewQueueElement, OldFirst) != OldFirst);

            Interlocked.Increment(ref _Count);

            // Multiple concurrent threads might remove more than expected!
            // But it is assumed, that this is not a problem to anyone.
            while ((UInt64)_Count > MaxNumberOfElements)
            {
                await Pop();
            }

            var OnAddedLocal = OnAdded;

            if (OnAddedLocal != null)
            {
                await Task.WhenAll(OnAddedLocal.GetInvocationList().
                                   Cast <QueueDelegate>().
                                   Select(e => e(this,
                                                 Value)));
            }

            return(NewQueueElement);
        }
Esempio n. 6
0
            public void Enque(QueueElement qe)
            {
                if (Count == 0)
                {
                    List.Add(qe);
                }
                else
                {
                    var start = 0;
                    var end   = Count;
                    var i     = (end - start) / 2;

                    while (end - start > 0)
                    {
                        if (qe.Weight > List[i].Weight)
                        {
                            start = i + 1;
                            i     = (end - start) / 2 + start;
                        }
                        else
                        {
                            end = i;
                            i   = (end - start) / 2;
                        }
                    }
                    List.Insert(start, qe);
                }
            }
Esempio n. 7
0
 public void Enqueue(int value, int priority)
 {
     if (this.tail == null)
     {
         this.tail = new QueueElement(value, priority, null);
     }
     else
     {
         if (tail.Priority < priority)
         {
             QueueElement exTail = this.tail;
             this.tail = new QueueElement(value, priority, exTail);
             return;
         }
         QueueElement temp = this.tail;
         QueueElement after;
         while (temp.Priority >= priority)
         {
             after = temp;
             if (temp.Previous == null)
             {
                 temp.Previous = new QueueElement(value, priority, null);
                 return;
             }
             temp = temp.Previous;
         }
         QueueElement newElement = new QueueElement(value, priority, temp);
         after.Previous = newElement;
     }
 }
Esempio n. 8
0
        /// <summary>
        /// The enqueue.
        /// </summary>
        /// <param name="item">
        /// The item.
        /// </param>
        public Status Enqueue(string item)
        {
            if (this.count == BufferLen)
            {
                Trace.Error("Queue is full. Dropping item.");
                return(Status.Full);
            }

            if (false == this.enabled)
            {
                Trace.Error("Queue in purge. Dropping item.");
                return(Status.Purge);

                ;
            }

            // Create a new queue item with a unique id
            var queueItem = new QueueElement(Interlocked.Increment(ref this.currentIndex), item);

            this.buffer[queueItem.Id % BufferLen] = queueItem;
            Interlocked.Increment(ref this.count);
            this.semaphore.Release();

            Trace.Info($"Item pushed to {this.name}, current count {this.count}");

            if (BufferLen - this.count < 100)
            {
                Trace.Warning($"{this.name} length {this.count} approaching maximum: {BufferLen}");
            }

            return(Status.Success);
        }
Esempio n. 9
0
 /// <summary>
 /// replaces an enqueued request with an updated version of that request. Is the old request not found, then the replacement will be added normaly,
 /// </summary>
 /// <param name="toReplace"></param>
 /// <param name="replacement"></param>
 public void Replace(IPdfRequest toReplace, IPdfRequest replacement)
 {
     lock (synchronisationLock)
     {
         if (firstElement == null || firstElement.value.Priority < replacement.Priority)
         {
             firstElement = new QueueElement <IPdfRequest>(replacement, firstElement);
             Monitor.Pulse(synchronisationLock);
         }
         else if (firstElement.value == toReplace)
         {
             firstElement.value = replacement;
         }
         else
         {
             QueueElement <IPdfRequest> element = firstElement;
             while (element.next != null && element.next.value.Priority >= toReplace.Priority && element.next.value != toReplace)
             {
                 element = element.next;
             }
             if (element.next != null && element.next.value == toReplace)
             {
                 element.next.value = replacement;
             }
             else
             {
                 element.next = new QueueElement <IPdfRequest>(replacement, element.next);
                 Monitor.Pulse(synchronisationLock);
             }
         }
     }
 }
Esempio n. 10
0
        public override String ToString()
        {
            QueueElement iterator = first;

            StringBuilder builder = new StringBuilder();

            builder.Append("[");

            if (iterator != null)
            {
                builder.Append(" ");
                builder.Append(iterator.GetPriority());
                builder.Append(". ");
                builder.Append(iterator.GetData());

                iterator = iterator.GetPrev();

                while (iterator != null)
                {
                    builder.Append(", ");
                    builder.Append(iterator.GetPriority());
                    builder.Append(". ");
                    builder.Append(iterator.GetData());

                    iterator = iterator.GetPrev();
                }
                builder.Append(" ");
            }

            builder.Append("]");

            return(builder.ToString());
        }
Esempio n. 11
0
        public static async Task HandleMessage <T>(QueueElement <T> message)
        {
            Console.WriteLine("Message received through HandleMessage()");
            var imageUrl = "";

            //var message = await serviceBus.GetMessage<QueueElement<object>>(m);
            switch (message.Type)
            {
            case "TelemetrySend":     // FROM OTHER WORKER
                var telemetrySendModel = ForceCast <Telemetry>(message.Data);
                telemetryRepository.Insert(telemetrySendModel);
                break;

            case "ActivityClose":     // TO WORKER TRIO
                var closeData = ForceCast <QueueElement <ActivityIdViewModel> >(message);
                activityRepository.Close(closeData.Data.Id);
                //--
                closeData.Data.FromOrganizer = true;
                await queueToOtherWorker.SendMessage(closeData);

                //--
                break;

            case "ActivityStart":
                var startData = ForceCast <QueueElement <ActivityIdViewModel> >(message);  // GetValue<int>(message.Data);
                activityRepository.Start(startData.Data.Id);
                //--
                startData.Data.FromOrganizer = true;
                await queueToOtherWorker.SendMessage(startData);

                //--

                break;

            case "ActivityCreate":
                var activityCreateModel = ForceCast <ActivityCreateViewModel>(message.Data);
                activityRepository.Insert(new Activity()
                {
                    //    Id = 0,
                    CreationDate = DateTime.Now,
                    EndDate      = null,
                    Location     = activityCreateModel.Location,
                    Name         = activityCreateModel.Name,
                    RaceUrl      = "", //$"https://localhost/raceSample/{new Random().Next(0, 1000)}",
                    IdUser       = activityCreateModel.IdUser,
                    Status       = 0,
                    Type         = activityCreateModel.Type,
                });
                break;

            case "ActivityJoin":
                var activityJoinModel = ForceCast <ActivityIdViewModel>(message.Data);
                activityRepository.AddRunner(
                    activityJoinModel.Id,
                    activityJoinModel.IdUser
                    );
                break;
            }
        }
        /// <summary>
        /// Tests the functionality of the queue passed in.
        /// </summary>
        /// <param name="queue">The queue.</param>
        /// <param name="numberOfElements">The number of elements.</param>
        /// <param name="performEnumerateTest">if set to <c>true</c> [perform enumerate test].</param>
        private static void PriorityQueueFunctionalityTest(PriorityQueueBase <QueueElement> queue, int numberOfElements, bool performEnumerateTest)
        {
            // create list of random priorities.
            List <int> priorities = new List <int>();
            Random     rand       = new Random(unchecked ((int)DateTime.Now.Ticks));

            for (int i = 0; i < numberOfElements; i++)
            {
                priorities.Add(rand.Next(numberOfElements));
            }

            // fill queue with elements
            for (int i = 0; i < numberOfElements; i++)
            {
                // add a new element to the queue, with a random priority from the list and a value.
                queue.Add(new QueueElement(priorities[i], "Value: " + i));
            }

            Assert.AreEqual(numberOfElements, queue.Count);

            // sort the priorities, descending, so we know the highest priority
            priorities.Sort(SortAlgorithm.ShellSort, SortDirection.Descending);

            // check if peek reveals the highest priority
            QueueElement highestPriorityElement = queue.Peek();

            Assert.IsNotNull(highestPriorityElement);
            Assert.AreEqual(priorities[0], highestPriorityElement.Priority);

            QueueElement current;
            QueueElement previous;

            if (performEnumerateTest)
            {
                // test the enumerator to see if it gives back the elements in the right order
                current = highestPriorityElement;
                foreach (QueueElement element in queue)
                {
                    previous = current;
                    current  = element;
                    Assert.IsTrue(previous.Priority >= current.Priority);
                }
            }

            // now remove all elements one by one. Each element has to have a lower (or equal) priority than the one before it.
            previous = queue.Remove();
            current  = queue.Remove();
            while (current != null)
            {
                Assert.IsTrue(previous.Priority >= current.Priority);
                previous = current;
                current  = queue.Remove();
            }

            // queue is now empty
            Assert.AreEqual(0, queue.Count);

            Assert.IsNull(queue.Peek());
        }
Esempio n. 13
0
    private bool CreateNextEnemies(bool atStart)
    {
        if (_queue.Count == 0)
        {
            return(false);
        }
        //TODO намагаємось заспавнити ворогів на поле (Enemies.cs) якщо ділей = 0 і є вільні слоти
        bool added          = false;
        bool continueAdding = true;

        // TODO можливо якщо жодного ворога немає - пришвидшуєм чергу, щоб не втикати довго
        if (Consts.ADD_ENAMY_ON_NO_ENEMIES_LEFT && _enemies.NoEnemiesLeft())
        {
            QueueElement element = _queue[0];
            element.Delay = 0;
            _queue[0]     = element;
        }
        // намагаємось додати
        do
        {
            if (_queue.Count == 0)
            {
                break;
            }
            if (_queue[0].Delay <= 0)
            {
                continueAdding = _queue[0].Delay < 0; // якщо < 0 (-1), то продовжуєм додавати (на старті так треба ставити), якщо 0 - стоп, один новий ворог за хід
                if (_enemies.TryToAddEnemy(_queue[0]))
                {
                    // додали вдало
                    added = true;
                    _queue.RemoveAt(0);
                }
                else
                {
                    // не було слота
                    continueAdding = false;
                }
            }
            else
            {
                // ще не час додавати
                continueAdding = false;
            }
        } while (continueAdding);

        //
        if (_queue.Count == 0)
        {
            HideQueue(atStart);
        }
        else
        {
            SetNextEnemy(atStart);
        }
        //

        return(added);
    }
 private static void EnqueueChild(LinkedList<QueueElement> childrenQueue, QueueElement nextChildNode, int precedents)
 {
     if (precedents > 1)
     {
         nextChildNode.PrecedentCount = 1;
         childrenQueue.AddLast(nextChildNode);
     }
 }
        private async Task DelayChat(QueueElement element)
        {
            var limiter = GetChatLimiter(element);

            await limiter.Wait();

            await DelayBase(element);
        }
        private async Task DelayGroup(QueueElement element)
        {
            var limiter = GetGroupLimiter(element);

            await limiter.Wait();

            await DelayChat(element);
        }
Esempio n. 17
0
 private static void EnqueueChild(LinkedList <QueueElement> childrenQueue, QueueElement nextChildNode, int precedents)
 {
     if (precedents > 1)
     {
         nextChildNode.PrecedentCount = 1;
         childrenQueue.AddLast(nextChildNode);
     }
 }
        private async Task GetPermission(string target)
        {
            var element = new QueueElement
            {
                Target = target
            };

            await Delay(element);
        }
            internal QueueElement(QueueElement head, AVLNode linkedNode)
            {
                this.linkedNode = linkedNode;

                next = head.next;
                head.next.previous = this;
                previous           = head;
                head.next          = this;
            }
Esempio n. 20
0
            public QueueElement Add(int value)
            {
                int insertedIdx = _size;

                _size++;
                _heap[insertedIdx] = new QueueElement(insertedIdx, int.MaxValue);

                return(Decrease(insertedIdx, value));
            }
Esempio n. 21
0
 /// <summary>
 /// Checks if two objects are the same
 /// </summary>
 /// <param name="obj">Target object to compare</param>
 /// <returns></returns>
 public override bool Equals(object obj)
 {
     if (obj is QueueElement)
     {
         QueueElement el = (QueueElement)obj;
         return(el.Url == Url && el.Destination == Destination && el.Completed == Completed && el.Id == Id);
     }
     return(false);
 }
Esempio n. 22
0
            /// <summary>
            /// Меняет значение и приоритеты первого со вторым
            /// </summary>
            public static void SwapValues(QueueElement first, QueueElement second)
            {
                int temp = first.value;

                first.value  = second.value;
                second.value = temp;
                temp         = first.prior;
                first.prior  = second.prior;
                second.prior = temp;
            }
Esempio n. 23
0
        public void Enqueue(T el, int priority = 0)
        {
            Array.Resize(ref queue, ++Size);
            for (int i = Size - 1; i > 0; i--)
            {
                queue[i] = queue[i - 1];
            }

            queue[0] = new QueueElement(priority, el);
        }
Esempio n. 24
0
 /// <summary>
 /// コンストラクタ
 /// </summary>
 /// <param name="eos">末尾の形態素ノード</param>
 public NBestGenerator(TNode eos)
 {
     this.eos = new QueueElement()
     {
         Node = eos,
         Next = null,
         Fx   = 0,
         Gx   = 0
     };
 }
Esempio n. 25
0
 public int Dequeue()
 {
     if (this.tail == null)
     {
         throw new EmptyQueueException();
     }
     int result = this.tail.Value;
     this.tail = this.tail.Previous;
     return result;
 }
            internal static void Remove(QueueElement element, QueuedAVLTree <TKey, TValue> tree, bool callFromQueue = false)
            {
                element.next.previous = element.previous;
                element.previous.next = element.next;

                if (callFromQueue && element.linkedNode != null)
                {
                    AVLNode.RemoveNode(element.linkedNode, tree, true);
                }
            }
            internal void Clear()
            {
                first = new QueueElement();
                last  = new QueueElement();

                first.next    = last;
                last.previous = first;

                size = 0;
            }
Esempio n. 28
0
    internal void AddGreenLightKeys(QueueElement qEle)
    {
        if (qEle.WasUsedToGreenLightOrDestroy)
        {
            return;
        }

        _passedQueue.Add(qEle.Key);
        qEle.WasUsedToGreenLightOrDestroy = true;
    }
 private static QueueElement DequeueFreeChild(LinkedList<QueueElement> childrenQueue, QueueElement parentNode, int precedents)
 {
     QueueElement freeChild = childrenQueue
         .FirstOrDefault(childNode =>
             parentNode.Edges.Count(_ => _ == childNode.Node) <= 0);
     if (freeChild == null) return null;
     if (++freeChild.PrecedentCount == precedents)
         childrenQueue.Remove(freeChild);
     return freeChild;
 }
Esempio n. 30
0
        private static QueueElement GetOrCreateNode(Dictionary <int, QueueElement> dictionary, int key)
        {
            if (dictionary.ContainsKey(key))
            {
                return(dictionary[key]);
            }
            var node = new QueueElement(key, 0, 0);

            dictionary.Add(key, node);
            return(node);
        }
        /// <summary>
        /// Get value from queue.
        /// </summary>
        /// <returns></returns>
        public int Dequeue()
        {
            if (this.IsEmpty())
            {
                throw new Exception("Queue is empty");
            }

            int value = this.head.Value;
            this.head = this.head.Next;
            return value;
        }
 private async Task Delay(QueueElement element)
 {
     if (IsGroup(element))
     {
         await DelayGroup(element);
     }
     else
     {
         await DelayChat(element);
     }
 }
Esempio n. 33
0
        public override String ToString()
        {
            StringBuilder b = new StringBuilder();
            QueueElement <IPdfRequest> current = firstElement;

            while (current != null)
            {
                b.Append(current.value.ToString());
                current = current.next;
            }
            return(b.ToString());
        }
Esempio n. 34
0
        /// <summary>
        /// Deletes element with highest priority
        /// </summary>
        /// <returns>Value of deleted element</returns>
        public TValue Dequeue()
        {
            if (Empty)
            {
                throw new EmptyQueueException();
            }
            size--;
            var result = head.Value;

            head = head.Next;
            return(result);
        }
Esempio n. 35
0
 public int CompareTo(object obj)
 {
     if (obj == null || GetType() != obj.GetType())
     {
         return(0);
     }
     else
     {
         QueueElement <TValue> b = (QueueElement <TValue>)obj;
         return(priority.CompareTo(b.priority));
     }
 }
        /// <summary>
        /// Inser to queue.
        /// </summary>
        /// <param name="value">Value to be insert.</param>
        /// <param name="priority">This priority.</param>
        public void Enqueue(int value, int priority)
        {
            if (this.IsEmpty())
            {
                this.head = new QueueElement(value, priority);
                return;
            }

            QueueElement tempElement = this.head;

            if (tempElement.Next == null)
            {
                if (priority > this.head.Priority)
                {
                    var element = this.head;
                    var thisElement = new QueueElement(value, priority);
                    this.head = thisElement;
                    this.head.Next = element;
                    return;
                }
                else
                {
                    this.head.Next = new QueueElement(value, priority);
                    return;
                }
            }
            QueueElement tempElementPrevious = this.head;

            while (tempElement.Priority >= priority)
            {
                if (tempElement.Next == null)
                {
                    break;
                }

                if (tempElement.Next.Priority >= priority)
                    tempElementPrevious = tempElementPrevious.Next;

                tempElement = tempElement.Next;
            }

            QueueElement newElement = new QueueElement(value, priority);

            tempElementPrevious.Next = newElement;
            newElement = tempElement.Next;
        }
 private static void EnqueueParent(Queue<QueueElement> parentQueue, QueueElement nextChildNode)
 {
     parentQueue.Enqueue(nextChildNode);
 }
Esempio n. 38
0
 public QueueElement(int value, int priority, QueueElement previous)
 {
     this.Value = value;
     this.Priority = priority;
     this.Previous = previous;
 }
Esempio n. 39
0
 public Queue()
 {
     this.tail = null;
 }
 private static QueueElement GetOrCreateNode(Dictionary<int, QueueElement> dictionary, int key)
 {
     if (dictionary.ContainsKey(key))
         return dictionary[key];
     var node = new QueueElement(key, 0, 0);
     dictionary.Add(key, node);
     return node;
 }