Example #1
0
 public SignalSeries(double value, SignalType st, Color stColor, bool canDrag)
 {
     this.value       = value;
     this.signal      = st;
     this.signalColor = stColor;
     this.canDrag     = canDrag;
 }
Example #2
0
        public static float SignalValue(SignalType signalType, float frequency, float time, float amplitude)
        {
            float value = 0f;
            float t     = frequency * time;

            switch (signalType)
            {
            case SignalType.Sine:     // sin( 2 * pi * t )
                value = Mathf.Sin(2f * Mathf.PI * t);
                break;

            case SignalType.Square:     // sign( sin( 2 * pi * t ) )
                value = Mathf.Sign(Mathf.Sin(2f * Mathf.PI * t));
                break;

            case SignalType.Triangle:
                // 2 * abs( t - 2 * floor( t / 2 ) - 1 ) - 1
                value = 1f - 4f * Mathf.Abs(Mathf.Round(t - 0.25f) - (t - 0.25f));
                break;

            case SignalType.Sawtooth:
                // 2 * ( t/a - floor( t/a + 1/2 ) )
                value = 2f * (t - Mathf.Floor(t + 0.5f));
                break;
            }

            return(amplitude * value);
        }
        public PhysioSignalView(float[] data, int bitsPerSample, float samplingRate, SignalType physioSignalType)
        {
            BitsPerSample = bitsPerSample;
            SamplingRate  = samplingRate;
            SignalType    = physioSignalType;
            Data          = data;

            if (Data.Length > 0)
            {
                var min = data[0];
                var max = data[0];
                for (int i = 1; i < data.Length; ++i)
                {
                    if (data[i] < min)
                    {
                        min = data[i];
                    }
                    else if (data[i] > max)
                    {
                        max = data[i];
                    }
                }
                Min = min;
                Max = max;
            }
        }
 public BranchProcessData(DPoint branchingTileLocation, DPoint firstWireLocation, SignalType signal): this() {
   this.BranchingTileLocation = branchingTileLocation;
   this.FirstWireLocation = firstWireLocation;
   this.LastWireLocation = DPoint.Empty;
   this.Signal = signal;
   this.Direction = AdvancedCircuits.DirectionFromTileLocations(branchingTileLocation, firstWireLocation);
 }
Example #5
0
        private readonly ushort[] mModulesCfg  = new ushort[16];  // numbers of outputs registers
        private bool IsValidAddress(SignalType type, ushort address, byte bit)
        {
            var signals = mSignals.Values.Where(s => s.Index == address).ToArray();

            if (signals.Length == 0)
            {
                signals = mSignals.Values.Where(s => s.Index == address - 1).ToArray();
                if (signals.Count(signal => signal.Type == SignalType.Float) > 0)// || signal.Type == SignalType.Uint) > 0)
                {
                    return(false);
                }

                // если у нас не однорегистровый сигнал, надо проверить, что нет сигналов ближе, чем через один регистр от стартового
                if (type != SignalType.Ushort || type != SignalType.Bool)
                {
                    if (mSignals.Values.Where(s => s.Index == address + 1).ToArray().Length > 0)
                    {
                        return(false);
                    }
                }

                return(true);
            }

            // discreet check
            if (type == SignalType.Bool && signals[0].Type == SignalType.Bool)
            {
                return(signals.All(signal => signal.Mask != (1 << bit)));
            }

            return(false);
        }
Example #6
0
        /// <summary>
        /// Get signal for the bar
        /// </summary>
        /// <returns></returns>
        protected SignalType GetSignal(int bar)
        {
            SignalType result = SignalType.None;

            if (this.IsLastPositionActive)
            {
                return(result);
            }

            if (stochKSeries[bar - 1] > stochDSeries[bar - 1] && // Fast stochK cross down low stochD
                stochKSeries[bar] < stochKSeries[bar] &&      //
                stochDSeries[bar] > 0
                // momentum go down
                && momentumSeries[bar - 1] > momentumSeries[bar])
            {
                return(SignalType.Sell);
            }
            else if (stochKSeries[bar - 1] < stochDSeries[bar - 1] && // Fast stochK cross up low stochD
                     stochKSeries[bar] > stochKSeries[bar] && //
                     stochDSeries[bar] < 0
                     // momentum go up
                     && momentumSeries[bar - 1] < momentumSeries[bar])
            {
                return(SignalType.Buy);
            }
            return(SignalType.None);
        }
Example #7
0
 protected override void OnResReceived(bool valid, int seq, SignalType sig)
 {
     if (valid && sig == SignalType.ACK)
     {
         if (seq == cseq)
         {
             rsc   = 0;
             cseq += Helper.DSZ;
         }
         else
         {
             goto Discard;  // Else, it's a redundant ACK
         }
     }
     // If corrupted or NAK, we will resend last packet (no change to nseq)
     if (cseq > filesize) // Check if file was completely transmitted
     {
         OnDone();
         return;
     }
     else
     {
         SendNext();
     }
     Discard : rttask.Start();
 }
        public async Task<UserSignalsUnorderedEntity> GetAsync(string userId, SignalType signal, string itemId)
        {
            string rowKey = BuildRowKey(userId, signal);
            BoundStatement antiBoundStatement = _getStatement.Value.Bind(rowKey, true, itemId);
            BoundStatement boundStatement = _getStatement.Value.Bind(rowKey, false, itemId);

            RowSet antiRowset = await _session.Get().ExecuteAsync(antiBoundStatement);
            List<UserSignalsUnorderedEntity> antiResults = antiRowset.Select(r => _mapper.Map<Row, UserSignalsUnorderedEntity>(r)).OrderBy(r => r.DateTime).ToList();
            UserSignalsUnorderedEntity lastAntiResult = antiResults.LastOrDefault();

            RowSet rowset = await _session.Get().ExecuteAsync(boundStatement);
            List<UserSignalsUnorderedEntity> results = rowset.Select(r => _mapper.Map<Row, UserSignalsUnorderedEntity>(r)).OrderBy(r => r.DateTime).ToList();
            UserSignalsUnorderedEntity lastResult = results.LastOrDefault();

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

            if (lastAntiResult == null)
            {
                return lastResult;
            }

            // Compare dates
            return lastResult.DateTime > lastAntiResult.DateTime ? lastResult : null;
        }
Example #9
0
        private void WriteFrame(SignalType signalType, BinaryNumber channelName, byte[] buffer, int offset, int count)
        {
            int frameCount = CONNECTION_FRAME_BUFFER_SIZE;

            do
            {
                if (count < frameCount)
                {
                    frameCount = count;
                }

                lock (_baseStream)
                {
                    _baseStream.WriteByte((byte)signalType);                                      //write frame signal
                    _baseStream.Write(channelName.Number, 0, 20);                                 //write channel name
                    _baseStream.Write(BitConverter.GetBytes(Convert.ToUInt16(frameCount)), 0, 2); //write data length

                    if (frameCount > 0)
                    {
                        _baseStream.Write(buffer, offset, frameCount); //write data
                    }
                    //flush base stream
                    _baseStream.Flush();
                }

                offset += frameCount;
                count  -= frameCount;
            }while (count > 0);
        }
Example #10
0
 public Trade(DateTime date, SignalType signal, decimal price, decimal quantity)
 {
     Date     = date;
     Signal   = signal;
     Price    = Math.Abs(price);
     Quantity = quantity == 0M ? 1M : Math.Abs(quantity);
 }
        public bool SetOutputState(Guid outputId, SignalType newSignal)
        {
            var output = FindOutputControl(outputId);

            if (output == null) // output not found, so it must be inside some integrated circuit
            {
                foreach (var element in elements)
                {
                    if (element is IntegratedCircuitControl)
                    {
                        var integratedCircuitControl = (IntegratedCircuitControl)element;
                        var found = integratedCircuitControl.SetSocketState(outputId, newSignal);
                        if (found)
                        {
                            return(true);
                        }
                    }
                }

                return(false);
            }

            output.Signal = newSignal;
            return(true);
        }
Example #12
0
        private async Task CheckSignalWithLast(SignalType signalType, MarketInfo marketInfo)
        {
            var table = await GetSignalsTable();

            var tableOperation = TableOperation.Retrieve <Signal>("bitmex", "");
            await table.ExecuteAsync(tableOperation);

            var query = new TableQuery <Signal>()
                        .Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, "bitmex"))
                        .Where(TableQuery.GenerateFilterCondition("Market", QueryComparisons.Equal, marketInfo.Market));
            var results = await table.ExecuteQuerySegmentedAsync(query, new TableContinuationToken());

            var lastResult = results.Results.OrderBy(o => o.Timestamp.DateTime).LastOrDefault();

            if (lastResult?.SignalType != signalType.ToString().ToLower() && signalType != SignalType.None)
            {
                string message;
                var    bitmexClient = new BitmexClient();
                if (signalType == SignalType.Bullish)
                {
                    message = await bitmexClient.GoLong(marketInfo);
                }
                else if (signalType == SignalType.Bearish)
                {
                    message = await bitmexClient.GoShort(marketInfo);
                }
                else
                {
                    return;
                }
                Logger.Log(message);

                await new Mailman().SendMailAsync($"Signal got changed to {signalType} for {marketInfo.Market}.\n {message}");
            }
        }
Example #13
0
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            SignalType signalType        = null;
            var        rockContext       = new RockContext();
            var        signalTypeService = new SignalTypeService(rockContext);

            if (SignalTypeId != 0)
            {
                signalType = signalTypeService.Get(SignalTypeId);
            }

            if (signalType == null)
            {
                signalType = new SignalType();
                signalTypeService.Add(signalType);
            }

            signalType.Name               = tbName.Text;
            signalType.Description        = tbDescription.Text;
            signalType.SignalColor        = cpColor.Text;
            signalType.SignalIconCssClass = tbIconCssClass.Text;

            if (!Page.IsValid || !signalType.IsValid)
            {
                return;
            }

            rockContext.SaveChanges();

            var people = new PersonSignalService(rockContext).Queryable()
                         .Where(s => s.SignalTypeId == signalType.Id)
                         .Select(s => s.PersonId)
                         .Distinct()
                         .ToList();

            //
            // If less than 250 people with this signal type then just update them all now,
            // otherwise put something in the rock queue to take care of it.
            //
            if (people.Count < 250)
            {
                new PersonService(rockContext).Queryable()
                .Where(p => people.Contains(p.Id))
                .ToList()
                .ForEach(p => p.CalculateSignals());

                rockContext.SaveChanges();
            }
            else
            {
                var updatePersonSignalTypesMsg = new UpdatePersonSignalTypes.Message()
                {
                    PersonIds = people
                };

                updatePersonSignalTypesMsg.Send();
            }

            NavigateToParentPage();
        }
Example #14
0
        public async Task <SignalType> GetLastSignal(string url, MarketInfo marketInfo)
        {
            SignalType lastSignal = SignalType.None;

            try
            {
                await DownloadChartImage(url, marketInfo);

                var bullishFilter = GetFilterForBullishSignal();
                var bearishFilter = GetFilterForBearishSignal();
                var bearishImage  = GetImageForFilter(bearishFilter);
                var bullishImage  = GetImageForFilter(bullishFilter);

                var bullishPixels = GetPixelInfo(bullishImage, _bullishSignalColor);
                var bearishPixels = GetPixelInfo(bearishImage, _bearishSignalColor);
                if (bullishPixels.LastIndex == 0 && bearishPixels.LastIndex == 0)
                {
                    return(SignalType.None);
                }
                if (bullishPixels.LastIndex > bearishPixels.LastIndex)
                {
                    lastSignal = SignalType.Bullish;
                }
                else
                {
                    lastSignal = SignalType.Bearish;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

            return(lastSignal);
        }
    private CircuitProcessingResult ProcessCircuit(TSPlayer triggerer, DPoint tileLocation, SignalType? overrideSignal = null, bool switchSender = true) {
      CircuitProcessor processor = new CircuitProcessor(this.PluginTrace, this, tileLocation);
      CircuitProcessingResult result = processor.ProcessCircuit(triggerer, overrideSignal, switchSender);

      this.NotifyPlayer(result);
      return result;
    }
Example #16
0
		public Signal(DateTime datetime, ComponentType sender, SignalType type, SignalSide side, double qty, double strategyPrice, Instrument instrument, string text)
			: base()
		{
			this.BuyColor = Color.Blue;
			this.BuyCoverColor = Color.SkyBlue;
			this.SellColor = Color.Pink;
			this.SellShortColor = Color.Red;
			this.ToolTipEnabled = true;
			this.ToolTipFormat = "dfdfs";

			this.DateTime = datetime;
			this.Sender = sender;
			this.Type = type;
			this.Side = side;
			this.Qty = qty;
			this.StrategyPrice = strategyPrice;
			this.Instrument = instrument;
			this.Price = this.Instrument.Price();
			this.TimeInForce = TimeInForce.GTC;
			this.Text = text;
			this.Strategy = (Strategy)null;
			this.Rejecter = ComponentType.Unknown;
			this.StopPrice = 0.0;
			this.LimitPrice = 0.0;
			this.Status = SignalStatus.New;
		}
Example #17
0
        private void addSignal(SignalType st)
        {
            TreeNode   tnSelected = MessageTreeView.SelectedNode;
            CANMessage cMsg;

            if (typeof(CANMessage).Equals(tnSelected.Tag.GetType()))
            {
                cMsg = tnSelected.Tag as CANMessage;
            }
            else if (typeof(CANSignal).Equals(tnSelected.Tag.GetType()))
            {
                cMsg = tnSelected.Parent.Tag as CANMessage;
            }
            else
            {
                throw new Exception("Invalid item.");
            }
            CANSignal       newSignal = new CANSignal(st);
            FrmModifySignal fms       = new FrmModifySignal(newSignal);

            fms.ShowDialog();
            if ((fms as Ensureable).isModified())
            {
                cMsg.GetSignalList().Add(newSignal);
                reloadDisplay();
            }
        }
Example #18
0
 public Signal(string name = "Unknown", SignalType type = SignalType.Unknown)
 {
     Name = name;
     Type = type;
     m_log = new Log(DateTime.Now.ToString(@"yyyyMMdd_HHmm") + "_" + name.ToLower() + ".csv");
     m_log.CSV(Log.Details.Raw, Log.Priority.Information, "time", "raw", "transformed");
 }
Example #19
0
 public SignalEvent(string symbol, DateTime timeStamp, SignalType signalType, decimal strength = 1m)
 {
     this.Symbol     = symbol;
     this.TimeStamp  = timeStamp;
     this.SignalType = signalType;
     this.Strength   = strength;
 }
Example #20
0
        //================================================================================================//
        /// <summary>
        /// Constructor for speedposts
        /// </summary>

        public SignalHead(Signal signal, int trackItem, int tbdRef, SpeedPostItem speedItem)
        {
            if (speedItem == null)
            {
                throw new ArgumentNullException(nameof(speedItem));
            }

            MainSignal            = signal ?? throw new ArgumentNullException(nameof(signal));
            TrackItemIndex        = trackItem;
            TDBIndex              = tbdRef;
            DrawState             = 1;
            SignalIndicationState = SignalAspectState.Clear_2;
            SignalType            = new SignalType(SignalFunction.Speed, SignalAspectState.Clear_2);

            double speedMpS = Speed.MeterPerSecond.ToMpS(speedItem.Distance, !speedItem.IsMPH);

            if (speedItem.IsResume)
            {
                speedMpS = 999.0;
            }

            float passSpeed    = speedItem.IsPassenger ? (float)speedMpS : -1;
            float freightSpeed = speedItem.IsFreight ? (float)speedMpS : -1;

            SpeedInfoSet[SignalIndicationState] = new SpeedInfo(passSpeed, freightSpeed, false, false, speedItem is TempSpeedPostItem ? (speedMpS == 999f ? 2 : 1) : 0, speedItem.IsWarning);
        }
        /// <summary>
        /// Creates a presentation from an alert
        /// </summary>
        /// <param name="alert">The alert</param>
        /// <param name="request">The Smart Detector request</param>
        /// <param name="smartDetectorName">The Smart Detector name</param>
        /// <param name="usedLogAnalysisClient">Indicates whether a log analysis client was used to create the alert</param>
        /// <param name="usedMetricClient">Indicates whether a metric client was used to create the alert</param>
        /// <returns>The presentation</returns>
        public static ContractsAlert CreateContractsAlert(this Alert alert, SmartDetectorAnalysisRequest request, string smartDetectorName, bool usedLogAnalysisClient, bool usedMetricClient)
        {
            // A null alert has null presentation
            if (alert == null)
            {
                return(null);
            }

            // Create presentation elements for each alert property
            List <AlertProperty> alertProperties = alert.ExtractProperties(AlertBaseClassPropertiesNames);

            // Generate the alert's correlation hash based on its predicates
            string correlationHash = string.Join("##", alert.ExtractPredicates().OrderBy(x => x.Key).Select(x => x.Key + "|" + x.Value.ToString())).ToSha256Hash();

            // Get the alert's signal type based on the clients used to create the alert
            SignalType signalType = GetSignalType(usedLogAnalysisClient, usedMetricClient);

            // Return the presentation object
            return(new ContractsAlert
            {
                Title = alert.Title,
                OccurenceTime = alert.OccurenceTime,
                ResourceId = alert.ResourceIdentifier.ToResourceId(),
                CorrelationHash = correlationHash,
                SmartDetectorId = request.SmartDetectorId,
                SmartDetectorName = smartDetectorName,
                AnalysisTimestamp = DateTime.UtcNow,
                AnalysisWindowSizeInMinutes = (int)request.Cadence.TotalMinutes,
                AlertProperties = alertProperties,
                SignalType = signalType,
                ResolutionParameters = alert.AlertResolutionParameters?.CreateContractsResolutionParameters()
            });
        }
Example #22
0
        //NOTE: Modified from here: https://www.codeproject.com/Articles/30180/Simple-Signal-Generator
        public static decimal GetValue(SignalType signalType, decimal time, decimal frequency, decimal amplitude)

        {
            float value = 0f;
            float t     = (float)frequency * (float)time;

            switch (signalType)
            {
            //http://en.wikipedia.org/wiki/Waveform
            case SignalType.Sine:     // sin( 2 * pi * t )
                value = (float)Math.Sin(2f * Math.PI * t);
                break;

            case SignalType.Square:     // sign( sin( 2 * pi * t ) )
                value = Math.Sign(Math.Sin(2f * Math.PI * t));
                break;

            case SignalType.Triangle:
                // 2 * abs( t - 2 * floor( t / 2 ) - 1 ) - 1
                value = 1f - 4f * (float)Math.Abs
                            (Math.Round(t - 0.25f) - (t - 0.25f));
                break;
            }

            return((decimal)((float)amplitude * value));
        }
Example #23
0
        //Добавить сигнал, возвращает сигнал прокси для пользователя
        public ProxySignal AddSignal(string fullCode, DataType dataType, SignalType signalType, string infObject, string infOut, string infProp)
        {
            var sig = SourceConnect.AddSignal(fullCode, dataType, signalType, infObject, infOut, infProp);

            ArchiveProxyConnect.AddSignal(SourceConnect, new QueuedProxySignal(SourceConnect.Code, sig));
            return(UserProxyConnect.AddSignal(SourceConnect, new ProxySignal(SourceConnect.Code, sig)));
        }
Example #24
0
        private void CheckForReversSignal(SignalType currentSignal)
        {
            switch (currentSignal)
            {
            case SignalType.SlowMACrosFastMABottomTop:
                if (_positionOpendSignalType == SignalType.SlowMACrosFastMATopBottom)
                {
                    ClosePosition();
                }
                break;

            case SignalType.SlowMACrosFastMATopBottom:
                if (_positionOpendSignalType == SignalType.SlowMACrosFastMABottomTop)
                {
                    ClosePosition();
                }
                break;

            case SignalType.QuoteAboveMA:
                if (_positionOpendSignalType == SignalType.QuoteBelowMA)
                {
                    ClosePosition();
                }
                break;

            case SignalType.QuoteBelowMA:
                if (_positionOpendSignalType == SignalType.QuoteAboveMA)
                {
                    ClosePosition();
                }
                break;
            }
        }
 public SignalEvent(string symbol, DateTime timeStamp, SignalType signalType, decimal strength = 1m)
 {
     this.Symbol = symbol;
     this.TimeStamp = timeStamp;
     this.SignalType = signalType;
     this.Strength = strength;
 }
Example #26
0
        public void SignalTypeTest()
        {
            var        target = CreateSignal();
            SignalType actual = target.SignalType;

            Assert.AreEqual(SignalType.Return, actual);
        }
Example #27
0
        public Task DeleteVersionAsync(string groupId, SignalType signal, long version)
        {
            string         rowKey         = BuildRowKey(groupId, signal, version);
            BoundStatement boundStatement = _deleteStatement.Value.Bind(rowKey);

            return(_session.Get().ExecuteAsync(boundStatement));
        }
Example #28
0
        /// <summary>
        /// Main function - robot Entry point
        /// </summary>
        protected override void Execute()
        {
            base.Execute();

            // Create sma
            smaPrice = new SMA(Bars.Close, priceMaPeriod.ValueInt, "Moving Average to smooth price volatility");
            PlotSeries(PricePane, smaPrice, Color.Green, LineStyle.Solid, 1);
            smaTrend = new SMA(Bars.Close, trendMaPeriod.ValueInt, "Trend Moving Average");
            PlotSeries(PricePane, smaTrend, Color.Brown, LineStyle.Solid, 1);

            for (int bar = 1; bar < Bars.Count; bar++)
            {
                // Calculate signal
                SignalType signal = GetSignal(bar);

                // Close opened
                if (IsLastPositionActive)
                {
                    // If isn't closed by stops
                    if (IsLastPositionActive)
                    {
                        //CheckStops(bar);

                        // Close long if go below low level
                        if (LastPosition.PositionType == PositionType.Long &&
                            signal == SignalType.Sell)
                        {
                            ExitAtMarket(bar + 1, LastPosition, "Sell signal");
                            ShortAtMarket(bar + 1, "Sell signal");
                        }
                        // Close short if go upper high level
                        else if (LastPosition.PositionType == PositionType.Short &&
                                 signal == SignalType.Buy)
                        {
                            ExitAtMarket(bar + 1, LastPosition, "Buy signal");
                            BuyAtMarket(bar + 1, "Buy signal");
                        }
                    }
                }
                // Open new positions
                else //if(bar > 1)
                {
                    // Buy if go up more then deltaUp
                    if (signal == SignalType.Buy)
                    {
                        BuyAtMarket(bar + 1, "Buy signal");
                    }
                    else if (signal == SignalType.Sell)
                    {
                        ShortAtMarket(bar + 1, "Sell signal");
                    }
                }
            }

            if (IsLastPositionActive)
            {
                ExitAtClose(Bars.Count - 1, LastActivePosition);
            }
        }
Example #29
0
        public SignalUnit(ConfigurationUnit confConfigurationUnit)
        {
            if (confConfigurationUnit.Type == ConfigurationUnitType.Signal)
            {
                foreach (KeyValuePair <string, string> param in confConfigurationUnit.Parameters)
                {
                    string value = param.Value;
                    switch (param.Key.ToUpper())
                    {
                    case "ИДЕНТИФИКАТОР":
                        Uid = Convert.ToInt32(value);
                        break;

                    case "ИМЯ":
                        Name = value;
                        break;

                    case "ИМЯСЕРВЕР":
                        ServerName = value;
                        break;

                    case "ТИП":
                        SignalType type = getSignalsTypes(value);
                        Type = type;
                        break;

                    case "ИДЕНТИФИКАТОРБЛОКАДАННЫХ":
                        DataBlockUid = Convert.ToInt32(value);
                        break;

                    case "БАЙТ":
                        Byte = Convert.ToInt32(value);
                        break;

                    case "БИТ":
                        Bit = Convert.ToInt32(value);
                        break;

                    case "ЗНАЧЕНИЕВИРТУАЛЬНОГОСИГНАЛА":
                        VirtualValue = Convert.ToDouble(value.Replace(".", ","));
                        break;

                    case "СОСТАВНОЙСИГНАЛ":
                        CompoundSignalType tmpType = getCompoundSignalsTypes(value);
                        CompoundSignal = tmpType;
                        break;

                    case "ЗАПИСЬКЛИЕНТАМИ":
                        int tmpValue = Convert.ToInt32(value);
                        UserWrite = tmpValue > 0;
                        break;

                    case "МИНИМАЛЬНЫЙУРОВЕНЬАНАЛОГОВОГОСИГНАЛА":
                        MinAnalogLevel = Convert.ToInt32(value);
                        break;
                    }
                }
            }
        }
Example #30
0
        private void SvcSignalToAddress(CpuThreadState ThreadState)
        {
            long       Address = (long)ThreadState.X0;
            SignalType Type    = (SignalType)ThreadState.X1;
            int        Value   = (int)ThreadState.X2;
            int        Count   = (int)ThreadState.X3;

            Logger.PrintDebug(LogClass.KernelSvc,
                              "Address = 0x" + Address.ToString("x16") + ", " +
                              "Type = " + Type.ToString() + ", " +
                              "Value = 0x" + Value.ToString("x8") + ", " +
                              "Count = 0x" + Count.ToString("x8"));

            if (IsPointingInsideKernel(Address))
            {
                Logger.PrintWarning(LogClass.KernelSvc, $"Invalid address 0x{Address:x16}!");

                ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.NoAccessPerm);

                return;
            }

            if (IsAddressNotWordAligned(Address))
            {
                Logger.PrintWarning(LogClass.KernelSvc, $"Unaligned address 0x{Address:x16}!");

                ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidAddress);

                return;
            }

            long Result;

            switch (Type)
            {
            case SignalType.Signal:
                Result = System.AddressArbiter.Signal(Address, Count);
                break;

            case SignalType.SignalAndIncrementIfEqual:
                Result = System.AddressArbiter.SignalAndIncrementIfEqual(Memory, Address, Value, Count);
                break;

            case SignalType.SignalAndModifyIfEqual:
                Result = System.AddressArbiter.SignalAndModifyIfEqual(Memory, Address, Value, Count);
                break;

            default:
                Result = MakeError(ErrorModule.Kernel, KernelErr.InvalidEnumValue);
                break;
            }

            if (Result != 0)
            {
                Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error 0x{Result:x}!");
            }

            ThreadState.X0 = (ulong)Result;
        }
Example #31
0
 public static void Unregister(SignalType signalType, Action callback)
 {
     List<Action> callbacks;
     if (sSignalMapping.TryGetValue(signalType, out callbacks) && callbacks != null)
     {
         callbacks.Remove(callback);
     }
 }
Example #32
0
 public VoltageChangedEventsArgs(bool valid, int HDMIChan, int fpgaId, SignalType sigTyp, double[] voltage)
 {
     isValid     = valid;
     HDMIchannel = HDMIChan;
     FPGAid      = fpgaId;
     signalType  = sigTyp;
     Voltage     = voltage;
 }
Example #33
0
 /// <summary>
 /// 新建一个开关量
 /// </summary>
 /// <param name="signame"></param>
 /// <param name="bitoffset"></param>
 public CANSignal(string signame, int bitoffset)
 {
     BitSizeOffsetValidCheck(bitoffset, 2);
     sType     = SignalType.Switch;
     BitOffset = bitoffset;
     BitSize   = 2;
     Name      = signame;
 }
 public TradeHistoryPerformanceEntry(DateTime dateTime, decimal? currentEquity, SignalType signalType, decimal percentageChange, decimal currentPrice)
 {
     this.DateTime = dateTime;
     this.CurrentEquity = currentEquity;
     this.SignalType = signalType;
     this.PercentageChange = percentageChange;
     this.CurrentPrice = currentPrice;
 }
 public BranchProcessData(DPoint branchingTileLocation, DPoint firstWireLocation, SignalType signal) : this()
 {
     this.BranchingTileLocation = branchingTileLocation;
     this.FirstWireLocation     = firstWireLocation;
     this.LastWireLocation      = DPoint.Empty;
     this.Signal    = signal;
     this.Direction = AdvancedCircuits.DirectionFromTileLocations(branchingTileLocation, firstWireLocation);
 }
Example #36
0
 protected override void PositionChanged(IPosition position, ModificationType type)
 {
     if ((type.Equals(ModificationType.Closed)) && (position.Id == _positionGuid))
     {
         _positionGuid            = Guid.Empty;
         _positionOpendSignalType = SignalType.None;
     }
 }
Example #37
0
		public PropExtension(SignalType signalType, EventType eventType, string name, byte mode)
		{
			this.SignalType = signalType;
			this.EventType = eventType;
			this.Name = name;
			this.Mode = mode;
			this.Value = new MabiDictionary();
		}
Example #38
0
 internal static Func <DataSeries <Bar>, double> GetSignalFunc(SignalType sigType)
 {
     if (sigType == SignalType.NextClose)
     {
         return(Signals.NextClose);
     }
     throw new NotImplementedException("Unexpected signal type: " + sigType);
 }
Example #39
0
 public PropExtension(SignalType signalType, EventType eventType, string name, byte mode)
 {
     this.SignalType = signalType;
     this.EventType  = eventType;
     this.Name       = name;
     this.Mode       = mode;
     this.Value      = new MabiDictionary();
 }
Example #40
0
 public static void Dispatch(SignalType signalType)
 {
     List<Action> callbacks;
     if (sSignalMapping.TryGetValue(signalType, out callbacks) && callbacks != null)
     {
         for (int i = 0, n = callbacks.Count; i < n; ++i)
         {
             callbacks[i]();
         }
     }
 }
        public async Task<IEnumerable<AffinityGroupItemCountsEntity>> GetSequenceAsync(string groupId, SignalType signal, int pageSize)
        {
            string rowKey = BuildRowKey(groupId, signal);
            BoundStatement boundStatement = _getStatement.Value.Bind(rowKey);

            // setting properties
            boundStatement.SetPageSize(pageSize);

            RowSet rowset = await _session.Get().ExecuteAsync(boundStatement);
            return rowset.Select(r => _mapper.Map<Row, AffinityGroupItemCountsEntity>(r));
        }
Example #42
0
 public static SignalType GetRandomSignalType(SignalType[] options, int total, int rand)
 {
     foreach (SignalType type in options)
     {
         int weight = type.GetSelectionWeight();
         if (rand < weight)
             return type;
         rand -= weight;
     }
     throw new System.ArgumentException("Invalid Options", "options");
 }
Example #43
0
 public DeviceProperty(string name,int type,string unit,int grpIndex, int grpCnt,int propIndex, SignalType sigType,float rangeLow,float rangeHigh)
 {
     this.Name = name;
     this.Type = type;
     this.Unit = unit;
     this.GroupIndex = grpIndex;
     this.GroupCount = grpCnt;
     this.SignalType = sigType;
     this.PropertyIndex = propIndex;
     this.RangeLow = rangeLow;
     this.RangeHigh = rangeHigh;
 }
Example #44
0
 public static SignalType FlipSignal(SignalType signal)
 {
     if (signal == SignalType.Plus)
     {
         signal = SignalType.Minus;
     }
     else if (signal == SignalType.Minus)
     {
         signal = SignalType.Plus;
     }
     return signal;
 }
 public RootBranchProcessData(DPoint senderLocation, DPoint firstWireLocation, SignalType signal, WireColor wireColor) {
   this.SenderLocation = senderLocation;
   this.FirstWireLocation = firstWireLocation;
   this.LastWireLocation = firstWireLocation;
   this.WireColor = wireColor;
   this.Direction = AdvancedCircuits.DirectionFromTileLocations(senderLocation, firstWireLocation);
   this.Signal = signal;
   this.SignaledComponentLocations = new List<DPoint>();
   this.BlockActivator = null;
   this.BlockActivatorLocation = DPoint.Empty;
   this.BlockActivatorDeactivatedBlockCounter = 0;
   this.BlockActivatorMode = BlockActivatorMode.Default;
 }
        public Task AddAsync(string groupId, SignalType signal, long version, List<AffinityGroupMostSignaledInsertOptions> options)
        {
            string rowKey = BuildRowKey(groupId, signal, version);

            var batch = new BatchStatement();
            foreach (var option in options)
            {
                BoundStatement boundStatement = _insertStatement.Value.Bind(rowKey, option.Count, option.ItemId);
                batch.Add(boundStatement);
            }

            return _session.Get().ExecuteAsync(batch.SetConsistencyLevel(ConsistencyLevel.One));
        }
Example #47
0
 public static void Register(SignalType signalType, Action callback)
 {
     List<Action> callbacks;
     if(!sSignalMapping.TryGetValue(signalType, out callbacks) || callbacks == null)
     {
         callbacks = new List<Action>();
         sSignalMapping[signalType] = callbacks;
     }
     if (!callbacks.Contains(callback))
     {
         callbacks.Add(callback);
     }
 }
        /// <summary>Determines what action to take on the current date.</summary>
        /// <param name="date">The date.</param>
        /// <returns>The trading signal to act on, on the date given.</returns>
        /// <exception cref="System.NotImplementedException"></exception>
        public override Signal ActionToTake(DateTime date, SignalType? lastSignalType)
        {
            var datapoint = this.DataPoints.FirstOrDefault(d => d.Date == date);
            if (datapoint == null) { return null; }
            if (SatisfiesCriteriaToShort(datapoint) && lastSignalType != SignalType.Sell)
            {
                return Signal.Create(datapoint.Symbol, date, SignalType.Sell, datapoint.Close);
            }

            if (this.SatisfiesCriteriaToTakeProfits(datapoint))
            {
                return Signal.Create(datapoint.Symbol, date, SignalType.TakeProfits, datapoint.Close);
            }

            return null;
        }
        public async Task<AffinityGroupCountsEntity> GetAsync(string groupId, SignalType signal)
        {
            string rowId = BuildRowKey(groupId, signal);
            BoundStatement boundStatement = _getStatement.Value.Bind(rowId);
            RowSet rowset = await _session.Get().ExecuteAsync(boundStatement);

            List<Row> rows = rowset.ToList();
            if (rows.Count == 0)
            {
                return new AffinityGroupCountsEntity
                {
                    AffinityGroupSignalType = rowId
                };
            }

            Row row = rows.First();
            return _mapper.Map<Row, AffinityGroupCountsEntity>(row);
        }
 public SignalGenerator(SignalType Type, float frequency, float phase = 0,
    float SampleRate = - 1, float amplitude = 1, int length = -1)
 {
     if (SampleRate == -1) SampleRate = 20 * frequency;
     if (length == -1) length = (int)SampleRate;
     BaseSignalGenerator bs = new BaseSignalGenerator(Type);
     this.SamplingRate = SampleRate;
     bs.Amplitude = amplitude;
     bs.Frequency = frequency;
     bs.Phase = phase;
     Samples = new double[length];
     float t = 0;
     float tmp = 1 / SampleRate;
     for (int i = 0 ; i < length ; i++)
     {
         Samples[i] = bs.GetValue(t);
         t += tmp;
     }
 }
        public static bool? SignalToBool(SignalType signal)
        {
            if (signal == SignalType.Swap)
            return null;

              return (signal == SignalType.On);
        }
Example #52
0
    public void LoadLevel(string data, Vector2i playerStartCell, Vector2i goalCell, SignalType goalSignalType, bool goalActive, LevelData.SpawnData[] spawnDatas = null)
    {
        ClearProjectiles();
        ClearSpecialObjects();
        ClearCollectables();
        ClearEnemies();

        mDungeon.LoadDungeon(data);
        mStartPos = mDungeon.GetTilePosition(playerStartCell.mX, playerStartCell.mY);
        RespawnPlayer1();
        mGoal.mSignalType = goalSignalType;
        mGoal.transform.position = mDungeon.GetTilePosition(goalCell.mX, goalCell.mY);
        mGoal.gameObject.SetActive(goalActive);
        mDungeon.SetCell(goalCell.mX, goalCell.mY, DungeonCell.TileType.Goal);
        
        if(spawnDatas != null)
        {
            for (int i = 0, n = spawnDatas.Length; i < n; ++i)
            {
                LevelData.SpawnData spawnData = spawnDatas[i];
                GameObject obj = SpawnPrefab(spawnData.mPrefab, mDungeon.GetTilePosition(spawnData.mCell.mX, spawnData.mCell.mY), Quaternion.Euler(0.0f, spawnData.mYRotation, 0.0f));
                switch(spawnData.mSpawnType)
                {
                    case LevelData.SpawnData.SpawnType.Special:
                        mSpecialObjects.Add(obj);
                        break;
                    case LevelData.SpawnData.SpawnType.Collectable:
                        mCollectables.Add(obj);
                        break;
                    case LevelData.SpawnData.SpawnType.Enemy:
                        EnemyController enemy = obj.GetComponent<EnemyController>();
                        if(enemy != null)
                        {
                            enemy.Init();
                            mEnemies.Add(enemy);
                        }
                        else
                        {
                            mSpecialObjects.Add(obj);
                        }
                        break;
                }
            }
        }
    }
Example #53
0
    /// <summary>
    /// Creates a full signal GameObject for a given SignalType
    /// </summary>
    /// <param name="type">The type of the signal</param>
    public virtual GameObject InstantiateSignal(SignalType type)
    {
        if (type == SignalType.Invalid)
            return null;
        GameObject signal = Instantiate(signalPrefab);
        SignalMovement sigObj = signal.GetComponent<SignalMovement>();
        signal.transform.SetParent(signalsCont.transform);//put the signals in a container, for a cleaner hierarchy
        sigObj.signalController = this;
        sigObj.SigType = type;
        sigObj.speed = this.signalSpeed;
        Button infoButton = signal.transform.Find("Canvas/InfoButton").GetComponent<Button>();
        infoButton.onClick.AddListener(() => inputManager.SignalClick(signal));//set the click event

        switch (type) //fill the appropppriate values for each SignalType
        {
            case SignalType.LegPain:
                sigObj.FillSignalInfo(SignalMovement.SignalClass.Sensory, "Legs", "Parietal", "כאב ברגל", 5,
                    @"תחושה וכאב מעובדים באונה הקודקודית");
                break;
            case SignalType.HandPain:
                sigObj.FillSignalInfo(SignalMovement.SignalClass.Sensory, "Arms", "Parietal", "כאב ביד", 5,
                    @"תחושה וכאב מעובדים באונה הקודקודית");
                break;
            case SignalType.ScaryObjectSight:
                sigObj.FillSignalInfo(SignalMovement.SignalClass.Sensory, "Eyes", "Occipital", "עצם מפחיד", 20,
                    @"נתונים חזותיים מהעיניים מעובדים באונה העורפית");
                break;
            case SignalType.FamiliarObjectSight:
                sigObj.FillSignalInfo(SignalMovement.SignalClass.Sensory, "Eyes", "Occipital", "עצם מוכר", 20,
                    @"נתונים חזותיים מהעיניים מעובדים באונה העורפית");
                break;
            case SignalType.HotObject:
                sigObj.FillSignalInfo(SignalMovement.SignalClass.Sensory, "Arms", "Parietal", "מגע חם מאוד", 30,
                    @"על תגובה לטמפרטורות קיצוניות אחראית האונה הקודקודית");
                break;
            case SignalType.ColdObject:
                sigObj.FillSignalInfo(SignalMovement.SignalClass.Sensory, "Arms", "Parietal", "מגע קר מאוד", 25,
                    @"על תגובה לטמפרטורות קיצוניות אחראית האונה הקודקודית");
                break;
            case SignalType.SweetTaste:
                sigObj.FillSignalInfo(SignalMovement.SignalClass.Sensory, "Tounge", "Parietal", "טעם מתוק", 5,
                    @"טעם מעובד באונה הקודקודית");
                break;
            case SignalType.SourTaste:
                sigObj.FillSignalInfo(SignalMovement.SignalClass.Sensory, "Tounge", "Parietal", "טעם חמוץ", 5,
                    @"טעם מעובד באונה הקודקודית");
                break;
            case SignalType.SpokenTo:
                sigObj.FillSignalInfo(SignalMovement.SignalClass.Sensory, "Ears", "Frontal", "שיחה", 10,
                    @"עיבוד ותגובה לדיבור מעובדים באונה המצחית");
                break;
            case SignalType.Falling:
                sigObj.FillSignalInfo(SignalMovement.SignalClass.Sensory, "Ears", "Cerebellum", "נפילה", 30,
                    @"שיווי משקל ושליטה מוטורית על השרירים הם תפקידיו של המוח הקטן");
                break;
            case SignalType.Running:
                sigObj.FillSignalInfo(SignalMovement.SignalClass.Sensory, "Legs", "Cerebellum", "ריצה", 20,
                    @"שיווי משקל ושליטה מוטורית על השרירים הם תפקידיו של המוח הקטן");
                break;
            case SignalType.HotBody:
                sigObj.FillSignalInfo(SignalMovement.SignalClass.Sensory, "Blood", "Thalamus", "חום גוף גבוה", 20,
                    @"בקרה על טמפרטורת הגוף היא אחריותו של ההיפותלמוס");
                break;
            case SignalType.ColdBody:
                sigObj.FillSignalInfo(SignalMovement.SignalClass.Sensory, "Blood", "Thalamus", "חום גוף נמוך", 20,
                    @"בקרה על טמפרטורת הגוף היא אחריותו של ההיפותלמוס");
                break;
            case SignalType.HighBloodPressure:
                sigObj.FillSignalInfo(SignalMovement.SignalClass.Sensory, "Blood", "Stem", "לחץ דם גבוה", 20,
                    @"שמירה על לחץ דם יציב נעשית ע""י גזע המוח");
                break;
            case SignalType.LowBloodPressure:
                sigObj.FillSignalInfo(SignalMovement.SignalClass.Sensory, "Blood", "Stem", "לחץ דם נמוך", 20,
                    @"שמירה על לחץ דם יציב נעשית ע""י גזע המוח");
                break;
            case SignalType.LowWater:
                sigObj.FillSignalInfo(SignalMovement.SignalClass.Sensory, "Blood", "Thalamus", "ריכוז מים נמוך", 25,
                    @"שמירה על ריכוז נוזלים תקין בדם נעשית ע""י ההיפותלמוס");
                break;
            case SignalType.HighWater:
                sigObj.FillSignalInfo(SignalMovement.SignalClass.Sensory, "Blood", "Thalamus", "ריכוז מים גבוה", 25,
                    @"שמירה על ריכוז נוזלים תקין בדם נעשית ע""י ההיפותלמוס");
                break;
            case SignalType.BlockedBreathing:
                sigObj.FillSignalInfo(SignalMovement.SignalClass.Sensory, "Trachea", "Stem", "חנק", 40,
                    @"אינסטינקטים כגון השתעלות, שנועדה בין השאר להוציא עצמים זרים מקנה הנשימה, נשלטים ע""י גזע המוח");
                break;
            case SignalType.Breath:
                sigObj.FillSignalInfo(SignalMovement.SignalClass.Motor, "Stem", "Lungs", "נשימה", 20,
                    @"נשימה מתבצעת ע""י הריאות");
                break;
            case SignalType.ReduceHeartRate:
                sigObj.FillSignalInfo(SignalMovement.SignalClass.Motor, "Stem", "Heart", "הורדת קצב הלב", 10,
                    @"הלב מזרים דם לכל חלקי הגוף, וקצב פעימות מופחת מפחית את לחץ הדם");
                break;
            case SignalType.IncreaseHeartRate:
                sigObj.FillSignalInfo(SignalMovement.SignalClass.Motor, "Stem", "Heart", "הגברת קצב הלב", 10,
                    @"הלב מזרים דם לכל חלקי הגוף, וקצב פעימות מוגבר מעלה את לחץ הדם");
                break;
            case SignalType.MoveHand:
                sigObj.FillSignalInfo(SignalMovement.SignalClass.Motor, "Cerebellum", "Arms", "הזזת הידיים", 25,
                    @"הרחקה של הידיים יכולה למנוע פגיעה פיזית");
                break;
            case SignalType.MoveLeg:
                sigObj.FillSignalInfo(SignalMovement.SignalClass.Motor, "Cerebellum", "Legs", "הזזת הרגליים", 25,
                    @"הרחקה של הרגליים יכולה למנוע פגיעה פיזית");
                break;
            case SignalType.Run:
                sigObj.FillSignalInfo(SignalMovement.SignalClass.Motor, "Cerebellum", "Legs", "ריצה", 15,
                    @"הפעלת שרירי הרגליים לריצה יכולה להרחיק את הגוף כולו מסכנה");
                break;
            case SignalType.Speak:
                sigObj.FillSignalInfo(SignalMovement.SignalClass.Motor, "Frontal", "Lungs", "דיבור", 10,
                    @"דיבור, שתלוי, בין השאר, בהוצאת אוויר מהריאות, הוא צורת תקשורת ייחודית לבני אדם, ומשפרת מאוד את יכולת ההישרדות של האדם בקבוצה");
                break;
            case SignalType.Shiver:
                sigObj.FillSignalInfo(SignalMovement.SignalClass.Motor, "Stem", "Arms", "רעד בידיים", 15,
                    @"רעידות (למשל של הידיים) הן חלק ממנגנוני הגוף לחימום. הרעידות יוצרות חימום ע""י הפעלת השרירים שכחלק מפעולתם פולטים חום");
                break;
            case SignalType.Cough:
                sigObj.FillSignalInfo(SignalMovement.SignalClass.Motor, "Stem", "Lungs", "שיעול", 35,
                    @"שיעול כולל הוצאת אוויר חזקה ומהירה מהריאות, והוא יכול להוציא עצמים זרים הגורמים לחנק מקנה הנשימה");
                break;
            default:
                throw new ArgumentException("Unknown SignalType: " + type.ToString(), "type");
        }

        signal.name = type.ToString() + " (" + sigObj.Origin.name + " -> " + sigObj.Target.name + ")"; //set a name, for debugging
        signal.transform.position = sigObj.Origin.transform.position;
        return signal;
    }
        protected bool SignalComponent(ref ObjectMeasureData measureData, RootBranchProcessData rootBranch, SignalType signal, bool localOnly = false)
        {
            int originX = measureData.OriginTileLocation.X;
              int originY = measureData.OriginTileLocation.Y;

              switch (measureData.BlockType) {
            case BlockType.Torch:
            case BlockType.XMasLight:
            case BlockType.Candle:
            case BlockType.PlatinumCandle:
            case BlockType.ChainLantern:
            case BlockType.ChineseLantern:
            case BlockType.Candelabra:
            case BlockType.PlatinumCandelabra:
            case BlockType.DiscoBall:
            case BlockType.TikiTorch:
            case BlockType.CopperChandelier:
            case BlockType.SilverChandelier:
            case BlockType.GoldChandelier:
            case BlockType.PlatinumChandelier:
            case BlockType.LampPost:
            case BlockType.MusicBox:
            case BlockType.XSecondTimer:
            case BlockType.WaterFountain:
            case BlockType.BubbleMachine: {
              bool currentState = TerrariaUtils.Tiles.ObjectHasActiveState(measureData);
              bool newState;
              if (signal == SignalType.Swap)
            newState = !currentState;
              else
            newState = AdvancedCircuits.SignalToBool(signal).Value;

              if (measureData.BlockType == BlockType.XSecondTimer) {
            // Directly wired Timers in an Advanced Circuit are not meant to be switched.
            if (this.IsAdvancedCircuit)
              return false;

            if (newState != currentState)
              this.CircuitHandler.RegisterUnregisterTimer(this.TriggeringPlayer, measureData, newState);
              }

              if (newState != currentState)
            TerrariaUtils.Tiles.SetObjectState(measureData, newState, !localOnly);

              return true;
            }
            case BlockType.ActiveStone:
            case BlockType.InactiveStone: {
              bool currentState = (measureData.BlockType == BlockType.ActiveStone);
              bool newState;
              if (signal == SignalType.Swap)
            newState = !currentState;
              else
            newState = AdvancedCircuits.SignalToBool(signal).Value;

              if (newState != currentState) {
            BlockType newBlockType;
            if (newState)
              newBlockType = BlockType.ActiveStone;
            else
              newBlockType = BlockType.InactiveStone;

            TerrariaUtils.Tiles[measureData.OriginTileLocation].type = (byte)newBlockType;
            WorldGen.SquareTileFrame(originX, originY);
            TSPlayer.All.SendTileSquareEx(originX, originY, 1);
              }

              return true;
            }
            case BlockType.DoorClosed:
            case BlockType.DoorOpened: {
              if (this.IsAdvancedCircuit)
            return false;

              this.OpenDoor(measureData, signal);
              return true;
            }
            case BlockType.InletPump:
            case BlockType.OutletPump: {
              if (signal == SignalType.Off)
            return false;

              PumpConfig pumpConfig;
              PaintColor componentPaint = (PaintColor)TerrariaUtils.Tiles[measureData.OriginTileLocation].color();
              if (
            (
              this.CircuitHandler.Config.PumpConfigs.TryGetValue(componentPaint, out pumpConfig) ||
              this.CircuitHandler.Config.PumpConfigs.TryGetValue(PaintColor.None, out pumpConfig)
            ) &&
              pumpConfig.Cooldown == 0 ||
              WorldGen.checkMech(originX, originY, pumpConfig.Cooldown
            )
              ) {
            if (this.Result.SignaledPumps > this.CircuitHandler.Config.MaxPumpsPerCircuit) {
              this.Result.WarnReason = CircuitWarnReason.SignalesTooManyPumps;
              return true;
            }
            if (
              pumpConfig.TriggerPermission != null &&
              this.TriggeringPlayer != TSPlayer.Server &&
              !this.TriggeringPlayer.Group.HasPermission(pumpConfig.TriggerPermission)
            ) {
              this.Result.WarnReason = CircuitWarnReason.InsufficientPermissionToSignalComponent;
              this.Result.WarnRelatedComponentType = measureData.BlockType;
              return true;
            }

            if (measureData.BlockType == BlockType.InletPump)
              this.SignaledInletPumps.Add(new DPoint(originX, originY));
            else
              this.SignaledOutletPumps.Add(new DPoint(originX, originY));

            this.Result.SignaledPumps++;
              }

              return true;
            }
            case BlockType.DartTrap: {
              if (signal == SignalType.Off)
            return false;

              TrapConfig trapConfig;
              Tile componentTile = TerrariaUtils.Tiles[measureData.OriginTileLocation];
              PaintColor componentPaint = (PaintColor)componentTile.color();
              TrapStyle trapStyle = TerrariaUtils.Tiles.GetTrapStyle(componentTile.frameY / 18);
              TrapConfigKey configKey = new TrapConfigKey(trapStyle, componentPaint);
              TrapConfigKey defaultKey = new TrapConfigKey(trapStyle, PaintColor.None);
              if (
            (
              this.CircuitHandler.Config.TrapConfigs.TryGetValue(configKey, out trapConfig) ||
              this.CircuitHandler.Config.TrapConfigs.TryGetValue(defaultKey, out trapConfig)
            ) &&
              trapConfig.Cooldown == 0 ||
              WorldGen.checkMech(originX, originY, trapConfig.Cooldown
            )
              ) {
            if (this.Result.SignaledTraps > this.CircuitHandler.Config.MaxTrapsPerCircuit) {
              this.Result.WarnReason = CircuitWarnReason.SignalesTooManyTraps;
              return true;
            }
            if (
              trapConfig.TriggerPermission != null &&
              this.TriggeringPlayer != TSPlayer.Server &&
              !this.TriggeringPlayer.Group.HasPermission(trapConfig.TriggerPermission)
            ) {
              this.Result.WarnReason = CircuitWarnReason.InsufficientPermissionToSignalComponent;
              this.Result.WarnRelatedComponentType = BlockType.DartTrap;
              return true;
            }

            int projectileIndex = 1000;
            for (int i = 0; i < 1000; ++i) {
              if (!Main.projectile[i].active) {
                projectileIndex = i;
                break;
              }
            }
            if (projectileIndex == 1000)
              return true;

            bool isFacingLeft = (TerrariaUtils.Tiles[originX, originY].frameX == 0);
            float projectileAngle = trapConfig.ProjectileAngle;
            if (isFacingLeft)
              projectileAngle += 180f;

            projectileAngle += CircuitProcessor.Random.Next(-(int)trapConfig.ProjectileAngleVariance, (int)trapConfig.ProjectileAngleVariance + 1);

            Vector2 normalizedPolarOffset = new Vector2(
              (float)Math.Cos(Math.PI * projectileAngle / 180f),
              (float)Math.Sin(Math.PI * projectileAngle / 180f)
            );
            Projectile projectile = Main.projectile[projectileIndex];
            projectile.SetDefaults(trapConfig.ProjectileType);
            Vector2 projectileSpawn = new Vector2(
              (originX * TerrariaUtils.TileSize + (trapConfig.ProjectileOffset * normalizedPolarOffset.X)),
              (originY * TerrariaUtils.TileSize + (trapConfig.ProjectileOffset * normalizedPolarOffset.Y))
            );
            projectileSpawn = projectileSpawn.Add(new Vector2(
              TerrariaUtils.TileSize / 2 - projectile.width / 2,
              TerrariaUtils.TileSize / 2 - projectile.height / 2
            ));
            projectile.position.X = projectileSpawn.X;
            projectile.position.Y = projectileSpawn.Y;
            projectile.owner = Main.myPlayer;
            projectile.velocity.X = (trapConfig.ProjectileSpeed * normalizedPolarOffset.X);
            projectile.velocity.Y = (trapConfig.ProjectileSpeed * normalizedPolarOffset.Y);
            projectile.damage = trapConfig.ProjectileDamage;
            projectile.knockBack = trapConfig.ProjectileKnockback;
            projectile.identity = projectileIndex;
            projectile.timeLeft = trapConfig.ProjectileLifeTime;
            projectile.wet = Collision.WetCollision(projectile.position, projectile.width, projectile.height);
            TSPlayer.All.SendData(PacketTypes.ProjectileNew, string.Empty, projectileIndex);

            this.Result.SignaledTraps++;
              }

              return true;
            }
            case BlockType.Explosives: {
              if (signal == SignalType.Off)
            return false;

              WorldGen.KillTile(originX, originY, false, false, true);
              TSPlayer.All.SendTileSquareEx(originX, originY, 1);
              Projectile.NewProjectile((originX * 16 + 8), (originY * 16 + 8), 0f, 0f, 108, 250, 10f, Main.myPlayer);

              return true;
            }
            case BlockType.Statue: {
              if (signal == SignalType.Off)
            return false;

              StatueStyle statueStyle = TerrariaUtils.Tiles.GetStatueStyle(TerrariaUtils.Tiles[measureData.OriginTileLocation]);
              StatueConfig statueConfig;
              if (
            this.CircuitHandler.Config.StatueConfigs.TryGetValue(statueStyle, out statueConfig) &&
            statueConfig.Actions.Count > 0 && (
              statueConfig.Cooldown == 0 ||
              WorldGen.checkMech(originX, originY, statueConfig.Cooldown)
            )
              ) {
            if (this.Result.SignaledStatues > this.CircuitHandler.Config.MaxStatuesPerCircuit) {
              this.Result.WarnReason = CircuitWarnReason.SignalesTooManyStatues;
              return true;
            }
            if (
              statueConfig.TriggerPermission != null &&
              this.TriggeringPlayer != TSPlayer.Server &&
              !this.TriggeringPlayer.Group.HasPermission(statueConfig.TriggerPermission)
            ) {
              this.Result.WarnReason = CircuitWarnReason.InsufficientPermissionToSignalComponent;
              this.Result.WarnRelatedComponentType = BlockType.Statue;
              return true;
            }

            if (statueConfig.PlayerCheckRange > 0) {
              bool isPlayerInRange = false;
              foreach (TSPlayer player in TShock.Players) {
                if (player == null || !player.Active)
                  continue;
                if (Math.Sqrt(Math.Pow(player.TileX - originX, 2) + Math.Pow(player.TileY - originY, 2)) <= statueConfig.PlayerCheckRange) {
                  isPlayerInRange = true;
                  break;
                }
              }
              if (!isPlayerInRange)
                return true;
            }

            if (statueConfig.ActionsProcessingMethod == ActionListProcessingMethod.ExecuteAll) {
              foreach (NullStatueAction action in statueConfig.Actions)
                this.ExecuteStatueAction(measureData.OriginTileLocation, action);
            } else {
              NullStatueAction randomAction = statueConfig.Actions[CircuitProcessor.Random.Next(0, statueConfig.Actions.Count)];
              this.ExecuteStatueAction(measureData.OriginTileLocation, randomAction);
            }

            this.Result.SignaledStatues++;
              }

              return true;
            }
            case BlockType.Sign: {
              if (!this.IsAdvancedCircuit || signal == SignalType.Off || this.TriggeringPlayer == TSPlayer.Server)
            return false;

              if (this.IsTriggeredPassively && !this.TriggeringPlayer.Group.HasPermission(AdvancedCircuitsPlugin.PassiveTriggerSign_Permission)) {
            this.Result.WarnReason = CircuitWarnReason.InsufficientPermissionToSignalComponent;
            this.Result.WarnRelatedComponentType = BlockType.Sign;
            return false;
              }

              string signText = Main.sign[Sign.ReadSign(originX, originY)].text;
              if (signText == null)
            return false;

              if (
            this.CircuitHandler.PluginCooperationHandler.IsSignCommandsAvailable &&
            this.CircuitHandler.PluginCooperationHandler.SignCommands_CheckIsSignCommand(signText)
              ) {
            if (!this.TriggeringPlayer.Group.HasPermission(AdvancedCircuitsPlugin.TriggerSignCommand_Permission)) {
              this.Result.WarnReason = CircuitWarnReason.InsufficientPermissionToSignalComponent;
              this.Result.WarnRelatedComponentType = BlockType.Sign;
              return false;
            }

            this.CircuitHandler.PluginCooperationHandler.SignCommands_ExecuteSignCommand(
              this.TriggeringPlayer, measureData.OriginTileLocation, signText
            );
            return true;
              }

              if (!WorldGen.checkMech(originX, originY, 300))
            return true;

              string fullText = this.CircuitHandler.Config.SignConfig.ReadPrefix + signText;
              int lineStartIndex = 0;
              int lineLength = 0;
              for (int i = 0; i < fullText.Length; i++) {
            if (lineLength == 60 || fullText[i] == '\n' || (i == fullText.Length - 1 && lineLength > 0)) {
              if (fullText[i] == '\n') {
                if (lineLength > 0)
                  this.TriggeringPlayer.SendInfoMessage(fullText.Substring(lineStartIndex, i - lineStartIndex));
                else
                  this.TriggeringPlayer.SendInfoMessage(string.Empty);

                lineStartIndex = i + 1;
              } else if (i == fullText.Length - 1) {
                this.TriggeringPlayer.SendInfoMessage(fullText.Substring(lineStartIndex, i - lineStartIndex + 1));
                lineStartIndex = i;
              } else {
                this.TriggeringPlayer.SendInfoMessage(fullText.Substring(lineStartIndex, i - lineStartIndex));
                lineStartIndex = i;
              }

              lineLength = 0;
              continue;
            }

            lineLength++;
              }

              return true;
            }
            case BlockType.Boulder: {
              if (!this.IsAdvancedCircuit || signal == SignalType.Off)
            return false;

              WorldGen.KillTile(originX, originY, false, false, true);
              TSPlayer.All.SendTileSquareEx(originX, originY, 2);
              return true;
            }
            case BlockType.LandMine: {
              if (signal == SignalType.Off)
            return false;

              WorldGen.ExplodeMine(originX, originY);
              return true;
            }
            case BlockType.Rocket: {
              if (signal == SignalType.Off)
            return false;

              WorldGen.LaunchRocket(originX, originY);
              return true;
            }
            case BlockType.Teleporter: {
              if (signal == SignalType.Off)
            return false;
              if (TerrariaUtils.Tiles[measureData.OriginTileLocation].wall == (int)WallType.LihzahrdBrickWall && !(originY <= Main.worldSurface || NPC.downedPlantBoss))
            return true;
              if (this.TriggeringPlayer != TSPlayer.Server && !this.TriggeringPlayer.Group.HasPermission(AdvancedCircuitsPlugin.TriggerTeleporter_Permission)) {
            this.Result.WarnReason = CircuitWarnReason.InsufficientPermissionToSignalComponent;
            this.Result.WarnRelatedComponentType = BlockType.Teleporter;
            return false;
              }

              if (rootBranch.TeleporterLocation == DPoint.Empty) {
            rootBranch.TeleporterLocation = measureData.OriginTileLocation;
              } else {
            WorldGen.teleport[0] = rootBranch.TeleporterLocation.ToXnaVector2();
            WorldGen.teleport[1] = measureData.OriginTileLocation.ToXnaVector2();
            WorldGen.Teleport();
            WorldGen.teleport[0] = WorldGen.teleport[1] = new Vector2(-1f, -1f);

            rootBranch.TeleporterLocation = DPoint.Empty;
              }
              return true;
            }
              }

              return false;
        }
 public Task<IEnumerable<ItemSignalsEntity>> GetSequenceAsync(string itemId, SignalType signal, int pageSize)
 {
     return GetSequenceInternalAsync(itemId, signal, pageSize, false);
 }
        protected virtual void ProcessTile(
            RootBranchProcessData rootBranch, DPoint tileLocation, DPoint adjacentTileLocation, SignalType signal
            )
        {
            if (this.IsCancellationPending)
            return;

              Tile tile = TerrariaUtils.Tiles[tileLocation];

              // If the tile has no wire it might be a AC-Component and thus the adjacent tile would be its port.
              if (!tile.HasWire(rootBranch.WireColor) && tile.active()) {
            if (!this.IsAdvancedCircuit || adjacentTileLocation == DPoint.Empty)
              return;
            if (!AdvancedCircuits.IsPortDefiningComponentBlock((BlockType)tile.type))
              return;
            if (signal == SignalType.Swap)
              throw new ArgumentException("A Port can not receive a Swap signal.", "signal");

            ObjectMeasureData acComponentMeasureData = TerrariaUtils.Tiles.MeasureObject(tileLocation);
            // The origin sender can only signal itself if it is a timer.
            if (
              acComponentMeasureData.OriginTileLocation == this.SenderMeasureData.OriginTileLocation &&
              tile.type != (int)BlockType.XSecondTimer
            ) {
              return;
            }

            int componentSignalCounter;
            this.PortDefiningComponentSignalCounter.TryGetValue(acComponentMeasureData.OriginTileLocation, out componentSignalCounter);
            if (componentSignalCounter > CircuitProcessor.PortDefiningComponentSignalMaximum) {
              this.Result.CancellationReason = CircuitCancellationReason.SignaledSameComponentTooOften;
              this.Result.CancellationRelatedComponentType = acComponentMeasureData.BlockType;
              return;
            }

            if (
              AdvancedCircuits.IsOriginSenderComponent((BlockType)tile.type) &&
              rootBranch.SignaledComponentLocations.Contains(acComponentMeasureData.OriginTileLocation)
            )
              return;

            if (this.SignalPortDefiningComponent(
              rootBranch, acComponentMeasureData, adjacentTileLocation, AdvancedCircuits.SignalToBool(signal).Value
            )) {
              rootBranch.SignaledComponentLocations.Add(acComponentMeasureData.OriginTileLocation);

              if (componentSignalCounter == default(int))
            this.PortDefiningComponentSignalCounter.Add(acComponentMeasureData.OriginTileLocation, 1);
              else
            this.PortDefiningComponentSignalCounter[acComponentMeasureData.OriginTileLocation] = componentSignalCounter + 1;

              this.Result.SignaledPortDefiningComponentsCounter++;
            }

            return;
              }

              if (!tile.HasWire(rootBranch.WireColor))
            return;

              try {
            // Actuator Handling
            if (tile.actuator() && (tile.type != (int)BlockType.LihzahrdBrick || tileLocation.Y <= Main.worldSurface || NPC.downedPlantBoss)) {
              bool currentState = tile.inActive();
              bool newState;
              if (signal == SignalType.Swap)
            newState = !currentState;
              else
            newState = AdvancedCircuits.SignalToBool(signal).Value;

              if (newState != currentState) {
            if (newState)
              WorldGen.DeActive(tileLocation.X, tileLocation.Y);
            else
              WorldGen.ReActive(tileLocation.X, tileLocation.Y);
              }
            }

            // Block Activator tile activation / deactivation.
            if (rootBranch.BlockActivator != null) {
              Tile blockActivatorTile = TerrariaUtils.Tiles[rootBranch.BlockActivatorLocation];
              if (tile.wall == blockActivatorTile.wall) {
            Tile tileAbove = TerrariaUtils.Tiles[tileLocation.OffsetEx(0, -1)];
            if (!tileAbove.active() || tileAbove.type != (int)BlockType.Chest) {
              if (
                signal == SignalType.Off && tile.active() && AdvancedCircuits.IsCustomActivatableBlock((BlockType)tile.type)
              ) {
                if (rootBranch.BlockActivator.RegisteredInactiveBlocks.Count > this.CircuitHandler.Config.BlockActivatorConfig.MaxChangeableBlocks) {
                  this.Result.WarnReason = CircuitWarnReason.BlockActivatorChangedTooManyBlocks;
                  return;
                }

                rootBranch.BlockActivator.RegisteredInactiveBlocks.Add(tileLocation, (BlockType)tile.type);

                tile.type = 0;
                tile.active(false);
                tile.frameX = -1;
                tile.frameY = -1;
                tile.frameNumber(0);
                this.TilesToFrameOnPost.Add(tileLocation);

                return;
              } else if (
                signal == SignalType.On && (rootBranch.BlockActivatorMode == BlockActivatorMode.ReplaceBlocks || !tile.active())
              ) {
                BlockType registeredBlockType;
                if (rootBranch.BlockActivator.RegisteredInactiveBlocks.TryGetValue(tileLocation, out registeredBlockType)) {
                  rootBranch.BlockActivator.RegisteredInactiveBlocks.Remove(tileLocation);

                  tile.type = (byte)registeredBlockType;
                  tile.active(true);
                  this.TilesToFrameOnPost.Add(tileLocation);

                  return;
                }
              }
            }
              }
            }

            if (!tile.active())
              return;

            ObjectMeasureData componentMeasureData = TerrariaUtils.Tiles.MeasureObject(tileLocation);
            if (rootBranch.SignaledComponentLocations.Contains(componentMeasureData.OriginTileLocation))
              return;

            // The origin sender can never signal itself if wired directly.
            if (componentMeasureData.OriginTileLocation == this.SenderMeasureData.OriginTileLocation)
              return;

            // Switches and Levers can not be signaled if they are wired directly.
            if (tile.type == (int)BlockType.Switch || tile.type == (int)BlockType.Lever)
              return;

            if (this.SignalComponent(ref componentMeasureData, rootBranch, signal)) {
              rootBranch.SignaledComponentLocations.Add(componentMeasureData.OriginTileLocation);
              this.Result.SignaledComponentsCounter++;
            }
              } finally {
            this.CircuitLength++;

            if (this.CircuitLength >= this.CircuitHandler.Config.MaxCircuitLength) {
              this.Result.CancellationReason = CircuitCancellationReason.ExceededMaxLength;
              this.PluginTrace.WriteLineInfo(
            "Processing of the circuit at {0} was cancelled because the signal reached the maximum transfer length of {1} wires.",
            this.SenderMeasureData.OriginTileLocation, this.CircuitHandler.Config.MaxCircuitLength
              );
            }
              }
        }
        public CircuitProcessingResult ProcessCircuit(TSPlayer player = null, SignalType? overrideSignal = null, bool switchSender = true, bool switchSenderLocalOnly = true)
        {
            if (this.wasExecuted)
            throw new InvalidOperationException("This Circuit Processor has already processed a circuit.");

              this.wasExecuted = true;
              this.SignaledInletPumps.Clear();
              this.SignaledOutletPumps.Clear();
              this.TilesToFrameOnPost.Clear();
              this.QueuedRootBranches.Clear();

              if (this.IsAdvancedCircuit) {
            this.PortDefiningComponentSignalCounter.Clear();
            this.TemporaryGateStates.Clear();
              }

              DateTime processingStartTime = DateTime.Now;
              BlockType senderBlockType = this.SenderMeasureData.BlockType;
              SignalType signal = SignalType.Swap;

              try {
            if (this.IsAdvancedCircuit) {
              if (!this.CircuitHandler.Config.AdvancedCircuitsEnabled)
            return this.Result;

              if (overrideSignal == null) {
            switch (senderBlockType) {
              case BlockType.PressurePlate:
                // Red sends "0", all the others send "1".
                signal = AdvancedCircuits.BoolToSignal(TerrariaUtils.Tiles[this.SenderMeasureData.OriginTileLocation].frameY > 0);

                break;
              case BlockType.Lever:
              case BlockType.Switch:
              case BlockType.XSecondTimer:
                signal = AdvancedCircuits.BoolToSignal(!TerrariaUtils.Tiles.ObjectHasActiveState(this.SenderMeasureData));
                break;

              default:
                signal = SignalType.On;
                break;
            }
              }
            } else {
              // Grandfather Clock is an Advanced Circuit component and thus wont work in Vanilla Circuits.
              if (senderBlockType == BlockType.GrandfatherClock)
            return this.Result;
              if (senderBlockType == BlockType.DoorOpened || senderBlockType == BlockType.DoorClosed)
            return this.Result;

              if (!this.CircuitHandler.Config.OverrideVanillaCircuits) {
            WorldGen.hitSwitch(this.SenderMeasureData.OriginTileLocation.X, this.SenderMeasureData.OriginTileLocation.Y);
            return this.Result;
              }

              signal = SignalType.Swap;
            }

            if (overrideSignal != null)
              signal = overrideSignal.Value;

            this.TriggeringPlayer = player ?? TSPlayer.Server;
            if (player != TSPlayer.Server && (senderBlockType == BlockType.XSecondTimer || senderBlockType == BlockType.GrandfatherClock)) {
              string triggeringPlayerName = null;
              if (senderBlockType == BlockType.XSecondTimer) {
            ActiveTimerMetadata activeTimer;
            if (!this.CircuitHandler.WorldMetadata.ActiveTimers.TryGetValue(this.SenderMeasureData.OriginTileLocation, out activeTimer))
              return result;

            triggeringPlayerName = activeTimer.TriggeringPlayerName;
              } else if (senderBlockType == BlockType.GrandfatherClock) {
            GrandfatherClockMetadata clock;
            if (!this.CircuitHandler.WorldMetadata.Clocks.TryGetValue(this.SenderMeasureData.OriginTileLocation, out clock))
              return result;

            triggeringPlayerName = clock.TriggeringPlayerName;
              }

              if (triggeringPlayerName != null) {
            TSPlayer actualTriggeringPlayer = TShockEx.GetPlayerByName(triggeringPlayerName);
            this.TriggeringPlayer = player ?? actualTriggeringPlayer ?? TSPlayer.Server;
              }
              this.IsTriggeredPassively = true;
            }

            if (
              switchSender && (
            senderBlockType == BlockType.Switch ||
            senderBlockType == BlockType.Lever ||
            senderBlockType == BlockType.XSecondTimer ||
            senderBlockType == BlockType.DoorOpened ||
            senderBlockType == BlockType.DoorClosed
              )
            ) {
              bool newSenderState;
              if (signal == SignalType.Swap)
            newSenderState = !TerrariaUtils.Tiles.ObjectHasActiveState(this.SenderMeasureData);
              else
            newSenderState = AdvancedCircuits.SignalToBool(signal).Value;

              if (TerrariaUtils.Tiles.ObjectHasActiveState(this.SenderMeasureData) != newSenderState) {
            TerrariaUtils.Tiles.SetObjectState(this.SenderMeasureData, newSenderState, !switchSenderLocalOnly);
            this.Result.SenderWasSwitched = true;
              }

              if (senderBlockType == BlockType.XSecondTimer) {
            this.CircuitHandler.RegisterUnregisterTimer(this.TriggeringPlayer, this.SenderMeasureData, newSenderState);

            // Timers do not execute circuits when they are switched.
            return this.Result;
              }
            }

            foreach (DPoint portLocation in AdvancedCircuits.EnumerateComponentPortLocations(this.SenderMeasureData)) {
              Tile portTile = TerrariaUtils.Tiles[portLocation];
              if (!portTile.HasWire())
            continue;

              DPoint portAdjacentTileLocation = AdvancedCircuits.GetPortAdjacentComponentTileLocation(this.SenderMeasureData, portLocation);
              SignalType portSignal = signal;
              if (this.IsAdvancedCircuit && portTile.active()) {
            if (portTile.type == (int)AdvancedCircuits.BlockType_NOTGate)
              portSignal = AdvancedCircuits.BoolToSignal(!AdvancedCircuits.SignalToBool(portSignal).Value);
            else if (portTile.type == (int)AdvancedCircuits.BlockType_XORGate)
              portSignal = SignalType.Off;
              }

              foreach (WireColor wireColor in AdvancedCircuits.EnumerateWireColors())
            if (portTile.HasWire(wireColor))
              this.QueuedRootBranches.Add(new RootBranchProcessData(portAdjacentTileLocation, portLocation, portSignal, wireColor));
            }

            if (this.IsAdvancedCircuit) {
              // Main Branch Processing Loop
              while (this.QueuedRootBranches.Count > 0) {
            RootBranchProcessData currentBranch = this.QueuedRootBranches[0];

            this.ProcessRootBranch(currentBranch);
            this.QueuedRootBranches.RemoveAt(0);
              }
            } else {
              // We know that the sender must have at least one of its tiles wired, we are too lazy to count them though, so we just
              // expect the wiring of the sender to be 1.
              this.CircuitLength++;

              foreach (WireColor wireColor in AdvancedCircuits.EnumerateWireColors()) {
            this.ProcessSubBranches(
              new RootBranchProcessData(
                this.SenderMeasureData.OriginTileLocation, this.SenderMeasureData.OriginTileLocation, signal, wireColor
              ),
              new List<BranchProcessData>(
                from rb in this.QueuedRootBranches
                where rb.WireColor == wireColor
                select rb.ToBranchProcessData()
              )
            );
              }
            }

            this.PostProcessCircuit();
              } catch (Exception ex) {
            throw new InvalidOperationException("Processing circuit failed. See inner exception for details.", ex);
              } finally {
            this.Result.ProcessingTime = DateTime.Now - processingStartTime;
            this.Result.OriginSignal = signal;
              }

              return this.Result;
        }
        private void OpenDoor(ObjectMeasureData measureData, SignalType signal)
        {
            bool currentState = (measureData.BlockType == BlockType.DoorOpened);
              bool newState;
              if (signal == SignalType.Swap)
            newState = !currentState;
              else
            newState = AdvancedCircuits.SignalToBool(signal).Value;

              if (newState != currentState) {
            int doorX = measureData.OriginTileLocation.X;
            int doorY = measureData.OriginTileLocation.Y;

            if (newState) {
              // A door will always try to open to the opposite site of the sender's location that triggered the circuit first.
              int direction = 1;
              if (doorX < this.SenderMeasureData.OriginTileLocation.X)
            direction = -1;

              // If opening it towards one direction doesn't work, try the other.
              currentState = WorldGen.OpenDoor(doorX, doorY, direction);
              if (!currentState) {
            direction *= -1;
            currentState = WorldGen.OpenDoor(doorX, doorY, direction);
              }

              if (currentState) {
            TSPlayer.All.SendData(PacketTypes.DoorUse, string.Empty, 0, doorX, doorY, direction);
            // Because the door changed its sprite, we have to re-measure it now.
            measureData = TerrariaUtils.Tiles.MeasureObject(measureData.OriginTileLocation);
              }
            } else {
              if (WorldGen.CloseDoor(doorX, doorY, true))
            TSPlayer.All.SendData(PacketTypes.DoorUse, string.Empty, 1, doorX, doorY);
            }

            WorldGen.numWire = 0;
            WorldGen.numNoWire = 0;
              }
        }
        private async Task<IEnumerable<ItemSignalsEntity>> GetSequenceInternalAsync(string itemId, SignalType signal, int pageSize, bool isAntiSequence)
        {
            string rowKey = BuildRowKey(itemId, signal);
            BoundStatement boundStatement = _getStatement.Value.Bind(rowKey, isAntiSequence);

            // setting properties
            boundStatement.SetPageSize(pageSize);

            RowSet rowset = await _session.Get().ExecuteAsync(boundStatement);
            return rowset.Select(r => _mapper.Map<Row, ItemSignalsEntity>(r));
        }
 private static string BuildRowKey(string itemId, SignalType signal)
 {
     return itemId + "|" + signal;
 }