public void Closures_Work_Properly() { int counter = 0; Func<int> request = () => counter++; var waitFor = new WaitFor<int>(1.Minutes()); Enumerable.Range(0, 5).ForEach(n => Assert.AreEqual(n, waitFor.Run(request))); Assert.AreEqual(5, counter); }
public void Expired_Request_Throws_Timeout_Exception() { Func<int> longRequest = () => { Thread.Sleep(1000); return 1; }; var waitFor = new WaitFor<int>(1.Milliseconds()); waitFor.Run(longRequest); }
public bool TryProcess(CommandProcessorContext context, string[] args) { if (args == null || args.Length == 0) { _log.Error("Empty command"); throw new Exception("Empty command"); } var commandName = args[0].ToUpper(); var commandArgs = args.Skip(1).ToArray(); ICommandProcessor commandProcessor; if (!_processors.TryGetValue(commandName, out commandProcessor)) { _log.Info("Unknown command: '{0}'", commandName); new UsageProcessor(this).Execute(context, CancellationToken.None, new string[0]); return false; } var result = false; var timeout = context.Client.Options.Timeout; using (var source = new CancellationTokenSource()) { try { var token = source.Token; if (timeout > 0) { result = new WaitFor<bool>(TimeSpan.FromSeconds(timeout)).Run( () => commandProcessor.Execute(context, token, commandArgs)); } else { result = commandProcessor.Execute(context, token,commandArgs); } } catch (TimeoutException ex) { _log.Error("Command didn't finish in {0} seconds", timeout); } catch (Exception exc) { _log.ErrorException(exc, "Failure while processing {0}", commandName); } finally { source.Cancel(); } } return result; }
public static void SelectAreaTypeAndWaitForPageToLoad(IWebDriver driver, string areaTypeLinkId) { var waitFor = new WaitFor(driver); var byAreaTypeLink = By.Id(areaTypeLinkId); waitFor.ExpectedElementToBeVisible(byAreaTypeLink); driver.FindElement(byAreaTypeLink).Click(); // Added because this method was finishing before the page had fully switched area type WaitFor.ThreadWait(0.1); waitFor.PageToFinishLoading(); waitFor.GoogleMapToLoad(); }
public void Count_OverHead() { var waitFor = new WaitFor<int>(1.Minutes()); var watch = Stopwatch.StartNew(); const int count = 10000; for (int i = 0; i < count; i++) { waitFor.Run(() => 1); } var ticks = watch.ElapsedTicks; Console.WriteLine("Overhead is {0} ms", TimeSpan.FromTicks(ticks / count).TotalMilliseconds); }
/// ------------------------------------------------------------------------------------ /// <summary> /// Shows an instance of this dialog on a separate thread. /// </summary> /// <param name="args">The application arguments</param> /// <param name="whatToWaitFor">The condition we're waiting for.</param> /// <param name="appToStart">The application to start.</param> /// <param name="appToWaitFor">The application to wait for (null if waiting for /// WindowToActivate).</param> /// ------------------------------------------------------------------------------------ internal static void ShowOnSeparateThread(FwAppArgs args, WaitFor whatToWaitFor, FwApp appToStart, FwApp appToWaitFor) { if (whatToWaitFor != WaitFor.WindowToActivate && appToWaitFor == null) throw new ArgumentNullException("appToWaitFor"); if (appToStart == null) throw new ArgumentNullException("appToStart"); ApplicationBusyDialog dlg = new ApplicationBusyDialog(); dlg.m_whatToWaitFor = whatToWaitFor; dlg.m_args = args; dlg.m_appToStart = appToStart; dlg.m_appToWaitFor = appToWaitFor; Thread thread = new Thread(dlg.WaitForOtherApp); thread.IsBackground = true; thread.SetApartmentState(ApartmentState.STA); thread.Name = "WaitForOtherBusyApp"; thread.CurrentUICulture = Thread.CurrentThread.CurrentUICulture; thread.Start(); }
private static IEnumerator StopSpam() { yield return(WaitFor.Seconds(12)); isSpamming = false; }
private IEnumerator StopElectrocutedOverlayAfter(float seconds) { yield return(WaitFor.Seconds(seconds)); DisableElectrocutedOverlay(); }
IEnumerator WaitForLoad() { yield return(WaitFor.Seconds(2f)); SetVoltage(voltageSync); }
public void StartCommend(TitanAccount account, CommendInfo info) { account.FeedCommendInfo(info); _count = 0; _log.Debug("Starting commending thread for {Target} using account {Account}.", info.SteamID, account.JsonAccount.Username); _taskDic.Add(account, Task.Run(() => { var timedOut = false; try { account.StartTick = DateTime.Now.Ticks; // Timeout on Sentry Account: 3min (so the user has enough time to input the 2FA code), else 60sec. var result = WaitFor <Result> .Run(account.JsonAccount.Sentry ? TimeSpan.FromMinutes(3) : TimeSpan.FromSeconds(60), account.Start); switch (result) { case Result.Success: _count++; break; case Result.AlreadyLoggedInSomewhereElse: _log.Error("Could not commend with account {Account}. The account is " + "already logged in somewhere else.", account.JsonAccount.Username); break; case Result.AccountBanned: _log.Warning("Account {Account} has VAC or game bans on record. The report may " + "have not been submitted."); _count++; break; case Result.TimedOut: _log.Error("Processing thread for {Account} has timed out."); break; case Result.SentryRequired: _log.Error("The account has 2FA enabled. Please set {sentry} to {true} " + "in the accounts.json file.", "sentry", true); break; case Result.RateLimit: _log.Error("The Steam Rate Limit has been reached. Please try again in a " + "few minutes."); break; } } catch (TimeoutException) { var timeSpent = new DateTime(DateTime.Now.Ticks).Subtract(new DateTime(account.StartTick)); _log.Error("Connection to account {Account} timed out. It was not possible to " + "commend the target after {Timespan} seconds.", account.JsonAccount.Username, timeSpent.Seconds); timedOut = true; } finally { if (timedOut) { account.Stop(); } _taskDic.Remove(account); } })); }
private IEnumerator WaitToTurnOff(float time) { yield return(WaitFor.Seconds(time)); spriteHandler.gameObject.SetActive(false); }
private IEnumerator SpeakAnnouncement() { yield return(WaitFor.Seconds(3f)); SunVox.sv_send_event((int)Slot.Announce, 0, 60, 128, SamplerModule + 1, 0, 0); }
private void CheckTileCollisions(MatrixIntersection i) { if (i.Matrix1 == null || i.Matrix2 == null) { return; } byte collisions = 0; foreach (Vector3Int worldPos in i.Rect.ToBoundsInt().allPositionsWithin) { Vector3Int cellPos1 = i.Matrix1.MetaTileMap.WorldToCell(worldPos); if (!i.Matrix1.Matrix.HasTile(cellPos1, true)) { continue; } Vector3Int cellPos2 = i.Matrix2.MetaTileMap.WorldToCell(worldPos); if (!i.Matrix2.Matrix.HasTile(cellPos2, true)) { continue; } float resistance1 = i.Matrix1.MetaTileMap.Resistance(cellPos1, true); if (resistance1 <= 0f) { continue; } float resistance2 = i.Matrix2.MetaTileMap.Resistance(cellPos2, true); if (resistance2 <= 0f) { continue; } collisionLocations.Add(worldPos); // // ******** DESTROY STUFF!!! ******** // //total damage to apply to victim tile if (resistance1 + (10 * i.Matrix1.Speed) >= resistance2 + (10 * i.Matrix2.Speed)) { //attacker tile is stronger: //destroy victim tile TryPushing(i.Matrix2, cellPos2, i.Matrix1.MovementVector, i.Matrix1.Speed); ApplyCritDamage(i.Matrix2, cellPos2, worldPos); //slightly damage adjacent victim tiles ApplyTilemapDamage(i.Matrix2, cellPos2 + Vector3Int.up, resistance1 * 0.4f, worldPos); ApplyTilemapDamage(i.Matrix2, cellPos2 + Vector3Int.down, resistance1 * 0.4f, worldPos); ApplyTilemapDamage(i.Matrix2, cellPos2 + Vector3Int.left, resistance1 * 0.4f, worldPos); ApplyTilemapDamage(i.Matrix2, cellPos2 + Vector3Int.right, resistance1 * 0.4f, worldPos); //damage back attacker TryPushing(i.Matrix1, cellPos1, i.Matrix2.MovementVector, i.Matrix2.Speed); ApplyDamage(i.Matrix1, cellPos1, resistance2, worldPos); if (resistance2 > EXTRA_COLLISION_THRESHOLD) { collisions += (byte)((resistance2 - EXTRA_COLLISION_THRESHOLD) / EXTRA_COLLISION_THRESHOLD); } } else { //victim tile is stronger //destroy weaker tile TryPushing(i.Matrix1, cellPos1, i.Matrix2.MovementVector, i.Matrix2.Speed); ApplyCritDamage(i.Matrix1, cellPos1, worldPos); //slightly damage adjacent tiles ApplyTilemapDamage(i.Matrix1, cellPos1 + Vector3Int.up, resistance2 * 0.4f, worldPos); ApplyTilemapDamage(i.Matrix1, cellPos1 + Vector3Int.down, resistance2 * 0.4f, worldPos); ApplyTilemapDamage(i.Matrix1, cellPos1 + Vector3Int.left, resistance2 * 0.4f, worldPos); ApplyTilemapDamage(i.Matrix1, cellPos1 + Vector3Int.right, resistance2 * 0.4f, worldPos); //damage back TryPushing(i.Matrix2, cellPos2, i.Matrix1.MovementVector, i.Matrix1.Speed); ApplyDamage(i.Matrix2, cellPos2, resistance1, worldPos); if (resistance1 > EXTRA_COLLISION_THRESHOLD) { collisions += (byte)((resistance1 - EXTRA_COLLISION_THRESHOLD) / EXTRA_COLLISION_THRESHOLD); } } collisions++; //Wires (since they don't have Integrity) ApplyWireDamage(i.Matrix1, cellPos1); ApplyWireDamage(i.Matrix2, cellPos2); //Heat shit up i.Matrix1.ReactionManager.ExposeHotspot(cellPos1); i.Matrix2.ReactionManager.ExposeHotspot(cellPos2); //Other foreach (var layer in layersToRemove) { i.Matrix1.TileChangeManager.RemoveTile(cellPos1, layer); i.Matrix2.TileChangeManager.RemoveTile(cellPos2, layer); } foreach (var layer in effectsToRemove) { i.Matrix1.TileChangeManager.RemoveAllOverlays(cellPos1, layer); i.Matrix2.TileChangeManager.RemoveAllOverlays(cellPos2, layer); } } if (collisions > 0) { var epicenter = collisionLocations[collisionLocations.Count / 2]; ExplosionUtils.PlaySoundAndShake( epicenter, (byte)Mathf.Clamp(collisions * 12, 16, byte.MaxValue), Mathf.Clamp(collisions * 8, 15, 127) ); SlowDown(i, collisions); if (collisions > 6 && Mathf.Max(i.Matrix1.Speed, i.Matrix2.Speed) > 6) { i.Matrix1.Matrix.OnEarthquake.Invoke(epicenter, collisions); i.Matrix2.Matrix.OnEarthquake.Invoke(epicenter, collisions); } collisionLocations.Clear(); } //Damage methods void ApplyDamage(MatrixInfo victimMatrix, Vector3Int cellPos, float hitEnergy, Vector3Int worldPos) { //LivingHealthBehaviour hitEnergy -= ApplyLivingDamage(victimMatrix, cellPos, hitEnergy); //TilemapDamage ApplyTilemapDamage(victimMatrix, cellPos, hitEnergy, worldPos); // //Integrity ApplyIntegrityDamage(victimMatrix, cellPos, hitEnergy); } void ApplyCritDamage(MatrixInfo victimMatrix, Vector3Int cellPos, Vector3Int worldPos) { //LivingHealthBehaviour ApplyLivingDamage(victimMatrix, cellPos, 9001); //TilemapDamage ApplyTilemapDamage(victimMatrix, cellPos, 9001, worldPos); //Integrity ApplyIntegrityDamage(victimMatrix, cellPos, 9001); //Underfloor RemoveUnderfloor(victimMatrix, cellPos); } void RemoveUnderfloor(MatrixInfo matrix, Vector3Int cellPos) { if (matrix == null) { return; } var Node = matrix.Matrix.GetMetaDataNode(cellPos); if (Node != null) { foreach (var electricalData in Node.ElectricalData) { electricalData.InData.DestroyThisPlease(); } } } void ApplyTilemapDamage(MatrixInfo matrix, Vector3Int cellPos, float damage, Vector3Int worldPos) { if (matrix == null) { return; } matrix.MetaTileMap.ApplyDamage(cellPos, damage, worldPos); if (damage > 9000) { foreach (var damageableLayer in matrix.MetaTileMap.LayersValues) { if (damageableLayer.LayerType == LayerType.Objects) { continue; } matrix.TileChangeManager.RemoveTile(cellPos, damageableLayer.LayerType); } } } void ApplyWireDamage(MatrixInfo matrix, Vector3Int cellPos) { if (matrix == null) { return; } foreach (var wire in matrix.Matrix.Get <CableInheritance>(cellPos, true)) { if (Random.value >= 0.5) { //Sparks wire.QueueForDemolition(wire); StartCoroutine(DestroyWireWithDelay(wire, (byte)(Random.value * 20f))); } else { //Destruction wire.toDestroy(); } } } float ApplyIntegrityDamage(MatrixInfo matrix, Vector3Int cellPos, float damage) { if (matrix == null) { return(0); } float resistance = 0f; foreach (var integrity in matrix.Matrix.Get <Integrity>(cellPos, true)) { resistance += integrity.integrity; integrity.ApplyDamage(damage, AttackType.Melee, DamageType.Brute); } return(resistance); } float ApplyLivingDamage(MatrixInfo matrix, Vector3Int cellPos, float damage) { if (matrix == null) { return(0); } byte count = 0; foreach (var healthBehaviour in matrix.Matrix.Get <LivingHealthBehaviour>(cellPos, true)) { healthBehaviour.ApplyDamageToBodyPart(matrix.GameObject, damage, AttackType.Melee, DamageType.Brute); count++; } return(count * 50); } void TryPushing(MatrixInfo matrix, Vector3Int cellPos, Vector2Int pushVector, float speed) { if (matrix == null || pushVector == Vector2Int.zero) { return; } foreach (var pushPull in matrix.Matrix.Get <PushPull>(cellPos, true)) { byte pushes = (byte)Mathf.Clamp(speed / 4, 1, 4); for (int j = 0; j < pushes; j++) { pushPull.QueuePush(pushVector, speed * Random.Range(0.8f, 1.1f)); } } } IEnumerator DestroyWireWithDelay(CableInheritance wire, byte timer) { yield return(WaitFor.Seconds(timer)); if (wire != null) { wire.toDestroy(); } } }
static void Poll() { PollSensor(); // send poll command to sensor StartTimer(); // wait for message from sensor waitfor = WaitFor.Message; phase = Phase.WaitForEvent; }
static void ReportLostMessage() { // sensor = Sensor.Error; NOT! Doesn't change sensor StartTimer(); // wait for next time to poll waitfor = WaitFor.Timeout; phase = Phase.WaitForEvent; }
public void GetNodeFunction(List <NodePort> _ports) { //cannot find a way to use a switch, so we'll have to stick with a bunch of if statements :notlikethis: foreach (NodePort _nodePort in _ports) { XNode.Node _node = _nodePort.node; if (_node.GetType() == typeof(DialogueNode)) { dialoguePanel.SetActive(true); currentDialogue = _node as DialogueNode; ShowDialogue(currentDialogue); return; //do NOT grab the node after this, and wait for the player to advance the dialogue } if (_node.GetType() == typeof(EndSceneNode)) { EndCutscene(); return; } else if (_node.GetType() == typeof(EndBattleSceneNode)) { EndCutscene(); BattleManager BM = GameObject.Find("BattleManager").GetComponent <BattleManager>(); BM.EnableUI(); BM.StartActor(); //Move Battle UI Back In? return; } if (_node is MovementNode movementNode) { movementNode.CharacterMovement(); } if (_node.GetType() == typeof(CloseDialogue)) { dialoguePanel.SetActive(false); speakerPanel.SetActive(false); } if (_node.GetType() == typeof(CG)) { CG scopedCGNode = _node as CG; showCG(_node as CG); if (scopedCGNode.waitForInput) { currentCGNode = scopedCGNode; dialoguePanel.gameObject.SetActive(false); _charactersInScene.SetActive(false); CGWaitingForInput = true; return; } } if (_node.GetType() == typeof(SetSpriteNode)) { SetImage(_node as SetSpriteNode); } if (_node.GetType() == typeof(CGHide)) { _cgGraphic.enabled = false; } if (_node.GetType() == typeof(WaitFor)) { WaitFor _waitForNode = _node as WaitFor; StartCoroutine(WaitToAdvance(_waitForNode)); //do not get next node automatically return; } if (_node.GetType() == typeof(Choices)) { ChoicePanel.SetActive(true); nodeOptions = new List <Node>(); int listIndex = 0; Choices _choiceNode = _node as Choices; NodePort _choicePort = _choiceNode.GetOutputPort("output"); List <NodePort> _nodePorts = _choicePort.GetConnections(); foreach (NodePort _NP in _nodePorts) { nodeOptions.Add(_NP.node); Button _newOption = Instantiate(choiceButton) as Button; _newOption.transform.SetParent(ChoicePanel.transform); listIndex++;//on this button it where on the list it is, using this //ChoiceOptionHolder _holder = _newOption.GetComponent<ChoiceOptionHolder>(); OptionNode optionNode = _NP.node as OptionNode; _newOption.GetComponentInChildren <Text>().text = optionNode.optionText; _newOption.GetComponent <ChoiceOptionHolder>().node = _NP.node; // _holder.node = _NP.node; // _holder.indexOfOptions = listIndex; } return; //do not load next node, since we want the player input to decide the branch to go down } if (_node.GetType() == typeof(TimelineNode)) { TimelineNode timelineNode = _node as TimelineNode; timelineNode.PlayTimeLine(); } //get next node(s) NodePort _port = _node.GetOutputPort("output"); if (_port.IsConnected) { GetNodeFunction(_port.GetConnections()); } } }
static void CheckMessage() { double tol = 5.0; try { double data = double.Parse(buffer); if (previous == double.MaxValue) previous = data; // initialize if (Math.Abs(data - previous) < tol) { previous = data; sensor = Sensor.OK; } else sensor = Sensor.Error; // retain old previous } catch { sensor = Sensor.Error; } CancelTimer(); // cancel messageTimeout StartTimer(); // wait for next time to poll waitfor = WaitFor.Timeout; phase = Phase.WaitForEvent; }
private IEnumerator SpawnMob() { yield return(WaitFor.Seconds(Random.Range(0, 5))); new SpawnByPortal(mobsToSpawn.PickRandom(), portalPrefab, RandomUtils.GetRandomPointOnStation(true, true), portalSettings); }
/// <summary> /// Destroy the exploded game object (removing it completely from the game) after a few seconds. /// </summary> /// <returns></returns> private IEnumerator WaitToDestroy() { yield return(WaitFor.Seconds(5f)); NetworkServer.Destroy(gameObject); }
public List <string> GetSections() { WaitFor.AjaxCallsToComplete(); return(Find.Elements(By.ClassName("section-id")).Select(we => we.Text).ToList()); }
private IEnumerator HideCode() { yield return(WaitFor.Seconds(1)); CodeDisplay.SetValueServer("".PadLeft(((string)CodeDisplay.ValueObject).Length, '*')); }
static void Reset() { ResetSensor(); // send reset command to sensor StartTimer(); // wait for message from from sensor waitfor = WaitFor.Message; phase = Phase.WaitForEvent; }
private System.Collections.IEnumerator CheckForTrains() { bool inIdleState = false; bool timeDirty = false; while (true) { yield return(WaitFor.SecondsRealtime(TRAIN_CHECK_INTERVAL)); // Check whether to update the time DateTime newTime = DVTime_Patch.GetCurrentTime(); TimeSpan timeDelta = newTime.Subtract(LastTime); if (timeDelta.TotalSeconds >= 60) { LastTime = newTime; LastTimeString = newTime.ToString("hh:mm"); timeDirty = true; } else { timeDirty = false; } // Check for loading train, is highest priority on sign loadInRange = IsAnyTrainAtPlatform(true); if (loadInRange) { if (loadCountdown == 0) { if (DelayedLoadUnloadRoutine == null) { inIdleState = false; DelayedLoadUnloadRoutine = StartCoroutine(DelayedLoadUnload(true)); } continue; } else { loadCountdown -= 1; } } else { // !loadInRange loadCountdown = START_XFER_DELAY; } // Check for unloading train, next highest priority unloadInRange = IsAnyTrainAtPlatform(false); if (unloadInRange) { if (unloadCountdown == 0) { if (DelayedLoadUnloadRoutine == null) { inIdleState = false; DelayedLoadUnloadRoutine = StartCoroutine(DelayedLoadUnload(false)); } continue; } else { unloadCountdown -= 1; } } else { // !unloadInRange unloadCountdown = START_XFER_DELAY; } // if no trains in progress, then display the default message if (!(loading || unloading) && !inIdleState) { ClearOverrideText(); inIdleState = true; } else if (JobListDirty || timeDirty) { RefreshDisplays(); } } }
private IEnumerator Delay() { yield return(WaitFor.Seconds(0.3f)); doorController.isPerformingAction = false; }
public void Nudge(Actor self, Actor nudger, bool force) { if (IsTraitDisabled) { return; } // Initial fairly braindead implementation. // don't allow ourselves to be pushed around by the enemy! if (!force && self.Owner.Stances[nudger.Owner] != Stance.Ally) { return; } // Don't nudge if we're busy doing something! if (!force && !self.IsIdle) { return; } // Pick an adjacent available cell. var availCells = new List <CPos>(); var notStupidCells = new List <CPos>(); for (var i = -1; i < 2; i++) { for (var j = -1; j < 2; j++) { var p = ToCell + new CVec(i, j); if (CanEnterCell(p)) { availCells.Add(p); } else if (p != nudger.Location && p != ToCell) { notStupidCells.Add(p); } } } var moveTo = availCells.Any() ? availCells.Random(self.World.SharedRandom) : (CPos?)null; if (moveTo.HasValue) { self.CancelActivity(); self.SetTargetLine(Target.FromCell(self.World, moveTo.Value), Color.Green, false); self.QueueActivity(new Move(self, moveTo.Value, WDist.Zero)); Log.Write("debug", "OnNudge #{0} from {1} to {2}", self.ActorID, self.Location, moveTo.Value); } else { var cellInfo = notStupidCells .SelectMany(c => self.World.ActorMap.GetActorsAt(c) .Where(a => a.IsIdle && a.Info.HasTraitInfo <MobileInfo>()), (c, a) => new { Cell = c, Actor = a }) .RandomOrDefault(self.World.SharedRandom); if (cellInfo != null) { self.CancelActivity(); var notifyBlocking = new CallFunc(() => self.NotifyBlocker(cellInfo.Cell)); var waitFor = new WaitFor(() => CanEnterCell(cellInfo.Cell)); var move = new Move(self, cellInfo.Cell); self.QueueActivity(ActivityUtils.SequenceActivities(notifyBlocking, waitFor, move)); Log.Write("debug", "OnNudge (notify next blocking actor, wait and move) #{0} from {1} to {2}", self.ActorID, self.Location, cellInfo.Cell); } else { Log.Write("debug", "OnNudge #{0} refuses at {1}", self.ActorID, self.Location); } } }
public bool GotoMachinePosition(Position pos, AxisFlags axisflags) { bool?res = null; bool wait = true; string command = "G53" + RapidCommand + pos.ToString(axisflags); Comms.com.PurgeQueue(); new Thread(() => { res = WaitFor.AckResponse <string>( cancellationToken, null, a => Grbl.OnResponseReceived += a, a => Grbl.OnResponseReceived -= a, 1000, () => Grbl.ExecuteCommand(command)); }).Start(); while (res == null) { EventUtils.DoEvents(); } if (res == true) { while (wait && !isCancelled) { res = null; new Thread(() => { res = WaitFor.SingleEvent <string>( cancellationToken, null, a => Grbl.OnRealtimeStatusProcessed += a, a => Grbl.OnRealtimeStatusProcessed -= a, 400, () => Comms.com.WriteByte(GrblLegacy.ConvertRTCommand(GrblConstants.CMD_STATUS_REPORT))); }).Start(); while (res == null) { EventUtils.DoEvents(); } wait = res != true; int i = 0, axes = (int)axisflags; while (axes != 0 && !wait) { if ((axes & 0x01) != 0) { wait = Math.Abs(pos.Values[i] - Grbl.MachinePosition.Values[i]) >= 0.003d; // use step resolution plus some? } i++; axes >>= 1; } if (wait) { Thread.Sleep(200); // needed? } } } return(isCancelled ? false : !wait); }
public void StartIdling(TitanAccount account, IdleInfo info) { account.FeedIdleInfo(info); _count = 0; _log.Debug("Starting idling thread in games {@Games} using account {Account}.", info.GameID, account.JsonAccount.Username); _taskDic.Add(account, Task.Run(() => { var timedOut = false; try { account.StartTick = DateTime.Now.Ticks; var result = WaitFor <Result> .Run(TimeSpan.FromMinutes(info.Minutes + 2), account.Start); switch (result) { case Result.Success: _count++; break; case Result.AlreadyLoggedInSomewhereElse: _log.Error("Could not idle with account {Account}. The account is " + "already logged in somewhere else.", account.JsonAccount.Username); break; case Result.TimedOut: _log.Error("Processing thread for {Account} has timed out."); break; case Result.SentryRequired: _log.Error("The account has 2FA enabled. Please set {sentry} to {true} " + "in the accounts.json file.", "sentry", true); break; case Result.RateLimit: _log.Error("The Steam Rate Limit has been reached. Please try again in a " + "few minutes."); break; } } catch (TimeoutException) { var timeSpent = new DateTime(DateTime.Now.Ticks).Subtract(new DateTime(account.StartTick)); _log.Error("Connection to account {Account} timed out. It was not possible to " + "stop idle in the games after {Timespan} seconds.", account.JsonAccount.Username, timeSpent.Seconds); timedOut = true; } finally { if (timedOut) { account.Stop(); } _taskDic.Remove(account); } })); }
private IEnumerator VendorInputCoolDown() { yield return(WaitFor.Seconds(cooldownTimer)); allowSell = true; }
/// <summary> /// Called after MatrixManager is initialized /// </summary> /// private void InitEscapeStuff() { //Primary escape shuttle lookup if (PrimaryEscapeShuttle == null) { var shuttles = FindObjectsOfType <EscapeShuttle>(); if (shuttles.Length != 1) { Logger.LogError("Primary escape shuttle is missing from GameManager!", Category.Round); return; } Logger.LogWarning("Primary escape shuttle is missing from GameManager, but one was found on scene"); primaryEscapeShuttle = shuttles[0]; } //later, maybe: keep a list of all computers and call the shuttle automatically with a 25 min timer if they are deleted //Starting up at Centcom coordinates if (GameManager.Instance.QuickLoad) { if (primaryEscapeShuttle?.MatrixInfo == null) { return; } if (primaryEscapeShuttle?.MatrixInfo.MatrixMove == null) { return; } if (primaryEscapeShuttle?.MatrixInfo.MatrixMove.InitialFacing == null) { return; } } var orientation = primaryEscapeShuttle.MatrixInfo.MatrixMove.InitialFacing; float width; if (orientation == Orientation.Up || orientation == Orientation.Down) { width = PrimaryEscapeShuttle.MatrixInfo.Bounds.size.x; } else { width = PrimaryEscapeShuttle.MatrixInfo.Bounds.size.y; } Vector3 newPos; switch (LandingZoneManager.Instance.centcomDocking.orientation) { case OrientationEnum.Right: newPos = new Vector3(LandingZoneManager.Instance.centcomDockingPos.x + Mathf.Ceil(width / 2f), LandingZoneManager.Instance.centcomDockingPos.y, 0); break; case OrientationEnum.Up: newPos = new Vector3(LandingZoneManager.Instance.centcomDockingPos.x, LandingZoneManager.Instance.centcomDockingPos.y + Mathf.Ceil(width / 2f), 0); break; case OrientationEnum.Left: newPos = new Vector3(LandingZoneManager.Instance.centcomDockingPos.x - Mathf.Ceil(width / 2f), LandingZoneManager.Instance.centcomDockingPos.y, 0); break; default: newPos = new Vector3(LandingZoneManager.Instance.centcomDockingPos.x, LandingZoneManager.Instance.centcomDockingPos.y - Mathf.Ceil(width / 2f), 0); break; } PrimaryEscapeShuttle.MatrixInfo.MatrixMove.ChangeFacingDirection(Orientation.FromEnum(PrimaryEscapeShuttle.orientationForDockingAtCentcom)); PrimaryEscapeShuttle.MatrixInfo.MatrixMove.SetPosition(newPos); primaryEscapeShuttle.InitDestination(newPos); bool beenToStation = false; PrimaryEscapeShuttle.OnShuttleUpdate?.AddListener(status => { //status display ETA tracking if (status == EscapeShuttleStatus.OnRouteStation) { PrimaryEscapeShuttle.OnTimerUpdate.AddListener(TrackETA); } else { PrimaryEscapeShuttle.OnTimerUpdate.RemoveListener(TrackETA); CentComm.UpdateStatusDisplay(StatusDisplayChannel.EscapeShuttle, string.Empty); } if (status == EscapeShuttleStatus.DockedCentcom && beenToStation) { Logger.Log("Shuttle arrived at Centcom", Category.Round); Chat.AddSystemMsgToChat($"<color=white>Escape shuttle has docked at Centcomm! Round will restart in {TimeSpan.FromSeconds(RoundEndTime).Minutes} minute.</color>", MatrixManager.MainStationMatrix); StartCoroutine(WaitForRoundEnd()); } IEnumerator WaitForRoundEnd() { Logger.Log($"Shuttle docked to Centcom, Round will end in {TimeSpan.FromSeconds(RoundEndTime).Minutes} minute", Category.Round); yield return(WaitFor.Seconds(1f)); EndRound(); } if (status == EscapeShuttleStatus.DockedStation && !primaryEscapeShuttle.hostileEnvironment) { beenToStation = true; SoundManager.PlayNetworked("ShuttleDocked"); Chat.AddSystemMsgToChat($"<color=white>Escape shuttle has arrived! Crew has {TimeSpan.FromSeconds(ShuttleDepartTime).Minutes} minutes to get on it.</color>", MatrixManager.MainStationMatrix); //should be changed to manual send later StartCoroutine(SendEscapeShuttle(ShuttleDepartTime)); } else if (status == EscapeShuttleStatus.DockedStation && primaryEscapeShuttle.hostileEnvironment) { beenToStation = true; SoundManager.PlayNetworked("ShuttleDocked"); Chat.AddSystemMsgToChat($"<color=white>Escape shuttle has arrived! The shuttle <color=#FF151F>cannot</color> leave the station due to the hostile environment!</color>", MatrixManager.MainStationMatrix); } }); }
public void ContextTesting() { const int outerCount = 100000; Func<int, double> operation = i => { double val = 0; var limit = Rand.Next(5000, 10000); for (int j = 0; j < limit; j++) { val = Math.Sin(val + j); } return val; }; using (Counter("Lokad")) { Range .Array(outerCount) .SelectInParallel(operation); } var wait = new WaitFor<double>(2.Seconds()); using (Counter("Lokad+WaitFor")) { Range .Array(outerCount) .SelectInParallel(i => wait.Run(() => operation(i))); } }
private void InitServerState() { serverState.FlyingDirection = InitialFacing; serverState.FacingDirection = InitialFacing; Logger.LogTraceFormat("{0} server initial facing / flying {1}", Category.Shuttles, this, InitialFacing); Vector3Int initialPositionInt = Vector3Int.RoundToInt(new Vector3(transform.position.x, transform.position.y, 0)); SyncInitialPosition(initialPosition, initialPositionInt); var child = transform.GetChild(0); var childPosition = Vector3Int.CeilToInt(new Vector3(child.transform.position.x, child.transform.position.y, 0)); SyncPivot(pivot, initialPosition - childPosition); Logger.LogTraceFormat("{0}: pivot={1} initialPos={2}", Category.Shuttles, gameObject.name, pivot, initialPositionInt); serverState.Speed = 1f; serverState.Position = initialPosition; serverTargetState = serverState; clientState = serverState; RecheckThrusters(); if (thrusters.Count > 0) { foreach (var thruster in thrusters) { var integrity = thruster.GetComponent <Integrity>(); if (integrity) { integrity.OnWillDestroyServer.AddListener(destructionInfo => { if (thrusters.Contains(thruster)) { thrusters.Remove(thruster); } if (thrusters.Count == 0 && IsMovingServer) { StartCoroutine(StopWithDelay(1f)); } }); } } } if (SensorPositions == null) { CollisionSensor[] sensors = GetComponentsInChildren <CollisionSensor>(); if (sensors.Length == 0) { SensorPositions = new Vector3Int[0]; return; } SensorPositions = sensors.Select(sensor => Vector3Int.RoundToInt(sensor.transform.localPosition)).ToArray(); Logger.Log($"Initialized sensors at {string.Join(",", SensorPositions)}," + $" direction is {ServerState.FlyingDirection}", Category.Shuttles); } if (RotationSensors == null) { RotationCollisionSensor[] sensors = GetComponentsInChildren <RotationCollisionSensor>(); if (sensors.Length == 0) { RotationSensors = new GameObject[0]; return; } if (rotationSensorContainerObject == null) { rotationSensorContainerObject = sensors[0].transform.parent.gameObject; } RotationSensors = sensors.Select(sensor => sensor.gameObject).ToArray(); } IEnumerator StopWithDelay(float delay) { SetSpeed(ServerState.Speed / 2); yield return(WaitFor.Seconds(delay)); Logger.LogFormat("{0}: Stopping due to missing thrusters!", Category.Shuttles, matrix.name); StopMovement(); } }
private IEnumerator WaitForLoad() { yield return(WaitFor.Seconds(3f)); UpdateState(visibleState); }
/// Waiting for scene to load before finding matrices private IEnumerator WaitForLoad() { yield return(WaitFor.Seconds(0.5f)); InitMatrices(); }
private CardId[] loadDeck() { CardId[] r = null; while (true) { WaitFor<string> w = new WaitFor<string>(); DeckEditorPanel.loadDeckFromFile((s) => w.signal(s)); CardId[] ids = DeckEditorPanel.loadDeck(w.wait()).ToArray(); if (gameInterface.connection is DummyConnection || DeckEditorPanel.deckVerificationThing(ids)) return ids; } }
IEnumerator PressureWarnDelay() { yield return(WaitFor.Seconds(pressureWarningCooldown)); pressureWarnActive = false; }
public static void Reset() { Console.WriteLine(" Reset"); ResetSensor(); // send reset command to sensor StartTimer(); // wait for message from from sensor waitfor = WaitFor.Message; phase = Phase.WaitForEvent; }
public bool Init() { bool?res = null; probing.Message = string.Empty; Grbl.Poller.SetState(0); // Disable status polling during probing // Clear error status if set if (Grbl.GrblError != 0) { new Thread(() => { res = WaitFor.AckResponse <string>( cancellationToken, null, a => Grbl.OnResponseReceived += a, a => Grbl.OnResponseReceived -= a, 1000, () => Grbl.ExecuteCommand("")); }).Start(); while (res == null) { EventUtils.DoEvents(); } res = null; } // Get a status report in order to establish current machine position new Thread(() => { res = WaitFor.SingleEvent <string>( cancellationToken, null, a => Grbl.OnResponseReceived += a, a => Grbl.OnResponseReceived -= a, 1000, () => Comms.com.WriteByte(GrblSettings.IsGrblHAL ? GrblConstants.CMD_STATUS_REPORT_ALL : GrblLegacy.ConvertRTCommand(GrblConstants.CMD_STATUS_REPORT))); }).Start(); while (res == null) { EventUtils.DoEvents(); } Grbl.Poller.SetState(AppConfig.Settings.Base.PollInterval); if (Grbl.GrblState.State == GrblStates.Alarm) { probing.Message = GrblAlarms.GetMessage(Grbl.GrblState.Substate.ToString()); res = false; } if (res == true && Grbl.Signals.Value.HasFlag(Signals.ProbeDisconnected)) { probing.Message = "Probing failed, probe is not connected"; res = false; } if (res == true && Grbl.Signals.Value.HasFlag(Signals.Probe)) { probing.Message = "Probing failed, probe signal is asserted"; res = false; } if (res == true && !(Grbl.GrblState.State == GrblStates.Idle || Grbl.GrblState.State == GrblStates.Tool)) { probing.Message = "Probing failed, Grbl is not in idle or tool changing state"; res = false; } if (res == true && !Grbl.IsMachinePositionKnown) { probing.Message = "Probing failed, could not establish current machine position"; res = false; } probing.StartPosition.Set(probing.Grbl.MachinePosition); hasPause = probeOnCycleStart = false; _program.Clear(); if (res != true) // Reenable status polling if init fails { Grbl.Poller.SetState(AppConfig.Settings.Base.PollInterval); } return(res == true); }
public static void CheckTartanRugLoadsForAllDomains(IWebDriver driver) { var waitFor = new WaitFor(driver); // Click through each domain var domains = GetDomainOptions(driver); string previousIndicatorName = string.Empty; int previousIndicatorCount = 0; foreach (var domain in domains) { SelectDomain(domain, waitFor); var indicatorName = driver.FindElement(By.Id(LongerLivesIds.TartanRugIndicatorNameOnFirstRow)).Text; var indicatorCount = driver.FindElements(By.ClassName("rugIndicator")).Count; // Check tartan rug is different for each domain Assert.IsFalse( string.Equals(previousIndicatorName, indicatorName) && previousIndicatorCount == indicatorCount ); previousIndicatorCount = indicatorCount; previousIndicatorName = indicatorName; } }
public int SetupAndOpen(string appname, GrblViewModel model, System.Windows.Threading.Dispatcher dispatcher) { int status = 0; bool selectPort = false; string port = string.Empty; CNC.Core.Resources.Path = AppDomain.CurrentDomain.BaseDirectory; string[] args = Environment.GetCommandLineArgs(); int p = 0; while (p < args.GetLength(0)) { switch (args[p++]) { case "-inifile": CNC.Core.Resources.IniName = GetArg(args, p++); break; case "-configmapping": CNC.Core.Resources.ConfigName = GetArg(args, p++); break; case "-language": CNC.Core.Resources.Language = GetArg(args, p++); break; case "-port": port = GetArg(args, p++); break; case "-selectport": selectPort = true; break; default: if (!args[p - 1].EndsWith(".exe") && File.Exists(args[p - 1])) { FileName = args[p - 1]; } break; } } if (!Load(CNC.Core.Resources.IniFile)) { if (MessageBox.Show("Config file not found or invalid, create new?", appname, MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes) { if (!Save(CNC.Core.Resources.IniFile)) { MessageBox.Show("Could not save config file.", appname); status = 1; } } else { return(1); } } if (!string.IsNullOrEmpty(port)) { selectPort = false; } if (!selectPort) { if (!string.IsNullOrEmpty(port)) { setPort(port); } #if USEWEBSOCKET if (Base.PortParams.ToLower().StartsWith("ws://")) { new WebsocketStream(Base.PortParams, dispatcher); } else #endif if (char.IsDigit(Base.PortParams[0])) // We have an IP address { new TelnetStream(Base.PortParams, dispatcher); } else #if USEELTIMA { new EltimaStream(Config.PortParams, Config.ResetDelay, dispatcher); } #else { new SerialStream(Base.PortParams, Base.ResetDelay, dispatcher); } #endif } if ((Comms.com == null || !Comms.com.IsOpen) && string.IsNullOrEmpty(port)) { PortDialog portsel = new PortDialog(); port = portsel.ShowDialog(Base.PortParams); if (string.IsNullOrEmpty(port)) { status = 2; } else { setPort(port); #if USEWEBSOCKET if (port.ToLower().StartsWith("ws://")) { new WebsocketStream(Base.PortParams, dispatcher); } else #endif if (char.IsDigit(port[0])) // We have an IP address { new TelnetStream(Base.PortParams, dispatcher); } else #if USEELTIMA { new EltimaStream(Config.PortParams, Config.ResetDelay, dispatcher); } #else { new SerialStream(Base.PortParams, Base.ResetDelay, dispatcher); } #endif Save(CNC.Core.Resources.IniFile); } } if (Comms.com != null && Comms.com.IsOpen) { Comms.com.DataReceived += model.DataReceived; CancellationToken cancellationToken = new CancellationToken(); // Wait 400ms to see if a MPG is polling Grbl... new Thread(() => { MPGactive = WaitFor.SingleEvent <string>( cancellationToken, null, a => model.OnRealtimeStatusProcessed += a, a => model.OnRealtimeStatusProcessed -= a, 500); }).Start(); while (MPGactive == null) { EventUtils.DoEvents(); } // ...if so show dialog for wait for it to stop polling and relinquish control. if (MPGactive == true) { MPGPending await = new MPGPending(model); await.ShowDialog(); if (await.Cancelled) { Comms.com.Close(); //!! status = 2; } } model.IsReady = true; } else if (status != 2) { MessageBox.Show(string.Format("Unable to open connection ({0})", Base.PortParams), appname, MessageBoxButton.OK, MessageBoxImage.Error); status = 2; } return(status); }
public static void Poll() { Console.WriteLine(" Poll"); PollSensor(); // send poll command to sensor StartTimer(); // wait for message from sensor waitfor = WaitFor.Message; phase = Phase.WaitForEvent; }
IEnumerator PerformFollowPath(List <Node> path) { int node = 1; while (node < path.Count) { if (!activated) { yield return(WaitFor.EndOfFrame); yield break; } if (!movingToTile) { if (tickRate != 0f) { yield return(WaitFor.Seconds(tickRate)); } var dir = path[node].position - Vector2Int.RoundToInt(transform.localPosition); if (!registerTile.Matrix.IsPassableAtOneMatrixOneTile(registerTile.LocalPositionServer + (Vector3Int)dir, true, context: gameObject)) { var dC = registerTile.Matrix.GetFirst <DoorController>( registerTile.LocalPositionServer + (Vector3Int)dir, true); if (dC != null) { dC.MobTryOpen(gameObject); yield return(WaitFor.Seconds(1f)); } else { ResetMovingValues(); FollowCompleted(); Logger.Log("Path following timed out. Something must be in the way", Category.Movement); yield break; } } if (directional != null) { directional.FaceDirection(Orientation.From(dir)); } cnt.Push(dir, context: gameObject); movingToTile = true; } else { if (arrivedAtTile) { movingToTile = false; arrivedAtTile = false; timeOut = 0f; node++; } else { //Mob has 5 seconds to get to the next tile //or the AI should do something else timeOut += Time.deltaTime; if (timeOut > 5f) { ResetMovingValues(); Logger.Log("Path following timed out. Something must be in the way", Category.Movement); FollowCompleted(); yield break; } } } yield return(WaitFor.EndOfFrame); } yield return(WaitFor.EndOfFrame); ResetMovingValues(); FollowCompleted(); }
protected override void Forward() { if (nowStep != nextStep) { return; } nextStep = ExecuteStep.Update; // Delay coroutine if (nowStep == ExecuteStep.Update) { if (delayTime > 0) { delayTime = Mathf.Max(0, delayTime - Time.deltaTime); if (delayTime > 0) { return; } } } IEnumerator item = null; while (stack.Count > 0) { item = stack.Peek(); if (item != null) { break; } stack.Pop(); } if (item != null) { if (item.MoveNext()) { object current = item.Current; if (current != null) { IEnumerator newItem = current as IEnumerator; if (newItem != null) { stack.Push(newItem); } else if (current is float) { delayTime = Mathf.Max(0, (float)current); } else if (current is WaitFor) { WaitFor wait = (WaitFor)current; if (wait == WaitFor.FixedUpdate) { nextStep = ExecuteStep.FixedUpdate; } else { nextStep = ExecuteStep.EndOfFrame; } } else if (current is WaitForFixedUpdate) { nextStep = ExecuteStep.FixedUpdate; } else if (current is WaitForEndOfFrame) { nextStep = ExecuteStep.EndOfFrame; } } } else { stack.Pop(); } } if (stack.Count == 0) { state = CoroutineState.Finish; } }
private int _count; // Amount of accounts that successfully reported or commended public void Start(BotMode mode, TitanAccount acc, uint target, ulong matchId) { acc.Feed(new Info { Mode = mode, Target = target, MatchID = matchId }); _count = 0; _log.Debug("Starting {Mode} thread for {Target} in match {MatchId} " + "using account {Account}.", mode.ToString().ToLower() + "ing", target, matchId, acc.JsonAccount.Username); _taskDic.Add(acc, Task.Run(() => { var timedOut = false; try { acc.StartTick = DateTime.Now.Ticks; // Timeout on Sentry Account: 3min (so the user has enough time to input the 2FA code), else 60sec. var result = WaitFor <Result> .Run(acc.JsonAccount.Sentry ? TimeSpan.FromMinutes(3) : TimeSpan.FromSeconds(60), acc.Start); switch (result) { case Result.Success: _count++; break; case Result.AlreadyLoggedInSomewhereElse: _log.Error("Could not report with account {Account}. The account is " + "already logged in somewhere else.", acc.JsonAccount.Username); break; case Result.AccountBanned: _log.Warning("Account {Account} has VAC or game bans on record. The report may " + "have not been submitted."); _count++; break; case Result.TimedOut: _log.Error("Processing thread for {Account} has timed out."); break; case Result.SentryRequired: _log.Error("The account has 2FA enabled. Please set {sentry} to {true} " + "in the accounts.json file.", "sentry", true); break; case Result.RateLimit: _log.Error("The Steam Rate Limit has been reached. Please try again in a " + "few minutes."); break; } } catch (TimeoutException) { var timeSpent = new DateTime(DateTime.Now.Ticks - acc.StartTick); _log.Error("Connection to account {Account} timed out. It was not possible to " + "report the target after {Timespan} seconds.", acc.JsonAccount.Username, timeSpent.Second); timedOut = true; } finally { if (timedOut) { acc.Stop(); } _taskDic.Remove(acc); } })); }
//Stops spamming from players IEnumerator CoolDown() { yield return(WaitFor.Seconds(1.2f)); buttonCoolDown = false; }
public void Proper_Request_Returns_Value() { Func<int> request = () => { Thread.Sleep(1); return 1; }; var waitFor = new WaitFor<int>(1.Minutes()); var result = waitFor.Run(request); Assert.AreEqual(1, result); }
private IEnumerator WaitToFireClientHooks() { yield return(WaitFor.Seconds(3f)); Spawn._CallAllClientSpawnHooksInScene(); }
public static void SelectDomain(IWebElement domain, WaitFor waitFor) { domain.Click(); WaitFor.ThreadWait(0.1); waitFor.AjaxLockToBeUnlocked(); }
public static void CheckMessage() { double tol = 5.0; Console.Write(" CheckMessage '" + buffer + "'"); try { double data = double.Parse(buffer); if (previous == double.MaxValue) previous = data; // initialize Console.Write(", compare to " + previous); if (Math.Abs(data - previous) < tol) { previous = data; sensor = Sensor.OK; } else sensor = Sensor.Error; // retain old previous Console.WriteLine(", " + sensor); } catch { sensor = Sensor.Error; Console.WriteLine(", Error"); } CancelTimer(); // cancel messageTimeout StartTimer(); // wait for next time to poll waitfor = WaitFor.Timeout; phase = Phase.WaitForEvent; }