/////////////////////////////////////////////////////////////////////////////// // Function /////////////////////////////////////////////////////////////////////////////// protected override void InitStateMachine() { base.InitStateMachine(); State start = new State("start", stateMachine); start.onEnter += (_from, _to, _event) => { EnterStartState(); }; State running = new State("running", stateMachine); running.onEnter += (_from, _to, _event) => { EnterRuningState(); }; running.onExit += (_from, _to, _event) => { ExitRuningState(); }; running.onAction += (_cur) => { UpdateRunningState(); }; State pause = new State("pause", stateMachine); pause.onEnter += (_from, _to, _event) => { }; pause.onExit += (_from, _to, _event) => { }; State over = new State("over", stateMachine); over.onEnter += (_from, _to, _event) => { EnterOverState(); }; over.onExit += (_from, _to, _event) => { }; start.Add<EventTransition>(running, (int)EventType.Run); start.Add<EventTransition>(over, (int)EventType.Over); running.Add<EventTransition>(over, (int)EventType.Over); running.Add<EventTransition>(pause, (int)EventType.Pause); pause.Add<EventTransition>(running, (int)EventType.Resume); pause.Add<EventTransition>(over, (int)EventType.Over); over.Add<EventTransition>(start, (int)EventType.Restart); }
public void Test_Runner_Jmp_5() { string programStr = " jz label1 " + Environment.NewLine + " mov rax, 10 " + Environment.NewLine + " jmp label2 " + Environment.NewLine + "label1: " + Environment.NewLine + " mov rax, 20 " + Environment.NewLine + "label2: "; Tools tools = this.CreateTools(); var sFlow = new StaticFlow(tools); sFlow.Update(programStr); tools.StateConfig = sFlow.Create_StateConfig(); //var dFlow = Runner.Construct_DynamicFlow_Backward(sFlow, tools); var dFlow = Runner.Construct_DynamicFlow_Forward(sFlow, tools); bool logToDisplay2 = true; tools.Quiet = true;// !logToDisplay2; State state = dFlow.EndState; Assert.IsNotNull(state); if (logToDisplay2) { Console.WriteLine("state:\n" + state); } TestTools.IsTrue(state.IsConsistent); TestTools.AreEqual(Rn.RAX, "00000000_00000000_00000000_00000000_00000000_00000000_00000000_000????0", state); var branch_Condition = dFlow.Get_Branch_Condition(0); if (logToDisplay2) { Console.WriteLine("Branch Condition:" + branch_Condition); } { State state2a = new State(state); state2a.Add(new BranchInfo(branch_Condition, true)); if (logToDisplay2) { Console.WriteLine("state with ZF = true:\n" + state2a); } TestTools.IsTrue(state2a.IsConsistent); TestTools.AreEqual(Rn.RAX, 10, state2a); // TODO why is 10 / 20 reversed? } { State state2b = new State(state); state2b.Add(new BranchInfo(branch_Condition, false)); if (logToDisplay2) { Console.WriteLine("state with ZF = false:\n" + state2b); } TestTools.IsTrue(state2b.IsConsistent); TestTools.AreEqual(Rn.RAX, 20, state2b); } }
protected override bool Validate (AccountTicket user, GroupRequest request, Group model) { if (model.Id > 0) { if (model.EnterpriseId == null) { State.Add("", Messages.EnterpriseId_ReadOnly); return(false); } if (model.EnterpriseId != user.EnterpriseId) { State.Add("", Messages.EnterpriseId_Invalid); return(false); } if (request.EntityVersion != null && request.EntityVersion != model.LastModifiedDate) { State.Add("EntityVersion", Messages.EntityVersion_Conflict); return(false); } } return(base.Validate(user, request, model)); }
/// <summary> /// Adding email address and text to the internal collection. (Example of commenting the methods, etc.) /// </summary> /// <param name="emailAddress">email address</param> /// <param name="text">Text about reasons for breaching</param> /// <returns>Returns email object wrapped in asynchronious operation</returns> public Task <UserEmailState> AddEmailAddress(string emailAddress, string text = "") { UserEmailState userEmail = GetMailAddressFromCollection(emailAddress); switch (userEmail.Message.Status) { case Status.NOT_FOUND: userEmail.Message.Status = Status.OK; userEmail.Message.Description = Constants.PWNED_EMAIL; //userEmail.AddDescription(text); State.Add(userEmail); break; case Status.ERROR: break; case Status.OK: break; case Status.HOST_NOT_SUPPORTED: break; case Status.PWNED: // userEmail.AddDescription(text); break; } return(Task.FromResult(userEmail)); }
private void SearchPlanAndSend() { this.doneSearching = false; this.searchSuccessful = false; if (GetComponent <WorldModelManager>()) { State initialState = GetComponent <WorldModelManager>().GetWorldStateCopy(); if (initialState.ContainsVar("at")) { initialState.Add("checked", initialState.GetStateOfVar("at")[0]); } List <List <string> > goalTasks = new List <List <string> >(); goalTasks.Add(new List <string>(new string[1] { "CollectItems" })); List <string> plan = planner.SolvePlanningProblem(initialState, goalTasks); this.doneSearching = true; if (plan != null) { this.searchSuccessful = SendPlanToAI(plan); } else { Debug.Log("no plan found"); } } }
public Task AggregateRange(string tag, List <ArticleSummary> articles) { Task AggregateRange() { if (!State.ContainsKey(tag)) { State.Add(tag, new List <ArticleSummary>()); } foreach (var article in articles) { var index = State[tag].BinarySearch(article, Comparer <ArticleSummary> .Create((summary, articleSummary) => DateTime.Compare(articleSummary.CreationDate, summary.CreationDate))); if (index >= 0) { continue; } State[tag].Insert(~index, article); } State[tag].RemoveRange(100, int.MaxValue); return(Task.CompletedTask); } CommitChanges(); return(SerialExecutor.AddNext(AggregateRange)); }
private void SearchPlanAndExecutePlan() { doneSearching = false; searchSuccessful = false; if (update) { return; } State initialState = (worldState != null) ? new State(worldState) : null; if (initialState.ContainsVar("at")) { initialState.Add("checked", initialState.GetStateOfVar("at")[0]); } List <List <string> > goalTasks = new List <List <string> >(); goalTasks.Add(new List <string>(new string[1] { "WinGame" })); List <string> plan = planner.SolvePlanningProblem(initialState, goalTasks); this.doneSearching = true; if (plan != null) { ExecutePlan(plan); } }
private static T CloneInternal <T>(this T self, bool deep, Dictionary <ICloneable, ICloneable> cloned) where T : ICloneable { // trace cloned objects to preserve object graph structure and deal with circular refs var clone = Activator.CreateInstance(self.GetType()); cloned.Add(self, (ICloneable)clone); var properties = self.GetPublicState(); var clonedProperties = new Dictionary <string, object>(); foreach (var propertyName in properties.Keys) { var propertyValue = properties[propertyName]; object clonedValue; if (propertyValue is ICloneable && deep) { ICloneable alreadyCloned; if (cloned.TryGetValue((ICloneable)propertyValue, out alreadyCloned)) { clonedValue = alreadyCloned; } else { clonedValue = ((ICloneable)propertyValue).CloneInternal(true, cloned); } } else if (propertyValue is IEnumerable <ICloneable> && deep) { // todo : observable collections etc var clonedList = propertyValue.CloneTypedList(); foreach (var item in (IEnumerable <ICloneable>)propertyValue) { ICloneable alreadyCloned; if (cloned.TryGetValue(item, out alreadyCloned)) { clonedList.Add(alreadyCloned); } else { clonedList.Add(item.CloneInternal(true, cloned)); } } clonedValue = clonedList; } else { clonedValue = propertyValue; } clonedProperties.Add(propertyName, clonedValue); } State.Remove(clone); // ctor might have stored some state already State.Add(clone, clonedProperties); return((T)clone); }
/// <summary> /// 批量评价 /// </summary> public void Judge(bool show_log = false) { var proc = Compiler.CreateJudgeProcess(RunID); if (proc is null) { State.Add(new TestInfo { Result = JudgeResult.CompileError }); if (show_log) { Console.WriteLine("0ms\t0mb\tCompileError"); } return; } /********************************************************** * Old ways: Windows Error Reporting APIs * - Open privilige to JudgeUser for * HKLM\SOFTWARE\Microsoft\Windows\Windows Error Reporting\ExcludedApplications * # WerAddExcludedApplication(pi.FileName, true); * # WerRemoveExcludedApplication(pi.FileName, true); * * New ways: * - Setup the flag JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION **********************************************************/ proc.StartInfo.Environment.Clear(); if (Compiler.GetType().Name == "MinGW") { proc.StartInfo.Environment["PATH"] = Compiler.ToolchainPath[0] + ";"; } else { proc.StartInfo.Environment["PATH"] = ""; } if (Environment.OSVersion.Platform == PlatformID.Win32NT) { // Prefetch proc.Setup(MemoryLimit, TimeLimit, 1, true); proc.Start(); proc.StandardOutput.Close(); proc.WaitForExit(1000); proc.Kill(); } for (int i = 0; i < Judger.Count; i++) { Judge(i); if (show_log) { Console.WriteLine("{0}ms\t{1}mb\t{2}", (int)Math.Round(State[i].Time), (int)Math.Round(State[i].Memory / 1048576.0), State[i].Result.ToString()); } } }
private void GenFirstSS(Resource ts, int value) { State state = new State(); foreach (Resource _ts in this.ResSpace) { if (_ts == ts) { state.Add(_ts, value); } else { state.Add(_ts, 0); } } _ss.Add(state); }
private void Add(int i) { State.Add(i); if (State.Count == NumberOfMessages) { Probe.Tell(new Done(State.ToArray())); } }
protected MessagePipeline(IServiceBus bus) { Guard.AgainstNull(bus, "bus"); _bus = bus; State.Add(bus); }
public void Test_Runner_Jmp_7() { string programStr = " jz label1 " + Environment.NewLine + " mov rax, 10 " + Environment.NewLine + " jmp label2 " + Environment.NewLine + "label1: " + Environment.NewLine + " mov rax, 20 " + Environment.NewLine + "label2: " + Environment.NewLine + " mov rbx, rax " + Environment.NewLine + " jz label3 " + Environment.NewLine + "label3: "; Tools tools = this.CreateTools(); StaticFlow sFlow = new StaticFlow(tools); sFlow.Update(programStr); tools.StateConfig = sFlow.Create_StateConfig(); //var dFlow = Runner.Construct_DynamicFlow_Backward(sFlow, tools); DynamicFlow dFlow = Runner.Construct_DynamicFlow_Forward(sFlow, tools); //DotVisualizer.SaveToDot(sFlow, dFlow, "test1.dot"); State state = dFlow.EndState; Assert.IsNotNull(state); if (logToDisplay) { Console.WriteLine("state:\n" + state); } TestTools.IsTrue(state.IsConsistent); TestTools.AreEqual(Rn.RAX, "00000000_00000000_00000000_00000000_00000000_00000000_00000000_000????0", state); Microsoft.Z3.BoolExpr branch_Condition = dFlow.Get_Branch_Condition(0); { State state2a = new State(state); state2a.Add(new BranchInfo(branch_Condition, true)); if (logToDisplay) { Console.WriteLine("state with ZF = true:\n" + state2a); } TestTools.IsTrue(state2a.IsConsistent); TestTools.AreEqual(Rn.RAX, 10, state2a); } { State state2b = new State(state); state2b.Add(new BranchInfo(branch_Condition, false)); if (logToDisplay) { Console.WriteLine("state with ZF = false:\n" + state2b); } TestTools.IsTrue(state2b.IsConsistent); TestTools.AreEqual(Rn.RAX, 20, state2b); } }
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e) { base.OnNavigatedTo(e); PushNotificationsHelper pHelper = PushNotificationsHelper.Instance; //there is no way to clear the query string. We must use the PhoneApplicationPage to store the ts and check it before opening the notifications screen bool firstLaunch = false; if (!State.ContainsKey("ts")) { firstLaunch = true; State.Add("ts", DateTime.Now); pHelper.checkPushNotificationsUserPermissions(); //Register the deviceURI and send the blogs list to the server, or disable notification and deregister the device from the server. pHelper.resetTileCount(); if (pHelper.pushNotificationsEnabled()) { pHelper.enablePushNotifications(); } else { pHelper.disablePushNotifications(); } } IDictionary <string, string> queryStrings = this.NavigationContext.QueryString; if (queryStrings.ContainsKey("FileId") && queryStrings.ContainsKey("Action") && queryStrings["Action"] == "ShareContent") { // sharing a photo App.MasterViewModel.SharingPhotoToken = queryStrings["FileId"]; } else if ((true == firstLaunch) && queryStrings.ContainsKey("blog_id") && queryStrings.ContainsKey("ts") && queryStrings.ContainsKey("comment_id") && queryStrings.ContainsKey("action") && queryStrings["action"] == "OpenComment") { string blogID = queryStrings["blog_id"]; string commentID = queryStrings["comment_id"]; System.Diagnostics.Debug.WriteLine("IDs received from PN are - blogID:" + blogID + " commentID:" + commentID); pHelper.showCommentScreenFromNotification(blogID, commentID); pHelper.resetLastPushNotificationData(); } else if (true == firstLaunch) { //App was opened by tapping on the Tile. Need to check if there are some notifications pending on the server. if (pHelper.pushNotificationsEnabled() && App.isNetworkAvailable()) { pHelper.loadLastPushNotificationData(OnLoadLastNotificationCompleted); loadingContentProgressBar.Opacity = 1.0; } } while (NavigationService.CanGoBack) { NavigationService.RemoveBackEntry(); } }
protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e) { base.OnNavigatedFrom(e); if (State.ContainsKey("TargetCategory")) { State.Remove("TargetCategory"); } State.Add("TargetCategory", _nextPageCategoryId); }
public Task AddShardKey(string key) { if (!State.Contains(key)) { State.Add(key); } return(WriteStateAsync()); }
private void Apply(TestEvent testEvent) { if (State.Count > 100) { State.Clear(); } State.Add(testEvent.Prop); }
public bool Execute(MsmqUriParser parser, TimeSpan timeout) { State.Clear(); State.Add(parser); State.Add("timeout", timeout); return(base.Execute()); }
private static Matcher Matcher() { // lf | cr lf var start = new State(); var cr = new State(); var done = new State(); var l = Integers.From('l'); var c = Integers.From('c'); start.Add(l, done); start.Add(c, cr); cr.Add(l, done); var nfa = FA.From(start, done); return(new Matcher(nfa.ToDfa().Minimize())); }
private static Matcher MakeMatcher() { // a?[ab] var first = new State(); var last = new State(); var end = new State(); var a1 = Integers.From('a'); var a2 = Integers.From('a', 'b'); first.Add(a1, last); first.Add(last); last.Add(a2, end); var nfa = FA.From(first, end); return new Matcher(nfa.ToDfa().Minimize()); }
public static FA Single(Codepoints terminal) { var start = new State(); var end = new State(); start.Add(terminal, end); return(FA.From(start, end)); }
//private void GenSSOneDemension(Resource ts) //{ // List<IMDPState> templist = new List<IMDPState>(); // State temp2; // foreach (State temp in _ss) // { // temp2 = temp; // for (; temp2[ts] < ts.Capacity;) // { // temp2 = (_ss as StateSpace).PlusOneUnit(temp2, ts); // templist.Add(temp2); // } // } // (_ss as StateSpace).AddRange(templist); //} private IMDPState GenZeroState() { State state = new State(); foreach (Resource ts in this.ResSpace) { state.Add(ts, 0); } return(state as IMDPState); }
//private List<string> messages = new List<string>(); public async Task SendMessage(string message) { Console.WriteLine(DateTime.Now); var messageId = Guid.NewGuid(); var chatMessage = GrainFactory.GetGrain <IChatMessage>(messageId); await chatMessage.UpdateMessage(message); State.Add(messageId); await WriteStateAsync(); }
public bool Execute(Guid messageId, MsmqUriParser parser, TimeSpan timeout) { State.Clear(); State.Add("messageId", messageId); State.Add(parser); State.Add("timeout", timeout); return(base.Execute()); }
//public void GenDS() //{ // _ds.Clear(); // _ds.Add(new Decision()); // IMDPDecisionSpace tempSet = new DecisionSpace(); // for (int i = 0; i < ProSpace.Count; i++) // { // tempSet.Clear(); // foreach (Decision dic in _ds) // { // Decision temp = new Decision(dic); // temp.OpenProductSet.Add(ProSpace[i]); // tempSet.Add(temp); // } // _ds.UnionWith(tempSet); // } //} //public void GenSS() //{ // _ss.Clear(); // IMDPState temp = GenZeroState(); // _ss.Add(temp); // foreach (Resource ts in ResSpace) // { // GenSSOneDemension(ts); // } //} //public void GenSS1()//依赖于InitialState //{ // _ss.Clear(); // State state = new State(); // foreach (Resource ts in (InitialState as State).Keys) // { // state.Add(ts, (InitialState as State)[ts]); // //GenFirstSS(ts, (InitialState as State)[ts]); // } // //_ss.Add(GenZeroState()); // _ss.Add(state); //} //public void GenSS2(ResouceState RecDic) //{ // _ss.Clear(); // State state = new State(); // foreach (Resource ts in RecDic.Keys) // { // state.Add(ts, RecDic[ts]); // //GenFirstSS(ts, RecDic[ts]); // } // //_ss.Add(GenZeroState()); // _ss.Add(state); //} public IMDPState GenInitialState(MetaResouceState s) { State state = new State(); foreach (Resource ts in ResSpace) { state.Add(ts, s.GetRemainNum(ts));//修改正确 } return(state); }
protected override void OnNavigatedFrom(NavigationEventArgs e) { if (State.ContainsKey(NumberKey)) { State[NumberKey] = _currentComicNumber; } else { State.Add(NumberKey, _currentComicNumber); } }
public void ShoudAddReduce() { State <char> state; Reduce <char> action; action = new Reduce <char>("A", true, new MockedTerminalInput('a'), null); state = new State <char>(); state.Add(action); Assert.AreEqual(1, state.ReduceActionCount); Assert.IsTrue(state.ReduceActions.Contains(action)); }
protected override void OnNavigatedFrom(NavigationEventArgs e) { if (State.ContainsKey(panoramaIndexStateKey)) { State.Remove(panoramaIndexStateKey); } State.Add(panoramaIndexStateKey, panorama.SelectedIndex); base.OnNavigatedFrom(e); }
/// <summary> /// Add a new item to the collection. /// </summary> /// <param name="item">Item we want to add.</param> public void Add(T item) { State.Add(item); //Notify the observer we added a new item. Notify(new ObservableArgs() { Content = item.ToString(), Action = "add" }); }
public void ShoudAddShift() { State <char> state; Shift <char> action; action = new Shift <char>(new MockedTerminalInput('a'), 1); state = new State <char>(); state.Add(action); Assert.AreEqual(1, state.ShiftActionCount); Assert.IsTrue(state.ShiftActions.Contains(action)); }
public static void SearchFiles(string directoryName, string stringToSearch) { Console.WriteLine($"Entered in file ${directoryName}"); List <Task> directoriesTasks = new List <Task>(); State myState = new State(); object theLock = new object(); foreach (var enumerateDirectory in Directory.EnumerateDirectories(directoryName)) { directoriesTasks.Add(Task.Run(() => SearchFiles(enumerateDirectory, stringToSearch))); } Parallel.ForEach( Directory.EnumerateFiles(directoryName), () => new State(), (fileName, loopState, partial) => { bool found = false; string line; partial.NumberOfFiles++; using (StreamReader r = new StreamReader(fileName)) { while ((line = r.ReadLine()) != null) { if (line.Contains(stringToSearch)) { found = true; partial.NumberOfLinesWithString++; } } } if (found) { partial.NumberOfFilesWithString++; } return(partial); }, (partial) => { lock (theLock) { myState.Add(partial); } } ); lock (globalState) { globalState.Add(myState); } try { Task.WaitAll(directoriesTasks.ToArray()); } catch (AggregateException ae) { throw ae.InnerExceptions[0]; } }
protected override void InitStateMachine() { base.InitStateMachine(); State start = new State("start", stateMachine); start.onEnter += (_from, _to, _event) => EnterStartState(_from, _to, _event); start.onExit += (_from, _to, _event) => { }; State loading = new State("loading", stateMachine); loading.onEnter += (_from, _to, _event) => { EnterLoadingState(_from, _to, _event); }; loading.onExit += (_from, _to, _event) => { }; State running = new State("running", stateMachine); running.onEnter += (_from, _to, _event) => { curState = GameState.Running; }; running.onExit += (_from, _to, _event) => { }; running.onAction += UpdateRunningState; State quit = new State("quit", stateMachine); quit.onEnter += (_from, _to, _event) => { curState = GameState.Quit; }; start.Add<EventTransition>(loading, (int)EventType.GameLoading); loading.Add<EventTransition>(running, (int)EventType.GameRunning); }
private List<State> SaveStates(Transform container) { var savedStates = new List<State>(); foreach (Transform state in container) { var currentState = new State(); foreach (Transform literal in state) { var script = literal.GetComponent<StateElementComponent>(); if (script != null) currentState.Add(script.LiteralName, script.IsNegated ? 0 : 1); } if (currentState.Count != 0) { savedStates.Add(currentState); } } return savedStates; }
public State GetDefaultState() { var state = new State(); foreach (Transform entity in EntitiesContainer.transform) { var entityElement = entity.GetComponent<EntityElement>(); if (entityElement != null) { foreach (var attrName in entityElement.EntityDefinition.Attributes) { state.Add(Literal.GenerateLiteralName(entityElement.Name, attrName), 0); } } } return state; }
private State[] SetToStates(Set set) { var statesStrings = set.ToString().Split(new string[] { "Set", "(" }, StringSplitOptions.RemoveEmptyEntries); var result = new List<State>(); for (var i = 0; i < statesStrings.Length; i++) { var stStr = statesStrings[i]; var literals = stStr.Replace("(", "").Replace(")", "").Replace(",", "").Split(' '); var newState = new State(); foreach (var literal in literals) { bool isTrue = !literal.Contains("!"); var prop = literal.Replace("!", ""); if (!string.IsNullOrEmpty(prop)) { newState.Add(prop, isTrue.NumVal()); } } if (newState.Keys.Count > 0) { result.Add(newState); } } return result.ToArray(); }
private List<State> GetStates(string statesFilename, string projectName) { var result = new List<State>(); string statesFile = FileReader.ReadFile(Path.Combine(GetRulesDirectory(projectName), statesFilename + rulesExtension)); if (statesFile == null) { return result; } var lines = Regex.Split(statesFile, "\r\n|\r|\n"); if (lines.Length < 2) { return result; // we need first line as a header and second line as an at least one state } var literals = lines[0].Split(new char[] { StatesSeparator }, StringSplitOptions.RemoveEmptyEntries); for (int lineNo = 1; lineNo < lines.Length; lineNo++) { if(lines[lineNo].Length == 0) { continue; } var newState = new State(); var values = lines[lineNo].Split(StatesSeparator); for (int i = 0; i < values.Length; i++) { int val; var parsed = int.TryParse(values[i], out val); if (parsed) { newState.Add(literals[i], val); } } result.Add(newState); } return result; }
public void AddTest() { State state = new State(); state.Add("url1", "label1", 1); Assert.AreEqual(state.Count(), 1); Assert.AreEqual(state.ElementAt(0).Key, 1); Assert.AreEqual(state.ElementAt(0).Value.Label, "label1"); Assert.AreEqual(state.ElementAt(0).Value.Url, "url1"); state.Add("url2", "label2", 2); Assert.AreEqual(state.Count(), 2); Assert.AreEqual(state.ElementAt(1).Key, 2); Assert.AreEqual(state.ElementAt(1).Value.Label, "label2"); Assert.AreEqual(state.ElementAt(1).Value.Url, "url2"); state.Add("url3", "label3", 3); Assert.AreEqual(state.Count(), 3); Assert.AreEqual(state.ElementAt(2).Key, 3); Assert.AreEqual(state.ElementAt(2).Value.Label, "label3"); Assert.AreEqual(state.ElementAt(2).Value.Url, "url3"); state.Add("url2", "label2_new", 4); //back to url2 Assert.AreEqual(state.Count(), 2); Assert.AreEqual(state.ElementAt(1).Key, 4); Assert.AreEqual(state.ElementAt(1).Value.Label, "label2_new"); Assert.AreEqual(state.ElementAt(1).Value.Url, "url2"); state.Add("url6", "label6", 6); Assert.AreEqual(state.Count(), 3); Assert.AreEqual(state.ElementAt(2).Key, 6); Assert.AreEqual(state.ElementAt(2).Value.Label, "label6"); Assert.AreEqual(state.ElementAt(2).Value.Url, "url6"); state.Add("url5", "label5", 5); //insert url5 before url6 Assert.AreEqual(state.Count(), 4); Assert.AreEqual(state.ElementAt(2).Key, 5); Assert.AreEqual(state.ElementAt(2).Value.Label, "label5"); Assert.AreEqual(state.ElementAt(2).Value.Url, "url5"); Assert.AreEqual(state.ElementAt(3).Key, 6); Assert.AreEqual(state.ElementAt(3).Value.Label, "label6"); Assert.AreEqual(state.ElementAt(3).Value.Url, "url6"); state.Add("url5", "label5_new", 5, true); Assert.AreEqual(state.Count(), 4); Assert.AreEqual(state.ElementAt(2).Key, 5); Assert.AreEqual(state.ElementAt(2).Value.Label, "label5"); Assert.AreEqual(state.ElementAt(2).Value.Url, "url5"); state.Add("url5", "label5_new", 5); Assert.AreEqual(state.Count(), 3); Assert.AreEqual(state.ElementAt(2).Key, 5); Assert.AreEqual(state.ElementAt(2).Value.Label, "label5_new"); Assert.AreEqual(state.ElementAt(2).Value.Url, "url5"); state.Add("url2_new", "label2_new", 2); Assert.AreEqual(state.Count(), 4); Assert.AreEqual(state.ElementAt(1).Key, 2); Assert.AreEqual(state.ElementAt(1).Value.Label, "label2_new"); Assert.AreEqual(state.ElementAt(1).Value.Url, "url2_new"); }
private static void Move(State state, string srcName, string dstName) { var srcPosition = state .Where(_ => _.Key.StartsWith(srcName)) .Select(_ => _.Key.Remove(0, 1)) .Select(int.Parse) .Min(); var dstPosition = state .Where(_ => _.Key.StartsWith(dstName)) .Select(_ => _.Key.Remove(0, 1)) .Select(int.Parse) .ToList(); var a = srcName + srcPosition; var dstNormalized = dstPosition.Count == 0 ? 7 : dstPosition.Min() - 1; var b = dstNormalized == 0 ? "" : dstName + dstNormalized; state.Add(b, state[a]); state.Remove(a); }