public SimpleLRUCache(int Capacity) { this.capacity = Capacity; this.list = new LinkedList<ListValueEntry>(); this.lookup = new Dictionary<object, LinkedListNode<ListValueEntry>>(Capacity + 1); this.openNode = new LinkedListNode<ListValueEntry>(new ListValueEntry(null, null)); }
public void AddMethod(MethodParamResult inMethod,Data.Inputs.Interfaces.IEventInput input) { MethodParamPair pair = new MethodParamPair(inMethod, input); _methods.AddLast(pair); if (_current == null) _current = _methods.First; }
public bool MoveNext() { if (personLinkedList == null) { personLinkedList = new LinkedList<Person>(); personLinkedList.AddLast(new Person {personId = 1, personName = "xxx", personLocation = "chennai"} ); personLinkedList.AddLast(new Person {personId = 2, personName = "YYY", personLocation = "chennai"} ); personLinkedList.AddLast(new Person {personId = 3, personName = "ZZZ", personLocation = "chennai"} ); } if (currentObj == null && personLinkedList.First != null) { currentObj = personLinkedList.First; return true; } if ( currentObj.Next!=null) { currentObj = currentObj.Next; return true; } else { return false; } }
public override void Put(object Key, object Value) { if (Get(Key) == null) { this.openNode.Value.ItemKey = Key; this.openNode.Value.ItemValue = Value; this.list.AddFirst(this.openNode); this.lookup.Add(Key, this.openNode); if (this.list.Count > this.capacity) { // last node is to be removed and saved for the next addition to the cache this.openNode = this.list.Last; // remove from list & dictionary this.list.RemoveLast(); this.lookup.Remove(this.openNode.Value.ItemKey); } else { // still filling the cache, create a new open node for the next time this.openNode = new LinkedListNode<ListValueEntry>(new ListValueEntry(null, null)); } } }
public void LoadLevelSelection(string fileAddress,ContentManager content) { levelData.Clear(); BFFileReader reader = new BFFileReader(fileAddress); reader.Open(); string line = null; while((line = reader.ReadLine())!= null) { LevelData levelInfo; string[] param = line.Split(' '); levelInfo.name = param[0]; levelInfo.texture = content.Load<Texture2D>(param[1]); levelData.AddLast(levelInfo); } reader.Close(); data = levelData.First; //load the left and right arrow textures leftArrowTex = content.Load<Texture2D>("Left"); rightArrowTex = content.Load<Texture2D>("Right"); Texture2D exit = content.Load<Texture2D>("Exit"); Texture2D start = content.Load<Texture2D>("Resume"); font = content.Load<SpriteFont>("Font"); selection = new Menu(4, new Rectangle(parent.ScreenWidth/2 -(exit.Width/2),parent.ScreenHeight/2+15,exit.Width,exit.Height),start,exit); time = InputDelay; }
/// <summary> /// Inserts the specified token at the given depth. /// </summary> /// <param name="token">The token.</param> /// <param name="depth">The depth.</param> public void Insert(Token token, int depth) { var index = (int)Hash(token.Lexeme) % PRIME_TABLE_SIZE; var newEntry = new LinkedListNode<Entry> { Value = new Entry { Token = token, Depth = depth } }; // Collision if (this._Table[index] != null) { var possibleDuplicateEntry = this.Lookup(token.Lexeme); // possibleDuplicateEntry is the latest [Lexeme] inserted into the table if (possibleDuplicateEntry != null && possibleDuplicateEntry.Depth == depth) { throw new DuplicateEntryException(token.Lexeme); } newEntry.Next = this._Table[index]; this._Table[index].Previous = newEntry; } this._Table[index] = newEntry; }
public void FinalizeDataHolder() { SpawnEntry = NPCMgr.GetSpawnEntry(SpawnId); if (SpawnEntry == null) { ContentMgr.OnInvalidDBData("{0} had an invalid SpawnId.", this); } else { var added = false; var cur = SpawnEntry.Waypoints.First; while (cur != null) { if (cur.Value.Id > Id) { Node = cur.List.AddBefore(cur, this); added = true; break; } if (cur.Value.Id == Id) { ContentMgr.OnInvalidDBData("Found multiple Waypoints with the same Id {0} for SpawnEntry {1}", Id, SpawnEntry); return; } cur = cur.Next; } if (!added) { SpawnEntry.HasDefaultWaypoints = false; Node = SpawnEntry.Waypoints.AddLast(this); } } }
public void Add(Controller controller) { if (controllerList.Contains(controller)) { if (this.controllerList.Count > 0) { this.controllerList.Remove(controller); } } if (current == null || this.controllerList.Count == 0) { this.controllerList.AddFirst(controller); this.current = controllerList.First; } else { if (this.current.Value != controller) { try { this.current = controllerList.AddAfter(current, controller); } catch (InvalidOperationException ex) { } } } }
public void IntersectionTestsNoSet() { var inputOne = new LinkedListNode<int>(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); for (var currentInt = inputOne; currentInt.Next != null; currentInt = currentInt.Next) { for (var i = 0; i < 10; i++) { var inputTwo = new LinkedListNode<int>(11, 12, 13, 14, 15, 16, 17, 18, 19, 20); var currentRepl = inputTwo; for (var j = 0; j < i; j++, currentRepl = currentRepl.Next) ; if (currentRepl.Last == null) { inputTwo = currentInt; } else { currentRepl.Last.Next = currentInt; } Assert.AreSame(currentInt, Answer.GetIntersectionNoSet(inputOne, inputTwo)); } } }
/// <summary> /// Moves caret to the next tab stop if any. /// </summary> internal bool MoveToNextEmptySlot() { if (_tabSpans == null || (_tabSpans.Count == 0)) return false; LinkedListNode<ITrackingSpan> node; if (null == _lastNavigatedSpan) { node = _tabSpans.First; _lastNavigatedSpan = node; } else if (null != _lastNavigatedSpan.Next) { node = _lastNavigatedSpan.Next; _lastNavigatedSpan = node; } else { _tabSpans = null; _lastNavigatedSpan = null; return false; } Span span = node.Value.GetSpan(_view.TextBuffer.CurrentSnapshot); MoveTab(span); return true; }
public override LinkedListNode<Token> GetLastNode(LinkedList<Token> lToken, LinkedListNode<Token> current) { //Find the partner if(current.Previous.Value.Type == TokenType.ROUND_BRANCE_OPEN) return current.Previous.Value.Partner; return current; }
public override LinkedListNode<Tag> Translate(TranslateContext context, LinkedListNode<Tag> self) { var cellCount = self.AsEnumerable().Skip(1).TakeWhile(x => !(x.Value is NewLineTag)).Count(x => x.Value is TableCellTag); // only start tables if this tag appears on start of line if (cellCount > 0 && self.AsReverseEnumerable().TakeWhile(x => !(x.Value is NewLineTag)).All(x => x.Value is SpaceTag)) { context.Append("<table class='wikitable'>"); var n = self; while (n?.Value is TableCellTag) { if (cellCount != n.AsEnumerable().Skip(1).TakeWhile(x => !(x.Value is NewLineTag)).Count(x => x.Value is TableCellTag)) break; context.Append("<tr>"); LinkedListNode<Tag> nextStop; while ((nextStop = n.Next.FirstNode(x => x.Value is NewLineTag || x.Value is TableCellTag))?.Value is TableCellTag) { context.Append("<td>"); n.Next.TranslateUntilNode(context, nextStop); context.Append("</td>"); n = nextStop; } context.Append("</tr>"); n = n.FirstNode(x => x.Value is NewLineTag)?.Next; // move after nextline } context.Append("</table>"); return n; } context.Append(Text); return self.Next; }
static void Main(string[] args) { Stack<int> s = new Stack<int>(); Queue<int> q = new Queue<int>(); for (int i = 0; i < 10; ++i) { s.Push(i); q.Enqueue(i); } while (s.Count > 0) Console.WriteLine(s.Pop()); //Writes them out in reverse order (9-0). 'Cause FILO while (q.Count > 0) Console.WriteLine(q.Dequeue()); //Writes them in order (FIFO). //New list LinkedList<Student> TwoKay = new LinkedList<Student>(); //New node with a new student LinkedListNode<Student> Current = new LinkedListNode<Student>(new Student("AJ", 123432)); //Take that node and add it to my list. TwoKay.AddFirst(Current); //Add a student without creating a node first TwoKay.AddBefore(TwoKay.First, new Student("Caleb", 123456)); //Show it PrintList(TwoKay); //Change AJ TwoKay.First.Next.Value = new Student("AJ the Mighty", 333); //Print the list again PrintList(TwoKay); //Now, note that the value of current changed, too, because reference. Console.WriteLine(Current.Value); }
public override NodeLinkedList compile(ref LinkedListNode<Token> currentToken) { Token leftToken = currentToken.Value; string leftName = leftToken.value; Token rightToken = currentToken.Next.Next.Value; string rightName = rightToken.value; //Compile left of + //var leftCompiled = CompilerFactory.Instance.CreateCompiledStatement(currentToken); //Temp variable for left if(leftToken.type == TokenType.Number) { leftName = CompiledStatement.getUniqueId(); Compiled.Add(new DirectFunctionCallNode(DirectFunctionCallNode.CONSTANTTORETURN, leftToken)); Compiled.Add(new DirectFunctionCallNode(DirectFunctionCallNode.RETURNTOVARIABLE, leftName)); } //Temp variable for right if(rightToken.type == TokenType.Number) { rightName = CompiledStatement.getUniqueId(); Compiled.Add(new DirectFunctionCallNode(DirectFunctionCallNode.CONSTANTTORETURN, rightToken)); Compiled.Add(new DirectFunctionCallNode(DirectFunctionCallNode.RETURNTOVARIABLE, rightName)); } currentToken = currentToken.Next; if(currentToken.Value.type == TokenType.Multiply) { Compiled.Add(new FunctionCallNode("Multiply", leftName, rightName)); } currentToken = currentToken.Next.Next; return Compiled; }
public override bool TryParse(IDictionary<string, string> properties, LinkedListNode<PathSegment> currentParser, ref LinkedListNode<string> currentSegment) { bool success = currentSegment != null && currentSegment.Value.EqualsNoCase(_path); if (success) currentSegment = currentSegment.Next; return success; }
//----------------------------------------// //----------Methods-----------------------// //----------------------------------------// //create and add a new page to the history given an url //only adds it if it's not the current loaded page public bool addPage(string url) { Page s = new Page(url); if (current.Value != null && !(current.Value.url.Equals(url))) { tabHistory.AddAfter(current, s); current = current.Next; //resets tab history to only contain previous pages from the new current node //removes forward history while(!tabHistory.Last.Equals(current)) { tabHistory.RemoveLast(); } return true; } else { if(current.Value == null) { tabHistory.AddFirst(s); current = tabHistory.First; return true; } } return false; }
private static List<LinkedListNode<Token>> GetUntilPartner(ref LinkedListNode<Token> fromToken) { List<LinkedListNode<Token>> l = new List<LinkedListNode<Token>>(); Token toToken = fromToken.Value.Partner; fromToken = fromToken.Next; while (fromToken.Value != toToken) { l.Add(fromToken); fromToken = fromToken.Next; } return l; //Token toToken = fromToken.Value.Partner; //fromToken = fromToken.Next; //string code = ""; //while (fromToken.Value != toToken) //{ // code += fromToken.Value.Text; // fromToken = fromToken.Next; //} //return code; }
public override DoubleLinkedList Compile(ref LinkedListNode<Token> currentToken) { compiledStatement.AddLast(NodeFactory.Create("FunctionCall", "DeclareVariableType", new List<Token>() { currentToken.Value, currentToken.Next.Value })); currentToken = currentToken.Next; return compiledStatement; }
private float SaltoElemento; //Valor real que separa dos elementos (ancho del boton + DistanciaElementos) #endregion Fields #region Methods public void AbrirContenido(List<GameObject> listaElementos) { foreach (GameObject item in listaElementos) { item.SetActive (true); item.GetComponent<Collider>().enabled = true; Tema esTema = item.GetComponent<Tema> (); Elemento esElemento = item.GetComponent<Elemento> (); if (esTema != null) { SeleccionarItem (item, false); esTema.EnDetalle = true; } else { esElemento.EnDetalle = true; SeleccionarItem(esElemento.gameObject, false); } item.transform.SetParent(ItemPanel.transform, false); RectTransform rt = item.GetComponent<RectTransform> (); rt.sizeDelta = new Vector2 (185, 185); item.transform.localPosition = PosDetalle; item.transform.localRotation = Quaternion.identity; item.transform.localScale = new Vector3 (1.0f, 1.0f, 1.0f); PosDetalle.y -= SaltoElemento; ListaDetalle.AddLast(item); if(ListaDetalle.Count == 1){ DetalleActual = ListaDetalle.First; SeleccionarItem(item, true); } } }
public void loadData(Action<CachedDS> callback, LinkedListNode<CachedDS> next) { var v_cli = new JsonStoreClient { AjaxMng = ajaxMng, BioCode = bioCode }; v_cli.Load(bioParams, (s, a) => { if (a.Response.Success) { if (v_cli.JSMetadata.Fields.Count > 1) { this.metadata = v_cli.JSMetadata; this.data = v_cli.DS; } var eve = this.OnLoaded; if (eve != null) eve(this, new EventArgs()); if (callback != null) callback(this); if (next != null) next.Value.loadData(callback, next.Next); } }); }
/// <summary> /// 获取某个角色的所有直接下级角色,形成链表返回 /// </summary> /// <param name="roleName"></param> /// <returns></returns> public static LinkedList<string> Get_Direct_Child_Roles(string roleName) { LinkedList<string> LinkRole = new LinkedList<string>(); OleDbConnection oleDB = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=dac.accdb"); oleDB.Open(); OleDbCommand cmd = new OleDbCommand(); cmd.Connection = oleDB; cmd.CommandText = "select * from [角色关系信息表] where 父角色名称=" + "'" + roleName.ToLower() + "'";//查找账号是否已经被注册 OleDbDataReader dr = cmd.ExecuteReader(); if (dr.HasRows) { while (dr.Read()) { if (string.Equals(dr["子角色名称"], "(null)") == false)//存在子级角色 { if (LinkRole.Find(dr["子角色名称"].ToString()) == null)//当前链表总不存在该名称时才查找 { LinkedListNode<string> L = new LinkedListNode<string>(dr["子角色名称"].ToString());//将父级角色添加到链表的第一个位置 LinkRole.AddLast(L); } } } } dr.Close(); oleDB.Close(); return LinkRole; }
protected internal void Back() { if (HasNoPreviousUrl()) throw new NoPreviousUrl(); _currentUrl = _currentUrl.Previous; }
public override NodeLinkedList compile(ref LinkedListNode<Token> currentToken) { Token leftToken = currentToken.Value; string leftName = leftToken.value; Token rightToken = currentToken.Next.Next.Value; string rightName = rightToken.value; //Compile left of + //var leftCompiled = CompilerFactory.Instance.CreateCompiledStatement(currentToken); //Temp variable for left if(leftToken.type == VariableType.Number) { leftName = CompiledStatement.getUniqueId(); Compiled.Add(new DirectFunctionCallNode("ConstantToReturn", leftToken.value)); Compiled.Add(new DirectFunctionCallNode("ReturnToVariable", leftName)); } //Temp variable for right if(rightToken.type == VariableType.Number) { rightName = CompiledStatement.getUniqueId(); Compiled.Add(new DirectFunctionCallNode("ConstantToReturn", rightToken.value)); Compiled.Add(new DirectFunctionCallNode("ReturnToVariable", rightName)); } currentToken = currentToken.Next; if(currentToken.Value.type == VariableType.Add){ Compiled.Add(new FunctionCallNode("Add", leftName, rightName)); } currentToken = currentToken.Next.Next; return Compiled; }
public void LoadDataIntoCells(ICell[] cells) { while (TokenNode != null) { switch (TokenNode.Value.Tag) { case Tag.FORMAT_START: { FAPFileVerifier verifier = new FAPFileVerifier(TokenNode); if (verifier.IsAssignmentFormat() == false) { throw new InvalidFAPFileException("The Format type of the given assignment file is not of an \"ASSIGNMENT\" type"); } } break; case Tag.GENERATION_INFORMATION_START: { FAPFileVerifier verifier = new FAPFileVerifier(TokenNode); if (verifier.ValidScenarioID(ScenarioID) == false) { throw new InvalidScenarioIDException("The given assignment file scenario id doesn't match the problem file scenario id"); } } break; case Tag.CELLS_START: FillCells(cells); break; } TokenNode = TokenNode.Next; } }
public bool MoveNext() { if (personLinkedList == null) { personLinkedList = new LinkedList<Person>(); personLinkedList.AddLast(new Person {Id = 1, Name = "Sanjana", Location = "Hyderabad"} ); personLinkedList.AddLast(new Person {Id = 2, Name = "Sumana", Location = "Hyderabad"} ); personLinkedList.AddLast(new Person {Id = 3, Name = "Srinivas", Location = "Hyderabad"} ); } if (currentObj == null && personLinkedList.First != null) { currentObj = personLinkedList.First; return true; } if ( currentObj.Next!=null) { currentObj = currentObj.Next; return true; } else { return false; } }
public unsafe void Write(Stream value) { if (value.Length > _availableLength) throw new ArgumentException("Value is too long."); var buffer = new byte[4096]; var lengthToWrite = value.Length; while (lengthToWrite > 0) { using (var stream = new UnmanagedMemoryStream(_currentPointer.Value.Ptr, _currentPointer.Value.AvailableLength, _currentPointer.Value.AvailableLength, FileAccess.ReadWrite)) { do { var read = value.Read(buffer, 0, Math.Min(buffer.Length, _currentPointer.Value.AvailableLength)); stream.Write(buffer, 0, read); lengthToWrite -= read; _currentPointer.Value.AvailableLength -= read; } while (_currentPointer.Value.AvailableLength > 0 && lengthToWrite > 0); _currentPointer = _currentPointer.Next; } } }
public void MoveNext() { bool final = enumer.MoveNext(); if (final) { if (enumer.Current is Coroutine) { var co = enumer.Current as Coroutine; LinkedListNode<Action> node = new LinkedListNode<Action>(co.MoveNext); stack.AddLast(node); co.MoveNext(); } if (enumer.Current is IEnumerator) { var co = new Coroutine(enumer.Current as IEnumerator); LinkedListNode<Action> node = new LinkedListNode<Action>(co.MoveNext); stack.AddLast(node); co.MoveNext(); } } else { stack.Last.Value -= MoveNext; if (stack.Last.Value == null) { stack.RemoveLast(); Run(); } } }
public override bool isMatch(LinkedListNode<Token> currentToken) { // matched if current is a variable or number, next is a plus en third is also a number or variable. return (currentToken.Value.type == VariableType.Variable || currentToken.Value.type == VariableType.Number) && currentToken.Next.Value.type == VariableType.Add && (currentToken.Next.Next.Value.type == VariableType.Variable || currentToken.Next.Next.Value.type == VariableType.Number); }
public void Add(ICommand state, bool callDo = true) { while (_list.Last != _currentState) { _list.RemoveLast(); } ICommand clonedState = state.ShallowClone(); if (_currentState == null) { _list.AddFirst(clonedState); } else { _list.AddAfter(_currentState, clonedState); } if (callDo) { clonedState.Do(); } if (_list.Count > UndoSteps + 1) { _list.RemoveFirst(); } _currentState = _list.Last; }
protected internal void Forward() { if (HasNoNextUrl()) throw new NoNextUrl(); _currentUrl = _currentUrl.Next; }
public abstract void Swap(LinkedListNode node1, LinkedListNode node2);
protected virtual void OnDisable() { instances.Remove(instancesNode); instancesNode = null; }
public void UnRegister(LinkedListNode <DragDropTarget> registerHandle) { managedTargets.Remove(registerHandle); }
private void OnSceneGUI() { var undoStack = grid.undoStack; var redoStack = grid.redoStack; var current = grid.current; if (!grid.showGrid) { Event eH = Event.current; //Show grid if (eH.type == EventType.KeyDown) { if (eH.keyCode == KeyCode.H) { grid.showGrid = true; } } return; } Event e = Event.current; //get mouse worldposition grid.mouseWorldPosition = GetWorldPosition(e.mousePosition); //Check Mouse Events if (e.type == EventType.MouseDown) { //On Mouse Down store current camera position and set last position to current currentCameraPosition = Camera.current.transform.position; lastCameraPosition = currentCameraPosition; if (e.button == 0) { grid.streets.Add(new List <Vector3> ()); streetNum = grid.streets.Count - 1; if (IsMouseOverGrid(e.mousePosition) && lastCameraPosition == currentCameraPosition) { //no possibility of painting streets if (grid.paintForestArea > -1) { var typeOfCell = GridCreator.CellType.Empty; if (grid.paintForestArea == 0) { typeOfCell = GridCreator.CellType.Forest; } else if (grid.paintForestArea == 1) { typeOfCell = GridCreator.CellType.ConeForest; } else { typeOfCell = GridCreator.CellType.Woods; } PaintCell(typeOfCell); if (grid.streets.Count == streetNum + 1) { grid.streets.RemoveAt(streetNum); } } else if (grid.paintForestArea == -1 && !grid.paintStreets) { var typeOfCell = grid.residential ? GridCreator.CellType.Residential : GridCreator.CellType.SkyScraper; PaintCell(typeOfCell); if (grid.streets.Count == streetNum + 1) { grid.streets.RemoveAt(streetNum); } } } } else if (e.button == 1) { if (IsMouseOverGrid(e.mousePosition) && lastCameraPosition == currentCameraPosition) { PaintCell(GridCreator.CellType.Empty); e.Use(); } } } // If Mouse Drag and left click. Start paint else if (e.type == EventType.MouseDrag && e.type != EventType.KeyDown) { currentCameraPosition = Camera.current.transform.position; //add cell if (e.button == 0) { if (IsMouseOverGrid(e.mousePosition) && lastCameraPosition == currentCameraPosition) { if (grid.paintStreets) { PaintStreet(streetNum); if (grid.streets.Count > grid.selectedStreet.Count) { grid.selectedStreet.Add(false); } } else if (grid.paintForestArea > -1) { var typeOfCell = GridCreator.CellType.Empty; if (grid.paintForestArea == 0) { typeOfCell = GridCreator.CellType.Forest; } else if (grid.paintForestArea == 1) { typeOfCell = GridCreator.CellType.ConeForest; } else { typeOfCell = GridCreator.CellType.Woods; } PaintCell(typeOfCell); if (grid.streets.Count == streetNum + 1) { grid.streets.RemoveAt(streetNum); } } else if (grid.paintForestArea == -1 && !grid.paintStreets) { var typeOfCell = grid.residential ? GridCreator.CellType.Residential : GridCreator.CellType.SkyScraper; PaintCell(typeOfCell); if (grid.streets.Count == streetNum + 1) { grid.streets.RemoveAt(streetNum); } } } } //remove cell else if (e.button == 1) { if (IsMouseOverGrid(e.mousePosition) && lastCameraPosition == currentCameraPosition) { PaintCell(GridCreator.CellType.Empty); e.Use(); } } } else if (e.type == EventType.MouseMove) { //check if mouse pointer is over grid grid.mouseOverGrid = IsMouseOverGrid(e.mousePosition); } else if (e.type == EventType.MouseUp) { if (grid.streets.Count > 0 && grid.streets [grid.streets.Count - 1].Count < 2) { grid.streets.RemoveAt(grid.streets.Count - 1); } if (grid.undoStack.Count == grid.maxStacksize - 1) { grid.undoStack.RemoveFirst(); } grid.undoStack.AddLast(new LinkedListNode <GridCreator.CellType[, ]> (grid.current)); grid.current = (GridCreator.CellType[, ])grid.worldMap.Clone(); currentCameraPosition = Camera.current.transform.position; lastCameraPosition = currentCameraPosition; Cursor.visible = true; } else if (e.type == EventType.Layout) { HandleUtility.AddDefaultControl(GUIUtility.GetControlID(GetHashCode(), FocusType.Passive)); } else if (e.type == EventType.KeyDown) { if (e.keyCode == KeyCode.H) { grid.showGrid = false; } else if (e.keyCode == KeyCode.Z) { LinkedListNode <GridCreator.CellType[, ]> node = undoStack.Last; if (node != null) { if (redoStack.Count == grid.maxStacksize - 1) { redoStack.RemoveFirst(); } redoStack.AddLast(new LinkedListNode <GridCreator.CellType[, ]> (current)); grid.worldMap = (GridCreator.CellType[, ])node.Value.Clone(); current = (GridCreator.CellType[, ])grid.worldMap.Clone(); undoStack.RemoveLast(); } } else if (e.keyCode == KeyCode.Y) { LinkedListNode <GridCreator.CellType[, ]> node = redoStack.Last; if (node != null) { if (undoStack.Count == grid.maxStacksize - 1) { undoStack.RemoveFirst(); } undoStack.AddLast(new LinkedListNode <GridCreator.CellType[, ]> (current)); grid.worldMap = (GridCreator.CellType[, ])node.Value.Clone(); current = (GridCreator.CellType[, ])grid.worldMap.Clone(); redoStack.RemoveLast(); } } } }
internal void Set(LinkedListNode <SimpleQueueCacheItem> item) { Element = item; SequenceToken = item.Value.SequenceToken; }
public KThread RelinquishMutex(long MutexAddress, out int Count) { Count = 0; if (MutexWaiters.First == null) { return(null); } KThread NewMutexOwner = null; LinkedListNode <KThread> CurrentNode = MutexWaiters.First; do { //Skip all threads that are not waiting for this mutex. while (CurrentNode != null && CurrentNode.Value.MutexAddress != MutexAddress) { CurrentNode = CurrentNode.Next; } if (CurrentNode == null) { break; } LinkedListNode <KThread> NextNode = CurrentNode.Next; MutexWaiters.Remove(CurrentNode); CurrentNode.Value.MutexOwner = NewMutexOwner; if (NewMutexOwner != null) { //New owner was already selected, re-insert on new owner list. NewMutexOwner.AddToMutexWaitersList(CurrentNode.Value); } else { //New owner not selected yet, use current thread. NewMutexOwner = CurrentNode.Value; } Count++; CurrentNode = NextNode; }while (CurrentNode != null); if (NewMutexOwner != null) { UpdatePriorityInheritance(); KThread CurrOwner = NewMutexOwner; while (CurrOwner != null) { CurrOwner.UpdatePriorityInheritance(); CurrOwner = CurrOwner.MutexOwner; } } return(NewMutexOwner); }
private void WriteShape() { LinkedList <ProfilePoint> points = new LinkedList <ProfilePoint>(); int colliderTri = 0; points.AddLast(CreatePoint(0, ref colliderTri)); points.AddLast(CreatePoint(1, ref colliderTri)); colliderTri /= 2; Queue <LinkedListNode <ProfilePoint> > process = new Queue <LinkedListNode <ProfilePoint> >(); process.Enqueue(points.First); while (process.Count > 0) { LinkedListNode <ProfilePoint> node = process.Dequeue(); ProfilePoint pM = node.Value; // ReSharper disable once PossibleNullReferenceException ProfilePoint pN = node.Next.Value; float tM = pM.v; float tN = pN.v; // So we want to find the point where the curve is maximally distant from the line between pM and pN // First we need the normal to the line: Vector2 norm = new Vector2(-pN.y + pM.y, pN.dia - pM.dia); // The deviation is: // Dev = B(t) . norm - B(m) . norm (where m = t at point M) // We want to know the maxima, so take the derivative and solve for = 0 // Dev' = B'(t) . norm // = 3(1-t)^2 ((p1.x-p0.x) norm.x + (p1.y-p0.y) norm.y) + 6t(1-t) ((p2.x-p1.x) norm.x + (p2.y-p1.y) norm.y) + 3t^2 ((p3.x-p2.x) norm.x + (p3.y-p2.y) norm.y) = 0 // This is a quadratic, which we can solve directly. float a = ((p1.x - p0.x) * norm.x + (p1.y - p0.y) * norm.y); float b = ((p2.x - p1.x) * norm.x + (p2.y - p1.y) * norm.y); float c = ((p3.x - p2.x) * norm.x + (p3.y - p2.y) * norm.y); // solve a (1-t)^2+2 b (t (1-t))+c t^2 = 0 // t = (-/+ sqrt(b^2-a c)-a+b)/(-a+2 b-c) for a-2 b+c!=0 // t = (2 b-c)/(2 (b-c)) for a = 2 b-c and b-c!=0 List <float> ts = new List <float>(2); //Debug.LogWarning(string.Format("t={0:F3}..{1:F3} perp=({2:F3}, {3:F3}) a={4:F3} b={5:F3} c={6:F3}", tM, tN, norm.x, norm.y, a, b, c)); if (Math.Abs(a - 2 * b + c) < 1e-6f) { if (Math.Abs(b - c) < 1e-6f) { // This is the straight line case, no need to subdivide continue; } float t1 = (2f * b - c) / (2f * (b - c)); //Debug.LogWarning(string.Format("t={0:F3}..{1:F3} -> {2:F3}", tM, tN, t1)); ts.Add(t1); } else { float sqrt = Mathf.Sqrt(b * b - a * c); float t1 = (sqrt - a + b) / (-a + 2 * b - c); float t2 = (-sqrt - a + b) / (-a + 2 * b - c); //Debug.LogWarning(string.Format("t={0:F3}..{1:F3} -> {2:F3} {3:F3} ", tM, tN, t1, t2)); ts.Add(t1); ts.Add(t2); ts.Sort(); } for (int i = 0; i < ts.Count; ++i) { if (ts[i] < tM || ts[i] > tN) { ts.RemoveAt(i--); } } if (ts.Count == 0) { throw new InvalidProgramException("There should be a point maximally distant from the line or the maths is really wrong."); } norm = norm.normalized; float devM = pM.dia * norm.x + pM.y * norm.y; for (int i = 0; i < ts.Count; ++i) { // The difference from the line float devTS = Vector2.Dot(B(ts[i]), norm) - devM; if (Mathf.Abs(devTS) < MaxCircleError) { ts.RemoveAt(i--); } } switch (ts.Count) { case 0: break; case 1: LinkedListNode <ProfilePoint> next = node.List.AddAfter(node, CreatePoint(ts[0], ref colliderTri)); process.Enqueue(node); process.Enqueue(next); break; case 2: LinkedListNode <ProfilePoint> next0 = node.List.AddAfter(node, CreatePoint(ts[0], ref colliderTri)); LinkedListNode <ProfilePoint> next1 = node.List.AddAfter(next0, CreatePoint(ts[1], ref colliderTri)); process.Enqueue(node); process.Enqueue(next0); process.Enqueue(next1); break; } } // Need to figure out the v coords. float sumLengths = 0; float[] cumLengths = new float[points.Count - 1]; LinkedListNode <ProfilePoint> pv = points.First; LinkedListNode <ProfilePoint> nx = pv.Next; for (int i = 0; i < cumLengths.Length; ++i, pv = nx, nx = nx.Next) { // ReSharper disable once PossibleNullReferenceException float dX = nx.Value.dia - pv.Value.dia; float dY = nx.Value.y - pv.Value.y; cumLengths[i] = sumLengths += Mathf.Sqrt(dX * dX + dY * dY); } points.First.Value.v = 0; nx = points.First.Next; for (int i = 0; i < cumLengths.Length; ++i, nx = nx.Next) { // ReSharper disable once PossibleNullReferenceException nx.Value.v = cumLengths[i] / sumLengths; } WriteMeshes(points); }
public abstract LinkedListNode NextOf(LinkedListNode node);
protected virtual void Read(LinkedListNode <SpanishCharComb> comb) { if (st == State.E || st == State.C) { if (st == State.E) { syl.FirstComb = comb; } if (SpanishCharCombHelper.IsSemiVowelComb(comb.Value) || SpanishCharCombHelper.IsYComb(comb.Value)) { st = State.SV; syl.VowelComb = comb; } else if (SpanishCharCombHelper.IsVowelComb(comb.Value)) { st = State.V; syl.VowelComb = comb; } else { st = State.C; } comb.Value.SetSyllable(syl); syl.LastComb = comb; } else if (st == State.V) { if (SpanishCharCombHelper.IsSemiVowelComb(comb.Value)) { syl.LastComb = comb; comb.Value.SetSyllable(syl); } else if (SpanishCharCombHelper.IsYComb(comb.Value)) { st = State.CacheConsonant; cacheLast = comb; comb.Value.SetSyllable(syl); } else if (SpanishCharCombHelper.IsVowelComb(comb.Value)) { syl = new Syllable() { FirstComb = comb, VowelComb = comb, LastComb = comb, Number = number++ }; word.SyllableList.AddLast(syl); comb.Value.SetSyllable(syl); } else { st = State.CacheConsonant; cacheLast = comb; } } else if (st == State.SV) { if (SpanishCharCombHelper.IsSemiVowelComb(comb.Value)) { comb.Value.SetSyllable(syl); syl.VowelComb = comb; syl.LastComb = comb; } else if (SpanishCharCombHelper.IsYComb(comb.Value)) { st = State.CacheConsonant; cacheLast = comb; } else if (SpanishCharCombHelper.IsVowelComb(comb.Value)) { comb.Value.SetSyllable(syl); st = State.V; syl.LastComb = comb; syl.VowelComb = comb; } else { st = State.CacheConsonant; cacheLast = comb; } } else if (st == State.CacheConsonant) { if (SpanishCharCombHelper.IsSemiVowelComb(comb.Value) || SpanishCharCombHelper.IsYComb(comb.Value)) { syl = new Syllable() { FirstComb = cacheLast, VowelComb = comb, LastComb = comb, Number = number++ }; word.SyllableList.AddLast(syl); cacheLast.Value.SetSyllable(syl); comb.Value.SetSyllable(syl); st = State.SV; } else if (SpanishCharCombHelper.IsVowelComb(comb.Value)) { syl = new Syllable() { FirstComb = cacheLast, VowelComb = comb, LastComb = comb, Number = number++ }; word.SyllableList.AddLast(syl); cacheLast.Value.SetSyllable(syl); comb.Value.SetSyllable(syl); st = State.V; } else { syl.LastComb = cacheLast; cacheLast.Value.SetSyllable(syl); syl = new Syllable() { FirstComb = comb, LastComb = comb, Number = number++ }; word.SyllableList.AddLast(syl); comb.Value.SetSyllable(syl); st = State.C; } } if (st != State.CacheConsonant) { cacheLast = null; } }
public abstract void SetValue(LinkedListNode node, double value);
public CacheEntry(string key, TValue value) { Key = key ?? throw new ArgumentNullException(nameof(key)); Rank = new LinkedListNode <string>(key); Value = value; }
/// <summary> /// 回合结束 /// </summary> public void TurnEnd(IShortCodeService shortCodeService) { UserContext uc = GameContext.GetActivationUserContext(), next_uc = null; uc.ComboSwitch = false; List <Card> buffCards = new List <Card>(); buffCards.AddRange(GameContext.DeskCards.GetDeskCardsByIsFirst(uc.IsFirst)); buffCards.AddRange(uc.HandCards); buffCards = buffCards.Where(c => c != null && c.Buffs.Count > 0).ToList(); foreach (Card card in buffCards) { LinkedListNode <IBuffRestore <ICardLocationFilter, IEvent> > buff = card.Buffs.First; MyTurnEndEvent myTurnEndEvent = new MyTurnEndEvent() { Parameter = new ActionParameter() { GameContext = GameContext, PrimaryCard = card } }; while (buff != null && buff.Value.TryCapture(card, myTurnEndEvent)) { buff.Value.Action(new ActionParameter() { GameContext = GameContext, PrimaryCard = card }); // card.Buffs.Remove(buff); buff = buff.Next; } } #region 调整玩家对象 if (GameContext.TurnIndex > 0) { next_uc = GameContext.GetNotActivationUserContext(); var para = new ActionParameter() { GameContext = GameContext, PrimaryCard = GameContext.GetHeroByActivation(next_uc.IsFirst) }; GameContext.EventQueue.AddLast(new MyTurnEndEvent() { Parameter = para }); GameContext.EventQueue.AddLast(new TouchOffComboEvent() { Parameter = para }); foreach (var bio in GameContext.DeskCards.Where(c => c != null)) { BaseBiology biology = bio as BaseBiology; biology.RemainAttackTimes = 0; } //在回合交换前结算 GameContext.QueueSettlement(); _gameCache.SetContext(GameContext); //DataExchangeBll.Instance.AsyncInsert("TurnEnd", "Controler_Base", "", JsonConvert.SerializeObject(GameContext), DataSourceEnum.GameControler); uc.IsActivation = false; next_uc.IsActivation = true; } else { //开局换完牌后,设置先手玩家费用=1 uc.FullPower = 1; uc.Power = 1; } #endregion #region 调整游戏环境对象 GameContext.CurrentTurnRemainingSecond = 60; GameContext.CurrentTurnCode = GameContext.NextTurnCode; GameContext.NextTurnCode = shortCodeService.CreateCode(); GameContext.TurnIndex++; #endregion GameContext.Settlement(); _gameCache.SetContext(GameContext); }
/* * Allows you to play songs depending on which is selected in the list. * If a song is currently playing than it will change to a pause button and allows you to pause it. * */ private void btnPlay_Click(object sender, EventArgs e) { try { if (btnPlay.Text == "Play") { if (lbSongs.SelectedIndex == 0) { WMP.URL = musicList.First().songPath; currentsong = musicList.First(); counter = 0; if (string.IsNullOrWhiteSpace(musicList.First().songName)) { lblSongName.Text = Path.GetFileNameWithoutExtension(musicList.First().songPath); } else { lblSongName.Text = Path.GetFileNameWithoutExtension(musicList.First().songName); } } else { Song searchSong = musicList.First(); for (int i = 0; i < musicList.Count - 1; i++) { LinkedListNode <Song> temp = musicList.Find(searchSong).Next; if (Path.GetFileNameWithoutExtension(temp.Value.songPath).Contains(lbSongs.SelectedItem.ToString())) { counter = i + 1; selectSong(); WMP.URL = temp.Value.songPath; currentsong = temp.Value; if (string.IsNullOrWhiteSpace(temp.Value.songName)) { lblSongName.Text = Path.GetFileNameWithoutExtension(temp.Value.songPath); } else { lblSongName.Text = Path.GetFileNameWithoutExtension(temp.Value.songName); } break; } else { searchSong = temp.Value; } } } selectSong(); btnPlay.Text = "Pause"; } else { WMP.Ctlcontrols.pause(); btnPlay.Text = "Play"; } } catch (Exception ex) { MessageBox.Show("Please add a song to the list \n\nReported Error: " + ex); } }
private void SetCurrentMarble(Marble marble, LinkedListNode <Marble> marbleNode) { CurrentMarbleNode = marbleNode; SetCurrentMarble(marble); }
private List <Data.MML.Part> CreatePartList(Data.Intermediate.Intermediate intermediate, Settings settings, List <Data.Intermediate.NotesStatus> statusList) { int[][] lentable = CreateLengthTable((uint)settings.mmlExpression.TimeBase, settings.noteRest); var partList = new List <Data.MML.Part>(); LinkedListNode <Data.Intermediate.Event.Tempo> tempoNode = intermediate.TempoList.First; foreach (Data.Intermediate.Track track in intermediate.TrackList) { Data.Intermediate.Notes notes = track.NotesList[0]; Data.Intermediate.NotesStatus status = statusList.Find(x => (x.TrackNumber == track.Number && x.NumberInTrack == notes.NumberInTrack)); LinkedListNode <Data.Intermediate.Event.NoteRest> noteNode = notes.NoteList.First; LinkedListNode <Data.Intermediate.Event.Instrument> instNode = track.InstrumentList.First; LinkedListNode <Data.Intermediate.Event.Volume> volNode = track.VolumeList.First; LinkedListNode <Data.Intermediate.Event.Pan> panNode = track.PanList.First; LinkedListNode <Data.Intermediate.Event.KeySignature> ksNode = intermediate.KeySignatureList.First; LinkedListNode <Data.Intermediate.Event.TimeSignature> tsNode = intermediate.TimeSignatureList.First; int barCnt = 1; Key key = Key.CMaj; var barList = new List <Data.MML.Bar>(); for (int i = 1; i <= track.Length.Bar; i++) { var comList = new LinkedList <Data.MML.Command.Command>(); bool prevTied = false; MMLCommandRelation relation = MMLCommandRelation.Clear; while (true) { string addCommandName; if (intermediate.TrackList.IndexOf(track) == 0) { addCommandName = GetEarliestCommandName(ksNode?.Value, tempoNode?.Value, instNode?.Value, volNode?.Value, panNode?.Value, noteNode?.Value, i, prevTied, settings); } else { addCommandName = GetEarliestCommandName(ksNode?.Value, null, instNode?.Value, volNode?.Value, panNode?.Value, noteNode?.Value, i, prevTied, settings); } Data.MML.Command.Command addCommand = null; if (addCommandName == typeof(Data.Intermediate.Event.KeySignature).Name) { key = ksNode.Value.Key; ksNode = ksNode.Next; continue; } else if (addCommandName == typeof(Data.Intermediate.Event.Tempo).Name) { if (comList.Count > 0) { comList.Last.Value.CommandRelation |= MMLCommandRelation.NextControl; } addCommand = CreateTempoInstance(tempoNode.Value.Value, relation); relation |= MMLCommandRelation.PrevControl; tempoNode = tempoNode.Next; } else if (addCommandName == typeof(Data.Intermediate.Event.Instrument).Name) { if (comList.Count > 0) { comList.Last.Value.CommandRelation |= MMLCommandRelation.NextControl; } addCommand = CreateInstrumentInstance(instNode.Value.Value, relation); relation |= MMLCommandRelation.PrevControl; instNode = instNode.Next; } else if (addCommandName == typeof(Data.Intermediate.Event.Volume).Name) { if (comList.Count > 0) { comList.Last.Value.CommandRelation |= MMLCommandRelation.NextControl; } addCommand = CreateVolumeInstance(volNode.Value.Value, relation); relation |= MMLCommandRelation.PrevControl; volNode = volNode.Next; } else if (addCommandName == typeof(Data.Intermediate.Event.Pan).Name) { if (comList.Count > 0) { comList.Last.Value.CommandRelation |= MMLCommandRelation.NextControl; } addCommand = CreatePanInstance(panNode.Value.Value, relation); relation |= MMLCommandRelation.PrevControl; panNode = panNode.Next; } else if (addCommandName == typeof(Data.Intermediate.Event.Note).Name) { if (comList.Count > 0) { comList.Last.Value.CommandRelation &= ~MMLCommandRelation.NextControl; } var note = (Data.Intermediate.Event.Note)noteNode.Value; Data.Intermediate.Position poslen = CalculateLength(note.Start, note.End, intermediate.TimeSignatureList, (int)settings.mmlExpression.TimeBase); List <int> length = ConvertLengthFormat(poslen, lentable); MMLCommandRelation tempRel = relation; if (note.TieFlag) { tempRel |= MMLCommandRelation.TieAfter; relation |= MMLCommandRelation.TieBefore; } else { tempRel &= ~MMLCommandRelation.TieAfter; relation &= ~MMLCommandRelation.TieBefore; } addCommand = CreateNoteInstance((note.KeyNumber / 12 - 1), Tables.NoteNameDictionary[key][note.KeyNumber % 12], length, tempRel); relation &= ~MMLCommandRelation.PrevControl; prevTied = note.TieFlag; noteNode = noteNode.Next; } else if (addCommandName == typeof(Data.Intermediate.Event.Rest).Name) { if (comList.Count > 0) { comList.Last.Value.CommandRelation &= ~MMLCommandRelation.NextControl; } var rest = (Data.Intermediate.Event.Rest)noteNode.Value; Data.Intermediate.Position poslen = CalculateLength(rest.Start, rest.End, intermediate.TimeSignatureList, (int)settings.mmlExpression.TimeBase); List <int> length = ConvertLengthFormat(poslen, lentable); MMLCommandRelation tempRel = relation; if (rest.TieFlag) { tempRel |= MMLCommandRelation.TieAfter; relation |= MMLCommandRelation.TieBefore; } else { tempRel &= ~MMLCommandRelation.TieAfter; relation &= ~MMLCommandRelation.TieBefore; } addCommand = CreateRestInstance(length, tempRel); relation &= ~MMLCommandRelation.PrevControl; prevTied = rest.TieFlag; noteNode = noteNode.Next; } else { break; } comList.AddLast(addCommand); } if (settings.mmlExpression.NewBlockByBar == 1 && i == tsNode.Value.Position.Bar) { barCnt = 1; } else { barCnt++; } uint nextTSBar = (tsNode.Next?.Value.Position.Bar ?? 0); if (i + 1 == nextTSBar) { tsNode = tsNode.Next; } string seperateSign = GetSeperateSign(i, barCnt, nextTSBar, settings.mmlExpression); barList.Add(new Data.MML.Bar(comList, i, seperateSign)); } if (track.Length.Tick == 0) { Data.MML.Bar lastBar = barList.Last(); if (lastBar.CommandList.Count == 0) { barList.Remove(lastBar); } } partList.Add(new Data.MML.Part(barList, status.SoundModule, track.Name)); } return(partList); }
// Selected protected override void DoSelect() { base.DoSelect(); selecteditem = map.SelectedLinedefs.AddLast(this); General.MainWindow.UpdateStatistics(); //mxd }
// Ensure the lock is held when calling this function public void OnRemoved() { this.node = null; }
private void UpdateNotUsedList(float timer, bool limitTick = true) { if (mNotUsedCacheList != null) { // FirstNode 才是最久没有使用的节点 LinkedListNode <AssetCache> node = mNotUsedCacheList.First; int cnt = mNotUsedCacheList.Count; int tick = 0; while (node != null) { if (tick >= cnt) { break; } if (limitTick && (tick >= cCacheTickCount)) { break; } /* * else * if ((!limitTick) && (tick >= cnt)) * break; */ LinkedListNode <AssetCache> delNode = null; LinkedListNode <AssetCache> lastNode = null; LinkedListNode <AssetCache> usedNode = null; // node.value不会为null if (node.Value != null) { if (timer - node.Value.LastUsedTime >= cCacheUnUsedTime && node.Value.IsNotUsed()) { // 删除资源 delNode = node; } else if (node.Value.RefCount > 0) { usedNode = node; } else { lastNode = node; } } node = node.Next; if (delNode != null) { RemoveCache(delNode.Value); //delNode.Value = null; mNotUsedCacheList.Remove(delNode); } else if (usedNode != null) { mNotUsedCacheList.Remove(usedNode); mUsedCacheList.AddLast(usedNode); } else if (lastNode != null) { mNotUsedCacheList.Remove(lastNode); mNotUsedCacheList.AddLast(lastNode); } ++tick; } } }
public void RemoveWaitingThread(LinkedListNode <KThread> Node) { WaitingThreads.Remove(Node); }
private Data.Intermediate.Position CalculateLength ( Data.Intermediate.Position start, Data.Intermediate.Position end, LinkedList <Data.Intermediate.Event.TimeSignature> tsList, int countsPerWholeNote ) { // Search current time signature LinkedListNode <Data.Intermediate.Event.TimeSignature> curTSNode = tsList.First; while (true) { if (curTSNode.Value.Position.CompareTo(start) < 0) { if (curTSNode.Next == null) { break; } else { curTSNode = curTSNode.Next; } } else if (curTSNode.Value.Position.CompareTo(start) == 0) { break; } else { curTSNode = curTSNode.Previous; break; } } // Calculate length data by Position Data.Intermediate.Position len = new Data.Intermediate.Position(0, 0); Data.Intermediate.Position tempStart = start; LinkedListNode <Data.Intermediate.Event.TimeSignature> nextTSNode = curTSNode.Next; while (true) { if (nextTSNode == null) { Data.Intermediate.Position sub = end.Subtract(tempStart, curTSNode.Value.TickPerBar); Data.Intermediate.Position sub2 = Data.Intermediate.Position.ConvertByTicksPerBar(sub, curTSNode.Value.TickPerBar, (uint)countsPerWholeNote); len = len.Add(sub2, (uint)countsPerWholeNote); break; } else { if (nextTSNode.Value.PrevSignedPosition.CompareTo(end) >= 0) { Data.Intermediate.Position sub = end.Subtract(tempStart, curTSNode.Value.TickPerBar); Data.Intermediate.Position sub2 = Data.Intermediate.Position.ConvertByTicksPerBar(sub, curTSNode.Value.TickPerBar, (uint)countsPerWholeNote); len = len.Add(sub2, (uint)countsPerWholeNote); break; } else { Data.Intermediate.Position sub = nextTSNode.Value.PrevSignedPosition.Subtract(tempStart, curTSNode.Value.TickPerBar); Data.Intermediate.Position sub2 = Data.Intermediate.Position.ConvertByTicksPerBar(sub, curTSNode.Value.TickPerBar, (uint)countsPerWholeNote); len = len.Add(sub2, (uint)countsPerWholeNote); tempStart = nextTSNode.Value.Position; curTSNode = curTSNode.Next; nextTSNode = nextTSNode.Next; } } } return(len); }
public string DecodeString(string s) { StringBuilder sb = new StringBuilder(); LinkedList <string> stringStack = new LinkedList <string>(); IList <int> numStack = new List <int>(); int i = 0, n = s.Length; while (i < n) { char c = s[i]; if (Specials.Contains(c)) { if (c == '[') { stringStack.AddLast((string)null); ++i; } else if (c == ']') { LinkedListNode <string> node, tmp = stringStack.Last; int count = 0, num = numStack[numStack.Count - 1]; numStack.RemoveAt(numStack.Count - 1); while (tmp.Value != null) { ++count; tmp = tmp.Previous; } node = tmp.Next; stringStack.Remove(tmp); sb.Clear(); while (node != null) { tmp = node.Next; sb.Append(node.Value); stringStack.Remove(node); node = tmp; } string once = sb.ToString(); sb.Clear(); while (num-- > 0) { sb.Append(once); } stringStack.AddLast(sb.ToString()); sb.Clear(); ++i; } else if (c >= '0' && c <= '9') { int start = i; do { ++i; } while (s[i] >= '0' && s[i] <= '9'); numStack.Add(int.Parse(s.Substring(start, i - start))); } continue; } int p = i; do { ++i; } while (i < n && !Specials.Contains(s[i])); stringStack.AddLast(s.Substring(p, i - p)); } foreach (string word in stringStack) { sb.Append(word); } return(sb.ToString()); }
private void Update() { if (m_LoadSceneInfos.Count > 0) { LinkedListNode <LoadSceneInfo> current = m_LoadSceneInfos.First; while (current != null) { LoadSceneInfo loadSceneInfo = current.Value; if (loadSceneInfo.AsyncOperation.isDone) { if (loadSceneInfo.AsyncOperation.allowSceneActivation) { if (loadSceneInfo.LoadSceneCallbacks.LoadSceneSuccessCallback != null) { loadSceneInfo.LoadSceneCallbacks.LoadSceneSuccessCallback(loadSceneInfo.SceneAssetName, (float)(DateTime.Now - loadSceneInfo.StartTime).TotalSeconds, loadSceneInfo.UserData); } } else { if (loadSceneInfo.LoadSceneCallbacks.LoadSceneFailureCallback != null) { loadSceneInfo.LoadSceneCallbacks.LoadSceneFailureCallback(loadSceneInfo.SceneAssetName, LoadResourceStatus.NotExist, "Can not load this scene from asset database.", loadSceneInfo.UserData); } } LinkedListNode <LoadSceneInfo> next = current.Next; m_LoadSceneInfos.Remove(loadSceneInfo); current = next; } else { if (loadSceneInfo.LoadSceneCallbacks.LoadSceneUpdateCallback != null) { loadSceneInfo.LoadSceneCallbacks.LoadSceneUpdateCallback(loadSceneInfo.SceneAssetName, loadSceneInfo.AsyncOperation.progress, loadSceneInfo.UserData); } current = current.Next; } } } if (m_UnloadSceneInfos.Count > 0) { LinkedListNode <UnloadSceneInfo> current = m_UnloadSceneInfos.First; while (current != null) { UnloadSceneInfo unloadSceneInfo = current.Value; if (unloadSceneInfo.AsyncOperation.isDone) { if (unloadSceneInfo.AsyncOperation.allowSceneActivation) { if (unloadSceneInfo.UnloadSceneCallbacks.UnloadSceneSuccessCallback != null) { unloadSceneInfo.UnloadSceneCallbacks.UnloadSceneSuccessCallback(unloadSceneInfo.SceneAssetName, unloadSceneInfo.UserData); } } else { if (unloadSceneInfo.UnloadSceneCallbacks.UnloadSceneFailureCallback != null) { unloadSceneInfo.UnloadSceneCallbacks.UnloadSceneFailureCallback(unloadSceneInfo.SceneAssetName, unloadSceneInfo.UserData); } } LinkedListNode <UnloadSceneInfo> next = current.Next; m_UnloadSceneInfos.Remove(unloadSceneInfo); current = next; } else { current = current.Next; } } } }
public void MoveLatest() { _current = _translations.Last; }
public static void Main() { // <Snippet2> // Create the link list. string[] words = { "the", "fox", "jumps", "over", "the", "dog" }; LinkedList <string> sentence = new LinkedList <string>(words); Display(sentence, "The linked list values:"); Console.WriteLine("sentence.Contains(\"jumps\") = {0}", sentence.Contains("jumps")); // </Snippet2> // Add the word 'today' to the beginning of the linked list. sentence.AddFirst("today"); Display(sentence, "Test 1: Add 'today' to beginning of the list:"); // <Snippet3> // Move the first node to be the last node. LinkedListNode <string> mark1 = sentence.First; sentence.RemoveFirst(); sentence.AddLast(mark1); // </Snippet3> Display(sentence, "Test 2: Move first node to be last node:"); // Change the last node be 'yesterday'. sentence.RemoveLast(); sentence.AddLast("yesterday"); Display(sentence, "Test 3: Change the last node to 'yesterday':"); // <Snippet4> // Move the last node to be the first node. mark1 = sentence.Last; sentence.RemoveLast(); sentence.AddFirst(mark1); // </Snippet4> Display(sentence, "Test 4: Move last node to be first node:"); // <Snippet12> // Indicate, by using parentheisis, the last occurence of 'the'. sentence.RemoveFirst(); LinkedListNode <string> current = sentence.FindLast("the"); // </Snippet12> IndicateNode(current, "Test 5: Indicate last occurence of 'the':"); // <Snippet5> // Add 'lazy' and 'old' after 'the' (the LinkedListNode named current). sentence.AddAfter(current, "old"); sentence.AddAfter(current, "lazy"); // </Snippet5> IndicateNode(current, "Test 6: Add 'lazy' and 'old' after 'the':"); // <Snippet6> // Indicate 'fox' node. current = sentence.Find("fox"); IndicateNode(current, "Test 7: Indicate the 'fox' node:"); // Add 'quick' and 'brown' before 'fox': sentence.AddBefore(current, "quick"); sentence.AddBefore(current, "brown"); // </Snippet6> IndicateNode(current, "Test 8: Add 'quick' and 'brown' before 'fox':"); // Keep a reference to the current node, 'fox', // and to the previous node in the list. Indicate the 'dog' node. mark1 = current; LinkedListNode <string> mark2 = current.Previous; current = sentence.Find("dog"); IndicateNode(current, "Test 9: Indicate the 'dog' node:"); // The AddBefore method throws an InvalidOperationException // if you try to add a node that already belongs to a list. Console.WriteLine("Test 10: Throw exception by adding node (fox) already in the list:"); try { sentence.AddBefore(current, mark1); } catch (InvalidOperationException ex) { Console.WriteLine("Exception message: {0}", ex.Message); } Console.WriteLine(); // <Snippet7> // Remove the node referred to by mark1, and then add it // before the node referred to by current. // Indicate the node referred to by current. sentence.Remove(mark1); sentence.AddBefore(current, mark1); // </Snippet7> IndicateNode(current, "Test 11: Move a referenced node (fox) before the current node (dog):"); // <Snippet8> // Remove the node referred to by current. sentence.Remove(current); // </Snippet8> IndicateNode(current, "Test 12: Remove current node (dog) and attempt to indicate it:"); // Add the node after the node referred to by mark2. sentence.AddAfter(mark2, current); IndicateNode(current, "Test 13: Add node removed in test 11 after a referenced node (brown):"); // The Remove method finds and removes the // first node that that has the specified value. sentence.Remove("old"); Display(sentence, "Test 14: Remove node that has the value 'old':"); // <Snippet9> // When the linked list is cast to ICollection(Of String), // the Add method adds a node to the end of the list. sentence.RemoveLast(); ICollection <string> icoll = sentence; icoll.Add("rhinoceros"); // </Snippet9> Display(sentence, "Test 15: Remove last node, cast to ICollection, and add 'rhinoceros':"); Console.WriteLine("Test 16: Copy the list to an array:"); //<Snippet10> // Create an array with the same number of // elements as the inked list. string[] sArray = new string[sentence.Count]; sentence.CopyTo(sArray, 0); foreach (string s in sArray) { Console.WriteLine(s); } //</Snippet10> //<Snippet11> // Release all the nodes. sentence.Clear(); Console.WriteLine(); Console.WriteLine("Test 17: Clear linked list. Contains 'jumps' = {0}", sentence.Contains("jumps")); //</Snippet11> Console.ReadLine(); }
public void MovePrevious() { _current = _current.Previous; }
private static DynValue RawGetValue(LinkedListNode <TablePair> linkedListNode) { return((linkedListNode != null) ? linkedListNode.Value.Value : DynValue.Nil); }
public override void Update(GameTime gameTime) { // really just 1? //int framesPassed = (int)Math.Ceiling(gameTime.ElapsedGameTime.TotalSeconds * 60F); int framesPassed = 1; Hitbox.X = (int)Position.X + HitboxXDisplacement; Hitbox.Y = (int)Position.Y + HitboxYDisplacement - (int)PositionZ; PickAggroBox.X = (int)Hitbox.X - 50; PickAggroBox.Y = (int)Hitbox.Y - 50; PickDefendingBox.X = (int)Hitbox.X - 25; PickDefendingBox.Y = (int)Hitbox.Y - 25; if (PassEffectTimer > 0 && (PassEffectTimer -= framesPassed) <= 0) { PassEffectTimer = 0; ShootAttack /= 5; } if (!(CharacterState == CharacterStates.PickState || CharacterState == CharacterStates.StunnedState) && PickHealth < MaxPickHealth) { PickHealthRegenerationTimer -= framesPassed; } if (PickHealthRegenerationTimer <= 0) { PickHealthRegenerationTimer = 60; PickHealth += PickHealthRegenerationRate; if (PickHealth > MaxPickHealth) { PickHealth = MaxPickHealth; } } CheckCollision(); if (CharacterState != CharacterStates.DamagedState) { ProcessIncomingDamage(); } if (FacingLeft) { AttackHitbox.X = (int)(Hitbox.X - AttackRange.X); } else { AttackHitbox.X = (int)Position.X + HitboxXDisplacement + Hitbox.Width; } AttackHitbox.Y = (int)Position.Y + 70; CurrentAnimation.Update(gameTime); switch (CharacterState) { case CharacterStates.ShootState: if (InputManager.GetCharacterActionState(Player.PlayerIndex, CharacterActions.ShootMode) != ActionStates.Held) { CharacterState = CharacterStates.DefaultState; PlayerManager.GetPlayer(Player.PlayerIndex).Target.Visible = false; break; } if (InputManager.GetCharacterActionState(Player.PlayerIndex, CharacterActions.Attack) == ActionStates.Pressed) { PlayerManager.GetPlayer(Player.PlayerIndex).Target.Visible = false; SelectAnimation(ShootingAnimation); CharacterState = CharacterStates.ShootingState; } break; case CharacterStates.ShootingState: StateTimer += framesPassed; if (StateTimer == (ShootingAnimation.NumFrames - 1) * ShootingAnimation.Frequency) { ShootBall shootBall = new ShootBall(Tint); int disp = 150; if (FacingLeft) { disp = 50; } shootBall.SourcePosition = new Vector2(Position.X + disp, Hitbox.Top); shootBall.DestinationPosition = new Vector2(PlayerManager.GetPlayer(Player.PlayerIndex).Target.Hitbox.Center.X, PlayerManager.GetPlayer(Player.PlayerIndex).Target.Hitbox.Center.Y); shootBall.Velocity.X = (shootBall.DestinationPosition.X - shootBall.SourcePosition.X) / 60; shootBall.Velocity.Y = -(shootBall.DestinationPosition.Y - .5F * 60 * 60 / 2 - shootBall.SourcePosition.Y) / 60; shootBall.ReleaseTime = gameTime.TotalGameTime; PlayerManager.EntityManager.Entities.Add(shootBall); } if (StateTimer >= ShootingAnimation.NumFrames * ShootingAnimation.Frequency - 1) { StateTimer = 0; CharacterState = CharacterStates.DefaultState; } break; case CharacterStates.PickState: Defending = false; if (InputManager.GetCharacterActionState(Player.PlayerIndex, CharacterActions.Pick) != ActionStates.Held) { CharacterState = CharacterStates.DefaultState; break; } foreach (Player player in PlayerManager.Players) { if (player.Character.Hitbox.Intersects(PickDefendingBox)) { Defending = true; break; } } break; case CharacterStates.PassState: ProcessMovement(Speed); Position += Velocity; if (Velocity.X < 0) { FacingLeft = true; } else if (Velocity.X > 0) { FacingLeft = false; } if (Velocity.X != 0 || Velocity.Y != 0) { SelectAnimation(RunningAnimation); } else { SelectAnimation(StandingAnimation); } if (InputManager.GetCharacterActionState(Player.PlayerIndex, CharacterActions.Pass) != ActionStates.Held) { CharacterState = CharacterStates.DefaultState; break; } LinkedListNode <Buttons> passButtonNode = InputManager.PassButtons.First; foreach (Player targetPlayer in PlayerManager.Players) { if (targetPlayer.PlayerIndex == Player.PlayerIndex) { continue; } if (targetPlayer.Character.CharacterState == CharacterStates.StunnedState) { passButtonNode = passButtonNode.Next; continue; } if (InputManager.GetButtonActionState(Player.PlayerIndex, passButtonNode.Value) == ActionStates.Pressed) { PassBall ball = new PassBall(Tint); ball.Position = new Vector2(Hitbox.Center.X, Hitbox.Center.Y); ball.SourcePlayer = Player; ball.TargetPlayer = targetPlayer; ball.ReleaseTime = gameTime.TotalGameTime; PlayerManager.EntityManager.Entities.Add(ball); HasBall = false; //SelectAnimation(StandingAnimation); CharacterState = CharacterStates.DefaultState; passButtonNode = passButtonNode.Next; } } break; case CharacterStates.AttackState: StateTimer += framesPassed; if (StateTimer >= AttackingAnimation.NumFrames * AttackingAnimation.Frequency) { StateTimer = 0; CharacterState = CharacterStates.DefaultState; } break; case CharacterStates.DamagedState: StateTimer += framesPassed; //if (StateTimer >= DamagedAnimation.NumFrames * DamagedAnimation.Frequency - 1) if (StateTimer >= 20) { StateTimer = 0; CharacterState = CharacterStates.DefaultState; } break; case CharacterStates.StunnedState: StateTimer += framesPassed; if (StateTimer >= AttackingAnimation.NumFrames * AttackingAnimation.Frequency) { StateTimer = 0; CharacterState = CharacterStates.DefaultState; } break; case CharacterStates.JumpingState: StateTimer += framesPassed; ProcessMovement(Speed); Position.X += Velocity.X; PositionZ += VelocityZ; VelocityZ -= 1F; if (PassEffectTimer > 180 - JumpingAnimation.NumFrames * JumpingAnimation.Frequency * (2 / 3) && InputManager.GetCharacterActionState(Player.PlayerIndex, CharacterActions.ShootMode) == ActionStates.Pressed) { // alley oop or dunk or some crazy thing } if (StateTimer > JumpingAnimation.NumFrames * JumpingAnimation.Frequency) { PositionZ = 0; StateTimer = 0; CharacterState = CharacterStates.DefaultState; } break; case CharacterStates.DeadState: MarkForDelete = true; break; case CharacterStates.DefaultState: ProcessMovement(Speed); Position += Velocity; if (Velocity.X < 0) { FacingLeft = true; } else if (Velocity.X > 0) { FacingLeft = false; } if (Velocity.X != 0 || Velocity.Y != 0) { SelectAnimation(RunningAnimation); } else { SelectAnimation(StandingAnimation); } if (InputManager.GetCharacterActionState(Player.PlayerIndex, CharacterActions.Pass) == ActionStates.Pressed && PlayerManager.Players.Count > 1 && HasBall) { //SelectAnimation(PassAnimation); CharacterState = CharacterStates.PassState; } else if (InputManager.GetCharacterActionState(Player.PlayerIndex, CharacterActions.ShootMode) == ActionStates.Pressed) { CharacterState = CharacterStates.ShootState; SelectAnimation(PrimeShotAnimation); int disp; if (FacingLeft) { disp = -5; } else { disp = 5; } PlayerManager.GetPlayer(Player.PlayerIndex).Target.Position = new Vector2(Hitbox.Center.X - 100 / 2 + disp, Hitbox.Center.Y - 100 / 2); PlayerManager.GetPlayer(Player.PlayerIndex).Target.Visible = true; } else if (InputManager.GetCharacterActionState(Player.PlayerIndex, CharacterActions.Attack) == ActionStates.Pressed) { SelectAnimation(AttackingAnimation); CharacterState = CharacterStates.AttackState; } else if (InputManager.GetCharacterActionState(Player.PlayerIndex, CharacterActions.Pick) == ActionStates.Pressed) { SelectAnimation(PickingAnimation); CharacterState = CharacterStates.PickState; } else if (InputManager.GetCharacterActionState(Player.PlayerIndex, CharacterActions.Jump) == ActionStates.Pressed) { SelectAnimation(JumpingAnimation); VelocityZ = 1F * JumpingAnimation.NumFrames * JumpingAnimation.Frequency / 2; CharacterState = CharacterStates.JumpingState; } break; } }
public void MoveNext() { _current = _current.Next; }
public void calculateslope() { DocumentCollection docCol = Application.DocumentManager; Database localDb = docCol.MdiActiveDocument.Database; Editor editor = docCol.MdiActiveDocument.Editor; Document doc = docCol.MdiActiveDocument; CivilDocument civilDoc = Autodesk.Civil.ApplicationServices.CivilApplication.ActiveDocument; using (Transaction tx = localDb.TransactionManager.StartTransaction()) { HashSet <Polyline> polies = localDb.HashSetOfType <Polyline>(tx); double bandWidth = 0.25; foreach (Polyline pline in polies) { int numOfVert = pline.NumberOfVertices - 1; LinkedList <SegmentProps> segmentsLinked = new LinkedList <SegmentProps>(); for (int i = 0; i < numOfVert; i++) { SegmentProps psp = new SegmentProps(); switch (pline.GetSegmentType(i)) { case SegmentType.Line: LineSegment2d seg = pline.GetLineSegment2dAt(i); Point2d sp = seg.StartPoint; Point2d ep = seg.EndPoint; psp.Slope = (ep.Y - sp.Y) / (ep.X - sp.X); psp.Index = i; psp.Type = pline.GetSegmentType(i); break; case SegmentType.Arc: psp.Type = pline.GetSegmentType(i); break; } segmentsLinked.AddLast(psp); } for (LinkedListNode <SegmentProps> node = segmentsLinked.First; node != null; node = node.Next) { LinkedListNode <SegmentProps> previousNode = node.Previous; if (previousNode == null) { node.Value.ChangeInSlopeFromPrevious = 0; continue; } node.Value.ChangeInSlopeFromPrevious = previousNode.Value.Slope - node.Value.Slope; node.Value.ChangeInChangeFromPrevious = previousNode.Value.ChangeInSlopeFromPrevious - node.Value.ChangeInSlopeFromPrevious; } AcceptedSequences acceptedSequences = new AcceptedSequences(); for (LinkedListNode <SegmentProps> node = segmentsLinked.First; node != null; node = node.Next) { LinkedListNode <SegmentProps> previousNode = node.Previous; if (previousNode == null) { continue; } } #region Output StringBuilder sb = new StringBuilder(); sb.AppendLine("Index;Slope;SlopeDelta;ChangeDelta;ExcelIndex"); for (LinkedListNode <SegmentProps> node = segmentsLinked.First; node != null; node = node.Next) { sb.AppendLine($"{node.Value.Index};{node.Value.Slope};{node.Value.ChangeInSlopeFromPrevious};" + $"{node.Value.ChangeInChangeFromPrevious};{node.Value.Index + 1}"); } string path = @"X:\0371-1158 - Gentofte Fase 4 - Dokumenter\01 Intern\02 Tegninger\08 Net udvikling\Polylines\"; string fileName = $"{pline.Handle.ToString()}.csv"; Utils.ClrFile(path + fileName); Utils.OutputWriter(path + fileName, sb.ToString()); #endregion } tx.Abort(); } }
public LinkedListNode(T data, LinkedListNode <T> next) { this.Data = data; this.Next = next; }