예제 #1
0
 /// <summary>Core of WakeUpWaiters, separated out for performance due to inlining.</summary>
 private static void WakeUpWaitersCore(SimpleQueue <Reader <bool> > waiters, bool result)
 {
     while (waiters.Count > 0)
     {
         waiters.Dequeue().Success(result);
     }
 }
예제 #2
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);
        }
예제 #3
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);
            }
예제 #5
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);
            }
        }
예제 #6
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);
        }
예제 #7
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);
                }
            }
        }
            public bool TryComplete(Exception error = null)
            {
                lock (SyncObj)
                {
                    AssertInvariants();

                    // Mark the channel as done for writing.  This may only be done once.
                    if (_doneWriting != null)
                    {
                        return(false);
                    }
                    _doneWriting = error ?? s_doneWritingSentinel;

                    // If there are no items in the channel, then there's no more work to be done,
                    // so we complete the completion task.
                    if (_items.Count == 0)
                    {
                        CompleteWithOptionalError(_completion, error);
                    }

                    // If there are any waiting readers, fail them all, as they'll now never be satisfied.
                    while (_blockedReaders.Count > 0)
                    {
                        var reader = _blockedReaders.Dequeue();
                        reader.Fail(error ?? CreateInvalidCompletionException());
                    }

                    // If there are any waiting writers, fail them all, as they shouldn't be writing
                    // now that we're complete for writing.
                    while (_blockedWriters.Count > 0)
                    {
                        var writer = _blockedWriters.Dequeue();
                        writer.Fail(CreateInvalidCompletionException());
                    }

                    // If there are any pending WaitToRead/WriteAsync calls, wake them up.
                    WakeUpWaiters(_waitingReaders, false);
                    WakeUpWaiters(_waitingWriters, false);
                }

                return(true);
            }
예제 #9
0
            public ValueTask <T> ReadAsyncCore(CancellationToken cancellationToken)
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    return(Task.FromCanceled <T>(cancellationToken));
                }

                lock (SyncObj)
                {
                    AssertInvariants();

                    // If there are any items, return one.
                    if (_items.Count > 0)
                    {
                        // Dequeue an item
                        T item = _items.Dequeue();
                        if (_doneWriting != null && _items.Count == 0)
                        {
                            // If we've now emptied the items queue and we're not getting any more, complete.
                            CompleteWithOptionalError(_completion, _doneWriting);
                        }

                        return(item);
                    }

                    // There are no items, so if we're done writing, 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);
                }
            }
예제 #10
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);
        }
예제 #11
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);
            }
        }
        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());
            }
        }
예제 #13
0
        private async Task Consume()
        {
            var queue = new SimpleQueue <SimpleDocument>(this.GetType().FullName);

            while (_totalConsumed < 40)
            {
                var item = await queue.Dequeue();

                if (item != null)
                {
                    Console.WriteLine($"[{Thread.CurrentThread.ManagedThreadId}] Consumed: {item.Payload}");
                    Interlocked.Increment(ref _totalConsumed);
                    await queue.Confirm(item);
                }

                //Very long work
                await Task.Delay(_random.Next(500));
            }
        }
예제 #14
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);
        }
예제 #15
0
        public async Task TestNoPriority()
        {
            var queue = new SimpleQueue <SimpleDocument>(this.GetType().FullName);

            await queue.Clear();

            for (int i = 0; i < 100; i++)
            {
                await queue.Enqueue(
                    new SimpleDocument()
                {
                    Value = i.ToString()
                });
            }


            for (int i = 0; i < 100; i++)
            {
                Assert.AreEqual(i.ToString(), (await queue.Dequeue()).Payload.Value);
            }
        }
예제 #16
0
        internal void ProcessPending()
        {
            if (_queue.count == 0)
            {
                return;
            }

            _watch.Start();

            do
            {
                Action next;
                lock (_queue)
                {
                    next = _queue.Dequeue();
                }

                next();
            }while (_queue.count > 0 && _watch.ElapsedMilliseconds < _maxMillisecondsPerFrame);

            _watch.Reset();
        }
예제 #17
0
파일: HiddenNeuron.cs 프로젝트: thild/NET
        /// <summary>
        /// Computes neuron's new output signal and updates statistics
        /// </summary>
        /// <param name="collectStatistics">Specifies whether to update internal statistics</param>
        public void Recompute(bool collectStatistics)
        {
            //Spike leak handling
            if (OutputData._spikingSignal > 0)
            {
                //Spike during previous cycle, so reset the counter
                OutputData._afterFirstSpike = true;
                OutputData._spikeLeak       = 0;
            }
            ++OutputData._spikeLeak;

            double normalizedActivation;

            if (_activation.TypeOfActivation == ActivationType.Spiking)
            {
                //Spiking activation
                OutputData._spikingSignal = _activation.Compute(_tStimuli);
                //OutputData._analogSignal = OutputData._spikingSignal;
                _activationState         = _activation.InternalState;
                normalizedActivation     = _outputRange.Rescale(_activation.InternalState, _activation.InternalStateRange).Bound(_outputRange.Min, _outputRange.Max);
                OutputData._analogSignal = normalizedActivation;
            }
            else
            {
                //Analog activation
                double newState = _activation.Compute(_tStimuli);
                _activationState     = (_analogRetainmentStrength * _activationState) + (1d - _analogRetainmentStrength) * newState;
                normalizedActivation = _outputRange.Rescale(_activationState, _activation.OutputRange).Bound(_outputRange.Min, _outputRange.Max);
                bool firingEvent = _histActivationsQueue == null ? ((normalizedActivation - OutputData._analogSignal) > _analogFiringThreshold) : (_histActivationsQueue.Full ? (normalizedActivation - _histActivationsQueue.Dequeue()) > _analogFiringThreshold : (normalizedActivation - 0.5d) > _analogFiringThreshold);
                _histActivationsQueue?.Enqueue(normalizedActivation);
                //New output data
                OutputData._analogSignal  = normalizedActivation;
                OutputData._spikingSignal = firingEvent ? 1d : 0d;
            }
            //Update predictors
            _predictors?.Update(_activationState, normalizedActivation, (OutputData._spikingSignal > 0));
            //Update statistics
            if (collectStatistics)
            {
                Statistics.Update(_iStimuli, _rStimuli, _tStimuli, _activationState, OutputData._analogSignal, OutputData._spikingSignal);
            }
            return;
        }
예제 #18
0
        /// <inheritdoc/>
        public void Recompute(bool collectStatistics)
        {
            //Spike leak handling
            if (OutputData._spikingSignal > 0)
            {
                //Spike during previous cycle, so reset the counter
                OutputData._afterFirstSpike = true;
                OutputData._spikeLeak       = 0;
            }
            ++OutputData._spikeLeak;

            double normalizedActivation;

            if (_activationFn.TypeOfActivation == ActivationType.Spiking)
            {
                //Spiking activation
                AFSpikingBase af = (AFSpikingBase)_activationFn;
                OutputData._spikingSignal = af.Compute(_tStimuli);
                //OutputData._analogSignal = OutputData._spikingSignal;
                _activationState         = af.InternalState;
                normalizedActivation     = OutputRange.Rescale(af.InternalState, af.InternalStateRange).Bound(OutputRange.Min, OutputRange.Max);
                OutputData._analogSignal = normalizedActivation;
            }
            else
            {
                //Analog activation
                _activationState     = (_analogRetainmentStrength * _activationState) + (1d - _analogRetainmentStrength) * _activationFn.Compute(_tStimuli);
                normalizedActivation = OutputRange.Rescale(_activationState, _activationFn.OutputRange).Bound(OutputRange.Min, OutputRange.Max);
                double activationDifference = _histActivationsQueue == null ? ((normalizedActivation - OutputData._analogSignal)) : (_histActivationsQueue.Full ? (normalizedActivation - _histActivationsQueue.Dequeue()) : (normalizedActivation - 0.5d));
                //Firing event decision
                bool firingEvent = activationDifference > _analogFiringThreshold;
                //Enqueue last normalized activation
                _histActivationsQueue?.Enqueue(normalizedActivation);
                //New output data
                OutputData._analogSignal  = normalizedActivation;
                OutputData._spikingSignal = firingEvent ? 1d : 0d;
            }
            //Update predictors
            _predictorsProvider?.Update(_activationState, normalizedActivation, (OutputData._spikingSignal > 0));
            //Update statistics
            if (collectStatistics)
            {
                Statistics.Update(_iStimuli, _rStimuli, _tStimuli, _activationState, OutputData._analogSignal, OutputData._spikingSignal);
            }
            return;
        }