public void Register(uint tick, uint entityId, Vector2 pos)
        {
            if (!Buffer.ContainsKey(tick))
            {
                Buffer.Add(tick, new Dictionary <uint, Vector2>(10));
            }

            if (!Buffer[tick].ContainsKey(entityId))
            {
                Buffer[tick].Add(entityId, pos); //Initial size of 5 commands per frame per player
            }
            else
            {
                throw new Exception();
            }
        }
        private void AddLeftParenthesis(string input)
        {
            //left parenthesis cannot immediately follow a value or unary operator
            if (KeyHistory.Last() == KeyType.Value || KeyHistory.Last() == KeyType.Unary)
            {
                throw new InvalidOperationException("Missing Operators.");
            }
            //left parenthesis cannot immediately follow right parenthesis
            if (KeyHistory.Last() == KeyType.Right)
            {
                throw new InvalidOperationException("Mismatched Parentheses.");
            }

            Buffer.Add(input);
            KeyHistory.Add(KeyType.Left);
        }
        /// <summary>
        /// To handle the input value.
        /// </summary>
        /// <param name="input">The input value.</param>
        /// <returns>The resulting value.</returns>
        protected override IIndicatorValue OnProcess(IIndicatorValue input)
        {
            var price = input.GetValue <Candle>().ClosePrice;

            if (Buffer.Count > Length)
            {
                Buffer.RemoveAt(0);
            }

            if (input.IsFinal)
            {
                Buffer.Add(price);
            }

            return(new DecimalIndicatorValue(this, price));
        }
        /// <summary>Pump the content of a source into a list</summary>
        public static async Task <List <T> > PumpToListAsync <T>(this IAsyncSource <T> source, CancellationToken ct)
        {
            if (ct.IsCancellationRequested)
            {
                ct.ThrowIfCancellationRequested();
            }

            var buffer = new Buffer <T>();

            var target = CreateTarget <T>(
                (x, _) => buffer.Add(x)
                );

            await PumpToAsync <T>(source, target, ct).ConfigureAwait(false);

            return(buffer.ToList());
        }
예제 #5
0
 void LinearCrossover()
 {
     Buffer.Clear();
     for (int i = 0; i < Population.Count - 1; i++)
     {
         var Children = Tuple.Create(new PopulationParameters
                                         (0, Population[i].Child((x, y) => (x + y) / 2, Population[i + 1], Funct)),
                                     new PopulationParameters(0, Population[i].Child((x, y) => (3 * x - y) / 2, Population[i + 1], Funct)),
                                     new PopulationParameters(0, Population[i].Child((x, y) => (-x + 3 * y) / 2, Population[i + 1], Funct)));
         Children.Item1.Fitness = Funct.Function(Children.Item1.Args);
         Children.Item2.Fitness = Funct.Function(Children.Item2.Args);
         Children.Item3.Fitness = Funct.Function(Children.Item3.Args);
         var BestChildren = Tournament(Children);
         Buffer.Add(BestChildren.Item1);
         Buffer.Add(BestChildren.Item2);
     }
 }
예제 #6
0
        /// <summary>
        /// Обработать входное значение.
        /// </summary>
        /// <param name="input">Входное значение.</param>
        /// <returns>Результирующее значение.</returns>
        protected override IIndicatorValue OnProcess(IIndicatorValue input)
        {
            var candle = input.GetValue <Candle>();

            decimal?result = null;
            var     buff   = _buffer;

            if (input.IsFinal)
            {
                _buffer.Add(candle);

                // если буффер стал достаточно большим (стал больше длины)
                if (_buffer.Count > Length)
                {
                    _buffer.RemoveAt(0);
                }
            }
            else
            {
                buff = _buffer.Skip(1).Concat(candle).ToList();
            }

            if (buff.Count >= Length)
            {
                // рассчитываем значение
                var max = buff.Max(t => t.HighPrice);
                var min = buff.Min(t => t.LowPrice);

                if (Kijun.IsFormed && input.IsFinal)
                {
                    Buffer.Add((max + min) / 2);
                }

                if (Buffer.Count >= Kijun.Length)
                {
                    result = Buffer[0];
                }

                if (Buffer.Count > Kijun.Length)
                {
                    Buffer.RemoveAt(0);
                }
            }

            return(result == null ? new DecimalIndicatorValue(this) : new DecimalIndicatorValue(this, result.Value));
        }
예제 #7
0
    private TagHelperContent AppendCore(object entry)
    {
        if (!_hasContent)
        {
            _isSingleContentSet = true;
            _singleContent      = entry;
        }
        else
        {
            Buffer.Add(entry);
        }

        _isModified = true;
        _hasContent = true;

        return(this);
    }
예제 #8
0
 private static void SendPlcSignals(Signal s)
 {
     /*  using (var sw = File.AppendText(file))
      * {
      *    sw.WriteLine("Start: " + processStart.ToString("HH:mm:ss") + " End: " + processEnd.ToString("HH:mm:ss") + " Elapsed: " + processEnd.Subtract(processStart).TotalMilliseconds);
      * }
      */
     if (_inProcess)
     {
         Buffer.Add(s, 0);
     }
     else
     {
         _inProcess = true;
         SendSignal(s.Cell, s.Offsets, s.Px, s.Py, s.Type, s.Count, s.CellFull, s.Boxed, s.OffX, s.OffY,
                    s.KatMax);
     }
 }
예제 #9
0
		/// <summary>
		/// To handle the input value.
		/// </summary>
		/// <param name="input">The input value.</param>
		/// <returns>The resulting value.</returns>
		protected override IIndicatorValue OnProcess(IIndicatorValue input)
		{
			var candle = input.GetValue<Candle>();
			decimal average = (candle.HighPrice + candle.LowPrice) / 2;
			var halfRange = (candle.HighPrice - candle.LowPrice) / 2;

			Buffer.Add(average);
			//var Chec1 = Buffer[Buffer.Count - 1];

			if (IsFormed)
			{
				if (Buffer.Count > Length)
					Buffer.RemoveAt(0);
				//Сглаженное приращение ****************************************************************************
				var avgDiff = Buffer[Buffer.Count - 1] - Buffer[Buffer.Count - 2];
				decimal smoothDiff = _smoothConstant * avgDiff + _smoothConstant1 * _value1Old;
				_value1Old = smoothDiff;

				//Сглаженный Half Range *********************************************************************************

				decimal smoothRng = _smoothConstant * halfRange + _smoothConstant1 * _value2Old;
				_value2Old = smoothRng;

				//Tracking index ***********************************************************************************
				if (smoothRng != 0)
					_lambda = System.Math.Abs(smoothDiff / smoothRng);

				//Alfa для альфа фильтра ***************************************************************************
				_alpha = (-_lambda * _lambda + (decimal)System.Math.Sqrt((double)(_lambda * _lambda * _lambda * _lambda + 16 * _lambda * _lambda))) / 8;

				//Smoothed result **********************************************************************************
				var check2 = _alpha * average;
				var check3 = (1 - _alpha) * _resultOld;
				decimal result = check2 + check3;
				_resultOld = result;

				return new DecimalIndicatorValue(this, result);
			}

			_value2Old = halfRange;
			_resultOld = average;

			return new DecimalIndicatorValue(this, _resultOld);
		}
        public override void init_population()
        {
            int targetLength = StrTarget.Length;

            Population.Clear();
            Buffer.Clear();
            for (int i = 0; i < GaPopSize; i++)
            {
                StringGen citizen = new StringGen(Rand, targetLength);
                //for (int j = 0; j < targetLength; j++)
                //{
                //    var randVal = Rand.Next();
                //    citizen.Str += Convert.ToChar((randVal % 90) + 32);
                //}

                Population.Add(citizen);
                Buffer.Add(new StringGen());
            }
        }
예제 #11
0
        private void UpdateAngularVelocityHistory()
        {
            if (rotationHistory.Count < 2)
            {
                return;
            }

            float      delta        = Time.deltaTime;
            float      angleDegrees = 0.0f;
            Vector3    unitAxis     = Vector3.zero;
            Quaternion rotation     = Quaternion.identity;

            rotation = (rotationHistory[rotationHistory.Count - 1]) * Quaternion.Inverse(rotationHistory[rotationHistory.Count - 2]);

            rotation.ToAngleAxis(out angleDegrees, out unitAxis);
            Vector3 angular = unitAxis * ((angleDegrees * Mathf.Deg2Rad) / delta);

            angularVelocityHistory.Add(angular);
        }
예제 #12
0
        /// <summary>
        /// To handle the input value.
        /// </summary>
        /// <param name="input">The input value.</param>
        /// <returns>The resulting value.</returns>
        protected override IIndicatorValue OnProcess(IIndicatorValue input)
        {
            //если кол-во в буфере больше Shift, то первое значение отдали в прошлый раз, удалим его.
            if (Buffer.Count > Shift)
            {
                Buffer.RemoveAt(0);
            }

            var smaResult = _sma.Process(_medianPrice.Process(input));

            if (_sma.IsFormed & input.IsFinal)
            {
                Buffer.Add(smaResult.GetValue <decimal>());
            }

            return(Buffer.Count > Shift
                                ? new DecimalIndicatorValue(this, Buffer[0])
                                : new DecimalIndicatorValue(this));
        }
예제 #13
0
            public override void TraceFromCallback()
            {
                var  regs   = DebuggableCore.GetCpuFlagsAndRegisters();
                uint pc     = (uint)regs["M68K PC"].Value;
                var  length = 0;
                var  disasm = Disassembler.Disassemble(MemoryDomains.SystemBus, pc, out length);

                var traceInfo = new TraceInfo
                {
                    Disassembly = string.Format("{0:X6}:  {1}", pc, disasm)
                };

                var sb = new StringBuilder();

                foreach (var r in regs)
                {
                    if (r.Key.StartsWith("M68K"))                        // drop Z80 regs until it has its own debugger/tracer
                    {
                        if (r.Key != "M68K SP" && r.Key != "M68K ISP" && // copies of a7
                            r.Key != "M68K PC" &&                        // already present in every line start
                            r.Key != "M68K IR")                          // copy of last opcode, already shown in raw bytes
                        {
                            sb.Append(
                                string.Format("{0}:{1} ",
                                              r.Key.Replace("M68K", string.Empty).Trim(),
                                              r.Value.Value.ToHexString(r.Value.BitSize / 4)));
                        }
                    }
                }
                var sr = regs["M68K SR"].Value;

                sb.Append(
                    string.Format("{0}{1}{2}{3}{4}",
                                  (sr & 16) > 0 ? "X" : "x",
                                  (sr & 8) > 0 ? "N" : "n",
                                  (sr & 4) > 0 ? "Z" : "z",
                                  (sr & 2) > 0 ? "V" : "v",
                                  (sr & 1) > 0 ? "C" : "c"));

                traceInfo.RegisterInfo = sb.ToString().Trim();

                Buffer.Add(traceInfo);
            }
        public void SetCharacterSize(ECharacterSize size)
        {
            LogController("SetCharacterSize(size:" + size.ToString() + ")");

            while ((CursorState.CurrentRow + TopRow) >= Buffer.Count)
            {
                Buffer.Add(new TerminalLine());
            }
            var currentLine = Buffer[CursorState.CurrentRow + TopRow];

            switch (size)
            {
            default:
            case ECharacterSize.SingleWidthLine:
                currentLine.DoubleWidth        = false;
                currentLine.DoubleHeightTop    = false;
                currentLine.DoubleHeightBottom = false;
                break;

            case ECharacterSize.DoubleHeightLineTop:
                currentLine.DoubleWidth        = true;
                currentLine.DoubleHeightBottom = false;
                currentLine.DoubleHeightTop    = true;
                break;

            case ECharacterSize.DoubleHeightLineBottom:
                currentLine.DoubleWidth        = true;
                currentLine.DoubleHeightTop    = false;
                currentLine.DoubleHeightBottom = true;
                break;

            case ECharacterSize.DoubleWidthLine:
                currentLine.DoubleHeightTop    = false;
                currentLine.DoubleHeightBottom = false;
                currentLine.DoubleWidth        = true;
                break;

            case ECharacterSize.ScreenAlignmentTest:
                ScreenAlignmentTest();
                break;
            }
        }
예제 #15
0
        protected bool Replaying(object message)
        {
            switch (message)
            {
            case ReplayedEvent replayed:
                Buffer.Add(new EventEnvelope(
                               offset: new Sequence(replayed.Offset),
                               persistenceId: replayed.Persistent.PersistenceId,
                               sequenceNr: replayed.Persistent.SequenceNr,
                               @event: replayed.Persistent.Payload));

                CurrentOffset = replayed.Offset;
                Buffer.DeliverBuffer(TotalDemand);
                return(true);

            case EventReplaySuccess success:
                Log.Debug("event replay completed, currOffset [{0}], highestSequenceNr [{1}]", CurrentOffset, success.HighestSequenceNr);
                ReceiveRecoverySuccess(success.HighestSequenceNr);
                return(true);

            case EventReplayFailure failure:
                Log.Debug("event replay failed, due to [{0}]", failure.Cause.Message);
                Buffer.DeliverBuffer(TotalDemand);
                OnErrorThenStop(failure.Cause);
                return(true);

            case Request _:
                Buffer.DeliverBuffer(TotalDemand);
                return(true);

            case Cancel _:
                Context.Stop(Self);
                return(true);

            case AllEventsPublisher.Continue _:
            case NewEventAppended _:
                return(true);

            default:
                return(false);
            }
        }
예제 #16
0
        public C64Sprite Undo(C64Sprite currentState)
        {
            if (!CanUndo)
            {
                throw new SystemException();
            }
            if (NeedsCurrentState(currentState))
            {
                Buffer.Add(currentState.Clone());
            }
            var result = Buffer[UndoPointer];

            UndoPointer--;
            if (result.CompareTo(currentState))
            {
                result = Buffer[UndoPointer];
                UndoPointer--;
            }
            return(result);
        }
예제 #17
0
        private static void TestBufferInternal(int interation, ManualResetEvent sinkWaitHandle, Buffer <int> buffer)
        {
            Task.Run(() =>
            {
                for (int i = 0; i < 20; i++)
                {
                    buffer.Add(i);
                }
            });
            Thread.Sleep(500);
            //Should block
            int count = buffer.Count;

            Assert.InRange(count, 10, 11);
            buffer.Requeue(-1, true);
            Assert.Equal(count + 1, buffer.Count);
            sinkWaitHandle.Set();
            Thread.Sleep(500);
            Assert.Equal(0, buffer.Count);
        }
        public void AddBinary(string input)
        {
            //consecutive binary operator input is not allowed
            if (KeyHistory.Last() == KeyType.Binary)
            {
                throw new InvalidOperationException("Missing Operand.");
            }

            /*
             * when binary operator input follows left parenthesis or nothing,
             * a value of zero will be added as default operand
             */
            if (KeyHistory.Last() == KeyType.Left || KeyHistory.Last() == KeyType.Empty)
            {
                AddValue(0);
            }

            Buffer.Add(input);
            KeyHistory.Add(KeyType.Binary);
        }
예제 #19
0
        public void ImplicitRemoveAt()
        {
            Buffer.MaxCapacity = 16;
            // generate 32 extra messsages to exceed the max capacity which
            // forces a RemoveAt() call of the oldest messages
            var bufferCount = Buffer.Count;
            var msgs        = new List <MessageModel>(Buffer);

            for (int i = 1; i <= 32; i++)
            {
                var builder = new MessageBuilder();
                builder.AppendText("msg{0}", bufferCount + i);
                var msg = builder.ToMessage();
                msgs.Add(msg);
                Buffer.Add(msg);
            }

            Assert.AreEqual(Buffer.MaxCapacity, Buffer.Count);
            Assert.AreEqual(msgs[32 - (Buffer.MaxCapacity - bufferCount)].ToString(), Buffer[0].ToString());
        }
예제 #20
0
        public override void init_population()
        {
            Population.Clear();
            Buffer.Clear();
            for (int i = 0; i < GaPopSize; i++)
            {
                List <int> emptyVols  = Enumerable.Repeat(-1, _volumes.Count).ToList();
                VolumesGen volumesGen = new VolumesGen(emptyVols);
                List <int> vols       = new List <int>(_volumes);
                for (int j = 0; j < _volumes.Count; j++)
                {
                    var index = Rand.Next() % vols.Count;
                    volumesGen.Volumes[j] = vols[index];
                    vols.RemoveAt(index);
                }

                Population.Add(volumesGen);
                Buffer.Add(new VolumesGen(emptyVols));
            }
        }
        public void PutChar(char character)
        {
            LogExtreme("PutChar(ch:'" + character + "'=" + ((int)character).ToString() + ")");

            if (CursorState.InsertMode == EInsertReplaceMode.Insert)
            {
                while (Buffer.Count <= (TopRow + CursorState.CurrentRow))
                {
                    Buffer.Add(new TerminalLine());
                }

                var line = Buffer[TopRow + CursorState.CurrentRow];
                while (line.Count < CursorState.CurrentColumn)
                {
                    line.Add(new TerminalCharacter());
                }

                line.Insert(CursorState.CurrentColumn, new TerminalCharacter());
            }

            if (CursorState.WordWrap)
            {
                if (CursorState.CurrentColumn >= Columns)
                {
                    CursorState.CurrentColumn = 0;
                    NewLine();
                }
            }

            SetCharacter(CursorState.CurrentColumn, CursorState.CurrentRow, character, CursorState.Attribute);
            CursorState.CurrentColumn++;

            var lineToClip = Buffer[TopRow + CursorState.CurrentRow];

            while (lineToClip.Count > Columns)
            {
                lineToClip.RemoveAt(lineToClip.Count - 1);
            }

            ChangeCount++;
        }
        private void AddRightParenthesis(string input)
        {
            //right parenthesis cannot immediately follow binary operator
            if (KeyHistory.Last() == KeyType.Binary)
            {
                throw new InvalidOperationException("Missing Operand.");
            }
            //parentheses must match
            if (MissingParentheses(Expression) < 1)
            {
                throw new InvalidOperationException("Mismatched Parentheses.");
            }

            if (KeyHistory.Last() == KeyType.Left)
            {
                AddValue(0);
            }

            Buffer.Add(input);
            KeyHistory.Add(KeyType.Right);
        }
예제 #23
0
        /// <summary>
        /// Обработать входное значение.
        /// </summary>
        /// <param name="input">Входное значение.</param>
        /// <returns>Результирующее значение.</returns>
        protected override IIndicatorValue OnProcess(IIndicatorValue input)
        {
            var newValue = input.GetValue <decimal>();

            if (input.IsFinal)
            {
                Buffer.Add(newValue);

                if (Buffer.Count > Length)
                {
                    Buffer.RemoveAt(0);
                }
            }

            if (input.IsFinal)
            {
                return(new DecimalIndicatorValue(this, Buffer.Sum() / Length));
            }

            return(new DecimalIndicatorValue(this, (Buffer.Skip(1).Sum() + newValue) / Length));
        }
        private void SetCharacter(int currentColumn, int currentRow, char ch, TerminalAttribute attribute)
        {
            while (Buffer.Count < (currentRow + TopRow + 1))
            {
                Buffer.Add(new TerminalLine());
            }

            var line = Buffer[currentRow + TopRow];

            while (line.Count < (currentColumn + 1))
            {
                line.Add(new TerminalCharacter {
                    Char = ' ', Attributes = CursorState.Attribute
                });
            }

            var character = line[currentColumn];

            character.Char       = ch;
            character.Attributes = attribute.Clone();
        }
예제 #25
0
        /// <inheritdoc />
        protected override IIndicatorValue OnProcess(IIndicatorValue input)
        {
            var newValue = input.GetValue <decimal>();

            if (input.IsFinal)
            {
                Buffer.Add(newValue);

                if ((Buffer.Count - 1) > Length)
                {
                    Buffer.RemoveAt(0);
                }
            }

            if (Buffer.Count == 0)
            {
                return(new DecimalIndicatorValue(this));
            }

            return(new DecimalIndicatorValue(this, newValue - Buffer[0]));
        }
예제 #26
0
        /// <summary>
        /// To handle the input value.
        /// </summary>
        /// <param name="input">The input value.</param>
        /// <returns>The resulting value.</returns>
        protected override IIndicatorValue OnProcess(IIndicatorValue input)
        {
            var smaValue = _sma.Process(input);

            if (_sma.IsFormed && input.IsFinal)
            {
                Buffer.Add(smaValue.GetValue <decimal>());
            }

            if (!IsFormed)
            {
                return(new DecimalIndicatorValue(this));
            }

            if (Buffer.Count > Length)
            {
                Buffer.RemoveAt(0);
            }

            return(new DecimalIndicatorValue(this, input.GetValue <decimal>() - Buffer[0]));
        }
예제 #27
0
        public void RunOpenBufferBenchmark(int itemCount)
        {
            Buffer.Dispose();
            Buffer = CreateBuffer();

            var bufferType = Buffer.GetType().Name;

            // generate items
            for (int i = 0; i < itemCount; i++)
            {
                Buffer.Add(new MessageModel(SimpleMessage));
            }
            // flush/close buffer
            Buffer.Dispose();

            int      runs = 10;
            var      messageCount = 0;
            DateTime start, stop;

            start = DateTime.UtcNow;
            for (int i = 0; i < runs; i++)
            {
                Buffer        = OpenBuffer();
                messageCount += Buffer.Count;
                Buffer.Dispose();
            }
            stop = DateTime.UtcNow;
            Assert.AreEqual(runs * itemCount, messageCount);

            var total = (stop - start).TotalMilliseconds;

            Console.WriteLine(
                "{0}(): avg: {1:0.00} ms items: {2} runs: {3} took: {4:0.00} ms",
                bufferType,
                total / runs,
                itemCount,
                runs,
                total
                );
        }
 /// <summary>
 /// Copies the values of the objects to capture
 /// into the buffer by reading capture objects.
 /// </summary>
 public void Capture(GXDLMSServer server)
 {
     lock (this)
     {
         object[]         values = new object[CaptureObjects.Count];
         int              pos    = 0;
         ValueEventArgs[] args   = new ValueEventArgs[] { new ValueEventArgs(server, this, 2, 0, null) };
         server.PreGet(args);
         if (!args[0].Handled)
         {
             foreach (GXKeyValuePair <GXDLMSObject, GXDLMSCaptureObject> it in CaptureObjects)
             {
                 if (it.Value.AttributeIndex == 0)
                 {
                     values[pos] = it.Key.GetValues();
                 }
                 else
                 {
                     values[pos] = it.Key.GetValues()[it.Value.AttributeIndex - 1];
                 }
                 ++pos;
             }
             lock (Buffer)
             {
                 //Remove first items if buffer is full.
                 if (ProfileEntries != 0 && ProfileEntries == Buffer.Count)
                 {
                     --EntriesInUse;
                     Buffer.RemoveAt(0);
                 }
                 Buffer.Add(values);
                 ++EntriesInUse;
             }
         }
         server.PostGet(args);
         server.NotifyAction(args);
         server.NotifyPostAction(args);
     }
 }
예제 #29
0
        public override SignalAndValue Process(Candle candle)
        {
            var val = candle.CloseBid;

            if (candle.IsComplete == 1)
            {
                Buffer.Add(val);
            }

            var smaValue = Sma.Process(candle).Value;

            if (Buffer.Count > Length)
            {
                Buffer.RemoveAt(0);
            }

            var md = candle.IsComplete == 1
                ? Buffer.Sum(t => Math.Abs(t - smaValue))
                : Buffer.Skip(IsFormed ? 1 : 0).Sum(t => Math.Abs(t - smaValue)) + Math.Abs(val - smaValue);

            return(new SignalAndValue(md / Length, IsFormed));
        }
예제 #30
0
        protected override IIndicatorValue OnProcess(IIndicatorValue input)
        {
            var candle      = input.GetValue <Candle>();
            var medianPrice = (candle.ClosePrice + candle.OpenPrice + candle.HighPrice + candle.LowPrice) / 4m;

            Buffer.Add(medianPrice);

            Vector <double> val = DenseVector.Create(1, (i) => 0);

            val[0] = (double)medianPrice;

            RecalculateFilterParameters(val);

            if (Buffer.Count < 5)
            {
                return(new DecimalIndicatorValue(this, medianPrice));
            }

            IsFormed = true;

            return(new DecimalIndicatorValue(this, (decimal)xplus[0]));
        }