public decimal Calculate(InputItem inputItem) { if (CurrenciesAreTheSame(inputItem)) { return(inputItem.MoneyAmount); } decimal?priceAmount = 0; if (inputItem.CurrencyTo.IsoName == _exchangeItemRepository.DefaultCurrency.IsoName) { priceAmount = GetAmountFromCurrencyToDefault(inputItem.CurrencyFrom, inputItem.CurrencyTo); } else if (inputItem.CurrencyFrom.IsoName == _exchangeItemRepository.DefaultCurrency.IsoName) { priceAmount = GetAmountFromDefaultToCurrency(inputItem.CurrencyTo, inputItem.CurrencyFrom); } else { var currencyFromToDefaultCurrencyAmount = GetAmountFromCurrencyToDefault(inputItem.CurrencyFrom, _exchangeItemRepository.DefaultCurrency); inputItem = new InputItem { CurrencyFrom = _exchangeItemRepository.DefaultCurrency, CurrencyTo = inputItem.CurrencyTo, MoneyAmount = currencyFromToDefaultCurrencyAmount * inputItem.MoneyAmount ?? 0 }; return(Calculate(inputItem)); } return(Math.Round(inputItem.MoneyAmount * priceAmount ?? 0, 4)); }
public List <InputItem> GetInputItemListFromProperties <T>() { var result = new List <InputItem>(); Type t = typeof(T); foreach (var field in t.GetFields()) { var propAttrs = field.GetCustomAttributes(typeof(InputItemAttribute), true); foreach (var attr in propAttrs) { var item = (InputItemAttribute)attr; var entry = new InputItem() { InputName = item.Label, InputType = field.FieldType.Name, InputValue = field.GetValue(this) }; if (attr is RangeInputItemAttribute) { var rangeAttr = (RangeInputItemAttribute)attr; if (rangeAttr != null) { entry.Max = rangeAttr.Max; entry.Min = rangeAttr.Min; entry.CoerceTo01 = rangeAttr.CoerceTo01; entry.Step = rangeAttr.Step; entry.ShowSlider = true; } } result.Add(entry); } } return(result); }
public void Test_If_Convertion_From_Currency_To_Currency_Returns_Correct_Amount() { var itemsAmount = 2; var inputItem = new InputItem { CurrencyFrom = new CurrencyItem { IsoName = CurrencyIso.EUR }, CurrencyTo = new CurrencyItem { IsoName = CurrencyIso.USD }, MoneyAmount = itemsAmount }; var mock = new Mock <IExchangeItemRepository>(); mock.Setup(m => m.GetByCurrencies(It.Is <CurrencyItem>(i => i.IsoName == CurrencyIso.EUR), It.Is <CurrencyItem>(i => i.IsoName == CurrencyIso.DKK))) .Returns(new ExchangeItem { Amount = 743.94m * itemsAmount }); mock.Setup(m => m.GetByCurrencies(It.Is <CurrencyItem>(i => i.IsoName == CurrencyIso.USD), It.Is <CurrencyItem>(i => i.IsoName == CurrencyIso.DKK))) .Returns(new ExchangeItem { Amount = 663.11m * itemsAmount }); mock.Setup(m => m.DefaultCurrency) .Returns(new CurrencyItem { IsoName = CurrencyIso.DKK }); var exchangeService = new ExchangeService(mock.Object); var amount = exchangeService.Calculate(inputItem); Assert.AreEqual(2.2438m, amount); }
// This dialogue handles time requests private void GenerateTimeDialogue() { Boolean isAlwaysAvailable = true; double inputTimeoutInterval = double.MaxValue; // No reason to have a timeout here, since the dialogue is _activated_ upon receiving matching input. int inputMaximumRepetitionCount = int.MaxValue; // No reason to have a repetition count here, for the reason just mentioned. Dialogue timeDialogue = new Dialogue("TimeRequest", isAlwaysAvailable); // Item TR1: User requests the current time InputItem itemTR1 = new InputItem("TR1", null, inputTimeoutInterval, inputMaximumRepetitionCount, "", ""); InputAction inputActionTR1 = new InputAction(timeDialogue.Context, "TR2"); inputActionTR1.PatternList.Add(new Pattern("What time is it")); itemTR1.InputActionList.Add(inputActionTR1); timeDialogue.DialogueItemList.Add(itemTR1); // Item TR2: The agent responds TimeItem itemTR2 = new TimeItem("TR2"); itemTR2.OutputAction = new OutputAction("", ""); // Abandon this context after completing the output itemTR2.OutputAction.PatternList.Add(new Pattern("It is ")); itemTR2.OutputAction.PatternList.Add(new Pattern("The time is ")); timeDialogue.DialogueItemList.Add(itemTR2); agent.DialogueList.Add(timeDialogue); }
public void Test_If_Convertion_From_Default_To_Currency_Returns_Correct_Amount() { var inputItem = new InputItem { CurrencyFrom = new CurrencyItem { IsoName = CurrencyIso.DKK }, CurrencyTo = new CurrencyItem { IsoName = CurrencyIso.EUR }, MoneyAmount = 1 }; var mock = new Mock <IExchangeItemRepository>(); mock.Setup(m => m.GetByCurrencies(It.IsAny <CurrencyItem>(), It.IsAny <CurrencyItem>())) .Returns(new ExchangeItem { Amount = 743.94m }); mock.Setup(m => m.DefaultCurrency) .Returns(new CurrencyItem { IsoName = CurrencyIso.DKK }); var exchangeService = new ExchangeService(mock.Object); var amount = exchangeService.Calculate(inputItem); Assert.AreEqual(0.1344m, amount); }
// 重置数据 private void ResetData() { members = Tool.GetField(data); foreach (FieldInfo item in members) { Log.Debug("字段:{0},值:{1}", item.Name, item.GetValue(data)); ShowMember show_mem = null; foreach (ShowMember mem in MemberList) { if (mem.id == item.Name) { show_mem = mem; break; } } if (show_mem == null) { return; } InputItem input_clone = InputItem.Clone <InputItem>(); input_clone.gameObject.name = item.Name; input_clone.RefreshData(show_mem.name, item.GetValue(data).ToString(), show_mem.read_only); InputList.Add(input_clone); } }
void Up(InputItem item) { item.OnUp?.Invoke(); item.OnTime = 0; item.LastOnTime = 0; item.Down = false; }
// This dialogue greets the user (as a result of face recognition input // from the vision process. private void GenerateGreetingDialogue() { Boolean isAlwaysAvailable = true; double inputTimeoutInterval = double.MaxValue; // No reason to have a timeout here, since the dialogue is _activated_ upon receiving matching input. int inputMaximumRepetitionCount = 1; // Greet the user only once. Dialogue greetingDialogue = new Dialogue("GreetingDialogue", isAlwaysAvailable); // The agent checks if a face has just been detected. // NOTE: This requires, of course, that the Vision process should send the // appropriate message, in this case "FaceDetected". InputItem itemGD1 = new InputItem("GD1", null, inputTimeoutInterval, inputMaximumRepetitionCount, "", ""); itemGD1.AllowVisionInput = true; // Default value = false. Must set to true for this dialogue item. //itemGD1.DoReset = false; // Make sure that the greeting runs only once. InputAction inputActionGD1 = new InputAction(greetingDialogue.Context, "GD2"); inputActionGD1.RequiredSource = AgentConstants.VISION_INPUT_TAG; inputActionGD1.PatternList.Add(new Pattern("FaceDetected")); itemGD1.InputActionList.Add(inputActionGD1); greetingDialogue.DialogueItemList.Add(itemGD1); OutputItem itemGD2 = new OutputItem("GD2", AgentConstants.SPEECH_OUTPUT_TAG, null, false, 1); OutputAction outputActionGD2 = new OutputAction("", ""); outputActionGD2.PatternList.Add(new Pattern("Hello user")); itemGD2.OutputAction = outputActionGD2; greetingDialogue.DialogueItemList.Add(itemGD2); agent.DialogueList.Add(greetingDialogue); }
// This dialogue simply serves to show that the agent is attentive private void GenerateAttentionDialogue() { Boolean isAlwaysAvailable = true; double inputTimeoutInterval = double.MaxValue; // No reason to have a timeout here, since the dialogue is _activated_ upon receiving matching input. int inputMaximumRepetitionCount = int.MaxValue; // No reason to have a repetition count here, for the reason just mentioned. Dialogue attentionDialogue = new Dialogue("AttentionDialogue", isAlwaysAvailable); // Item AD1: The user requests the agent's attention InputItem itemAD1 = new InputItem("AD1", null, inputTimeoutInterval, inputMaximumRepetitionCount, "", ""); InputAction inputActionAD1 = new InputAction(attentionDialogue.Context, "AD2"); inputActionAD1.PatternList.Add(new Pattern("Hazel")); itemAD1.InputActionList.Add(inputActionAD1); attentionDialogue.DialogueItemList.Add(itemAD1); // Item TR2: The agent responds Boolean useVerbatimString = false; OutputItem itemAD2 = new OutputItem("AD2", AgentConstants.SPEECH_OUTPUT_TAG, null, useVerbatimString, 1); itemAD2.OutputAction = new OutputAction("", ""); // Abandon this context after completing the wu1 item itemAD2.OutputAction.PatternList.Add(new Pattern("How can I be of service?")); itemAD2.OutputAction.PatternList.Add(new Pattern("Yes?")); attentionDialogue.DialogueItemList.Add(itemAD2); agent.DialogueList.Add(attentionDialogue); }
private bool IsConvertible(float dt) { bool flag = true; InputItem[] inputs = formula.inputs; for (int i = 0; i < inputs.Length; i++) { InputItem inputItem = inputs[i]; GameObject gameObject = storage.FindFirst(inputItem.tag); if ((UnityEngine.Object)gameObject != (UnityEngine.Object)null) { PrimaryElement component = gameObject.GetComponent <PrimaryElement>(); float num = inputItem.consumptionRate * dt; flag = (flag && component.Mass >= num); } else { flag = false; } if (!flag) { break; } } return(flag); }
public FormItem(InputItem item, FormOptions frmoptins) { Options = item; formOptions = frmoptins; InitializeComponent(); Init(); }
public static dynamic GetTSObject(InputItem dynObject) { if (dynObject is null) { return(null); } return(dynObject.teklaObject); }
private static int CalculateQuantityForX(InputItem item) { double size = item.SummedUpSize; // size in meter StringParserService.ParseType(item.Type, out int a, out int b); // a, b in millimeter double bInMeter = b / 1000.0; return((int)Math.Ceiling(size / bInMeter)); }
public InputBuffer(string but) { bufferList = new InputItem[bufferLength]; for (int i = 0; i < bufferList.Length; i++) { bufferList[i] = new InputItem(); } button = but; }
private static int CalculateQuantityForB(InputItem item) { double size = item.SummedUpSize; // size in meter double unitLength = StringParserService.ParseUnitLength(item.UnitLength); // unitLength in meter StringParserService.ParseType(item.Type, out int a, out int b); // a, b in millimeter double aInMeter = a / 1000.0, bInMeter = b / 1000.0; return((int)Math.Ceiling(size / aInMeter / Math.Floor(bInMeter / unitLength))); }
public void setControlBinding(InputItem inputItem, Control control) { ControlBinding controlJobItem = getControlBinding(control); if (controlJobItem != null) { controlJobItem.inputItem = inputItem; return; } controlBindings.Add(new ControlBinding(inputItem, control)); }
public ControlBinding getControlBinding(InputItem inputItem) { for (int i = 0; i < controlBindings.Count; i++) { if (controlBindings[i].inputItem.inputName == inputItem.inputName) { return(controlBindings[i]); } } return(null); }
public void OpenServerDialog() { var inputs = new System.Collections.Generic.List <InputItem>(); var i = new InputItem(); // ScriptableObject.CreateInstance<InputItem>(); i.InputName = INPUT_SERVERNAME; i.InputType = typeof(string).Name; inputs.Add(i); // inputs.Add(new InputItem() { InputName = INPUT_SERVERNAME, InputType = typeof(string).Name }); InputDialog.instance.OpenDialog(inputs, delegate { OnStartServer(); }); //InputDialogManager.instance.OpenDialog("StartServer", inputs); }
public ActionResult <bool> Post1(InputItem item) { ReInputItems reInput = new ReInputItems(); try { bool status = false; string url = "https://api.smartdove.net/index.php?r=smsApi/SendOneSms"; string responseString = string.Empty; string phone_number = item.MobileNumber; string content = item.MessageContent; string campaign_id = "test123"; SendMbMessage inputFlyFove = new SendMbMessage() { token = flyFoveToken, phone_number = phone_number, content = content, campaign_id = campaign_id }; string postData = string.Format("token={0}&phone_number={1}&content={2}&campaign_id={3}", flyFoveToken, phone_number, content, campaign_id); byte[] bs = Encoding.UTF8.GetBytes(postData); HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; req.ContentLength = bs.Length; //using (Stream reqStream = req.GetRequestStream()) //{ // reqStream.Write(bs, 0, bs.Length); // reqStream.Close(); //} //responseString = GetResponse(req); //var aaaa = "{\"is_error\":true,\"error_code\":0,\"error_message\":\"\",\"sms_id\":\"5\",\"sms_code\":\"1\"}"; var bbb = "aasss"; //var bbb = JsonConvert.DeserializeObject(aaaa); JObject jo = (JObject)JsonConvert.DeserializeObject(responseString); string is_error = jo["is_error"].ToString(); if (!Convert.ToBoolean(is_error)) { status = true; } return(status); } catch (Exception ex) { return(false); } }
private void AddExchangeItem(string inOrOut, string inputItemId) { string[] quantAndElementSet = inputItemId.Split('.'); if (quantAndElementSet.Length != 2) { throw new Exception("No \".\" specified in \"" + inputItemId + "\"" + ", component " + Id); } string elementSetId = quantAndElementSet[0]; string quantId = quantAndElementSet[1]; if (!_quantities.ContainsKey(quantId)) { throw new Exception("Quantity \"" + quantId + "\" does not exist in component " + Id); } if (!_elementSets.ContainsKey(elementSetId)) { throw new Exception("ElementSet \"" + elementSetId + "\" does not exist in component " + Id); } if (inOrOut.Equals("inputitem")) { foreach (EngineInputItem inputItem in EngineInputItems) { if (inputItem.Id.Equals(inputItemId)) { throw new Exception("InputItem \"" + inputItemId + "\" already exists in component " + Id); } } EngineInputItem newInputItem = new InputItem(inputItemId, _quantities[quantId], _elementSets[elementSetId], this); newInputItem.StoreValuesInExchangeItem = true; EngineInputItems.Add(newInputItem); } else if (inOrOut.Equals("outputitem")) { foreach (EngineOutputItem outputItem in EngineOutputItems) { if (outputItem.Id.Equals(inputItemId)) { throw new Exception("OutputItem \"" + inputItemId + "\" already exists in component " + Id); } } EngineOutputItem newOutputItem = new OutputItem(inputItemId, _quantities[quantId], _elementSets[elementSetId], this); newOutputItem.StoreValuesInExchangeItem = true; EngineOutputItems.Add(newOutputItem); } else { throw new Exception("Unknown inOrOutOption: " + inOrOut); } }
/// <summary> /// Erzeugt eine neue Instanz eines CreativeModeScreen-Objekts und initialisiert diese mit einem Knot3Game-Objekt game, sowie einem Knoten knot. /// </summary> public VisualTestsScreen(GameCore game) : base(game) { // die Spielwelt world = new World(screen: this, drawOrder: DisplayLayer.GameWorld, bounds: Bounds.FromLeft(0.60f)); // Hintergrund //SkyCube skyCube = new SkyCube (screen: this, position: Vector3.Zero, distance: world.Camera.MaxPositionDistance + 500); //world.Add (skyCube); // Menü settingsMenu = new Menu(this, DisplayLayer.Overlay + DisplayLayer.Menu); settingsMenu.Bounds = Bounds.FromRight(0.40f).FromBottom(0.9f).FromLeft(0.8f); settingsMenu.Bounds.Padding = new ScreenPoint(this, 0.010f, 0.010f); settingsMenu.RelativeItemHeight = 0.030f; float[] validEdgeCounts = new float[] { 500, 1000, 2000, 3000, 4000, 5000, 7500, 10000, 15000 }; optionEdgeCount = new FloatOption( section: "visualtests", name: "edgecount", defaultValue: validEdgeCounts.At(0), validValues: validEdgeCounts, configFile: Config.Default ) { Verbose = false }; optionEdgeCount.Value = validEdgeCounts.At(0); itemEdgeCount = new ComboBox( screen: this, drawOrder: DisplayLayer.Overlay + DisplayLayer.MenuItem, text: "Edges:" ); itemEdgeCount.AddEntries(optionEdgeCount); itemEdgeCount.ValueChanged += OnEdgeCountChanged; itemDisplayTime = new InputItem( screen: this, drawOrder: DisplayLayer.Overlay + DisplayLayer.MenuItem, text: "Time:", inputText: "" ); itemFPS = new InputItem( screen: this, drawOrder: DisplayLayer.Overlay + DisplayLayer.MenuItem, text: "FPS:", inputText: "" ); OnEdgeCountChanged(null); }
public void Test_If_The_Same_Currencies_Return_Same_Amount() { var expectedAmount = 10; var inputItem = new InputItem { MoneyAmount = expectedAmount }; var mock = new Mock <IExchangeItemRepository>(); var exchangeService = new ExchangeService(mock.Object); var amount = exchangeService.Calculate(inputItem); Assert.AreEqual(expectedAmount, amount); }
public async Task <ViewItem> Update(int id, InputItem item) { var dbItem = await context.items.FirstOrDefaultAsync(x => x.id == id); if (dbItem == null) { throw new KeyNotFoundException(); } dbItem.text = item.text; await context.SaveChangesAsync(); return(mapper.Map <ViewItem>(dbItem)); }
/// <summary> /// 设置一个输入检查对象 /// </summary> /// <param name="control"></param> /// <param name="key">输入对象的值</param> /// <param name="message">错误消息</param> /// <param name="clear">是否清除集合</param> public void SetCheckItem(Control control, string key, string message, bool clear = false) { if (clear) { checkItems.Clear(); } var item = new InputItem { control = control, key = key, message = message }; checkItems.Add(item); }
private void RumModel2() { //输入参数 List <InputItem> input = new List <InputItem>(); //中证 InputItem item1 = new InputItem(); item1.Type = IndexType.ZZSize; item1.CategoryList = new FundAssetCategory[] { FundAssetCategory.Equity, FundAssetCategory.Hybrid }; item1.YieldSpanList = new int[] { 1 }; item1.StepList = new int[] { 21 }; input.Add(item1); this.RunModel(2, input); }
private void RumModel1() { //输入参数 List <InputItem> input = new List <InputItem>(); //申万一级行业 InputItem item1 = new InputItem(); item1.Type = IndexType.SWIndustry; item1.CategoryList = new FundAssetCategory[] { FundAssetCategory.Equity, FundAssetCategory.Hybrid }; item1.YieldSpanList = new int[] { 1 }; item1.StepList = new int[] { 26 }; input.Add(item1); this.RunModel(1, input); }
public async Task <ViewItem> Create(InputItem item) { var newItem = new DbItem() { id = 0, text = item.text, isPerformed = false }; context.items.Add(newItem); await context.SaveChangesAsync(); return(mapper.Map <ViewItem>(newItem)); }
public static int CalculateInputItemQuantity(InputItem inputItem) { switch (inputItem.BorX) { case "b": return(CalculateQuantityForB(inputItem)); case "x": return(CalculateQuantityForX(inputItem)); default: throw new Exception("B or X not selected"); } }
List <ShowMember> MemberList = new List <ShowMember>(); // 要显示的字段 protected override void Initialize() { title = GetControl <Text>(this, "Title"); Ensure = GetControl <Button>(this, "Ensure"); Reset = GetControl <Button>(this, "Reset"); InputItem = NewElement <InputItem>(this, Get(this, "input")); MemberList.Add(new ShowMember("Id", "编号", true)); MemberList.Add(new ShowMember("Name", "名称")); MemberList.Add(new ShowMember("Price", "单价")); MemberList.Add(new ShowMember("Stock", "库存")); MemberList.Add(new ShowMember("Type", "类型", false, 1)); MemberList.Add(new ShowMember("Desc", "描述")); }
public ControlBinding getControlBinding(Control control) { for (int i = 0; i < controlBindings.Count; i++) { if (controlBindings[i].control.index == control.index) { return(controlBindings[i]); } } InputItem inputItem = new InputItem(InputType.Key, control.defaultKey, control.defaultKey.ToString()); controlBindings.Add(new ControlBinding(inputItem, control)); return(controlBindings[controlBindings.Count - 1]); }
public static bool GetValue(InputItem item, IConsoleInInterface consoleIn, IConsoleAdapter consoleOut) { var redirected = consoleIn.InputIsRedirected; var displayPrompt = ConstructPromptText.FromItem(item); do { consoleOut.Wrap(displayPrompt); object value; if (ReadValue.UsingReadLine(item, consoleIn, consoleOut, out value)) { item.Value = value; return true; } } while (!redirected); return false; }
public SequenceItem(InputItem key, float timePressed) { KeyPressed = key; TimePressed = timePressed; }
public string ReadUserXML(XmlTextReader xr) { string tagName = string.Empty; bool inStartElement, inEmptyElement, skipread = false; inEmptyElement = xr.IsEmptyElement; if (!inEmptyElement) { while ((skipread) || (xr.Read())) { inStartElement = xr.IsStartElement(); inEmptyElement = xr.IsEmptyElement; if (skipread) { skipread = false; } else { tagName = xr.LocalName; } if (inStartElement) { // a module start if (tagName == "module") { string name = xr.GetAttribute("name"); if (this.ChildModules.Contains(name)) { ZeusModule module = this.ChildModules[name]; tagName = module.ReadUserXML(xr); skipread = true; } } // a saved item start else if (tagName == "item") { InputItem item = new InputItem(); item.ReadXML(xr); this.UserSavedItems.Add(item); } } else { // if not in a sub module and this is an end module tag, break! if (tagName == "module") { break; } } } } xr.Read(); inStartElement = xr.IsStartElement(); tagName = xr.LocalName; return tagName; }
public string ReadXML(XmlTextReader xr) { string tagName = string.Empty; bool inStartElement, inEmptyElement, skipread = false; this.Name = xr.GetAttribute("name"); this.Description = xr.GetAttribute("description"); string tmp = xr.GetAttribute("defaultSettingsOverride"); if (!string.IsNullOrEmpty(tmp)) { this.DefaultSettingsOverride = Convert.ToBoolean(tmp); } inEmptyElement = xr.IsEmptyElement; if (!inEmptyElement) { while ( (skipread) || (xr.Read()) ) { inStartElement = xr.IsStartElement(); inEmptyElement = xr.IsEmptyElement; if (skipread) { skipread = false; } else { tagName = xr.LocalName; } if (inStartElement) { // a module start if (tagName == "module") { ZeusModule module = new ZeusModule(); tagName = module.ReadXML(xr); skipread = true; module.SetParentModule(this); this.ChildModules.Add(module); } // a saved item start else if (tagName == "item") { InputItem item = new InputItem(); item.ReadXML(xr); this.SavedItems.Add(item); } // a saved object start else if (tagName == "obj") { SavedTemplateInput input = new SavedTemplateInput(); tagName = input.ReadXML(xr); skipread = true; this.SavedObjects.Add(input); } } else { // if not in a sub module and this is an end module tag, break! if (tagName == "module") { break; } } } } xr.Read(); inStartElement = xr.IsStartElement(); tagName = xr.LocalName; return tagName; }
void bot_cycle() { try { typeof(BotCycle).GetField("Id", BindingFlags.NonPublic| BindingFlags.Instance).SetValue(this, Log.Id); lock (id2bot_cycles) { id2bot_cycles[Id] = this; } if (Created != null) Created.Invoke(Id); bot = CustomizationApi.CreateBot(); if (bot == null) throw (new Exception("Could not create Bot instance.")); typeof(Bot).GetField("BotCycle", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(bot, this); Counter processor_errors = new Counter("processor_errors", Properties.General.Default.MaxProcessorErrorNumber); bot.CycleBeginning(); while (run) { current_item = Session.This.GetNext(); if (current_item == null) return; InputItemState state = InputItemState.COMPLETED; try { current_item.PROCESSOR(this); } catch (ThreadAbortException) { return; } catch (Exception e) { if (e is TargetInvocationException) e = e.InnerException; if (e is ProcessorException) { switch (((ProcessorException)e).Type) { case ProcessorExceptionType.ERROR: state = InputItemState.ERROR; break; case ProcessorExceptionType.RESTORE_AS_NEW: state = InputItemState.ERROR_RESTORE_AS_NEW; Session.This.IsItem2Restore = true; break; case ProcessorExceptionType.COMPLETED: break; default: throw new Exception("No case for " + ((ProcessorException)e).Type.ToString()); } } else state = InputItemState.ERROR; Log.Error(e); } current_item.__State = state; if (state == InputItemState.ERROR || state == InputItemState.ERROR_RESTORE_AS_NEW) processor_errors.Increment(); else processor_errors.Reset(); Start(); } bot.CycleFinishing(); } catch (ThreadAbortException) { } catch (Exception e) { LogMessage.Exit(e); } finally { close_thread(Id); } }
// Takes state originating with a KeyDownEvent or TextInputEvent and // schedules it for eventual handling. // // Normally we delay handling until a Background priority event fires. // This has the effect of batching multiple input events when // layout cannot keep up with the input stream. // // However, if any mouse events are pending, we handle the event // immediately, since otherwise we risk the possibility of handling // the events out of order. private static void ScheduleInput(TextEditor This, InputItem item) { if (!This.AcceptsRichContent || IsMouseInputPending(This)) { // We have to do the work now, or we'll get out of synch. TextEditorTyping._FlushPendingInputItems(This); item.Do(); } else { TextEditorThreadLocalStore threadLocalStore; threadLocalStore = TextEditor._ThreadLocalStore; if (threadLocalStore.PendingInputItems == null) { threadLocalStore.PendingInputItems = new ArrayList(1); Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background, new DispatcherOperationCallback(BackgroundInputCallback), This); } threadLocalStore.PendingInputItems.Add(item); } }
/// <summary> /// Gets or creates an item for the given address. /// </summary> private InputItem GetItem(int address, bool isFeedback) { InputItem item; var key = InputItem.GetKey(address, isFeedback); if (!items.TryGetValue(key, out item)) { item = new InputItem(address, isFeedback); items.Add(key, item); // Start update timer itemsModified = true; } return item; }
private void AddSequenceItem(InputItem inputItem) { var newKey = new SequenceItem(inputItem, Time.timeSinceLevelLoad - startedRecodingTime); CurrentKeySequence.Add(newKey); }
private void ChangeDancer(InputItem key) { switch (key) { case InputItem.None: if (player1.isActive) player1.SetSprite(0); else player2.SetSprite(0); break; case InputItem.Up: if (player1.isActive) player1.SetSprite(1); else player2.SetSprite(1); break; case InputItem.Down: if (player1.isActive) player1.SetSprite(2); else player2.SetSprite(2); break; case InputItem.Left: if (player1.isActive) player1.SetSprite(3); else player2.SetSprite(3); break; case InputItem.Right: if (player1.isActive) player1.SetSprite(4); else player2.SetSprite(4); break; case InputItem.A: if (player1.isActive) player1.SetSprite(5); else player2.SetSprite(5); break; case InputItem.B: if (player1.isActive) player1.SetSprite(6); else player2.SetSprite(6); break; case InputItem.X: if (player1.isActive) player1.SetSprite(7); else player2.SetSprite(7); break; case InputItem.Y: if (player1.isActive) player1.SetSprite(8); else player2.SetSprite(8); break; } }
void bot_cycle() { try { try { typeof(BotCycle).GetField("Id", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(this, Log.Id); lock (id2bot_cycles) { id2bot_cycles[Id] = this; } Created?.Invoke(Id); __Starting(); while (run) { current_item = Session.This.GetNext(); if (current_item == null) return; InputItemState state = InputItemState.COMPLETED; try { current_item.__Processor(this); } catch (ThreadAbortException) { Thread.ResetAbort(); return; } catch (Session.FatalException) { throw; } catch (Exception e) { if (e is TargetInvocationException) { e = e.InnerException; //throw; } if (e is ProcessorException) { switch (((ProcessorException)e).Type) { case ProcessorExceptionType.ERROR: state = InputItemState.ERROR; break; //case ProcessorExceptionType.FatalError: case ProcessorExceptionType.RESTORE_AS_NEW: state = InputItemState.ERROR_RESTORE_AS_NEW; Session.This.IsItem2Restore = true; break; case ProcessorExceptionType.COMPLETED: break; default: throw new Exception("No case for " + ((ProcessorException)e).Type.ToString()); } } else { if (TreatExceptionAsFatal) throw new Session.FatalException(e); state = InputItemState.ERROR; } Log.Error(e); } current_item.__State = state; if (state == InputItemState.ERROR || state == InputItemState.ERROR_RESTORE_AS_NEW) Session.This.ProcessorErrors.Increment(); else Session.This.ProcessorErrors.Reset(); Start(); } } catch (ThreadAbortException) { Thread.ResetAbort(); } //catch (Exception e) //{ // throw new Session.FatalException(e); //} finally { __Exiting(); } } catch (Exception e) { Session.__FatalErrorClose(e); } finally { close_thread(Id); } }
internal void WriteInputItem(InputItem item) { if (!Settings.Engine.WriteSessionRestoringLog) return; if (!recorded_InputItem_ids.Contains(item.__Id)) { if (item.__State != InputItemState.NEW) throw new Exception("InputItem has state not NEW but was not recorded."); recorded_InputItem_ids.Add(item.__Id); Dictionary<string, TagItem> tag_item_names2tag_item = item.GetTagItemNames2TagItem(); foreach (KeyValuePair<string, TagItem> n2ti in tag_item_names2tag_item) { if (recorded_TagItem_ids.Contains(n2ti.Value.__Id)) continue; recorded_TagItem_ids.Add(n2ti.Value.__Id); if (!restoring) writeElement(n2ti.Value.GetType().Name, new { id = n2ti.Value.__Id, seed = n2ti.Value.GetSeed() }); } Dictionary<string, object> d = new Dictionary<string, object>(); d["id"] = item.__Id; d["state"] = item.__State; d["seed"] = item.GetSeed(); if (item.__Queue.Name != item.GetType().Name) d["queue"] = item.__Queue.Name; if (item.__ParentItem != null) d["parent_id"] = item.__ParentItem.__Id; foreach (KeyValuePair<string, TagItem> kv in tag_item_names2tag_item) d["id_of_" + kv.Key] = kv.Value.__Id; if (!restoring) writeElement(item.GetType().Name, d); } else if (!restoring) writeElement(item.GetType().Name, new { id = item.__Id, state = item.__State }); }