Example #1
0
    void ChangeAnimation(State animation) {
        m_currentAnimation = animation;

        //페이드 아웃 시에만 다른 애니메이션이 됩니다.
        if (m_currentAnimation == State.FadeOut) {
            //FadeOut_Rock, FadeOut_Paper, FadeOut_Scissor,
            string name = m_currentAnimation.ToString() + "_" + m_rpsKind.ToString();
            m_animation.Play(name);
        }
        else {
            m_animation.Play(m_currentAnimation.ToString());
        }
    }
Example #2
0
        public LogElement ToLogElement()
        {
            var statemsg = string.Empty;
            IEnumerable <LogElement.ItemElement> elms;

            if (State is SolaceLogState sls)
            {
                statemsg = sls.Message;
                elms     = sls.Values.Select(x =>
                                             new LogElement.ItemElement()
                {
                    Position = x.Position,
                    Value    = x.Value?.ToString() ?? string.Empty
                });
            }
            else
            {
                elms     = new List <LogElement.ItemElement>();
                statemsg = State?.ToString() ?? string.Empty;
            }

            var le = new LogElement()
            {
                TimeStamp     = this.TimeStamp,
                Level         = this.Level,
                EventId       = this.Id.Id,
                SenderService = this.Name,
                Message       = statemsg,
                Elements      = elms,
                Exception     = new LogElement.ExceptionElement(this.Exception),
            };

            return(le);
        }
    static string? GetState(Feature feature, State? state)
    {
        if (feature.Properties.TryGetValue("State", out var stateFromProperties))
        {
            return (string) stateFromProperties;
        }

        return state?.ToString();
    }
    public void Start()
    {
        kathyBegginingSounds = GetComponent<Kathy_BeginningSounds>();

        states = Enum.GetValues(typeof(State)).Cast<State>().ToList();
        currentState = states.ElementAt(0);
        Debug.Log("State is now " + currentState.ToString());

        movingCamera.enabled = false;
    }
Example #5
0
 public void NotifyPrepared()
 {
     switch (_state)
     {
         case State.INIT:
             _state = State.PREPARED;
             _prepared.Signal();
             break;
         default:
             throw new InvalidOperationException(_state.ToString());
     }
 }
Example #6
0
	// 初回の処理
	private void Step(State state) {
		_state = state;
		
		switch (_state) {
		case State.None: break;
		case State.StartServer: StepStartServer(); break;
		case State.WaitClient: StepWaitClient(); break;
		case State.ConnectToHost: StepConnectToHost(); break;
		case State.Connecting: StepConnecting(); break;
		default: throw new ArgumentOutOfRangeException(_state.ToString());
		}
	}
Example #7
0
 public void NotifyStartable()
 {
     switch (_state)
     {
         case State.PREPARED:
             _state = State.STARTABLE;
             _startable.Signal();
             break;
         default:
             throw new InvalidOperationException(_state.ToString());
     }
 }
Example #8
0
        /// <summary>
        /// Applies the round in the forward direction (for encryption).
        /// </summary>
        /// <param name="state">The current state of the cipher.</param>
        /// <param name="keyIndex">The round key index to use.</param>
        public void Apply(State state, int keyIndex)
        {
            // Apply the layers in forward order
            for (int ixLayer = 0; ixLayer < _Layers.Length; ixLayer++)
            {
                _Layers[ixLayer].ApplyLayer(state, keyIndex);

                if(Debugging.IsEnabled)
                {
                    Debugging.Trace("After applying {0} in round {1}, the state is now:", _Layers[ixLayer], keyIndex);
                    Debugging.Trace(state.ToString());
                }
            }
        }
Example #9
0
        /// <summary>
        /// Applies the round in the reverse direction (for decryption).
        /// </summary>
        /// <param name="state">The current state of the cipher.</param>
        /// <param name="keyIndex">The round key index to use.</param>
        public void Inverse(State state, int keyIndex)
        {
            // Apply the layers in reverse order
            for (int ixLayer = _Layers.Length - 1; ixLayer >= 0; ixLayer--)
            {
                _Layers[ixLayer].InverseLayer(state, keyIndex);

                if (Debugging.IsEnabled)
                {
                    Debugging.Trace("After applying {0} in round {1}, the state is now:", _Layers[ixLayer].ToString());
                    Debugging.Trace(state.ToString());
                }
            }
        }
Example #10
0
        private Dictionary <string, string> CreateParametersForUsingFilters(string header, string description, string branch, State?state, Priority?priority, Guid?developerId, Guid?reviewerId, Guid?columnId, Guid?boardId)
        {
            var parameters = GetDefaultParameters();

            AddParameterIfNotNullOrEmpty(parameters, HttpParameters.TaskHeader, header);
            AddParameterIfNotNullOrEmpty(parameters, HttpParameters.TaskDescription, description);
            AddParameterIfNotNullOrEmpty(parameters, HttpParameters.TaskBranch, branch);
            AddParameterIfNotNullOrEmpty(parameters, HttpParameters.TaskState, state?.ToString());
            AddParameterIfNotNullOrEmpty(parameters, HttpParameters.TaskPriority, priority?.ToString());
            AddParameterIfNotNullOrEmpty(parameters, HttpParameters.TaskDeveloperId, developerId?.ToString());
            AddParameterIfNotNullOrEmpty(parameters, HttpParameters.TaskReviewerId, reviewerId?.ToString());
            AddParameterIfNotNullOrEmpty(parameters, HttpParameters.TaskColumnId, columnId?.ToString());
            AddParameterIfNotNullOrEmpty(parameters, HttpParameters.TaskBoardId, boardId?.ToString());

            return(parameters);
        }
Example #11
0
        public static void Write(State s, String msg)
        {
            if (!Settings.Debug) return;
            while (isBeingUsed) ;

            lock (privateListToUseInLockToIndicateWhenFileIsBeingWrittenInto)
            {
                isBeingUsed = true;
                SanityCheck();
                System.IO.BinaryWriter sw = new BinaryWriter(new FileStream("debug/debug.log", FileMode.Append));
                sw.Write(Encode("[" + DateTime.Now.ToString() + "] " +
                    "[" + Debug.DebugInfo.FramesPerSecond.ToString() + "FPS] [" + Debug.DebugInfo.UpdatesPerSecond.ToString() + "TPS] " +
                    "[" + (System.Diagnostics.Process.GetCurrentProcess().WorkingSet64 / 1024 / 1024).ToString() + "mb] " +
                    "[" + s.ToString() + "]" +
                    " : " + msg + "\r\n"));
                sw.Close();
                sw.Dispose();
                isBeingUsed = false;
            }
        }
    private void CheckPresence()
    {
        Log(Microsoft.Extensions.Logging.LogLevel.Information,
            "Presence changed, checking to possibly take action with alarm");
        if (this.AnyoneJustArrived())
        {
            this.NotifyDiscord(DiscordChannel.Alarm, "🚻 Someone just got home.");
            Disarm();
        }
        else if (!this.AnyoneHome())
        {
            this.NotifyDiscord(DiscordChannel.Alarm, "🚷 Presence changed, but no one is home.");

            if (State(CleaningDayCalendar !)?.State?.ToString().ToLower() == "on")
            {
                ArmHome();
            }
            else
            {
                ArmAway();
            }
        }
        public ActionResult State(State state)
        {
            PropertyPageViewModel propertyModel = new PropertyPageViewModel();

            var properties = ServiceLocator.GetPropertyService().GetProperties(state);

            propertyModel.CompleteProperties = properties.ToList().FindAll(o => o.IsComplete);
            propertyModel.InCompleteProperties = properties.ToList().FindAll(o => !o.IsComplete);
            propertyModel.State = state.ToString();

            if (this.Request.IsAjaxRequest())
            {
                return this.PartialView("PropertiesInState", propertyModel);
            }

            var model = new PageViewModel();
            model.View = "AustralianMap";
            model.Title = "Properties";
            model.SelectedNavigation = "Properties";
            model.Model = propertyModel;

            return View("StandardPageLayout", model);
        }
Example #14
0
 /// <summary>
 /// Convert typed State to raw string.
 /// </summary>
 /// <param name="state"></param>
 /// <returns></returns>
 public static string ToString(State state)
 {
     switch (state)
     {
         case State.Unknown:
             return "unknown";
         case State.Label:
             return "label";
         case State.Starred:
             return "starred";
         case State.Broadcast:
             return "broadcast";
         case State.Like:
             return "like";
         case State.Read:
             return "read";
         case State.Fresh:
             return "fresh";
         case State.ReadingList:
             return "reading-list";
         default:
             return state.ToString();
     }
 }
 public State[] FindPath(State fromState, State toState)
 {
     var from = LogicOperations.NodeFromString(fromState.ToString());
     var to = LogicOperations.NodeFromString(toState.ToString());
     return ListToStates(LogicOperations.FindPath(historyGraph, from, to));
 }
Example #16
0
        private void HandleTransferFrame(Transfer transfer, ByteBuffer buffer)
        {
            if (State != LinkStateEnum.ATTACHED)
            {
                throw new AmqpException(ErrorCode.IllegalState, $"Received Transfer frame but link state is {State.ToString()}.");
            }
            if (LinkCredit <= 0)
            {
                throw new AmqpException(ErrorCode.TransferLimitExceeded, "The link credit has dropped to 0. Wait for messages to finishing processing.");
            }
            if (!IsReceiverLink)
            {
                throw new AmqpException(ErrorCode.NotAllowed, "A Sender Link cannot receive Transfers.");
            }

            Delivery delivery;

            if (continuationDelivery == null)
            {
                // new transfer
                delivery                        = new Delivery();
                delivery.Link                   = this;
                delivery.DeliveryId             = transfer.DeliveryId.Value;
                delivery.DeliveryTag            = transfer.DeliveryTag;
                delivery.Settled                = transfer.Settled.IsTrue();
                delivery.State                  = transfer.State;
                delivery.PayloadBuffer          = new ByteBuffer(buffer.LengthAvailableToRead, true);
                delivery.ReceiverSettlementMode = receiverSettlementMode;
                if (transfer.ReceiverSettlementMode.HasValue)
                {
                    delivery.ReceiverSettlementMode = (LinkReceiverSettlementModeEnum)transfer.ReceiverSettlementMode.Value;
                    if (receiverSettlementMode == LinkReceiverSettlementModeEnum.First &&
                        delivery.ReceiverSettlementMode == LinkReceiverSettlementModeEnum.Second)
                    {
                        throw new AmqpException(ErrorCode.InvalidField, "rcv-settle-mode: If the negotiated link value is first, then it is illegal to set this field to second.");
                    }
                }
            }
            else
            {
                // continuation
                if (transfer.DeliveryId.HasValue && transfer.DeliveryId.Value != continuationDelivery.DeliveryId)
                {
                    throw new AmqpException(ErrorCode.NotAllowed, "Expecting Continuation Transfer but got a new Transfer.");
                }
                if (transfer.DeliveryTag != null && !transfer.DeliveryTag.SequenceEqual(continuationDelivery.DeliveryTag))
                {
                    throw new AmqpException(ErrorCode.NotAllowed, "Expecting Continuation Transfer but got a new Transfer.");
                }
                delivery = continuationDelivery;
            }

            if (transfer.Aborted.IsTrue())
            {
                continuationDelivery = null;
                return; // ignore message
            }

            // copy and append the buffer (message payload) to the cached PayloadBuffer
            AmqpBitConverter.WriteBytes(delivery.PayloadBuffer, buffer.Buffer, buffer.ReadOffset, buffer.LengthAvailableToRead);

            if (transfer.More.IsTrue())
            {
                continuationDelivery = delivery;
                return; // expecting more payload
            }

            // assume transferred complete payload at this point
            continuationDelivery = null;

            if (!delivery.Settled)
            {
                Session.NotifyUnsettledIncomingDelivery(this, delivery);
            }

            LinkCredit--;
            DeliveryCount++;

            Session.Connection.Container.OnDelivery(this, delivery);
        }
Example #17
0
        public virtual void GetHtmlString(Mobile viewer, StringBuilder html, bool preview = false)
        {
            var col = SuperGump.DefaultHtmlColor;

            html.Append(String.Empty.WrapUOHtmlColor(SuperGump.DefaultHtmlColor, false));

            if (Deleted)
            {
                html.AppendLine("This battle no longer exists.".WrapUOHtmlColor(Color.IndianRed, col));
                return;
            }

            html.AppendLine("{0} ({1})", Name, Ranked ? "Ranked" : "Unranked");
            html.AppendLine("State: {0}".WrapUOHtmlColor(Color.SkyBlue, col), State.ToString().SpaceWords());

            if (viewer != null && viewer.AccessLevel >= AutoPvP.Access)
            {
                var errors = new List <string>();

                if (!Validate(viewer, errors))
                {
                    html.AppendLine(UniGlyph.CircleX + " This battle has failed validation: ".WrapUOHtmlColor(Color.IndianRed, false));
                    html.AppendLine(String.Empty.WrapUOHtmlColor(Color.Yellow, false));
                    html.AppendLine(String.Join("\n", errors));
                    html.AppendLine(String.Empty.WrapUOHtmlColor(col, false));
                }
            }

            int curCap = CurrentCapacity, minCap = MinCapacity, maxCap = MaxCapacity;

            if (!preview)
            {
                if (IsPreparing && RequireCapacity && curCap < minCap)
                {
                    var req = minCap - curCap;

                    var fmt = "{0} more {1} required to start the battle.".WrapUOHtmlColor(Color.IndianRed, col);

                    html.AppendLine(fmt, req, req != 1 ? "players are" : "player is");
                }

                if (!IsInternal)
                {
                    var timeLeft = GetStateTimeLeft(DateTime.UtcNow);

                    if (timeLeft > TimeSpan.Zero)
                    {
                        var fmt = "Time Left: {0}".WrapUOHtmlColor(Color.LawnGreen, col);

                        html.AppendLine(fmt, timeLeft.ToSimpleString("h:m:s"));
                    }
                }

                html.AppendLine();
            }

            if (!String.IsNullOrWhiteSpace(Description))
            {
                html.AppendLine(Description.WrapUOHtmlColor(Color.SkyBlue, col));
                html.AppendLine();
            }

            if (Schedule != null && Schedule.Enabled)
            {
                html.AppendLine(
                    Schedule.NextGlobalTick != null
                                                ? "This battle is scheduled.".WrapUOHtmlColor(Color.LawnGreen, col)
                                                : "This battle is scheduled, but has no future dates.".WrapUOHtmlColor(Color.IndianRed, col));
            }
            else
            {
                html.AppendLine("This battle is automatic.".WrapUOHtmlColor(Color.LawnGreen, col));
            }

            html.AppendLine();

            if (!preview)
            {
                html.Append(String.Empty.WrapUOHtmlColor(Color.YellowGreen, false));

                var fmt = "{0:#,0} players in the queue.";

                html.AppendLine(fmt, Queue.Count);

                fmt = "{0:#,0} players in {1:#,0} team{2} attending.";

                html.AppendLine(fmt, curCap, Teams.Count, Teams.Count != 1 ? "s" : String.Empty);

                fmt = "{0:#,0} invites available of {1:#,0} max.";

                html.AppendLine(fmt, maxCap - curCap, maxCap);
                html.AppendLine(String.Empty.WrapUOHtmlColor(col, false));
            }

            if (Options.Missions.Enabled)
            {
                html.Append(String.Empty.WrapUOHtmlColor(Color.PaleGoldenrod, false));

                Options.Missions.GetHtmlString(html);

                html.AppendLine(String.Empty.WrapUOHtmlColor(col, false));
            }

            GetHtmlCommandList(viewer, html, preview);
        }
Example #18
0
	// DoDegub()
	// Does the degubs for the testing on the features
	//private void DoDegub()
	//{
	//	if (debugMove || debugCamera)
	//	{
	//		debugAngle += Time.deltaTime * 2.0f;
	//		if (debugAngle >= 2.0f * Mathf.PI)
	//			debugAngle -= 2.0f * Mathf.PI;
	//	}
	//	if (debugMove)
	//	{
	//		moveTest.x = Mathf.Cos(debugAngle);
	//		moveTest.z = Mathf.Sin(debugAngle);

	//		Move(moveTest);
	//	}
	//	if (debugCamera)
	//	{
	//		moveTest.x = 1.0f;
	//		moveTest.y = 0.0f;
	//		MoveCamera(camTest);
	//	}
	//	if (debugDodge)
	//	{
	//		debugDodgeTmr += Time.deltaTime;
	//		//if (debugDodgeTmr > DgeTmrMax * 2.0f)
	//		{
	//			debugDodgeTmr = 0.0f;
	//			int res = 1;
	//			switch (debugDodgeType)
	//			{
	//				case 0:
	//					res = DodgeLeft();
	//					break;
	//				case 1:
	//					res = DodgeForward();
	//					break;
	//				case 2:
	//					res = DodgeRight();
	//					break;
	//				case 3:
	//					res = DodgeRight();
	//					break;
	//				case 4:
	//					res = DodgeBackwards();
	//					break;
	//				case 5:
	//					res = DodgeLeft();
	//					break;
	//			}
	//			debugDodgeType++;
	//			if (debugDodgeType > 5)
	//				debugDodgeType = 0;
	//		}
	//	}
	//	if (debugGuard)
	//	{
	//		debugGrdTmr += Time.deltaTime;
	//		int res = 1;
	//		switch (debugGrdType)
	//		{
	//			case 0:
	//				res = GuardUpwards();
	//				break;
	//			case 1:
	//				res = GuardLeft();
	//				break;
	//			case 2:
	//				res = GuardRight();
	//				break;
	//		}

	//		//if (debugGrdTmr > GrdTmrMax * 5.0f)
	//		{
	//			debugGrdTmr = 0.0f;
	//			debugGrdType++;
	//			if (debugGrdType > 2)
	//				debugGrdType = 0;
	//		}
	//	}

	//}
	#endregion


	// Change State Function
	// returns -1 on failure
	// returns 1 on success
	public int ChangeState(State _nextState)
	{
		//if (attackScript.AtkTmrCur != 0.0f || dodgeScript.DgeTmrCur != 0.0f)
		//	return -1;
		if (stateTable[(int)curState, (int)_nextState] == false)
			return -1;
		if (_nextState == State.IDLE)
			animation.CrossFade("Idle", 0.1f);
		if ((_nextState == State.GRD_TOP && curState != State.PARRY
			&& curState != State.GRD_TOP && curState != State.GRD_LEFT && curState != State.GRD_RIGHT)
			|| (_nextState == State.GRD_LEFT && curState != State.PARRY
			&& curState != State.GRD_TOP && curState != State.GRD_LEFT && curState != State.GRD_RIGHT)
			|| (_nextState == State.GRD_RIGHT && curState != State.PARRY
			&& curState != State.GRD_TOP && curState != State.GRD_LEFT && curState != State.GRD_RIGHT))
		{
			lastState = curState;
			curState = State.PARRY;
			return 1;
		}

		if (_nextState == State.DEAD)
		{
			if (Targeting_CubeSpawned != null)
			{
				Destroy(Targeting_CubeSpawned.gameObject);
				Destroy(Targeting_CubeSpawned.gameObject); // apparently the solution.
				Destroy(Targeting_CubeSpawned.gameObject);
				Destroy(Targeting_CubeSpawned.gameObject);
				Destroy(Targeting_CubeSpawned.gameObject);
				Destroy(Targeting_CubeSpawned.gameObject);
				Destroy(Targeting_CubeSpawned.gameObject);
				Destroy(Targeting_CubeSpawned.gameObject);
				Targeting_CubeSpawned = null;
			}
			if (rockedOn)
				ToggleLockon();
		}

		//if (_nextState == State.ATK_VERT
		//	|| _nextState == State.ATK_LTR
		//	|| _nextState == State.ATK_RTL
		//	|| _nextState == State.ATK_STAB
		//	|| _nextState == State.ATK_KICK)
		//{
		//	NextAttack = _nextState;
		//}
		//else
		//	NextAttack = State.IDLE; // cant set to null =(

		lastState = curState;
		curState = _nextState;

		// New things, added by Dakota 1/13 whatever PM
		// Degub Stuff
		if (lastState != curState && degubber != null)
			degubber.GetComponent<DebugMonitor>().UpdateText("New State: " + transform.tag + " " + curState.ToString());

		return 1;
	}
Example #19
0
        private void HandleAttachFrame(Attach attach)
        {
            if (State != LinkStateEnum.DETACHED && State != LinkStateEnum.ATTACH_SENT)
            {
                throw new AmqpException(ErrorCode.IllegalState, $"Received Attach frame but link state is {State.ToString()}.");
            }

            if (!IsInitiatingLink && IsSenderLink)
            {
                senderSettlementMode = (LinkSenderSettlementModeEnum)attach.SenderSettlementMode;
                SourceAddress        = attach.Source.Address;
            }
            if (!IsInitiatingLink && IsReceiverLink)
            {
                receiverSettlementMode = (LinkReceiverSettlementModeEnum)attach.ReceiverSettlementMode;
                TargetAddress          = attach.Target.Address;
            }

            if (State == LinkStateEnum.DETACHED)
            {
                State = LinkStateEnum.ATTACH_RECEIVED;

                attach.Handle                 = this.LocalHandle;
                attach.IsReceiver             = this.IsReceiverLink;
                attach.SenderSettlementMode   = (byte)senderSettlementMode;
                attach.ReceiverSettlementMode = (byte)receiverSettlementMode;
                attach.InitialDelieveryCount  = this.initialDeliveryCount;

                // send back a cooresponding attach frame
                Session.SendFrame(attach);
            }

            if (State == LinkStateEnum.ATTACH_SENT)
            {
                if (IsReceiverLink)
                {
                    if (attach.InitialDelieveryCount == null)
                    {
                        throw new AmqpException(ErrorCode.InvalidField, "initial-delivery-count must be set on attach from of sender.");
                    }
                    // expecting initial delivery count
                    DeliveryCount = attach.InitialDelieveryCount.Value;
                }
            }

            State = LinkStateEnum.ATTACHED;
            Session.Connection.Container.OnLinkAttached(this);
        }
Example #20
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="runawayAttack">behavior to use while running away (should not require facing target.) should be null if not needed</param>
        /// <param name="jumpturnAttack">behavior to use in middle of jump turn (while facing target.)  should be null if not needed</param>
        /// <returns></returns>
        public static Composite CreateKitingBehavior(Composite runawayAttack, Composite jumpturnAttack)
        {
            return
                new PrioritySelector(
                    new Decorator(
                        ret => bstate != State.None,

                        new PrioritySelector(
                            new Decorator(ret => !StyxWoW.IsInGame, new Action(ret => EndKiting("BP: not in game so cancelling"))),
                            new Decorator(ret => !Me.IsAlive, new Action(ret => EndKiting("BP: i am dead so cancelling"))),
                            new Decorator(ret => timeOut < DateTime.Now, new Action(ret => EndKiting("BP: taking too long, so cancelling"))),
                            new Decorator(ret => jumpturnAttack != null && !Me.GotTarget, new Action(ret => EndKiting("BP: attack behavior but no target, cancelling"))),

                            new Decorator(ret => Me.Stunned || Me.IsStunned(), new Action(ret => EndKiting("BP: stunned, cancelling"))),
                            new Decorator(ret => Me.Rooted || Me.IsRooted(), new Action(ret => EndKiting("BP: rooted, cancelling"))),

                            new Decorator(ret => Me.Location.Distance(safeSpot) < DISTANCE_CLOSE_ENOUGH_TO_DESTINATION, new Action(ret => EndKiting("BP: reached safe spot!!!!"))),
                            new Decorator(ret => Me.Location.Distance(safeSpot) > DISTANCE_TOO_FAR_FROM_DESTINATION, new Action(ret => EndKiting("BP: too far from safe spot, cancelling"))),

                            new Decorator(ret => bstate == State.Moving,
                                new Sequence(
                                    new Action(d => Navigator.MoveTo(safeSpot)),
                // following 3 lines make sure we are facing and have started moving in the correct direction.  it will force
                //  .. a minimum wait of 250 ms after movement has started in the correct direction
                                    new WaitContinue(new TimeSpan(0, 0, 0, 0, 250), r => Me.IsDirectlyFacing(safeSpot), new ActionAlwaysSucceed()),
                                    new WaitContinue(new TimeSpan(0, 0, 0, 0, 500), r => Me.IsMoving, new ActionAlwaysSucceed()),  // wait till we are moving (should be very quick)
                                    new WaitContinue(new TimeSpan(0, 0, 0, 0, 250), r => !Me.IsMoving, new ActionAlwaysFail()),    // wait for 250ms, failing if we stop moving

                                    new Action(ret =>
                                    {
                                        if (runawayAttack != null)
                                        {
                                            bstate = State.NonFaceAttack;
                                            Logger.WriteDebug(Color.Cyan, "BP: transition from Moving to NonFaceAttack");
                                            return RunStatus.Failure;
                                        }
                                        return RunStatus.Success;
                                    }),

                                    new Action(delegate
            {
                if (jumpturnAttack != null)
                {
                    if (JumpTurn.IsJumpTurnInProgress())
                    {
                        bstate = State.JumpTurnAndAttack;
                        Logger.WriteDebug(Color.Cyan, "BP: transition error - active jumpturn? forcing state JumpTurn");
                        return RunStatus.Failure;
                    }

                    if (Me.IsMoving && Me.IsSafelyFacing(Me.CurrentTarget, 120f))
                    {
                        bstate = State.AttackWithoutJumpTurn;
                        Logger.WriteDebug(Color.Cyan, "BP: already facing so transition from Moving to AttackNoJumpTurn");
                        return RunStatus.Failure;
                    }

                    if (JumpTurn.IsJumpTurnNeeded())
                    {
                        bstate = State.JumpTurnAndAttack;
                        Logger.WriteDebug(Color.Cyan, "BP: transition from Moving to JumpTurn");
                        return RunStatus.Failure;
                    }
                }
                return RunStatus.Success;
            })
                                    )
                /*
                                                new Action( delegate {
                                                    Navigator.MoveTo( safeSpot );
                                                    if (attackBehavior != null )
                                                    {
                                                        if (WoWMathHelper.IsFacing( Me.Location, Me.RenderFacing, safeSpot, SafeArea.ONE_DEGREE_AS_RADIAN ))
                                                        {
                                                            if (JumpTurn.IsNeeded())
                                                            {
                                                                bstate = State.JumpTurn;
                                                                Logger.WriteDebug(Color.Cyan, "BP: transition from Moving to JumpTurn");
                                                            }
                                                            else if (JumpTurn.ActiveJumpTurn())
                                                            {
                                                                bstate = State.JumpTurn;
                                                                Logger.WriteDebug(Color.Cyan, "BP: transition error - active jumpturn? forcing state JumpTurn");
                                                            }
                                                        }
                                                    }
                                                    })
                */
                                ),

                            new Decorator(ret => bstate == State.NonFaceAttack,
                                new PrioritySelector(
                                    new Sequence(
                                        new Action(ret => Logger.WriteDebug(Color.Cyan, "BP: entering NonFaceAttack behavior")),
                                        runawayAttack ?? new ActionAlwaysFail(),
                                        new ActionAlwaysFail()
                                        ),
                                    new Action(delegate
            {
                Logger.WriteDebug(Color.Cyan, "BP: transition from NonFaceAttack to Moving");
                bstate = State.Moving;
            })
                                    )
                                ),

                            new Decorator(ret => bstate == State.AttackWithoutJumpTurn,
                                new PrioritySelector(
                                    new Sequence(
                                        new Action(ret => Logger.WriteDebug(Color.Cyan, "BP: entering AttackNoJumpTurn behavior")),
                                        jumpturnAttack ?? new ActionAlwaysFail(),
                                        new ActionAlwaysFail()
                                        ),
                                    new Action(delegate
            {
                Logger.WriteDebug(Color.Cyan, "BP: transition from AttackNoJumpTurn to Moving");
                bstate = State.Moving;
            })
                                    )
                                ),

                            new Decorator(ret => bstate == State.JumpTurnAndAttack,
                                new PrioritySelector(
                                    JumpTurn.CreateBehavior(jumpturnAttack),
                                    new Decorator(ret => !JumpTurn.IsJumpTurnInProgress(),
                                        new Action(delegate
            {
                bstate = State.Moving;
                Logger.WriteDebug(Color.Cyan, "BP: transition from JumpTurn to Moving");
            })
                                        )
                                    )
                                ),

                            new Action(ret => Logger.WriteDebug(Color.Cyan, "BP: fell through with state {0}", bstate.ToString()))
                            )
                        ),

                    new Decorator(
                        ret => IsKitingNeeded(),
                        new Action(delegate
            {
                bstate = State.Moving;
                Logger.WriteDebug(Color.Cyan, "Back Peddle");
            }))
                    );
        }
Example #21
0
 public void Update(State state)
 {
     State = state;
     Message = state.ToString();
     if (state == LoadBalancer.State.Stopped)
         Color = Color.Red;
     if (state == LoadBalancer.State.Starting)
         Color = Color.Orange;
     if (state == LoadBalancer.State.Failed)
         Color = Color.Red;
     if (state == LoadBalancer.State.Running)
         Color = Color.Green;
     if (state == LoadBalancer.State.Stopping)
         Color = Color.Orange;
     if (Changed != null)
         Changed(null, null);
 }
        public override void DebugDraw(SpriteBatch spriteBatch)
        {
            if (Character.IsDead)
            {
                return;
            }

            Vector2 pos = Character.WorldPosition;

            pos.Y = -pos.Y;

            if (State == AIState.Idle && PreviousState == AIState.Attack)
            {
                var target = _selectedAiTarget ?? _lastAiTarget;
                if (target != null && target.Entity != null)
                {
                    var memory = GetTargetMemory(target, false);
                    if (memory != null)
                    {
                        Vector2 targetPos = memory.Location;
                        targetPos.Y = -targetPos.Y;
                        GUI.DrawLine(spriteBatch, pos, targetPos, Color.White * 0.5f, 0, 4);
                        GUI.DrawString(spriteBatch, pos - Vector2.UnitY * 60.0f, $"{target.Entity} ({memory.Priority.FormatZeroDecimal()})", Color.White, Color.Black);
                    }
                }
            }
            else if (SelectedAiTarget?.Entity != null)
            {
                Vector2 targetPos = SelectedAiTarget.WorldPosition;
                if (State == AIState.Attack)
                {
                    targetPos = attackWorldPos;
                }
                targetPos.Y = -targetPos.Y;
                GUI.DrawLine(spriteBatch, pos, targetPos, GUI.Style.Red * 0.5f, 0, 4);
                if (wallTarget != null && (State == AIState.Attack || State == AIState.Aggressive || State == AIState.PassiveAggressive))
                {
                    Vector2 wallTargetPos = wallTarget.Position;
                    if (wallTarget.Structure.Submarine != null)
                    {
                        wallTargetPos += wallTarget.Structure.Submarine.Position;
                    }
                    wallTargetPos.Y = -wallTargetPos.Y;
                    GUI.DrawRectangle(spriteBatch, wallTargetPos - new Vector2(10.0f, 10.0f), new Vector2(20.0f, 20.0f), Color.Orange, false);
                    GUI.DrawLine(spriteBatch, pos, wallTargetPos, Color.Orange * 0.5f, 0, 5);
                }
                GUI.DrawString(spriteBatch, pos - Vector2.UnitY * 60.0f, $"{SelectedAiTarget.Entity} ({GetTargetMemory(SelectedAiTarget, false)?.Priority.FormatZeroDecimal()})", GUI.Style.Red, Color.Black);
                GUI.DrawString(spriteBatch, pos - Vector2.UnitY * 40.0f, $"({targetValue.FormatZeroDecimal()})", GUI.Style.Red, Color.Black);
            }

            /*GUI.Font.DrawString(spriteBatch, targetValue.ToString(), pos - Vector2.UnitY * 80.0f, GUI.Style.Red);
             * GUI.Font.DrawString(spriteBatch, "updatetargets: " + MathUtils.Round(updateTargetsTimer, 0.1f), pos - Vector2.UnitY * 100.0f, GUI.Style.Red);
             * GUI.Font.DrawString(spriteBatch, "cooldown: " + MathUtils.Round(coolDownTimer, 0.1f), pos - Vector2.UnitY * 120.0f, GUI.Style.Red);*/

            Color stateColor = Color.White;

            switch (State)
            {
            case AIState.Attack:
                stateColor = IsCoolDownRunning ? Color.Orange : GUI.Style.Red;
                break;

            case AIState.Escape:
                stateColor = Color.LightBlue;
                break;

            case AIState.Flee:
                stateColor = Color.White;
                break;

            case AIState.Eat:
                stateColor = Color.Brown;
                break;
            }
            GUI.DrawString(spriteBatch, pos - Vector2.UnitY * 80.0f, State.ToString(), stateColor, Color.Black);

            if (LatchOntoAI != null)
            {
                foreach (Joint attachJoint in LatchOntoAI.AttachJoints)
                {
                    GUI.DrawLine(spriteBatch,
                                 ConvertUnits.ToDisplayUnits(new Vector2(attachJoint.WorldAnchorA.X, -attachJoint.WorldAnchorA.Y)),
                                 ConvertUnits.ToDisplayUnits(new Vector2(attachJoint.WorldAnchorB.X, -attachJoint.WorldAnchorB.Y)), GUI.Style.Green, 0, 4);
                }

                if (LatchOntoAI.WallAttachPos.HasValue)
                {
                    //GUI.DrawLine(spriteBatch, pos,
                    //    ConvertUnits.ToDisplayUnits(new Vector2(LatchOntoAI.WallAttachPos.Value.X, -LatchOntoAI.WallAttachPos.Value.Y)), GUI.Style.Green, 0, 3);
                }
            }

            if (steeringManager is IndoorsSteeringManager pathSteering)
            {
                var path = pathSteering.CurrentPath;
                if (path != null)
                {
                    if (path.CurrentNode != null)
                    {
                        GUI.DrawLine(spriteBatch, pos,
                                     new Vector2(path.CurrentNode.DrawPosition.X, -path.CurrentNode.DrawPosition.Y),
                                     Color.DarkViolet, 0, 3);

                        GUI.DrawString(spriteBatch, pos - new Vector2(0, 100), "Path cost: " + path.Cost.FormatZeroDecimal(), Color.White, Color.Black * 0.5f);
                    }
                    for (int i = 1; i < path.Nodes.Count; i++)
                    {
                        var previousNode = path.Nodes[i - 1];
                        var currentNode  = path.Nodes[i];
                        GUI.DrawLine(spriteBatch,
                                     new Vector2(currentNode.DrawPosition.X, -currentNode.DrawPosition.Y),
                                     new Vector2(previousNode.DrawPosition.X, -previousNode.DrawPosition.Y),
                                     GUI.Style.Red * 0.5f, 0, 3);

                        GUI.SmallFont.DrawString(spriteBatch,
                                                 currentNode.ID.ToString(),
                                                 new Vector2(currentNode.DrawPosition.X - 10, -currentNode.DrawPosition.Y - 30),
                                                 GUI.Style.Red);
                    }
                }
            }
            else
            {
                if (steeringManager.AvoidDir.LengthSquared() > 0.0001f)
                {
                    Vector2 hitPos = ConvertUnits.ToDisplayUnits(steeringManager.AvoidRayCastHitPosition);
                    hitPos.Y = -hitPos.Y;

                    GUI.DrawLine(spriteBatch, hitPos, hitPos + new Vector2(steeringManager.AvoidDir.X, -steeringManager.AvoidDir.Y) * 100, GUI.Style.Red, width: 5);
                    //GUI.DrawLine(spriteBatch, pos, ConvertUnits.ToDisplayUnits(steeringManager.AvoidLookAheadPos.X, -steeringManager.AvoidLookAheadPos.Y), Color.Orange, width: 4);
                }
            }
            GUI.DrawLine(spriteBatch, pos, pos + ConvertUnits.ToDisplayUnits(new Vector2(Character.AnimController.TargetMovement.X, -Character.AnimController.TargetMovement.Y)), Color.SteelBlue, width: 2);
            GUI.DrawLine(spriteBatch, pos, pos + ConvertUnits.ToDisplayUnits(new Vector2(Steering.X, -Steering.Y)), Color.Blue, width: 3);
        }
Example #23
0
        protected void Update()
        {
            if (_isActive == false)
            {
                return;
            }

            if (CanvasPointerCheck.IsOverCanvas)
            {
                GoToInertState();
                _state = State.BlockedByCanvas;
                return;
            }
            // We're no longer pointed at a canvas: go to Seek state
            else if (_state == State.BlockedByCanvas)
            {
                _state = State.Seek;
            }

            // Store previous state
            Collider     previousHoveredCollider = _hoveredCollider;
            IClickTarget previousClickTarget     = _clickTarget;
            IGrabTarget  previousGrabTarget      = _grabTarget;
            IHoverTarget previousHoverTarget     = _hoverTarget;

            bool isPrimaryButtonDown = IsPrimaryButtonDown();

            // An inert state is triggered when the button is pressed without a target
            if (_state == State.Inert)
            {
                if (isPrimaryButtonDown == false)
                {
                    // Continue with normal Seek behavior
                    _state = State.Seek;
                }
                else
                {
                    // Do nothing and clear current state
                    _hoveredCollider = null;
                    _clickTarget     = null;
                    _grabTarget      = null;
                    _hoverTarget     = null;
                    return;
                }
            }

            // Always identify the object under the pointer
            _hoveredCollider = GetHoveredCollider();

            if (_hoveredCollider)
            {
                // note that these might be null
                _clickTarget = _hoveredCollider.transform.GetComponentInParent <IClickTarget>();
                _hoverTarget = _hoveredCollider.transform.GetComponentInParent <IHoverTarget>();
            }
            else
            {
                _clickTarget = null;
                _hoverTarget = null;
            }

            // Hover / Unhover
            if (_state == State.Seek)
            {
                // if we have a new target, unhover the old and hover the new
                if (_hoverTarget != previousHoverTarget)
                {
                    if (previousHoverTarget != null)
                    {
                        previousHoverTarget.HandleUnhover(this);
                    }
                    if (_hoverTarget != null)
                    {
                        _hoverTarget.HandleHover(this);
                    }
                }

                if (isPrimaryButtonDown)
                {
                    if (_hoveredCollider == null)
                    {
                        GoToInertState();
                    }
                    else
                    {
                        _buttonDownTime = Time.timeSinceLevelLoad;
                        _state          = State.Active;
                    }
                }

                return;
            }

            // Button is down. Click, Grab, or Cancel.
            // NOTE: This means it is possible for objects to move between the pointer and the target and interrupt events.
            if (_state == State.Active)
            {
                // Did the hovered collider change? Then unhover and cancel.
                if (_hoveredCollider != previousHoveredCollider)
                {
                    if (previousHoverTarget != null)
                    {
                        previousHoverTarget.HandleUnhover(this);
                    }
                    GoToInertState();
                    return;
                }

                // Still trying to click (mouse up within duration on same collider)
                if (ButtonDownDuration < _maxClickDuration)
                {
                    // Try to click, then return to Seek
                    if (isPrimaryButtonDown == false)
                    {
                        if (_clickTarget != null && _clickTarget == previousClickTarget)
                        {
                            _clickTarget.HandleClick(this);
                            _clickTarget = null;
                            _state       = State.Seek;
                        }
                    }
                }
                // Button is still down, we are moving to grab state if we have a valid target
                else
                {
                    _grabTarget = _hoveredCollider.transform.GetComponentInParent <IGrabTarget>();
                    if (_grabTarget != null && _grabTarget == previousGrabTarget)
                    {
                        _grabTarget.HandleGrab(this);
                        _state = State.Grab;
                    }
                    else
                    {
                        GoToInertState();
                    }
                }

                return;
            }

            // The grabbed object has the reins at this point. We're just waiting for primary button up.
            if (_state == State.Grab)
            {
                if (isPrimaryButtonDown)
                {
                    // the target was destroyed, bail.
                    if (previousGrabTarget == null)
                    {
                        GoToInertState();
                        return;
                    }
                }
                else                 // release
                {
                    // the target was destroyed, bail.
                    if (previousGrabTarget != null)
                    {
                        previousGrabTarget.HandleRelease(this);
                    }
                    _state = State.Seek;
                    return;
                }
            }

            Debug.LogError("Pointer fell through to unknown state " + _state.ToString());
        }
Example #24
0
 public static string ToClass(this State state)
 {
     return(state == State.NoState
         ? string.Empty
         : state.ToString().ToLower());
 }
        public static void CreateRecord(Punishment punishment)
        {
            var ERecordId = CheckForRecords(punishment.AccountId, punishment.Type);

            if (ERecordId != "-1")
            {
                DisposeRecord(ERecordId);
            }
            Server.Database.Punishments.Add(punishment);
            Storage.Database.Helper.Save();

            var Connection = Server.Connections.Find(c => c.Owner.Id == punishment.AccountId);

            if (!Connection.Owner.Online)
            {
                return;
            }
            F2CE.ClientState State;
            if (punishment.Type == F2CE.PunishmentType.Bann || punishment.Type == F2CE.PunishmentType.BannTemporarily)
            {
                State = F2CE.ClientState.Banned;
            }
            else
            {
                State = F2CE.ClientState.Muted;
            }
            Connection.SetStreamContent(string.Join("|", F2CE.Action.SetState.ToString(), State.ToString(), JsonConvert.SerializeObject(punishment)));
        }
Example #26
0
 void JumpToState(State new_state)
 {
     cur_state     = new_state;
     cur_sub_state = SubState.Enter;
     Debug.Log("new_state : " + new_state.ToString());
 }
 protected override IConnectionState NextState(State state)
 {
     switch (state)
     {
         case State.CONNECTED:
             return new TcpConnectedState(connection, param, tcpControlConnection);
         case State.DISCONNECTED:
             return new TcpDisconnectedState(connection, param);
         default:
             throw new ArgumentException("Next State non valido: " + state.ToString());
     }
 }
Example #28
0
        /// <summary>
        /// Updates the UI to reflect the current state. Thread-safe.
        /// </summary>
        private void doSetStateSafe(State state)
        {
            string btnLabelClose  = tprov.GetString("AuButtonClose");
            string btnLabelCancel = tprov.GetString("AuButtonCancel");

            string           strStatus;
            string           strDetail;
            ProgressBarStyle pbarStyle;
            ProgressBarState pbarState;
            int    pbarValue;
            string strButtonText;
            bool   btnEnabled;
            bool   linkVisible = false;

            switch (state)
            {
            case State.InitFailed:
                strStatus       = tprov.GetString("AuStateInitFailedStatus");
                strDetail       = tprov.GetString("AuStateInitFailedDetail");
                pbarStyle       = ProgressBarStyle.Continuous;
                pbarState       = ProgressBarState.Error;
                pbarValue       = 1000;
                strButtonText   = btnLabelClose;
                btnEnabled      = true;
                btnClosesWindow = true;
                linkVisible     = true;
                break;

            case State.DLoading:
                strStatus       = tprov.GetString("AuStateDownloadingStatus");
                strDetail       = "";
                pbarStyle       = ProgressBarStyle.Continuous;
                pbarState       = ProgressBarState.Normal;
                pbarValue       = 0;
                strButtonText   = btnLabelCancel;
                btnEnabled      = true;
                btnClosesWindow = false;
                break;

            case State.DLoadCanceled:
                strStatus       = tprov.GetString("AuStateDownloadCanceledStatus");
                strDetail       = tprov.GetString("AuStateDownloadCanceledDetail");
                pbarStyle       = ProgressBarStyle.Continuous;
                pbarState       = ProgressBarState.Warning;
                pbarValue       = 1000;
                strButtonText   = btnLabelClose;
                btnEnabled      = true;
                btnClosesWindow = true;
                break;

            case State.DLoadFailed:
                strStatus       = tprov.GetString("AuStateDownloadFailedStatus");
                strDetail       = tprov.GetString("AuStateDownloadFailedDetail");
                pbarStyle       = ProgressBarStyle.Continuous;
                pbarState       = ProgressBarState.Error;
                pbarValue       = 1000;
                strButtonText   = btnLabelClose;
                btnEnabled      = true;
                btnClosesWindow = true;
                break;

            case State.Verifying:
                strStatus       = tprov.GetString("AuStateVerifyingStatus");
                strDetail       = tprov.GetString("AuStateVerifyingDetail");
                pbarStyle       = ProgressBarStyle.Marquee;
                pbarState       = ProgressBarState.Normal;
                pbarValue       = 0;
                strButtonText   = btnLabelCancel;
                btnEnabled      = false;
                btnClosesWindow = false;
                break;

            case State.VerifyFailed:
                strStatus       = tprov.GetString("AuStateVerifyFailedStatus");
                strDetail       = tprov.GetString("AuStateVerifyFailedDetail");
                pbarStyle       = ProgressBarStyle.Continuous;
                pbarState       = ProgressBarState.Error;
                pbarValue       = 1000;
                strButtonText   = btnLabelClose;
                btnEnabled      = true;
                btnClosesWindow = true;
                break;

            case State.Installing:
                strStatus       = tprov.GetString("AuStateInstallingStatus");
                strDetail       = tprov.GetString("AuStateInstallingDetail");
                pbarStyle       = ProgressBarStyle.Marquee;
                pbarState       = ProgressBarState.Normal;
                pbarValue       = 0;
                strButtonText   = btnLabelCancel;
                btnEnabled      = false;
                btnClosesWindow = false;
                break;

            case State.InstallFailed:
                strStatus       = tprov.GetString("AuStateInstallFailedStatus");
                strDetail       = tprov.GetString("AuStateInstallFailedDetail");
                pbarStyle       = ProgressBarStyle.Continuous;
                pbarState       = ProgressBarState.Error;
                pbarValue       = 1000;
                strButtonText   = btnLabelClose;
                btnEnabled      = true;
                btnClosesWindow = true;
                break;

            case State.InstallSuccess:
                strStatus       = tprov.GetString("AuStateSuccessStatus");
                strDetail       = tprov.GetString("AuStateSuccessDetail");
                pbarStyle       = ProgressBarStyle.Continuous;
                pbarState       = ProgressBarState.Normal;
                pbarValue       = 1000;
                strButtonText   = btnLabelClose;
                btnEnabled      = true;
                btnClosesWindow = true;
                break;

            default:
                throw new Exception("Unhandled state:" + state.ToString());
            }
            if (InvokeRequired)
            {
                Invoke((MethodInvoker) delegate
                {
                    doUpdateUI(strStatus, strDetail, pbarStyle, pbarState, pbarValue, strButtonText, btnEnabled, linkVisible);
                });
            }
            else
            {
                doUpdateUI(strStatus, strDetail, pbarStyle, pbarState, pbarValue, strButtonText, btnEnabled, linkVisible);
            }
        }
 public void setState(State s)
 {
     // could have used property setter, but what would be the name of the property... ? setter is just as good
     Console.WriteLine("old state: "+currentState.ToString()+" --- new state: "+s.ToString());
     currentState = s;
     timeInState = 0;
 }
Example #30
0
 public static void LoadScene(State state_to_load)
 {
     Debug.Log(state_to_load.ToString());
     SceneManager.LoadScene(state_to_load.ToString());
 }
 public override string ToString()
 {
     return(State?.ToString());
 }
        /// <summary>
        /// Preprocessing and sending out packets to the manager.
        /// </summary>
        private void OnPacket(Packet packet)
        {
            if (packet.AttachmentCount != 0 && !packet.HasAllAttachment)
            {
                PacketWithAttachment = packet;
                return;
            }

            switch (packet.TransportEvent)
            {
            case TransportEventTypes.Open:
                if (this.State != TransportStates.Opening)
                {
                    HTTPManager.Logger.Warning("PollingTransport", "Received 'Open' packet while state is '" + State.ToString() + "'");
                }
                else
                {
                    State = TransportStates.Open;
                }
                goto default;

            case TransportEventTypes.Message:
                if (packet.SocketIOEvent == SocketIOEventTypes.Connect)   //2:40
                {
                    this.State = TransportStates.Open;
                }
                goto default;

            default:
                (Manager as IManager).OnPacket(packet);
                break;
            }
        }
Example #33
0
 /// <summary>
 /// Checks to make sure that the port is in <paramref name="state" />
 /// </summary>
 /// <param name="state">The state to require</param>
 private void _requireState(State state)
 {
     if(_state != state)
     {
         throw new Exception("Can't perform the desired operation in " + state.ToString() + " state");
     }
 }
Example #34
0
 private void stateChanged(Label label, State state)
 {
     label.Content = state.ToString();
     switch (state)
     {
         case State.NoConnection:
             label.Foreground = new SolidColorBrush(Colors.Red);
             break;
         case State.Initializing:
             label.Foreground = new SolidColorBrush(Colors.Yellow);
             break;
         case State.Ready:
             label.Foreground = new SolidColorBrush(Colors.Green);
             break;
     }
 }
Example #35
0
 private void Display(Mode m, Color c, State s, Types t) {
     string mstr = m.ToString();
     string cstr = c.ToString();
     string sstr = s.ToString();
     string tstr = t.ToString();
 }
Example #36
0
        private void setUI()
        {
            // test
            //MessageBox.Show("current culture name: " + CultureInfo.CurrentCulture.Name + ". current ui culture name: " + CultureInfo.CurrentUICulture.Name, "Retail POS");");

            logger.Info("Resetting the main window");

            currentState = State.READY;
            logger.Info("Current state: " + currentState.ToString());

            // user priveleges
            logger.Info("Current user level: " + Configuration.USER_LEVEL.ToString());
            switch (Configuration.USER_LEVEL)
            {
            case Configuration.Role.ADMIN:
                databaseToolStripMenuItem.Enabled    = true;
                addNewStaffToolStripMenuItem.Enabled = true;

                button_Discount.Enabled = true;
                //button_newItem.Enabled = true;

                break;

            case Configuration.Role.NORMAL:
                databaseToolStripMenuItem.Enabled    = false;
                addNewStaffToolStripMenuItem.Enabled = false;

                button_Discount.Enabled = false;
                //button_newItem.Enabled = false;

                break;

            default:
                break;
            }

            // regardless of user priveleges, some UI functions are not yet needed
            textBox_customerAddress.Enabled  = false;
            textBox_customerCity.Enabled     = false;
            textBox_customerEmail.Enabled    = false;
            textBox_customerName.Enabled     = false;
            textBox_customerPhone.Enabled    = false;
            textBox_customerPostCode.Enabled = false;
            comboBox_customerState.Enabled   = false;
            textBox_customerAccNo.Enabled    = false;

            textBox_customerAccNo.Text    = null;
            textBox_customerAddress.Text  = null;
            textBox_customerCity.Text     = null;
            textBox_customerEmail.Text    = null;
            textBox_customerName.Text     = null;
            textBox_customerPhone.Text    = null;
            textBox_customerPostCode.Text = null;
            textBox_itemProductID.Text    = null;
            textBox_itemQuantity.Text     = null;

            button_checkout.Enabled     = false;
            button_Discount.Enabled     = false;
            button_clearSale.Enabled    = false;
            button_addItem.Enabled      = false;
            button_removeItem.Enabled   = false;
            button_priceLookup.Enabled  = false;
            button_findCustomer.Enabled = false;

            if (Configuration.USER_LEVEL == Configuration.Role.ADMIN)
            {
                //transactionToolStripMenuItem.Enabled = true;
            }
            else
            {
                //transactionToolStripMenuItem.Enabled = false;
            }

            button_newSaleMember.Enabled    = true;
            button_newSaleNonMember.Enabled = true;

            textBox_itemProductID.Enabled = true;
            textBox_itemQuantity.Enabled  = false;

            double priceDisplayed  = 0.00;
            string sPriceDisplayed = priceDisplayed.ToString("C2", CultureInfo.GetCultureInfo("en-AU"));

            richTextBox_itemPrice.Text = sPriceDisplayed;
            //richTextBox_itemPrice.Text = "0.00";

            scriptingToolStripMenuItem.Enabled = false;

            foreach (ListViewItem listItem in listView_sales.Items)
            {
                listView_sales.Items.Remove(listItem);
            }

            switch (Configuration.USER_LEVEL)
            {
            case Configuration.Role.ADMIN:
                toolStripStatusLabel_accType.Text = "Admin";
                break;

            case Configuration.Role.NORMAL:
                toolStripStatusLabel_accType.Text = "Normal";
                break;

            default:
                // shouldn't happen
                throw new Exception("Unknown user access level");
            }

            toolStripStatusLabel_state.Text = "Ready";
        }
 public ApplicationState Value(State newState)
 {
     File.WriteAllText(stateFile, newState.ToString().ToLower());
     this.container.SetRWPermissions(this.stateFile);
     return this;
 }
Example #38
0
 void Update()
 {
     Invoke(currentState.ToString() + "Stay", 0f);
 }
Example #39
0
        private void HandleFlowFrame(Flow flow)
        {
            if (State != LinkStateEnum.ATTACHED && State != LinkStateEnum.DETACH_SENT && State != LinkStateEnum.DESTROYED)
            {
                throw new AmqpException(ErrorCode.IllegalState, $"Received Flow frame but link state is {State.ToString()}.");
            }
            if (State == LinkStateEnum.DESTROYED)
            {
                throw new AmqpException(ErrorCode.ErrantLink, $"Received Flow frame but link state is {State.ToString()}."); // TODO end session
            }
            if (State == LinkStateEnum.DETACH_SENT)
            {
                return; // ignore
            }
            if (IsReceiverLink)
            {
                // flow control from sender
                if (flow.DeliveryCount.HasValue)
                {
                    DeliveryCount = flow.DeliveryCount.Value;
                }
                // TODO: ignoring Available field for now
                //if (flow.Available.HasValue)
                //    available = flow.Available.Value;
                // TODO: respond to new flow control
            }

            if (IsSenderLink)
            {
                // flow control from receiver
                if (flow.LinkCredit.HasValue)
                {
                    LinkCredit = flow.LinkCredit.Value;
                }
                drainFlag = flow.Drain ?? false;
                // TODO respond to new flow control
                var receivedFlowCallback = this.ReceivedFlow;
                if (receivedFlowCallback != null)
                {
                    receivedFlowCallback(this, EventArgs.Empty);
                }
            }

            if (flow.Echo)
            {
                SendFlow(drain: false, echo: false);
            }
        }
Example #40
0
 public override string ToString()
 {
     return($@"Quantidade: {Count} - Estado: {State.ToString()}");
 }
Example #41
0
        private void HandleDetachFrame(Detach detach)
        {
            if (State != LinkStateEnum.ATTACHED && State != LinkStateEnum.DETACH_SENT && State != LinkStateEnum.DESTROYED)
            {
                throw new AmqpException(ErrorCode.IllegalState, $"Received Detach frame but link state is {State.ToString()}.");
            }

            if (detach.Error != null)
            {
                trace.Debug("Detaching Link {0} Due to Error From Remote Link Endpoint: '{1}'", LocalHandle, detach.Error);
            }

            if (State == LinkStateEnum.ATTACHED)
            {
                State = LinkStateEnum.DETACH_RECEIVED;
            }

            DetachLink(null, destoryLink: detach.Closed);
        }
        public override Entities.EventResult BrowserDocumentComplete()
        {
            if (!_disableLogging)
            {
                MessageHandler.Info("Netflix. Url: {0}, State: {1}", Url, _currentState.ToString());
            }
            switch (_currentState)
            {
            case State.Login:
                if (Url.ToLower().Contains("/login") && activateLoginTimer)
                {
                    activateLoginTimer = false;
                    System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
                    timer.Tick += (object sender, EventArgs e) =>
                    {
                        timer.Stop();
                        timer.Dispose();
                        if (_use2200Mode)
                        {
                            string data = Browser.DocumentText;
                            _currentState = State.SelectProfile;
                            Regex  rgx     = new Regex(@"""authURL"":""(?<authURL>[^""]*)");
                            Match  m       = rgx.Match(data);
                            string authUrl = "";
                            if (m.Success)
                            {
                                authUrl = m.Groups["authURL"].Value;
                                authUrl = HttpUtility.UrlDecode(authUrl.Replace("\\x", "%"));
                                string loginPostDataFormat = "email={0}&password={1}&rememberMe=true&flow=websiteSignUp&mode=login&action=loginAction&withFields=email%2Cpassword%2CrememberMe%2CnextPage%2CshowPassword&authURL={2}&nextPage=&showPassword="******"", Encoding.UTF8.GetBytes(loginPostData), "Referer: " + Url + "\r\nContent-Type: application/x-www-form-urlencoded\r\n");
                            }
                        }
                        else
                        {
                            if (_showLoading)
                            {
                                HideLoading();
                            }
                            string[]    stringToSend = { "a", "{BACKSPACE}" };
                            HtmlElement elt          = GetFirstElement("input", "name", "emailOrPhoneNumber") ?? GetFirstElement("input", "name", "email");
                            HtmlElement eltp         = GetFirstElement("input", "name", "password");
                            if (elt != null && eltp != null)
                            {
                                elt.Focus();
                                elt.SetAttribute("Value", _username);
                                foreach (string s in stringToSend)
                                {
                                    Thread.Sleep(50);
                                    SendKeys.SendWait(s);
                                }
                                Thread.Sleep(100);
                                eltp.Focus();
                                eltp.SetAttribute("Value", _password);
                                foreach (string s in stringToSend)
                                {
                                    Thread.Sleep(50);
                                    SendKeys.SendWait(s);
                                }
                                Thread.Sleep(500);
                                _currentState = State.SelectProfile;
                                InvokeScript(Properties.Resources.NetflixJs);
                                InvokeScript(@"doClickDelay();");
                            }
                        }
                    };
                    timer.Interval = 1000;
                    timer.Start();
                }
                else if (!Url.ToLower().Contains("/login"))
                {
                    Url           = "https://www.netflix.com";
                    _currentState = State.SelectProfile;
                }
                break;

            case State.SelectProfile:
                if (activateProfileTimer)
                {
                    activateProfileTimer = false;
                    System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
                    timer.Tick += (object sender, EventArgs e) =>
                    {
                        timer.Stop();
                        timer.Dispose();
                        Regex  rgx     = new Regex(@"""authURL"":""(?<authURL>[^""]*)");
                        Match  m       = rgx.Match(Browser.DocumentText);
                        string authUrl = "";
                        if (m.Success)
                        {
                            authUrl = m.Groups["authURL"].Value;
                            authUrl = HttpUtility.UrlDecode(authUrl.Replace("\\x", "%"));
                        }
                        InvokeScript(Properties.Resources.NetflixJs);
                        InvokeScript("switchProfile('" + _profileUrl + HttpUtility.UrlEncode(authUrl) + "'," + _profileIndex + ");");
                        _currentState = State.ReadyToPlay;
                    };
                    timer.Interval = 2000;
                    timer.Start();
                }
                break;

            case State.ReadyToPlay:
                if (activateReadyTimer)
                {
                    activateReadyTimer = false;
                    System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
                    timer.Tick += (object sender, EventArgs e) =>
                    {
                        timer.Stop();
                        timer.Dispose();
                        _currentState = State.GotoToPlay;
                        InvokeScript("window.location.href = 'https://www.netflix.com/';");
                    };
                    timer.Interval = 1500;
                    timer.Start();
                }
                break;

            case State.GotoToPlay:
                ProcessComplete.Finished = true;
                ProcessComplete.Success  = true;
                break;

            case State.Playing:
                if (_showLoading)
                {
                    HideLoading();
                }
                _currentState            = State.Playing;
                ProcessComplete.Finished = true;
                ProcessComplete.Success  = true;
                break;
            }
            return(EventResult.Complete());
        }
Example #43
0
        public override string Print(bool link = true, DwarfObject pov = null)
        {
            string eventString = GetYearTime() + HistoricalFigure.ToLink(link, pov);

            if (State == HfState.Visiting)
            {
                eventString += " visited ";
            }
            else if (State == HfState.Settled)
            {
                switch (SubState)
                {
                case 45:
                    eventString += " fled to ";
                    break;

                case 46:
                case 47:
                    eventString += " moved to study in ";
                    break;

                default:
                    eventString += " settled in ";
                    break;
                }
            }
            else if (State == HfState.Wandering)
            {
                eventString += " began wandering ";
            }
            else if (State == HfState.Refugee || State == HfState.Snatcher || State == HfState.Thief)
            {
                eventString += " became a " + State.ToString().ToLower() + " in ";
            }
            else if (State == HfState.Scouting)
            {
                eventString += " began scouting the area around ";
            }
            else if (State == HfState.Hunting)
            {
                eventString += " began hunting great beasts in ";
            }
            else if (Mood != Mood.Unknown)
            {
                switch (Mood)
                {
                case Mood.Macabre:
                    eventString += " began to skulk and brood in ";
                    break;

                case Mood.Secretive:
                    eventString += " withdrew from society in ";
                    break;

                case Mood.Insane:
                    eventString += " became crazed in ";
                    break;

                case Mood.Possessed:
                    eventString += " was possessed in ";
                    break;

                case Mood.Berserk:
                    eventString += " went berserk in ";
                    break;

                case Mood.Fey:
                    eventString += " was taken by a fey mood in ";
                    break;

                case Mood.Melancholy:
                    eventString += " was striken by melancholy in ";
                    break;

                case Mood.Fell:
                    eventString += " was taken by a fell mood in ";
                    break;

                case Mood.Catatonic:
                    eventString += " stopped responding to the outside world in ";
                    break;
                }
            }
            else
            {
                eventString += " changed state in ";
            }

            if (Site != null)
            {
                eventString += Site.ToLink(link, pov);
            }
            else if (Region != null)
            {
                eventString += Region.ToLink(link, pov);
            }
            else if (UndergroundRegion != null)
            {
                eventString += UndergroundRegion.ToLink(link, pov);
            }
            else
            {
                eventString += "the wilds";
            }

            if (Reason != ChangeHfStateReason.Unknown)
            {
                switch (Reason)
                {
                case ChangeHfStateReason.FailedMood:
                    eventString += " after failing to create an artifact";
                    break;

                case ChangeHfStateReason.GatherInformation:
                    eventString += " to gather information";
                    break;

                case ChangeHfStateReason.BeWithMaster:
                    eventString += " in order to be with the master";
                    break;

                case ChangeHfStateReason.Flight:
                    eventString += " in order to flee";
                    break;

                case ChangeHfStateReason.Scholarship:
                    eventString += " in order to pursue scholarship";
                    break;

                case ChangeHfStateReason.Pilgrimage:
                    eventString += " on a pilgrimage";
                    break;

                case ChangeHfStateReason.LackOfSleep:
                    eventString += " due to lack of sleep";
                    break;
                }
            }
            eventString += PrintParentCollection(link, pov);
            eventString += ".";
            return(eventString);
        }
Example #44
0
    // allows more control over changing state
    void setState(State s)
    {
        if (s.Equals(state))
            return;
        print(state.ToString()+" -> "+s.ToString());

        // previous state
        switch (state) {
        case State.Dead:
            return; // stay dead forever!
        case State.Hiding:
            animator.SetInteger ("ShutEyes", 0);
            break;
        case State.TimeTraveling:
            rb.gravityScale = defaultGravityScale;
            break;
        case State.Standard:
            break;
        }
        // next state
        switch (s) {
        case State.Dead:
            rb.gravityScale = 0;
            rb.velocity = Vector2.zero;
            random = Random.Range(1, 2);
            animator.SetInteger ("Dead", random);
            break;
        case State.Hiding:
            random = Random.Range(1, 5);
            animator.SetInteger ("ShutEyes", random);
            break;
        case State.TimeTraveling:
            rb.gravityScale = 0;
            rb.velocity = Vector2.zero;
            break;
        case State.Standard:
            rb.gravityScale = defaultGravityScale;
            break;
        }

        state = s;
    }
 public bool PathExitsts(State fromState, State toState)
 {
     var from = LogicOperations.NodeFromString(fromState.ToString());
     var to = LogicOperations.NodeFromString(toState.ToString());
     return LogicOperations.PathExists(historyGraph, from, to);
 }
Example #46
0
        internal CodeExpression GenerateObjectBuild(GeneratorContext ctx)
        {
            string varName = ctx.NewId();
            CodeVariableDeclarationStatement varDec = new CodeVariableDeclarationStatement(typeof(Gtk.IconSource), varName);

            varDec.InitExpression = new CodeObjectCreateExpression(typeof(Gtk.IconSource));
            ctx.Statements.Add(varDec);

            CodeVariableReferenceExpression var = new CodeVariableReferenceExpression(varName);

            ctx.Statements.Add(new CodeAssignStatement(
                                   new CodePropertyReferenceExpression(var, "Pixbuf"),
                                   imageInfo.ToCodeExpression(ctx)
                                   ));

            if (!SizeWildcarded)
            {
                ctx.Statements.Add(new CodeAssignStatement(
                                       new CodePropertyReferenceExpression(var, "SizeWildcarded"),
                                       new CodePrimitiveExpression(false)
                                       ));
                ctx.Statements.Add(new CodeAssignStatement(
                                       new CodePropertyReferenceExpression(var, "Size"),
                                       new CodeFieldReferenceExpression(
                                           new CodeTypeReferenceExpression("Gtk.IconSize"),
                                           Size.ToString()
                                           )
                                       ));
            }

            if (!StateWildcarded)
            {
                ctx.Statements.Add(new CodeAssignStatement(
                                       new CodePropertyReferenceExpression(var, "StateWildcarded"),
                                       new CodePrimitiveExpression(false)
                                       ));
                ctx.Statements.Add(new CodeAssignStatement(
                                       new CodePropertyReferenceExpression(var, "State"),
                                       new CodeFieldReferenceExpression(
                                           new CodeTypeReferenceExpression("Gtk.StateType"),
                                           State.ToString()
                                           )
                                       ));
            }

            if (!DirectionWildcarded)
            {
                ctx.Statements.Add(new CodeAssignStatement(
                                       new CodePropertyReferenceExpression(var, "DirectionWildcarded"),
                                       new CodePrimitiveExpression(false)
                                       ));
                ctx.Statements.Add(new CodeAssignStatement(
                                       new CodePropertyReferenceExpression(var, "Direction"),
                                       new CodeFieldReferenceExpression(
                                           new CodeTypeReferenceExpression("Gtk.TextDirection"),
                                           Direction.ToString()
                                           )
                                       ));
            }

            return(var);
        }
        private int Callback(int msg, int param)
        {
            switch (msg)
            {
                case 1: // Receive window handle
                    hWnd = new IntPtr(param);
                    break;
                case 2: // Receive second window handle, the window is now setup completely
                    hWnd2 = new IntPtr(param);
                    Debug("Started, now loading ...");
                    state = State.Loading;
                    break;
                case 3: // We're moving one step further while loading
                    if (state == State.Loading)
                    {
                        if (currentSlide >= 0)
                        {
                            slideSteps[currentSlide]++;
                            Debug("Updating steps of slide #" + currentSlide + ": " + slideSteps[currentSlide]);
                        }
                    }
                    break;
                case 4: // Slide change
                    new Thread(() =>
                        {
                            try
                            {
                                Debug("Slide changed: " + param + " (" + state.ToString() + ")");

                                if ((state == State.Starting || state == State.Loading) && param != 0)
                                {
                                    currentSlide++;
                                    if (!slideIds.ContainsKey(param))
                                    {
                                        slideIds.Add(param, currentSlide);
                                        slideSteps.Add(currentSlide, 0);
                                    }
                                    else
                                    {
                                        endless = true;
                                    }
                                }
                                else if (state == State.Running || state == State.Resetting)
                                {
                                    if (param == 0)
                                    {
                                        PrevStep();
                                    }
                                    else
                                    {
                                        if (!slideIds.ContainsKey(param))
                                        {
                                            if (state == State.Resetting)
                                            {
                                                throw new PowerpointViewerController.PowerpointViewerOpenException();
                                            }
                                            else
                                            {
                                                OnHiddenSlide();
                                            }
                                        }
                                        else
                                        {
                                            currentSlide = slideIds[param];

                                            if (state == State.Running)
                                            {
                                                OnSlideChanged();
                                            }
                                        }
                                    }
                                }

                                bool resetNow = false;

                                if (state == State.Loading && currentSlide != -1)
                                {
                                    if (param == 0 || endless) // reached last slide or noticed that slide id's are repeating
                                    {
                                        // If we don't go back every single step, PowerPoint remembers
                                        // that the slides have been animated and won't show the animations
                                        // the next time.

                                        state = State.Resetting;

                                        // If we're repeating a single slide without any steps, going one step back
                                        // won't change the slide, therefore we need to do the resetting directly
                                        // without waiting for the next event
                                        if (endless && slideIds.Count == 1 && slideSteps[0] <= 1)
                                        {
                                            currentSlide = 0;
                                            resetNow = true;
                                        }
                                        else
                                        {
                                            PrevStep();
                                        }
                                    }
                                }
                                else if (state == State.Resetting)
                                {
                                    resetNow = true;
                                }

                                if (resetNow)
                                {
                                    if (captureThumbs != null)
                                    {
                                        Bitmap bmp = Capture(this.thumbnailWidth);
                                        captureThumbs.Add(new ThumbnailWrapper { Bitmap = bmp, Slide = currentSlide });
                                    }

                                    int goBackSteps = currentSlide == 0 ? slideSteps[currentSlide] - 1 : slideSteps[currentSlide];

                                    for (int i = 0; i < goBackSteps; i++)
                                    {
                                        Debug("Going back (slide #" + currentSlide + ")");
                                        PrevStep();
                                    }
                                    if (currentSlide == 0) // back at the beginning
                                    {
                                        state = State.Running;
                                        if (captureThumbs != null)
                                        {
                                            this.Thumbnails = (from t in captureThumbs orderby t.Slide ascending select t.Bitmap).ToList();
                                        }
                                        Unblank();
                                        if (!openHidden)
                                            Show();
                                        OnLoaded();
                                        OnSlideChanged();
                                        Debug("Now running ...");
                                    }
                                }
                            }
                            catch (Exception e)
                            {
                                Close();
                                OnError(e);
                            }
                        }).Start();
                    break;
                case 5: // Slideshow window has been closed (e.g. ESC)
                    Debug("Window has been closed");
                    new Thread(() => Close()).Start();
                    break;
                case 6: // The slideshow is closing
                    Debug("Close event");
                    new Thread(() =>
                        {
                            OnClosed();
                            closed = true;
                        }).Start();
                    break;
                default:
                    Debug("Unknown message: " + msg + "(param: "+param+")");
                    break;
            }
            return 0;
        }
 public static List<ExpertDetails> GetBalanceAdvisorDetailsByState(this Repository<ExpertDetails> repository, State state )
 {
     return repository.GetAll().Where(q => q.State == state.ToString()).ToList();
 }
 private string ParseKeyValue(string line, State state, State nextState, ref bool readNextLine)
 {
     string result = string.Empty;
     if (!string.IsNullOrEmpty(line))
     {
         if (line.Length > 0)
         {
             int index = line.IndexOf('=');
             if (index > 0 && line.Substring(0, index).Equals(state.ToString(), StringComparison.OrdinalIgnoreCase))
             {
                 result = line.Substring(index + 1, line.Length - index - 1);
                 _state = nextState;
             }
             readNextLine = true;
             return result;
         }
     }
     readNextLine = true;
     return result;
 }
Example #50
0
        public void State_ToString_ReturnsName()
        {
            var s = new State <StubStateModel>("state");

            Assert.Equal("state", s.ToString());
        }
Example #51
0
        public static Composite CreateBehavior(Composite jumpturnAttack)
        {
            return
                new PrioritySelector(
                    new Decorator(
                        ret => jstate != State.None,
                        new PrioritySelector(
                // add sanity checks here to test if jump should continue
                            new Decorator(ret => !StyxWoW.Me.IsAlive, new Action(ret => EndJumpTurn("JT: I am dead, cancelling"))),
                            new Decorator(ret => StyxWoW.Me.Rooted || StyxWoW.Me.IsRooted(), new Action(ret => EndJumpTurn("JT: I am rooted, cancelling"))),
                            new Decorator(ret => StyxWoW.Me.Stunned || StyxWoW.Me.IsStunned(), new Action(ret => EndJumpTurn("JT: I am stunned, cancelling"))),

                            new Decorator(ret => jstate == State.Jump,
                                new Sequence(
                                    new Action(delegate
            {
                // jump up
                Logger.WriteDebug(Color.Cyan, "JT: enter Jump state");
                WoWMovement.Move(WoWMovement.MovementDirection.JumpAscend);
            }),
                                    new WaitContinue(new TimeSpan(0, 0, 0, 0, 100), ret => false, new ActionAlwaysSucceed()),
                                    new PrioritySelector(
                                        new Wait(new TimeSpan(0, 0, 0, 0, 250), ret => StyxWoW.Me.MovementInfo.IsAscending || StyxWoW.Me.MovementInfo.IsDescending || StyxWoW.Me.MovementInfo.IsFalling, new ActionAlwaysSucceed()),
                                        new Action(ret => { EndJumpTurn("JT: timed out waiting for JumpAscend to occur"); return RunStatus.Failure; })
                                        ),
                                    new Action(delegate
            {
                Logger.WriteDebug(Color.Cyan, "JT: transition from Jump to Face");
                jstate = State.Face;
            })
                                    )
                                ),
                            new Decorator(ret => jstate == State.Face,
                                new Sequence(
                                    new Action(ret => StyxWoW.Me.SetFacing(StyxWoW.Me.CurrentTarget)),
                                    new PrioritySelector(
                                        new Wait(new TimeSpan(0, 0, 0, 0, 500), ret => StyxWoW.Me.IsSafelyFacing(StyxWoW.Me.CurrentTarget, 20f), new ActionAlwaysSucceed()),
                                        new Action(ret => Logger.WriteDebug("JT: timed out waiting for SafelyFacing to occur"))
                                        ),
                                    new Action(delegate
            {
                WoWMovement.StopFace();
                if (StyxWoW.Me.IsSafelyFacing(StyxWoW.Me.CurrentTarget, 20f))
                {
                    Logger.WriteDebug(Color.Cyan, "JT: transition from Face to Attack");
                    jstate = State.Attack;
                }
                else
                {
                    Logger.WriteDebug(Color.Cyan, "JT: transition from Face to FaceRestore");
                    jstate = State.FaceRestore;
                }
            })
                                    )
                                ),
                            new Decorator(ret => jstate == State.Attack,
                                new PrioritySelector(
                                    new Sequence(
                                        new ActionDebugString("JT: entering Attack behavior"),
                                        jumpturnAttack ?? new ActionAlwaysFail(),
                                        new ActionAlwaysFail()
                                        ),
                                    new Action(delegate
            {
                Logger.WriteDebug(Color.Cyan, "JT: transition from Attack to FaceRestore");
                jstate = State.FaceRestore;
            })
                                    )
                                ),
                            new Decorator(ret => jstate == State.FaceRestore,
                                new Sequence(
                /*
                                                    new Action( ret => StyxWoW.Me.SetFacing( originalFacing)),
                                                    new WaitContinue( new TimeSpan(0,0,0,0,250), ret => StyxWoW.Me.IsDirectlyFacing(originalFacing), new ActionAlwaysSucceed()),
                */
                                    new Action(ret => Navigator.MoveTo(Kite.safeSpot)),
                                    new WaitContinue(new TimeSpan(0, 0, 0, 0, 250), ret => StyxWoW.Me.IsDirectlyFacing(originalFacing), new ActionAlwaysSucceed()),

                                    new Action(delegate
            {
                Logger.WriteDebug(Color.Cyan, "JT: transition from FaceRestore to EndJump");
                WoWMovement.StopFace();
                jstate = State.EndJump;
            })
                                    )
                                ),
                            new Decorator(ret => jstate == State.EndJump,
                                new Action(delegate
            {
                EndJumpTurn("JT: transition from EndJump to None");
            })
                                ),

                            new Action(ret => Logger.WriteDebug(Color.Cyan, "JT: fell through with state {0}", jstate.ToString()))
                            )
                        ),
                    new Decorator(
                        ret => IsJumpTurnNeeded(),
                        new Action(delegate
            {
                originalFacing = StyxWoW.Me.RenderFacing;
                jstate = State.Jump;
                Logger.WriteDebug(Color.Cyan, "Jump Turn");
            })
                        )
                    );
        }
Example #52
0
        internal void WriteXml(string nodeName, XmlWriter writer)
        {
            writer.WriteStartElement(nodeName);

            writer.WriteAttributeString("id", Id.ToString());

            if (Location != null)
            {
                writer.WriteAttributeString("location-country", Location.Country);
                if (!string.IsNullOrEmpty(Location.StateProvince))
                {
                    writer.WriteAttributeString("location-state-province", Location.StateProvince);
                }
            }

            writer.WriteAttributeString(
                "record-custodian",
                XmlConvert.ToString(_custodian));

            writer.WriteAttributeString(
                "rel-type",
                XmlConvert.ToString((int)_relationshipType));

            if (!string.IsNullOrEmpty(_relationshipName))
            {
                writer.WriteAttributeString(
                    "rel-name",
                    _relationshipName);
            }

            writer.WriteAttributeString(
                "auth-expires",
                DateAuthorizationExpires == null ? "9999-12-31T23:59:59.999Z" : SDKHelper.XmlFromInstant(DateAuthorizationExpires.Value));

            writer.WriteAttributeString(
                "auth-expired",
                SDKHelper.XmlFromBool(_authExpired));

            if (!string.IsNullOrEmpty(_displayName))
            {
                writer.WriteAttributeString(
                    "display-name",
                    _displayName);
            }

            writer.WriteAttributeString(
                "state",
                State.ToString());

            writer.WriteAttributeString(
                "date-created",
                SDKHelper.XmlFromInstant(DateCreated));

            if (QuotaInBytes.HasValue)
            {
                writer.WriteAttributeString(
                    "max-size-bytes",
                    XmlConvert.ToString(QuotaInBytes.Value));
            }

            if (QuotaUsedInBytes.HasValue)
            {
                writer.WriteAttributeString(
                    "size-bytes",
                    XmlConvert.ToString(QuotaUsedInBytes.Value));
            }

            writer.WriteAttributeString(
                "app-record-auth-action",
                HealthRecordAuthorizationStatus.ToString());

            writer.WriteAttributeString(
                "app-specific-record-id",
                ApplicationSpecificRecordId);

            writer.WriteAttributeString(
                "date-updated",
                SDKHelper.XmlFromInstant(DateUpdated));

            writer.WriteValue(_name);

            writer.WriteEndElement();
        }
 public State[] GetSuccessors(State fromState)
 {
     var from = LogicOperations.NodeFromString(fromState.ToString());
     return SetToStates(LogicOperations.GetSuccessors(historyGraph, from));
 }
Example #54
0
        void ThreadFunc(object param)
        {
            bool alreadyReconnected = false;
            bool redirected         = false;

            RetryCauses cause = RetryCauses.None;

            try
            {
#if !BESTHTTP_DISABLE_PROXY
                if (!HasProxy && CurrentRequest.HasProxy)
                {
                    Proxy = CurrentRequest.Proxy;
                }
#endif

#if !BESTHTTP_DISABLE_CACHING && (!UNITY_WEBGL || UNITY_EDITOR)
                // Try load the full response from an already saved cache entity. If the response
                if (TryLoadAllFromCache())
                {
                    return;
                }
#endif

                if (Client != null && !Client.IsConnected())
                {
                    Close();
                }

                do // of while (reconnect)
                {
                    if (cause == RetryCauses.Reconnect)
                    {
                        Close();
#if NETFX_CORE
                        await Task.Delay(100);
#else
                        Thread.Sleep(100);
#endif
                    }

                    LastProcessedUri = CurrentRequest.CurrentUri;

                    cause = RetryCauses.None;

                    // Connect to the server
                    Connect();

                    if (State == HTTPConnectionStates.AbortRequested)
                    {
                        throw new Exception("AbortRequested");
                    }

                    #if !BESTHTTP_DISABLE_CACHING && (!UNITY_WEBGL || UNITY_EDITOR)
                    // Setup cache control headers before we send out the request
                    if (!CurrentRequest.DisableCache)
                    {
                        HTTPCacheService.SetHeaders(CurrentRequest);
                    }
                    #endif

                    // Write the request to the stream
                    // sentRequest will be true if the request sent out successfully(no SocketException), so we can try read the response
                    bool sentRequest = false;
                    try
                    {
#if !NETFX_CORE
                        Client.NoDelay = CurrentRequest.TryToMinimizeTCPLatency;
#endif
                        CurrentRequest.SendOutTo(Stream);

                        sentRequest = true;
                    }
                    catch (Exception ex)
                    {
                        Close();

                        if (State == HTTPConnectionStates.TimedOut ||
                            State == HTTPConnectionStates.AbortRequested)
                        {
                            throw new Exception("AbortRequested");
                        }

                        // We will try again only once
                        if (!alreadyReconnected && !CurrentRequest.DisableRetry)
                        {
                            alreadyReconnected = true;
                            cause = RetryCauses.Reconnect;
                        }
                        else // rethrow exception
                        {
                            throw ex;
                        }
                    }

                    // If sending out the request succeeded, we will try read the response.
                    if (sentRequest)
                    {
                        bool received = Receive();

                        if (State == HTTPConnectionStates.TimedOut ||
                            State == HTTPConnectionStates.AbortRequested)
                        {
                            throw new Exception("AbortRequested");
                        }

                        if (!received && !alreadyReconnected && !CurrentRequest.DisableRetry)
                        {
                            alreadyReconnected = true;
                            cause = RetryCauses.Reconnect;
                        }

                        if (CurrentRequest.Response != null)
                        {
#if !BESTHTTP_DISABLE_COOKIES && (!UNITY_WEBGL || UNITY_EDITOR)
                            // Try to store cookies before we do anything else, as we may remove the response deleting the cookies as well.
                            if (CurrentRequest.IsCookiesEnabled)
                            {
                                CookieJar.Set(CurrentRequest.Response);
                            }
#endif

                            switch (CurrentRequest.Response.StatusCode)
                            {
                            // Not authorized
                            // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.2
                            case 401:
                            {
                                string authHeader = DigestStore.FindBest(CurrentRequest.Response.GetHeaderValues("www-authenticate"));
                                if (!string.IsNullOrEmpty(authHeader))
                                {
                                    var digest = DigestStore.GetOrCreate(CurrentRequest.CurrentUri);
                                    digest.ParseChallange(authHeader);

                                    if (CurrentRequest.Credentials != null && digest.IsUriProtected(CurrentRequest.CurrentUri) && (!CurrentRequest.HasHeader("Authorization") || digest.Stale))
                                    {
                                        cause = RetryCauses.Authenticate;
                                    }
                                }

                                goto default;
                            }

#if !BESTHTTP_DISABLE_PROXY
                            // Proxy authentication required
                            // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.8
                            case 407:
                            {
                                if (CurrentRequest.HasProxy)
                                {
                                    string authHeader = DigestStore.FindBest(CurrentRequest.Response.GetHeaderValues("proxy-authenticate"));
                                    if (!string.IsNullOrEmpty(authHeader))
                                    {
                                        var digest = DigestStore.GetOrCreate(CurrentRequest.Proxy.Address);
                                        digest.ParseChallange(authHeader);

                                        if (CurrentRequest.Proxy.Credentials != null && digest.IsUriProtected(CurrentRequest.Proxy.Address) && (!CurrentRequest.HasHeader("Proxy-Authorization") || digest.Stale))
                                        {
                                            cause = RetryCauses.ProxyAuthenticate;
                                        }
                                    }
                                }

                                goto default;
                            }
#endif

                            // Redirected
                            case 301:     // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.2
                            case 302:     // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.3
                            case 307:     // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.8
                            case 308:     // http://tools.ietf.org/html/rfc7238
                            {
                                if (CurrentRequest.RedirectCount >= CurrentRequest.MaxRedirects)
                                {
                                    goto default;
                                }
                                CurrentRequest.RedirectCount++;

                                string location = CurrentRequest.Response.GetFirstHeaderValue("location");
                                if (!string.IsNullOrEmpty(location))
                                {
                                    Uri redirectUri = GetRedirectUri(location);

                                    if (HTTPManager.Logger.Level == Logger.Loglevels.All)
                                    {
                                        HTTPManager.Logger.Verbose("HTTPConnection", string.Format("{0} - Redirected to Location: '{1}' redirectUri: '{1}'", this.CurrentRequest.CurrentUri.ToString(), location, redirectUri));
                                    }

                                    // Let the user to take some control over the redirection
                                    if (!CurrentRequest.CallOnBeforeRedirection(redirectUri))
                                    {
                                        HTTPManager.Logger.Information("HTTPConnection", "OnBeforeRedirection returned False");
                                        goto default;
                                    }

                                    // Remove the previously set Host header.
                                    CurrentRequest.RemoveHeader("Host");

                                    // Set the Referer header to the last Uri.
                                    CurrentRequest.SetHeader("Referer", CurrentRequest.CurrentUri.ToString());

                                    // Set the new Uri, the CurrentUri will return this while the IsRedirected property is true
                                    CurrentRequest.RedirectUri = redirectUri;

                                    // Discard the redirect response, we don't need it any more
                                    CurrentRequest.Response = null;

                                    redirected = CurrentRequest.IsRedirected = true;
                                }
                                else
                                            #if !NETFX_CORE
                                { throw new MissingFieldException(string.Format("Got redirect status({0}) without 'location' header!", CurrentRequest.Response.StatusCode.ToString())); }
                                            #else
                                { throw new Exception(string.Format("Got redirect status({0}) without 'location' header!", CurrentRequest.Response.StatusCode.ToString())); }
                                            #endif

                                goto default;
                            }


                            default:
#if !BESTHTTP_DISABLE_CACHING && (!UNITY_WEBGL || UNITY_EDITOR)
                                TryStoreInCache();
#endif
                                break;
                            }

                            // Closing the stream is done manually
                            if (CurrentRequest.Response == null || !CurrentRequest.Response.IsClosedManually)
                            {
                                // If we have a response and the server telling us that it closed the connection after the message sent to us, then
                                //  we will close the connection too.
                                bool closeByServer = CurrentRequest.Response == null || CurrentRequest.Response.HasHeaderWithValue("connection", "close");
                                bool closeByClient = !CurrentRequest.IsKeepAlive;

                                if (closeByServer || closeByClient)
                                {
                                    Close();
                                }
                                else if (CurrentRequest.Response != null)
                                {
                                    var keepAliveheaderValues = CurrentRequest.Response.GetHeaderValues("keep-alive");
                                    if (keepAliveheaderValues != null && keepAliveheaderValues.Count > 0)
                                    {
                                        if (KeepAlive == null)
                                        {
                                            KeepAlive = new KeepAliveHeader();
                                        }
                                        KeepAlive.Parse(keepAliveheaderValues);
                                    }
                                }
                            }
                        }
                    }
                } while (cause != RetryCauses.None);
            }
            catch (TimeoutException e)
            {
                CurrentRequest.Response  = null;
                CurrentRequest.Exception = e;
                CurrentRequest.State     = HTTPRequestStates.ConnectionTimedOut;

                Close();
            }
            catch (Exception e)
            {
                if (CurrentRequest != null)
                {
#if !BESTHTTP_DISABLE_CACHING && (!UNITY_WEBGL || UNITY_EDITOR)
                    if (CurrentRequest.UseStreaming)
                    {
                        HTTPCacheService.DeleteEntity(CurrentRequest.CurrentUri);
                    }
#endif

                    // Something gone bad, Response must be null!
                    CurrentRequest.Response = null;

                    switch (State)
                    {
                    case HTTPConnectionStates.Closed:
                    case HTTPConnectionStates.AbortRequested:
                        CurrentRequest.State = HTTPRequestStates.Aborted;
                        break;

                    case HTTPConnectionStates.TimedOut:
                        CurrentRequest.State = HTTPRequestStates.TimedOut;
                        break;

                    default:
                        CurrentRequest.Exception = e;
                        CurrentRequest.State     = HTTPRequestStates.Error;
                        break;
                    }
                }

                Close();
            }
            finally
            {
                if (CurrentRequest != null)
                {
                    // Avoid state changes. While we are in this block changing the connection's State, on Unity's main thread
                    //  the HTTPManager's OnUpdate will check the connections's State and call functions that can change the inner state of
                    //  the object. (Like setting the CurrentRequest to null in function Recycle() causing a NullRef exception)
                    lock (HTTPManager.Locker)
                    {
                        if (CurrentRequest != null && CurrentRequest.Response != null && CurrentRequest.Response.IsUpgraded)
                        {
                            State = HTTPConnectionStates.Upgraded;
                        }
                        else
                        {
                            State = redirected ? HTTPConnectionStates.Redirected : (Client == null ? HTTPConnectionStates.Closed : HTTPConnectionStates.WaitForRecycle);
                        }

                        // Change the request's state only when the whole processing finished
                        if (CurrentRequest.State == HTTPRequestStates.Processing && (State == HTTPConnectionStates.Closed || State == HTTPConnectionStates.WaitForRecycle))
                        {
                            if (CurrentRequest.Response != null)
                            {
                                CurrentRequest.State = HTTPRequestStates.Finished;
                            }
                            else
                            {
                                CurrentRequest.Exception = new Exception(string.Format("Remote server closed the connection before sending response header! Previous request state: {0}. Connection state: {1}",
                                                                                       CurrentRequest.State.ToString(),
                                                                                       State.ToString()));
                                CurrentRequest.State = HTTPRequestStates.Error;
                            }
                        }

                        if (CurrentRequest.State == HTTPRequestStates.ConnectionTimedOut)
                        {
                            State = HTTPConnectionStates.Closed;
                        }

                        LastProcessTime = DateTime.UtcNow;

                        if (OnConnectionRecycled != null)
                        {
                            RecycleNow();
                        }
                    }

                    #if !BESTHTTP_DISABLE_CACHING && (!UNITY_WEBGL || UNITY_EDITOR)
                    HTTPCacheService.SaveLibrary();
                    #endif

                    #if !BESTHTTP_DISABLE_COOKIES && (!UNITY_WEBGL || UNITY_EDITOR)
                    CookieJar.Persist();
                    #endif
                }
            }
        }
Example #55
0
 void ChangeAnimation(State animation) {
     m_currentAnimation = animation;
     m_animation.Play(m_currentAnimation.ToString());
 }
Example #56
0
        private void AutoComplete(JsonToken tokenBeingWritten)
        {
            int token;

            switch (tokenBeingWritten)
            {
            default:
                token = (int)tokenBeingWritten;
                break;

            case JsonToken.Integer:
            case JsonToken.Float:
            case JsonToken.String:
            case JsonToken.Boolean:
            case JsonToken.Null:
            case JsonToken.Undefined:
            case JsonToken.Date:
                // a value is being written
                token = 6;
                break;
            }

            // gets new state based on the current state and what is being written
            State newState = stateArray[token, (int)_currentState];

            if (newState == State.Error)
            {
                throw new JsonWriterException(string.Format("Token {0} in state {1} would result in an invalid JavaScript object.", tokenBeingWritten.ToString(), _currentState.ToString()));
            }

            if ((_currentState == State.Object || _currentState == State.Array || _currentState == State.Constructor) && tokenBeingWritten != JsonToken.Comment)
            {
                _writer.Write(',');
            }
            else if (_currentState == State.Property)
            {
                if (_formatting == Formatting.Indented)
                {
                    _writer.Write(' ');
                }
            }

            // don't indent a property when it is the first token to be written (i.e. at the start)
            if ((tokenBeingWritten == JsonToken.PropertyName && WriteState != WriteState.Start) ||
                WriteState == WriteState.Array || WriteState == WriteState.Constructor)
            {
                WriteIndent();
            }

            _currentState = newState;
        }
Example #57
0
 private void EnsureState(State requiredState)
 {
     if (InitializationState != requiredState)
         throw new InvalidOperationException("InitializationState != " + requiredState.ToString());
 }
Example #58
0
 public void HandleLinkFrame(AmqpFrame frame, ByteBuffer buffer = null)
 {
     lock (stateSyncRoot)
     {
         try
         {
             if (frame is Attach)
             {
                 HandleAttachFrame(frame as Attach);
             }
             else if (frame is Flow)
             {
                 HandleFlowFrame(frame as Flow);
             }
             else if (frame is Transfer)
             {
                 HandleTransferFrame(frame as Transfer, buffer);
             }
             else if (frame is Detach)
             {
                 HandleDetachFrame(frame as Detach);
             }
             else
             {
                 throw new AmqpException(ErrorCode.IllegalState, $"Received frame {frame.Descriptor.ToString()} but link state is {State.ToString()}.");
             }
         }
         catch (AmqpException amqpException)
         {
             trace.Error(amqpException);
             DetachLink(amqpException.Error, destoryLink: true);
         }
         catch (Exception fatalException)
         {
             trace.Fatal(fatalException, "Ending Session due to fatal exception.");
             var error = new Error()
             {
                 Condition   = ErrorCode.InternalError,
                 Description = "Ending Session due to fatal exception: " + fatalException.Message,
             };
             DetachLink(error, destoryLink: true);
         }
     }
 }
 private void LogAction(Event stateEvent, State preState, State postState)
 {
     Console.WriteLine("Event: {0}", stateEvent.ToString());
     Console.WriteLine(" - Pre  State: {0}" + preState.ToString());
     Console.WriteLine(" - Post State: {0}" + postState.ToString());
 }
Example #60
0
 private void ChangeState(State state)
 {
     if (this.state != state) {
         this.state = state;
         state.Entry();
         if (Logger.IsInfoEnabled) {
             Logger.Info(state.ToString());
         }
     }
 }