Пример #1
0
        public void TestQueueBehavior()
        {
            List <char> chars = new List <char> {
                'a', 'b', 'c'
            };

            SimpleQueue <char> charQueue = new SimpleQueue <char>(chars);

            chars.Add('d');
            chars.Add('e');
            chars.Add('f');

            charQueue.Enqueue('d');
            charQueue.Enqueue('e');
            charQueue.Enqueue('f');

            int index = 0;

            while (!charQueue.IsEmpty())
            {
                Assert.AreEqual(chars[index++], charQueue.Dequeue());
            }

            Assert.AreEqual(0, charQueue.Count);
        }
Пример #2
0
        static bool TestCase_Find() //Moritz Breschan
        {                           //rgw gibt an wie viele Elemente gefunden wurde
            bool        rgw     = true;
            SimpleQueue s1      = new SimpleQueue(20);
            int         counter = 0;

            for (counter = 0; counter < 10; counter++)
            {
                s1.Enqueue(counter);
            }
            for (counter = 9; counter >= 0; counter--)
            {
                s1.Enqueue(counter);
            }
            counter = 0;
            while (counter < 10 && rgw)
            {
                if (s1.Find(counter) != 2)
                {
                    rgw = false;
                }
                counter++;
            }
            return(rgw);
        }
Пример #3
0
        private IEnumerable <TreeNode> TraverseBreadthFirst()
        {
            if (Count == 0)
            {
                yield break;
            }

            var queue = new SimpleQueue <TreeNode>();

            queue.Enqueue(_root);
            while (queue.Count > 0)
            {
                var current = queue.Dequeue();
                yield return(current);

                if (current.Left != null)
                {
                    queue.Enqueue(current.Left);
                }
                if (current.Right != null)
                {
                    queue.Enqueue(current.Right);
                }
            }
        }
Пример #4
0
        private static bool TestCase_Resize()     //Melanie Bugelnig
        {
            int         newCapacity = 5;
            SimpleQueue s1          = new SimpleQueue(newCapacity);
            bool        result      = true;
            int         counter;

            for (counter = 0; counter < newCapacity; counter++)
            {
                s1.Enqueue(counter);
            }
            newCapacity = 10;

            s1.Resize(newCapacity);

            for (; counter < newCapacity; counter++)
            {
                s1.Enqueue(counter);
            }
            counter--;

            if (s1.GetElement() != counter)
            {
                result = false;
            }
            counter--;

            return(result);
        }
Пример #5
0
        private void StartFastMarchingMethod()
        {
            _destination = _currentPath.Last().position;

            // find the first cell used for traversal - i.e. the path destination
            // note however, that the destination must be the first found portal node in the path if it exists - we must never go past this
            int pathCount = _currentPath.count - 1;

            for (int i = 1; i < pathCount; i++)
            {
                var pathNode = _currentPath[i];
                if (pathNode is IPortalNode)
                {
                    _destination = _currentPath[i - 1].position;
                    break;
                }
            }

            Cell destinationCell = _grid.GetCell(_destination, true);

            _openSet.Enqueue(destinationCell);

            while (_openSet.count > 0)
            {
                FastMarchingMethod(_openSet.Dequeue());
            }
        }
            /// <summary>Dequeues an item, and then fixes up our state around writers and completion.</summary>
            /// <returns>The dequeued item.</returns>
            private T DequeueItemAndPostProcess()
            {
                Debug.Assert(Monitor.IsEntered(SyncObj));

                // Dequeue an item.
                T item = _items.Dequeue();

                // If we're now empty and we're done writing, complete the channel.
                if (_doneWriting != null && _items.Count == 0)
                {
                    CompleteWithOptionalError(_completion, _doneWriting);
                }

                // If there are any writers blocked, there's now room for at least one
                // to be promoted to have its item moved into the items queue.  We need
                // to loop while trying to complete the writer in order to find one that
                // hasn't yet been canceled (canceled writers transition to canceled but
                // remain in the physical queue).
                while (_blockedWriters.Count > 0)
                {
                    Writer <T> w = _blockedWriters.Dequeue();
                    if (w.Success(default(VoidResult)))
                    {
                        _items.Enqueue(w.Item);
                        return(item);
                    }
                }

                // There was no blocked writer, so see if there's a WaitToWriteAsync
                // we should wake up.
                WakeUpWaiters(_waitingWriters, true);

                // Return the item
                return(item);
            }
Пример #7
0
 private void ResetHistValues()
 {
     _histValues.Reset();
     while (!_histValues.Full)
     {
         _histValues.Enqueue(InitialValue);
     }
     return;
 }
Пример #8
0
        public void TestMethodForQueue()
        {
            SimpleQueue que = new SimpleQueue();

            que.Enqueue(10);
            que.Enqueue(1);
            que.Enqueue(3);
            que.Enqueue(0);

            Assert.AreEqual(que.CurrMax(), 10);

            que.Enqueue(100);

            Assert.AreEqual(que.CurrMax(), 100);
        }
Пример #9
0
        public async Task TestPriority()
        {
            var rand = new Random();

            var priorities = Enumerable.Range(1, 200).OrderBy(q => rand.Next()).ToList();

            var queue = new SimpleQueue <SimpleDocument>(this.GetType().FullName);

            await queue.Clear();

            foreach (var priority in priorities)
            {
                await queue.Enqueue(
                    new SimpleDocument()
                {
                    Value = priority.ToString()
                },
                    new EnqueOptions()
                {
                    Priority = (byte)priority
                });
            }

            for (byte i = 200; i >= 1; i--)
            {
                Assert.AreEqual(i.ToString(), (await queue.Dequeue()).Payload.Value);
            }
        }
Пример #10
0
        public async Task TestEnqueueDeque()
        {
            var queue = new SimpleQueue <SimpleDocument>(this.GetType().FullName);

            await queue.Clear();

            var simpleStrings = new List <string>();

            for (int i = 0; i < 100; i++)
            {
                simpleStrings.Add(Guid.NewGuid().ToString().Replace("-", ""));
            }

            var documents = simpleStrings.Select(q => new SimpleDocument()
            {
                Value = q
            });


            await Task.WhenAll(documents.Select(simpleDocument => queue.Enqueue(simpleDocument, new EnqueOptions())));

            for (int i = 0; i < 100; i++)
            {
                Assert.IsNotNull(await queue.Dequeue(new DequeueOptions()));
            }
            var document = await queue.Dequeue(new DequeueOptions());

            Assert.IsNull(document);
        }
Пример #11
0
 /// <summary>
 /// Executes the action on the main thread.
 /// </summary>
 /// <param name="a">The action.</param>
 public void ExecuteOnMainThread(Action a)
 {
     lock (_queue)
     {
         _queue.Enqueue(a);
     }
 }
Пример #12
0
            public bool TryWrite(T item)
            {
                lock (SyncObj)
                {
                    AssertInvariants();

                    // If writing has already been marked as done, fail the write.
                    if (_doneWriting != null)
                    {
                        return(false);
                    }

                    // If there are any blocked readers, wake one of them up to transfer
                    // the data to.  Note that readers may be canceled but still be in the
                    // queue, so we need to loop.
                    while (_blockedReaders.Count > 0)
                    {
                        Reader <T> r = _blockedReaders.Dequeue();
                        if (r.Success(item))
                        {
                            return(true);
                        }
                    }

                    // There were no blocked readers, so just add the data to the queue
                    _items.Enqueue(item);

                    // Then let any waiting readers know that they should try to read it.
                    WakeUpWaiters(_waitingReaders, true);

                    return(true);
                }
            }
Пример #13
0
        public async Task TestConfirmed()
        {
            var queue = new SimpleQueue <SimpleDocument>(GetType().FullName);
            await queue.Clear();

            await queue.Enqueue(new SimpleDocument()
            {
                Value = "test"
            });

            var value = await queue.Dequeue(new DequeueOptions()
            {
                ConfirmTime = TimeSpan.FromMilliseconds(500)
            });

            Assert.AreEqual("test", value.Payload.Value);

            await queue.Confirm(value);


            value = await queue.Dequeue();

            Assert.IsNull(value);

            await Task.Delay(1000);

            value = await queue.Dequeue();

            Assert.IsNull(value);
        }
            public ValueTask <T> ReadAsync(CancellationToken cancellationToken)
            {
                // Fast-path cancellation check
                if (cancellationToken.IsCancellationRequested)
                {
                    return(Task.FromCanceled <T>(cancellationToken));
                }

                lock (SyncObj)
                {
                    AssertInvariants();

                    // If there are any items, hand one back.
                    if (_items.Count > 0)
                    {
                        return(DequeueItemAndPostProcess());
                    }

                    // There weren't any items.  If we're done writing so that there
                    // will never be more items, fail.
                    if (_doneWriting != null)
                    {
                        return(Task.FromException <T>(_doneWriting != s_doneWritingSentinel ? _doneWriting : CreateInvalidCompletionException()));
                    }

                    // Otherwise, queue the reader.
                    var reader = Reader <T> .Create(cancellationToken);

                    _blockedReaders.Enqueue(reader);
                    return(reader.Task);
                }
            }
Пример #15
0
        private static bool TestCase_Dequeue()  //Hebein Fabian
        {
            bool        status = true;
            int         size   = 5;
            int         idx;
            SimpleQueue q1 = new SimpleQueue(size);

            for (idx = 0; idx < size; idx++)
            {
                q1.Enqueue(idx);
            }
            idx = 0;
            while (idx < size && status == true)
            {
                if (q1.Dequeue() != idx)
                {
                    status = false;
                }
                idx++;
            }
            if (status == true)
            {
                try
                {
                    status = false;
                    q1.Dequeue();
                }
                catch
                {
                    status = true;
                }
            }

            return(status);
        }
            public Task <bool> WaitToReadAsync(CancellationToken cancellationToken)
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    return(Task.FromCanceled <bool>(cancellationToken));
                }

                lock (SyncObj)
                {
                    AssertInvariants();

                    // If there are any items available, a read is possible.
                    if (_items.Count > 0)
                    {
                        return(s_trueTask);
                    }

                    // There were no items available, so if we're done writing, a read will never be possible.
                    if (_doneWriting != null)
                    {
                        return(s_falseTask);
                    }

                    // There were no items available, but there could be in the future, so ensure
                    // there's a blocked reader task and return it.
                    var r = Reader <bool> .Create(cancellationToken);

                    _waitingReaders.Enqueue(r);
                    return(r.Task);
                }
            }
Пример #17
0
        static bool TestCase_Copy()         //Fahrgruber Samuel
        {
            int         capacity         = 100;
            int         numberOfElements = 50;
            bool        result           = false;
            SimpleQueue q1 = new SimpleQueue(capacity);
            SimpleQueue q2;
            int         idx;

            for (idx = 0; idx < numberOfElements; idx++)
            {
                q1.Enqueue(idx);
            }
            q2 = q1.Copy();
            if (q1 != q2)
            {
                result = true;
            }
            while (result == true && idx > 0)
            {
                try
                {
                    if (q1.Dequeue() != q2.Dequeue())
                    {
                        result = false;
                    }
                }
                catch
                {
                    result = false;
                }
                idx--;
            }
            return(result);
        }
            public Task <bool> WaitToWriteAsync(CancellationToken cancellationToken)
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    return(Task.FromCanceled <bool>(cancellationToken));
                }

                lock (SyncObj)
                {
                    AssertInvariants();

                    // If we're done writing, no writes will ever succeed.
                    if (_doneWriting != null)
                    {
                        return(s_falseTask);
                    }

                    // If there's space to write, a write is possible.
                    if (_items.Count < _bufferedCapacity)
                    {
                        return(s_trueTask);
                    }

                    // We're still allowed to write, but there's no space,
                    // so ensure a waiter is queued and return it.
                    var w = Reader <bool> .Create(cancellationToken);

                    _waitingWriters.Enqueue(w);
                    return(w.Task);
                }
            }
Пример #19
0
            public Task <bool> WaitToReadAsync(CancellationToken cancellationToken)
            {
                lock (SyncObj)
                {
                    AssertInvariants();

                    // If there are any items, readers can try to get them.
                    if (_items.Count > 0)
                    {
                        return(s_trueTask);
                    }

                    // There are no items, so if we're done writing, there's never going to be data available.
                    if (_doneWriting != null)
                    {
                        return(s_falseTask);
                    }

                    // Queue the waiter
                    var r = Reader <bool> .Create(cancellationToken);

                    _waitingReaders.Enqueue(r);
                    return(r.Task);
                }
            }
Пример #20
0
        static bool TestCase_Enqueue()      //Judth Marcel
        {
            SimpleQueue Queue1        = new SimpleQueue(1);
            int         NumbertoQueue = 1;

            Queue1.Enqueue(NumbertoQueue);

            return(Queue1.GetElement() == NumbertoQueue);
        }
        private void StartFastMarchingMethod()
        {
            Cell destinationCell = EnsureDestinationCell();

            if (destinationCell == null)
            {
                // if there really is no destination cell - i.e. the cell we start traversal at, then just quit
                return;
            }

            _destination = destinationCell.position;
            _openSet.Enqueue(destinationCell);

            while (_openSet.count > 0)
            {
                FastMarchingMethod(_openSet.Dequeue());
            }
        }
Пример #22
0
 public void HandleAction(ClientAction action)
 {
     if (action.IsServerRecipient())
     {
         HandleServerAction(action);
     }
     else
     {
         _incomingCommands.Enqueue(action);
     }
 }
Пример #23
0
        public Cell BestMatch(IGrid grid, Vector3 start, Func <Cell, bool> match, Func <Cell, bool> discard)
        {
            var startCell = grid.GetCell(start, true);

            if (startCell == null)
            {
                return(null);
            }

            _set.Add(startCell);
            _queue.Enqueue(startCell);

            while (_queue.count > 0)
            {
                var current = _queue.Dequeue();

                var count = current.GetNeighbours(_buffer);
                for (int i = 0; i < count; i++)
                {
                    var n = _buffer[i];
                    if (!_set.Add(n))
                    {
                        continue;
                    }

                    if (match(n))
                    {
                        Reset();
                        return(n);
                    }

                    if (!discard(n))
                    {
                        _queue.Enqueue(n);
                    }
                }
            }

            Reset();
            return(null);
        }
Пример #24
0
        public void Execute()
        {
            SimpleQueue <TestModel> .OnDataConsumed += (sender, args) =>
            {
                Console.WriteLine(JsonHelper.SerializeIgnoreNullValue(args.QueueData));
                Console.WriteLine("===================================");
            };
            SimpleQueue <TestModel> .OnDataBatchConsumed += (sender, args) =>
            {
                args.QueueData.ForEach(c =>
                {
                    Console.WriteLine(JsonHelper.SerializeIgnoreNullValue(c));
                });
                Console.WriteLine("===================================");
            };
            SimpleQueue <TestModel> .OnException += (sender, args) =>
            {
                Console.WriteLine($"出现异常:{args.Data?.Message}");
            };

            var queue = new SimpleQueue <TestModel>(options =>
            {
                //options.QueueTriggerType = QueueTriggerType.Count;
                options.QueueTriggerType  = QueueTriggerType.Count | QueueTriggerType.Timer | QueueTriggerType.Manual;
                options.TimerInterval     = 1000;
                options.CountLimit        = 3;
                options.MaxReconsumeCount = 5;
                options.ConsumeAsync      = false;
            });

            var id  = 0L;
            var now = DateTime.Now;

            //var list = new List<TestModel>();
            DelegateHelper.BatchFunc(() =>
            {
                Thread.Sleep(100);

                now       = now.AddSeconds(1);
                var model = new TestModel
                {
                    Id         = ++id,
                    CreateTime = now
                };
                queue.Enqueue(model);
                //list.Add(model);
                return(false);
            }, 50);

            Console.WriteLine($"当前队列中的数据量:{queue.Count}");
            Console.WriteLine($"队列配置:{JsonHelper.Serialize(queue.Options)}");
        }
Пример #25
0
        static bool TestCase_Merge() //Kandut Nico
        {                            //die 2. Queue wird auf den 1. gesetzt
            bool        result = true;
            int         testwert;
            SimpleQueue SimpleQueue01;
            SimpleQueue SimpleQueue02;
            SimpleQueue ResultingQueue;
            int         idxCounter = 0;

            testwert      = 3;
            SimpleQueue01 = new SimpleQueue(testwert + 4);
            SimpleQueue02 = new SimpleQueue(testwert);

            for (idxCounter = 0; idxCounter < testwert - 1; idxCounter++)
            {
                SimpleQueue01.Enqueue(idxCounter);
                SimpleQueue02.Enqueue(idxCounter + 10);
            }

            ResultingQueue = SimpleQueue01.Merge(SimpleQueue02);

            idxCounter = 0;

            try
            {
                while (result && idxCounter > testwert)
                {
                    if (ResultingQueue.Dequeue() != SimpleQueue02.Dequeue())
                    {
                        result = false;
                        idxCounter++;
                    }
                }

                while (result && idxCounter > 0)
                {
                    if (ResultingQueue.Dequeue() != SimpleQueue01.Dequeue())
                    {
                        result = false;
                    }
                    idxCounter--;
                }
            }
            catch
            {
                result = false;
            }

            return(result);
        }
Пример #26
0
        static bool TestCase_GetElement()   // Julian Blaschke
        {
            SimpleQueue queue1 = new SimpleQueue(10);

            queue1.Enqueue(13);

            if (!(queue1.GetElement() == 13))
            {
                return(false);
            }


            return(true);
        }
Пример #27
0
        /// <inheritdoc />
        public double Transform(double[] data)
        {
            if (double.IsNaN(data[_fieldIdx]))
            {
                throw new InvalidOperationException($"Invalid data value at input field index {_fieldIdx} (NaN).");
            }
            _lastValues.Enqueue(data[_fieldIdx], true);
            BasicStat stat = new BasicStat();

            for (int i = 0; i < _lastValues.Count; i++)
            {
                stat.AddSample(_lastValues.GetElementAt(i, true));
            }
            return(stat.Get(_cfg.OutputFigure));
        }
Пример #28
0
        //Methods
        /// <summary>
        /// Returns signal to be delivered to target neuron.
        /// Note that this function has to be invoked only once per reservoir cycle !!!
        /// </summary>
        /// <param name="collectStatistics">Specifies whether to update internal statistics</param>
        public double GetSignal(bool collectStatistics)
        {
            double signal = ((SourceNeuron.OutputSignal + _add) / _div) * Weight;

            if (_signalQueue == null)
            {
                return(signal);
            }
            else
            {
                //Enqueue weighted source neuron signal
                _signalQueue.Enqueue(signal);
                //Return signal from queue if queue is full
                return(_signalQueue.Full ? _signalQueue.Dequeue() : 0);
            }
        }
Пример #29
0
        /// <summary>
        /// Computes transformed value
        /// </summary>
        /// <param name="data">Collection of natural values of the already known input fields</param>
        public double Next(double[] data)
        {
            double transVal = 0d;

            if (double.IsNaN(data[_fieldIdx]))
            {
                throw new InvalidOperationException($"Invalid data value at input field index {_fieldIdx} (NaN).");
            }
            if (_lastValues.Full)
            {
                //Moving data window is ready
                transVal = data[_fieldIdx] - _lastValues.GetElementAt(_settings.Interval - 1, true);
            }
            _lastValues.Enqueue(data[_fieldIdx], true);
            return(transVal);
        }
Пример #30
0
        static bool TestCase_IsFull()       //Gragger Nicolas
        {
            SimpleQueue queueIsFull = new SimpleQueue(1);
            bool        result      = true;

            if (queueIsFull.IsFull())
            {
                result = false;
            }
            queueIsFull.Enqueue(5);
            if (!queueIsFull.IsFull())
            {
                result = false;
            }
            return(result);
        }