// Implement the data structure linked list. public static void Main() { var linkedList = new LinkedList<string>(); linkedList.AddFirst("first"); linkedList.AddLast("second"); Console.WriteLine(string.Join(", ", linkedList)); linkedList.Clear(); linkedList.AddLast("second"); linkedList.AddFirst("first"); Console.WriteLine(string.Join(", ", linkedList)); string value = "first"; Console.WriteLine("List contains \"{0}\": {1}", value, linkedList.Contains(value)); Console.WriteLine("List contains {0} item(s)", linkedList.Count); var item = linkedList.Find("second"); Console.WriteLine(item); linkedList.Remove("first"); Console.WriteLine(string.Join(", ", linkedList)); linkedList.Remove("second"); Console.WriteLine("List contains {0} item(s): {1}", linkedList.Count, string.Join(", ", linkedList)); linkedList.AddFirst("second"); linkedList.AddFirst("first"); linkedList.AddLast("third"); Console.WriteLine(string.Join(", ", linkedList)); linkedList.Remove("second"); Console.WriteLine(string.Join(", ", linkedList)); }
private void GetTests() { methods = methods ?? new LinkedList<MethodInfo>(); methods.Clear(); status = status ?? new Dictionary<MethodInfo, Status>(); status.Clear(); toggleGroup = toggleGroup ?? new Dictionary<string, bool>(); var bindingFlags = BindingFlags.Public; bindingFlags |= BindingFlags.Static; bindingFlags |= BindingFlags.DeclaredOnly; Type[] typelist = GetTypesInNamespace("Exodrifter.ExpressionParser.Test"); for (int i = 0; i < typelist.Length; i++) { foreach (var method in typelist[i].GetMethods(bindingFlags)) { if (0 == method.GetParameters().Length) { methods.AddLast(method); status.Add(method, Status.UNKNOWN); if (!toggleGroup.ContainsKey(method.DeclaringType.Name)) { toggleGroup[method.DeclaringType.Name] = false; } } } } }
/// <summary> /// a constructor. /// </summary> /// <param name="fieldTermStack">FieldTermStack object</param> /// <param name="fieldQuery">FieldQuery object</param> /// <param name="phraseLimit">maximum size of phraseList</param> public FieldPhraseList(FieldTermStack fieldTermStack, FieldQuery fieldQuery, int phraseLimit) { String field = fieldTermStack.FieldName; LinkedList<TermInfo> phraseCandidate = new LinkedList<TermInfo>(); QueryPhraseMap currMap = null; QueryPhraseMap nextMap = null; while (!fieldTermStack.IsEmpty() && (phraseList.Count < phraseLimit) ) { phraseCandidate.Clear(); TermInfo ti = fieldTermStack.Pop(); currMap = fieldQuery.GetFieldTermMap(field, ti.Text); // if not found, discard top TermInfo from stack, then try next element if (currMap == null) continue; // if found, search the longest phrase phraseCandidate.AddLast(ti); while (true) { ti = fieldTermStack.Pop(); nextMap = null; if (ti != null) nextMap = currMap.GetTermMap(ti.Text); if (ti == null || nextMap == null) { if (ti != null) fieldTermStack.Push(ti); if (currMap.IsValidTermOrPhrase(new List<TermInfo>(phraseCandidate))) { AddIfNoOverlap(new WeightedPhraseInfo(phraseCandidate, currMap.Boost, currMap.TermOrPhraseNumber)); } else { while (phraseCandidate.Count > 1) { TermInfo last = phraseCandidate.Last.Value; phraseCandidate.RemoveLast(); fieldTermStack.Push(last); currMap = fieldQuery.SearchPhrase(field, new List<TermInfo>(phraseCandidate)); if (currMap != null) { AddIfNoOverlap(new WeightedPhraseInfo(phraseCandidate, currMap.Boost, currMap.TermOrPhraseNumber)); break; } } } break; } else { phraseCandidate.AddLast(ti); currMap = nextMap; } } } }
public RezultatKomanda addMaterijal(string Naslov, string Opis, string DodadenOd, string Slika, string Pateka,String Type) { RezultatKomanda rezultat = new RezultatKomanda(false); try { parametriKomanda = new LinkedList<SqlParameter>(); parametriKomanda.Clear(); //Parametar za @Naslov = Naslov //Input Parametar SqlParam = new SqlParameter("@Naslov", SqlDbType.NVarChar); SqlParam.Value = Naslov; parametriKomanda.AddLast(SqlParam); //Parametar za @Opis = Opis //Input Parametar SqlParam = new SqlParameter("@Opis", SqlDbType.NVarChar); SqlParam.Value = Opis; parametriKomanda.AddLast(SqlParam); //Parametar za @DodadenOd = DodadenOd //Input Parametar SqlParam = new SqlParameter("@DodadenOd", SqlDbType.VarChar); SqlParam.Value = DodadenOd; parametriKomanda.AddLast(SqlParam); //Parametar za @Slika = Slika //Input Parametar SqlParam = new SqlParameter("@Slika", SqlDbType.NVarChar); SqlParam.Value = Slika ; parametriKomanda.AddLast(SqlParam); //Parametar za @Pateka = Pateka //Input Parametar SqlParam = new SqlParameter("@Pateka", SqlDbType.NVarChar); SqlParam.Value = Pateka; parametriKomanda.AddLast(SqlParam); //Parametar za @Type = Type //Input Parametar SqlParam = new SqlParameter("@Type", SqlDbType.NVarChar); SqlParam.Value = Type; parametriKomanda.AddLast(SqlParam); BazaDB.ExecuteScalar(parametriKomanda.ToArray(), "sp_ZacuvajMaterijal", sqlCn: null); rezultat.Rezultat = RezultatKomandaEnum.Uspeh; return rezultat; } catch (Exception ex) { rezultat.Rezultat = RezultatKomandaEnum.Neuspeh; rezultat.Pricina = ex.Message; return rezultat; } }
// Looks like I ended up with the typical sliding-window deque solution. Here's an example for k = 3: // 1 3 2 8 4 7 2, initialize left looking dominators like {3, 2}. These dominate everything to their // left until a bigger dominator. Leftmost dominator goes to max value for subarray. // [1 3 2] 8 4 7 2, {3, 2} // 1 [3 2 8] 4 7 2, {8}, lost 1 but it wasn't a dominator, gained 8 and it dominates everything, kills 3 and 2. // 1 3 [2 8 4] 7 2, {8, 4}, lost 3 but wasn't a dominator, gained 4 which dominates til 8. // 1 3 2 [8 4 7] 2, {8, 7}, lost 2 but wasn't a dominator, gained 7 which kills 4 and domaintes til 8. // 1 3 2 8 [4 7 2], {7, 2}, lost 8 so pop it off, gained 2 which dominates til 7. // I say dominate because if you're an element and there's an element in your sliding window to your right // that's greater than you (dominating you), you're never going to be the max for any of your remaining subarrays. // That dominating element to your right will always be there until you're kicked out of the window. // When a big number slides in it can dominate all of the dominators and be the only one left; the existing // dominators would be to its left so they'd never be able to be the max for any remaining subarrays. // We have to keep track of the dominators to the right of other, larger dominators because those other dominators // are going to slide out before the ones to their right, and we need to know where to pick up from. It should be // clear the dominators are always sorted, descending, from left to right. Dominators could be thought of recursively // as greatest element in subarray, followed by greatest element in subarray to that element's right, etc. O(n) // because we add or remove an array element from the dominators at most one time. public static int[] Solve(int[] array, int k) { if (k == array.Length) return new[] { array.Max() }; if (k == 1) return array; // Initializing the dominators for the first subarray. Gotta have the rightmost, then the next to the left that's // larger than (or equal to) it, and so on. Equal to because we need the next one after an equal one is popped off. var leftLookingDominators = new LinkedList<int>(); leftLookingDominators.AddFirst(array[k - 1]); for (int i = k - 2; i >= 0; --i) { if (array[i] >= leftLookingDominators.Last.Value) { leftLookingDominators.AddLast(array[i]); } } // Each iteration we're looking at the next subarray, slid over from the previous. We lose an element during the // slide which might've been the leftmost dominator (the leftmost dominator is the only one that can be lost). We // gain an element which might start dominating everything, or just some dominators til hitting some dominator to its // left that's greater than it, or just itself. Don't have to worry about dominators ever becoming empty, because // base case handled above. Even for k = 2, if there's only 1 dominator going in to the next iteration, it must be // the rightmost element of the previous subarray, so it's not going to get popped off the end until the next next iteration. int subarrayCount = array.Length - k + 1; int[] subarrayMaximums = new int[subarrayCount]; subarrayMaximums[0] = leftLookingDominators.Last.Value; for (int i = 1, j = k; i < subarrayCount; ++i, ++j) { int lostLeftValue = array[i - 1]; int gainedRightValue = array[j]; if (lostLeftValue == leftLookingDominators.Last.Value) { leftLookingDominators.RemoveLast(); } if (gainedRightValue > leftLookingDominators.Last.Value) { leftLookingDominators.Clear(); leftLookingDominators.AddFirst(gainedRightValue); } else { while (gainedRightValue > leftLookingDominators.First.Value) { leftLookingDominators.RemoveFirst(); } leftLookingDominators.AddFirst(gainedRightValue); } subarrayMaximums[i] = leftLookingDominators.Last.Value; } return subarrayMaximums; }
public virtual void Clear() { _objects?.Clear(); _trackedTypes?.Clear(); Serializer = null; _buffer = null; _nextObjectId = 0; }
/// <summary> /// Disposable pattern /// </summary> /// <param name="disposing"></param> protected virtual void Dispose(bool disposing) { ReleaseUnmanagedResources(); if (disposing) { _udpClient?.Dispose(); _mutex?.Dispose(); _receivedPackets?.Clear(); } }
public Boolean TryCalculateFanMotif (IGraph oGraph, BackgroundWorker oBackgroundWorker, out ICollection<Motif> oMotifs) { Debug.Assert(oGraph != null); oMotifs = null; LinkedList<Motif> oFanMotifs = new LinkedList<Motif>(); LinkedList<IVertex> oLeaves = new LinkedList<IVertex>(); IVertexCollection oVertices = oGraph.Vertices; Int32 iVertices = oVertices.Count; Int32 iCalculationsSoFar = 0; foreach (IVertex oVertex in oVertices) { if ((iCalculationsSoFar % 100 == 0) && !ReportProgressAndCheckCancellationPending(iCalculationsSoFar, iVertices, oBackgroundWorker) ) { return (false); } ICollection<IVertex> oAdjacentVertices = oVertex.AdjacentVertices; if (oAdjacentVertices.Count >= 2) { foreach (IVertex oAdjacentVertex in oAdjacentVertices) { if (oAdjacentVertex.AdjacentVertices.Count == 1) { oLeaves.AddLast(oAdjacentVertex); } } if (oLeaves.Count >= 2) { oFanMotifs.AddLast( new FanMotif(oVertex, oLeaves.ToArray())); } oLeaves.Clear(); } iCalculationsSoFar++; } // Set the ArcScale property on each FanMotif object. SetFanMotifArcScale(oFanMotifs); oMotifs = oFanMotifs; return (true); }
public RezultatKomanda addUstanova(string Ime, string Adresa, string WebStrana, int Institucija_ID) { RezultatKomanda rezultat = new RezultatKomanda(false); dsKomanda = null; try { parametriKomanda = new LinkedList<SqlParameter>(); parametriKomanda.Clear(); //Parametar za @Ime = Ime //Input Parametar SqlParam = new SqlParameter("@Ime", SqlDbType.NVarChar); SqlParam.Value = Ime; parametriKomanda.AddLast(SqlParam); //Parametar za @Adresa = Adresa //Input Parametar SqlParam = new SqlParameter("@Adresa", SqlDbType.NVarChar); SqlParam.Value = Adresa; parametriKomanda.AddLast(SqlParam); //Parametar za @WebAdresa = WebAdresa //Input Parametar SqlParam = new SqlParameter("@WebStrana", SqlDbType.NVarChar); SqlParam.Value = WebStrana; parametriKomanda.AddLast(SqlParam); //Parametar za @Institucija_ID = Institucija_ID //Input Parametar SqlParam = new SqlParameter("@Institucija_ID", SqlDbType.Int); SqlParam.Value = Institucija_ID; parametriKomanda.AddLast(SqlParam); //Parametar za @Aktiven = D //Input Parametar SqlParam = new SqlParameter("@Aktiven", SqlDbType.Char); SqlParam.Value = 'D'; parametriKomanda.AddLast(SqlParam); BazaDB.ExecuteScalar(parametriKomanda.ToArray(), "sp_ZacuvajUstanova", sqlCn: null); rezultat.Rezultat = RezultatKomandaEnum.Uspeh; return rezultat; } catch (Exception ex) { rezultat.Rezultat = RezultatKomandaEnum.Neuspeh; rezultat.Pricina = ex.Message; return rezultat; } }
public override void SetPolygons() { base.SetPolygons(); LinkedList<float> tempList = new LinkedList<float>(); foreach ( Polygon poly in filledPolygons ) { for ( int i = 2 ; i < poly.Points.Count ; ++i ) { tempList.AddLast( poly.Points[ 0 ].X ); tempList.AddLast( poly.Points[ 0 ].Y ); tempList.AddLast( 1 ); tempList.AddLast( 1 ); tempList.AddLast( poly.Colors[ 0 ].X ); tempList.AddLast( poly.Colors[ 0 ].Y ); tempList.AddLast( poly.Colors[ 0 ].Z ); tempList.AddLast( poly.Colors[ 0 ].W ); tempList.AddLast( poly.Points[ i - 1 ].X ); tempList.AddLast( poly.Points[ i - 1 ].Y ); tempList.AddLast( 1 ); tempList.AddLast( 1 ); tempList.AddLast( poly.Colors[ i - 1 ].X ); tempList.AddLast( poly.Colors[ i - 1 ].Y ); tempList.AddLast( poly.Colors[ i - 1 ].Z ); tempList.AddLast( poly.Colors[ i - 1 ].W ); tempList.AddLast( poly.Points[ i ].X ); tempList.AddLast( poly.Points[ i ].Y ); tempList.AddLast( 1 ); tempList.AddLast( 1 ); tempList.AddLast( poly.Colors[ i ].X ); tempList.AddLast( poly.Colors[ i ].Y ); tempList.AddLast( poly.Colors[ i ].Z ); tempList.AddLast( poly.Colors[ i ].W ); } } fillArray = tempList.ToArray(); tempList.Clear(); foreach ( Polygon poly in outlinePolygons ) { for ( int i = 0 ; i < poly.Points.Count ; ++i ) { tempList.AddLast( poly.Points[ i ].X ); tempList.AddLast( poly.Points[ i ].Y ); tempList.AddLast( 1 ); tempList.AddLast( 1 ); tempList.AddLast( poly.Colors[ i ].X ); tempList.AddLast( poly.Colors[ i ].Y ); tempList.AddLast( poly.Colors[ i ].Z ); tempList.AddLast( poly.Colors[ i ].W ); } } outlineArray = tempList.ToArray(); GenerateBuffers(); }
public static LinkedList<String> NetworkToConnections(double[,] matrix, bool[] rev, String[] metabolite_names = null, String[] reaction_names = null) { if (metabolite_names == null) { metabolite_names = new String[matrix.Length / rev.Length]; for (int i = 0; i < matrix.Length / rev.Length; ++i) metabolite_names[i] = "M_" + (i + 1); } if (reaction_names == null) { reaction_names = new String[rev.Length]; for (int i = 0; i < rev.Length; ++i) reaction_names[i] = "R_" + (i + 1); } LinkedList<String> res = new LinkedList<string>(); res.AddFirst("digraph Network {"); res.AddLast("\tnodesep=0.7;"); res.AddLast("\trankdir=LR;"); int n = rev.Length, m = matrix.Length / n; for (int i = 0; i < m; ++i) res.AddLast(String.Format("\t{0}[label=\"{1}\"];", i + 1, metabolite_names[i])); LinkedList<int> produced = new LinkedList<int>(), consumed = new LinkedList<int>(); for (int j = 0; j < n; ++j) { produced.Clear(); consumed.Clear(); for (int i = 0; i < m; ++i) { if (matrix[i, j] < 0) consumed.AddLast(i); if (matrix[i, j] > 0) produced.AddLast(i); } foreach (int m1 in produced) foreach (int m2 in consumed) if (rev[j]) res.AddLast(String.Format("{0}->{1}[dir=both]", m1 + 1, m2 + 1)); else res.AddLast(String.Format("{0}->{1}", m1 + 1, m2 + 1)); } res.AddLast("}"); return res; }
private void EndPointerTool() { if (lastFocusObject != null) { lastFocusObject.SetState(IdleState.GetState()); lastFocusObject = null; } SetPreparedState(IdleState.GetState()); prepareComposite?.Clear(); OnCompositeNotReady?.Invoke(); propertiesPanel.Hide(); }
public virtual void Clear() { m_waitQueue?.Clear(); if (m_loadingMap != null) { foreach (var handler in m_loadingMap.Values) { StopLoad(handler); } m_loadingMap.Clear(); } }
private List<FriendshipLink> CreateFriendships(List<Person> people) { List<FriendshipLink> friendships = new List<FriendshipLink>(); Person p1, p2; int totalCount = people.Count; int missing; LinkedList<DistanceNode> list = new LinkedList<DistanceNode>(); for (int i = 0; i < totalCount; i++) { p1 = people[i]; missing = Mathf.Clamp((int) Utils.GetRandomValue(avgConnections, avgConnections*1.2f, 3), 1, 100) - p1.FriendCount; if (missing <= 0) continue; list.Clear(); for (int j = i+1; j < totalCount; j++) { p2 = people[j]; if (p2.FriendCount < avgConnections * 1.2) list.AddLast(new DistanceNode(p1, p2)); } while (list.Count > 0 && missing > 0) { DistanceNode smallest = list.First.Value; //Lerp between probability and 1, depending on how many are left and how many are missing float prob = Mathf.Lerp(probability, 1, missing / list.Count); foreach (DistanceNode node in list) { if (node.dist < smallest.dist) smallest = node; } //TODO Code/use a heap instead if (Random.value < prob) { friendships.Add(CreateFriendship(p1, smallest.p)); missing--; } list.Remove(smallest); } } return friendships; }
public void ItShouldBeAbleToClear() { LinkedList<object> list = new LinkedList<object>(); list.Add('a'); list.Add('b'); list.Add('c'); list.Add('d'); list.Add('e'); list.Clear(); object expected = 0; object actual = list.Count; Assert.AreEqual(expected, actual); }
public void Clear_Empty() { LinkedList<int> list = new LinkedList<int>(); Assert.IsNull(list.Head); Assert.IsNull(list.Tail); Assert.AreEqual(0, list.Count); list.Clear(); Assert.IsNull(list.Head); Assert.IsNull(list.Tail); Assert.AreEqual(0, list.Count); }
public void buttonRemoveSTL_Click(object sender, EventArgs e) { //STL stl = (STL)listSTLObjects.SelectedItem; //if (stl == null) return; LinkedList<STL> list = new LinkedList<STL>(); foreach (STL stl in listSTLObjects.SelectedItems) list.AddLast(stl); foreach (STL stl in list) { cont.models.Remove(stl); listSTLObjects.Items.Remove(stl); } list.Clear(); cont.UpdateChanges(); }
public virtual SetOfSentences doProcess(SetOfSentences sos) { List< Eojeol [] > eojeolSetArray = sos.getEojeolSetArray(); LinkedList < Eojeol > eojeolArray = new LinkedList < Eojeol >(); for (int i = 0; i < eojeolSetArray.Count; i++) { Eojeol[] eojeolSet = eojeolSetArray[i]; eojeolArray.Clear(); for (int j = 0; j < eojeolSet.Length; j++) { eojeolArray.AddLast(eojeolSet[j]); } int unkCount = 0; for (int j = 0; j < eojeolArray.Count; j++) { Eojeol eojeol = eojeolArray.Get_Renamed(j); System.String[] tags = eojeol.Tags; System.String[] morphemes = eojeol.Morphemes; for (int k = 0; k < tags.Length; k++) { if (tags[k].Equals("unk")) { tags[k] = "nqq"; Eojeol newEojeol = new Eojeol(morphemes.Clone() as string[], tags.Clone() as string[]); eojeolArray.AddLast(newEojeol); tags[k] = "ncn"; unkCount++; } } } if (unkCount > 0) { eojeolSetArray[i] = eojeolArray.ToArray(eojeolSet); } } return sos; }
public void Clear_VariousItems(int[] testCase) { LinkedList<int> list = new LinkedList<int>(); foreach (int value in testCase) { list.AddLast(new LinkedListNode<int>(value)); } Assert.IsNotNull(list.Head); Assert.IsNotNull(list.Tail); Assert.AreEqual(testCase.Length, list.Count); list.Clear(); Assert.IsNull(list.Head); Assert.IsNull(list.Tail); Assert.AreEqual(0, list.Count); }
private int DbSetComparison(DbSet dbSet1, DbSet dbSet2) { var parentDbNames = new LinkedList<string>(); this.getAllParentDbSets(parentDbNames,dbSet1.dbSetName); var names1 = parentDbNames.ToArray(); if (Array.IndexOf(names1, dbSet2.dbSetName) > -1) { return 1; } parentDbNames.Clear(); this.getAllParentDbSets(parentDbNames, dbSet2.dbSetName); var names2 = parentDbNames.ToArray(); if (Array.IndexOf(names2, dbSet1.dbSetName) > -1) { return -1; } return String.Compare(dbSet1.dbSetName,dbSet2.dbSetName); }
private static void Calcular(int[] l, int M, int lim, int i, LinkedList<int> r, ref int max, LinkedList<int> aux, int auxv, int auxt) { if(i < M) { if(auxt + l[i] <= lim) { aux.AddLast(i); Calcular(l, M, lim, i + 1, r, ref max, aux, auxv + 1, auxt + l[i]); aux.RemoveLast(); } Calcular(l, M, lim, i + 1, r, ref max, aux, auxv, auxt); } else if(auxv > max) { max = auxv; r.Clear(); foreach(int n in aux) { r.AddLast(n); } } }
static void Main() { string decorationLine = new string('-', Console.WindowWidth); Console.Write(decorationLine); Console.WriteLine("***Presenting the functionality of the data structure 'Linked List'***"); Console.Write(decorationLine); LinkedList<string> names = new LinkedList<string>(); Console.WriteLine("---Add operation---"); names.Add("Pesho"); names.Add("Gosho"); names.Add("Lili"); names.Add("Marin"); names.Add("Elena"); Console.WriteLine("Elements count after adding: " + names.Count); Console.WriteLine(); Console.WriteLine("---Iterator functionality---"); PrintPeopleOnConsole(names); Console.WriteLine(); Console.WriteLine("---Remove by value operation---"); names.Remove("Marin"); Console.WriteLine("Linked list after removal: "); PrintPeopleOnConsole(names); Console.WriteLine(); Console.WriteLine("---Remove by index operation---"); names.RemoveAt(1); Console.WriteLine("Linked list after removal: "); PrintPeopleOnConsole(names); Console.WriteLine(); Console.WriteLine("---IndexOf operation---"); Console.WriteLine(names.IndexOf("Elena")); Console.WriteLine(); Console.WriteLine("---Clear operation---"); names.Clear(); Console.WriteLine("Elements count after clearing: " + names.Count); }
/// <summary> /// Dodavanje na del vo baza. /// </summary> /// <param name="Ime">Ime na del</param> /// <param name="ImaPredavac">Dali delot ima predavac</param> /// <param name="Vid_Izgled">Izgled na delot</param> /// <returns>Ishod od dodavanje na del.</returns> public RezultatKomanda addDel(string Ime, char ImaPredavac, int Vid_Izgled) { RezultatKomanda rezultat = new RezultatKomanda(false); try { parametriKomanda = new LinkedList<SqlParameter>(); parametriKomanda.Clear(); //Parametar za @Ime = Ime //Input Parametar SqlParam = new SqlParameter("@Ime", SqlDbType.NVarChar); SqlParam.Value = Ime; parametriKomanda.AddLast(SqlParam); //Parametar za @ImaPredavac = ImaPredavac //Input Parametar SqlParam = new SqlParameter("@ImaPredavac", SqlDbType.Char); SqlParam.Value = ImaPredavac; parametriKomanda.AddLast(SqlParam); //Parametar za @Vid_Izgled = Vid_Izgled //Input Parametar SqlParam = new SqlParameter("@Vid_Izgled", SqlDbType.Int); SqlParam.Value = Vid_Izgled ; parametriKomanda.AddLast(SqlParam); BazaDB.ExecuteScalar(parametriKomanda.ToArray(), "sp_ZacuvajDel", sqlCn: null); rezultat.Rezultat = RezultatKomandaEnum.Uspeh; return rezultat; } catch (Exception ex) { rezultat.Rezultat = RezultatKomandaEnum.Neuspeh; rezultat.Pricina = ex.Message; return rezultat; } }
static void Main() { var test = new LinkedList<string>(); test.AddFirst("apple"); Console.WriteLine(test); test.AddLast("banana"); Console.WriteLine(test); test.AddLast("orange"); Console.WriteLine(test); test.AddLast("kiwi"); Console.WriteLine(test); test.AddFirst("ananas"); Console.WriteLine(test); test.Remove("orange"); Console.WriteLine(test); test[1] = "melon"; Console.WriteLine(test); Console.WriteLine(test[0]); test.Clear(); Console.WriteLine(test); }
/// <summary> /// State manager class constructor /// </summary> public StateManager(StateID id, object[] parameters) { //Save starting state data m_StartState = id; m_StartParameters = parameters; //Set device m_SpriteBatch = null; m_Device = new GraphicsDeviceManager(this); //Configure engine #region Engine configuration Content.RootDirectory = CONTENT_ROOT; IsMouseVisible = SHOW_CURSOR; IsFixedTimeStep = FIXED_STEP; m_Device.IsFullScreen = Global.APP_FULLSCREEN; m_Device.PreferMultiSampling = Global.APP_ANTIALIAS; m_Device.PreferredBackBufferWidth = Global.APP_WIDTH; m_Device.PreferredBackBufferHeight = Global.APP_HEIGHT; #endregion //Create GUI Manager #region Global GUI manager instantiation Global.GUIManager = new Manager(this, m_Device, GUI_SKIN, false); Global.GUIManager.RenderTargetUsage = RenderTargetUsage.DiscardContents; #endregion //Create other global engines Global.SoundManager = new SoundManager(); Global.Logger = new Logger(Global.APP_NAME); //Create state list m_Depth = 0; m_StateList = new LinkedList<State>(); m_StateList.Clear(); //Logging Global.Logger.AddLine("Engine started."); }
/// <summary> /// Calculates the modes of a collection of numbers using the specified discretization unit epsilon. /// </summary> /// <param name="numbers">The collection whose modes are to be calculated.</param> /// <param name="discretizationEpsilon">Discretization unit epsilon.</param> /// <returns> /// An array containing the arithmetic mean of all intervals /// (that are at most one epsilon wide) with the most occurences. /// </returns> public static double[] Modes(IEnumerable<double> numbers, double discretizationEpsilon) { if (numbers == null) { throw ArgumentNullException; } if (!numbers.Any()) { throw EmptyNumbersCollectionException; } LinkedList<Interval> bestIntervals = new LinkedList<Interval>(); int maxCount = 0; // Sort numbers IOrderedEnumerable<double> sorted = numbers.OrderBy(x => x); // Iterate over all maximum-sized intervals foreach (Interval interval in IntervalHelper.Intervals(sorted, discretizationEpsilon)) { // If new maximum found, delete all maximums until now if (interval.ElementsInside > maxCount) { maxCount = interval.ElementsInside; bestIntervals.Clear(); } // Save this interval as a maximum one if necessary if (interval.ElementsInside == maxCount) { bestIntervals.AddLast(interval); } } // Return the arithmetic mean of the mid points return bestIntervals .Select(x => x.MidPoint) .ToArray(); }
// ------------------------ /// <summary> /// Проверка на то, насколько хорошо реорганизуются /// в соответствии с массивом узлов узлы связного списка. /// </summary> public static void _DBM_LinkedList_ReorderNodeArrayTest(int tests, int n) { Random gen = new Random(); LinkedList<int> list = new LinkedList<int>(); for (int i = 0; i < tests; i++) { list.Clear(); for (int j = 0; j < n; j++) list.AddLast(gen.Next()); LinkedListNode<int>[] nodes = list.GetNodes(); nodes.SortMerge(Comparer<int>.Default.GetLinkedListNodeComparer()); list.Reorder_As_In_NodeList(nodes); if (nodes.IsObsolete(list)) Console.WriteLine("fail"); } }
private string deleteCollection() { string winner; ArrayList al = new ArrayList(); LinkedList<int> ll = new LinkedList<int>(); al = insertInHeadAL(al); ll = insertInHeadLL(ll); int sizeAL = al.Count; int sizeLL = ll.Count; Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); al.Clear(); stopWatch.Stop(); TimeSpan ts = stopWatch.Elapsed; Console.WriteLine("\n\n================================================================================="); Console.WriteLine("Time to delete all elements in ArrayList with {0} elements: {1}", sizeAL, ts); stopWatch.Reset(); stopWatch.Start(); ll.Clear(); stopWatch.Stop(); TimeSpan ts2 = stopWatch.Elapsed; Console.WriteLine("Time to delete all elements in ArrayList with {0} elements: {1}", sizeLL, ts2); if (ts > ts2) { Console.WriteLine("\tLinkedList is quicker!"); return winner = "LinkedList"; } else { Console.WriteLine("\tArrayList is quicker!"); return winner = "ArrayList"; } }
protected override void Dispose(bool explicitDispose) { if (explicitDispose) { _innerListSpinLock?.EnterAndExitLock(); // var innerList = _innerList; if (innerList != null) { var innerListNode = innerList.First; for (; innerListNode != null;) { innerListNode.Value?.Dispose(); innerListNode = innerListNode.Next; } } _innerList?.Clear(); } _innerList = null; _innerListSpinLock = null; _ownerComponent = null; // base.Dispose(explicitDispose); }
static void Añadir(LinkedList<Nodo> C, Nodo Y) { LinkedList<Nodo> aux = new LinkedList<Nodo>(C); aux.AddLast(Y); C.Clear(); foreach(Nodo X in aux.OrderBy(x => x.Cestimado)) { C.AddLast(X); } //************************************************************ Console.WriteLine("(+) Se añade " + (char)(A + Y.lugar)); Mostrar(C); //************************************************************ }
public void Clear() { _states.Clear(); _currentNode = null; }
/// <summary> /// Recursive function that processes the entire scene graph, collecting up /// all of the animation data. /// </summary> /// <param name="input">The input scene graph node</param> /// <param name="animationClips">The animation clips object we put animation in</param> private void ProcessAnimationsRecursive(NodeContent input, AnimationClips animationClips) { foreach (KeyValuePair<string, AnimationContent> animation in input.Animations) { // Do we have this animation before? AnimationClips.Clip clip; if (!animationClips.Clips.TryGetValue(animation.Key, out clip)) { // Never before seen clip System.Diagnostics.Trace.WriteLine("New clip: " + animation.Key); clip = new AnimationClips.Clip(); clip.Name = animation.Key; clip.Duration = animation.Value.Duration.TotalSeconds; clip.Keyframes = new List<AnimationClips.Keyframe>[bones.Count]; for (int b = 0; b < bones.Count; b++) clip.Keyframes[b] = new List<AnimationClips.Keyframe>(); animationClips.Clips[animation.Key] = clip; } else if (animation.Value.Duration.TotalSeconds > clip.Duration) { clip.Duration = animation.Value.Duration.TotalSeconds; } // // For each channel, determine the bone and then process all of the // keyframes for that bone. // LinkedList<AnimationClips.Keyframe> keyframes = new LinkedList<AnimationClips.Keyframe>(); foreach (KeyValuePair<string, AnimationChannel> channel in animation.Value.Channels) { keyframes.Clear(); // What is the bone index? int boneIndex; if (!bones.TryGetValue(channel.Key, out boneIndex)) continue; // Ignore if not a named bone if ( !skinned && UselessAnimationTest(boneIndex)) continue; foreach (AnimationKeyframe keyframe in channel.Value) { Matrix transform = keyframe.Transform; // Keyframe transformation AnimationClips.Keyframe newKeyframe = new AnimationClips.Keyframe(); newKeyframe.Time = keyframe.Time.TotalSeconds; transform.Right = Vector3.Normalize(transform.Right); transform.Up = Vector3.Normalize(transform.Up); transform.Backward = Vector3.Normalize(transform.Backward); newKeyframe.Rotation = Quaternion.CreateFromRotationMatrix(transform); newKeyframe.Translation = transform.Translation; keyframes.AddLast(newKeyframe); } LinearKeyframeReduction(keyframes); foreach (AnimationClips.Keyframe keyframe in keyframes) { clip.Keyframes[boneIndex].Add(keyframe); } } } foreach (NodeContent child in input.Children) { ProcessAnimationsRecursive(child, animationClips); } }
public UIGameplay(ContentManager Content) : base(Content) { m_RightPanel = Content.Load<Texture2D>("UI/UI_Right"); m_LeftPanel = Content.Load<Texture2D>("UI/UI_Left"); m_FixedFont = Content.Load<SpriteFont>("Fonts/FixedText"); m_FixedSmall = Content.Load<SpriteFont>("Fonts/FixedSmall"); m_StatusFont = Content.Load<SpriteFont>("Fonts/FixedTitle"); // Load the massive number of localized strings, so we don't repeat lookups InitializeLocStrings(Content); // Hot zones for tooltips int Width = GraphicsManager.Get().Width; int Height = GraphicsManager.Get().Height; const int iSmallSpacing = 22; Rectangle rect = new Rectangle(Width - 290, Height - 223, 200, 22); // Life m_Buttons.AddLast(new Button(rect, "tip_life")); rect.Y += iSmallSpacing; // Money m_Buttons.AddLast(new Button(rect, "tip_money")); rect.Y += iSmallSpacing * 2; // Wave LinkedList<TipData> tipdata = new LinkedList<TipData>(); tipdata.AddLast(new TipData(eTipData.Generic, Balance.TotalWaves)); m_Buttons.AddLast(new Button(rect, "tip_wave", tipdata)); rect.Y += iSmallSpacing; // Money m_Buttons.AddLast(new Button(rect, "tip_wavetime")); rect.Y += iSmallSpacing * 2; // Speed tipdata.Clear(); tipdata.AddLast(new TipData(eTipData.Keybind, eBindings.UI_Slow)); tipdata.AddLast(new TipData(eTipData.Keybind, eBindings.UI_Fast)); tipdata.AddLast(new TipData(eTipData.Keybind, eBindings.UI_Stop)); m_Buttons.AddLast(new Button(rect, "tip_speed", tipdata)); rect.Y += iSmallSpacing; // Initialize the buttons for the bottom left grids InitializeGrid(Content); }
private void frmDadosVacinas_FormClosing(object sender, FormClosingEventArgs e) { list.Clear(); }
//float now; public void ClearPath() { m_path.Clear(); m_curNode = null; }
private void StoreMessages(NetworkStream providedStream) { var config = new SerializerConfig(); config.Advanced.PersistTypeCache = true; config.OnResolveFormatter.Add((c, t) => { if (t == typeof(HashSet <byte[]>)) { return(new NetCore.NetCore_Extensions.HashSetFormatterThatKeepsItsComparer()); } return(null); // continue searching }); var serializer = new CerasSerializer(config); TcpListener server = null; Socket socket = null; NetworkStream networkStream = null; if (providedStream != null) { networkStream = providedStream; } try { if (networkStream == null) { server = new TcpListener((IP == "127.0.0.1" ? IPAddress.Loopback : IPAddress.Any), Port); server.Start(); socket = KillableAcceptSocket(server); networkStream = new NetworkStream(socket); server.Stop(); } networkStream.ReadTimeout = 20; networkStream.WriteTimeout = int.MaxValue; //Using {BOOP} commands routed through UDP/TCP if (spec.Side == NetworkSide.CLIENT) { SendMessage(new NetCoreAdvancedMessage("{HI}")); //The exchange of {HI} command confirms that link is established on Receiving } while (true) { if (networkStream != null && networkStream.DataAvailable) { if (spec.Side == NetworkSide.SERVER && (!socket?.Connected ?? true)) { return; } NetCoreAdvancedMessage message = null; try { using (MemoryStream ms = new MemoryStream()) { Stopwatch sw = new Stopwatch(); sw.Start(); //Read the size int lengthToReceive = 0; byte[] _lengthToReceive = new byte[4]; networkStream.Read(_lengthToReceive, 0, _lengthToReceive.Length); lengthToReceive = BitConverter.ToInt32(_lengthToReceive, 0); //Console.WriteLine("I want this many bytes: " + lengthToReceive); //Now read until we have that many bytes long bytesRead = CopyBytes(lengthToReceive, networkStream, ms); //Console.WriteLine("I got this many bytes: " + bytesRead); //Deserialize it ms.Position = 0; //cmd = (RTC_Command)binaryFormatter.Deserialize(ms); var temp = ms.ToArray(); message = serializer.Deserialize <NetCoreAdvancedMessage>(temp); sw.Stop(); if (message.Type != "{BOOP}" && sw.ElapsedMilliseconds > 50) { Console.WriteLine("It took " + sw.ElapsedMilliseconds + " ms to deserialize cmd " + message.Type + " of " + temp.Length + " bytes"); } } } catch { throw; } if (message != null) { if (message.Type == "{RETURNVALUE}") { spec.Connector.watch.AddReturn(message); } else { spec.Connector.hub.QueueMessage(message); } } } while (PeerMessageQueue.Count > 0) { NetCoreMessage pendingMessage; lock (PeerMessageQueueLock) { pendingMessage = PeerMessageQueue.First.Value; PeerMessageQueue.RemoveFirst(); } try { Stopwatch sw = new Stopwatch(); sw.Start(); //Write the length of the command to the first four bytes byte[] buf = serializer.Serialize(pendingMessage); //Write the length of the incoming object to the NetworkStream byte[] length = BitConverter.GetBytes(buf.Length); networkStream.Write(length, 0, length.Length); networkStream.Write(buf, 0, buf.Length); sw.Stop(); if (pendingMessage.Type != "{BOOP}" && sw.ElapsedMilliseconds > 50) { Console.WriteLine("It took " + sw.ElapsedMilliseconds + " ms to serialize backCmd " + pendingMessage.Type + " of " + buf.Length + " bytes"); } } catch { throw; } if (pendingMessage.Type == "{BYE}") { lock (PeerMessageQueueLock) //Since we're shutting down, let's clear the message queue PeerMessageQueue?.Clear(); } if (status == NetworkStatus.DISCONNECTED || status == NetworkStatus.CONNECTIONLOST) { //If the link's status changed from an outside factor, we want to stop the thread. lock (PeerMessageQueueLock) PeerMessageQueue?.Clear(); return; } } Thread.Sleep(spec.messageReadTimerDelay); } } catch (Exception ex) { if (ex is ThreadAbortException) { ConsoleEx.WriteLine("Ongoing TCPLink Thread Killed"); } else if (ex.InnerException != null && ex.InnerException is SocketException) { ConsoleEx.WriteLine("Ongoing TCPLink Socket Closed during use"); } else if (ex is SerializationException) { ConsoleEx.WriteLine("Ongoing TCPLink Closed during Serialization operation"); } else if (ex is ObjectDisposedException) { ConsoleEx.WriteLine("Ongoing TCPLink Closed during Socket acceptance"); } else { DiscardException(ex); } } finally { //Let's force close everything JUST IN CASE try { networkStream?.Close(); networkStream?.Dispose(); } catch { } //nobody cares why this failed try { socket?.Shutdown(SocketShutdown.Both); socket?.Dispose(); } catch { } //nobody cares why this failed try { server?.Stop(); } catch (Exception ex) { DiscardException(ex); } if (status == NetworkStatus.CONNECTED) { status = (expectingSomeone ? NetworkStatus.CONNECTIONLOST : NetworkStatus.DISCONNECTED); } else if (status != NetworkStatus.CONNECTIONLOST) { status = NetworkStatus.DISCONNECTED; } //Kill synced query if happenning spec.Connector.watch.Kill(); } }
public virtual void LoadLevel(string sLevelName) { m_Tiles.Clear(); int iWidth = 10; int iHeight = 5; int[,] TileData = { { 2, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 2, 2, 0, 0, 0, 0, 0, 0, 0, 0 }, { 4, 0, 0, 0, 0, 0, 0, 0, 0, 3 }, { 2, 2, 0, 0, 0, 0, 0, 0, 0, 0 }, { 2, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, }; // Generate tile array based on width/height // (used to setup neighbors) Objects.Tile[,] Tiles = new Objects.Tile[iHeight, iWidth]; float fPerColumn = 1.72f; float fPerRow = 1.5f; Objects.Tile BaseTile = null; Objects.Tile SpawnTile = null; int iColCount = 0; float fXOffset = -1.0f * (iWidth / 2) * fPerColumn; while (iColCount < iWidth) { int iRowCount = 0; float fZOffset = -1.0f * (iHeight / 2) * fPerRow; while (iRowCount < iHeight) { eTileType type = (eTileType)TileData[iRowCount, iColCount]; float fTileHeight = GlobalDefines.fTileHeight; Objects.Tile t; if (iRowCount % 2 == 0) { t = CreateTile(new Vector3(fXOffset, fTileHeight, fZOffset), type); } else { t = CreateTile(new Vector3(fXOffset - 0.875f, fTileHeight, fZOffset), type); } Tiles[iRowCount, iColCount] = t; if (type == eTileType.Base) { BaseTile = t; } else if (type == eTileType.EnemySpawn) { SpawnTile = t; } fZOffset += fPerRow; iRowCount++; } fXOffset += fPerColumn; iColCount++; } // Now loop through the array of tiles to assign neighbors. // Since these are hexagons, the row affects which hexagons are neighbors. for (int i = 0; i < iHeight; i++) { for (int j = 0; j < iWidth; j++) { // East/West are same regardless of row modulus // E if (j + 1 < iWidth) { Tiles[i, j].AddNeighbor(Tiles[i, j + 1]); } // W if (j - 1 >= 0) { Tiles[i, j].AddNeighbor(Tiles[i, j - 1]); } if (i % 2 == 0) { // NE if ((i - 1 >= 0) && (j + 1 < iWidth)) { Tiles[i, j].AddNeighbor(Tiles[i - 1, j + 1]); } // SE if ((i + 1 < iHeight) && (j + 1 < iWidth)) { Tiles[i, j].AddNeighbor(Tiles[i + 1, j + 1]); } // SW if (i + 1 < iHeight) { Tiles[i, j].AddNeighbor(Tiles[i + 1, j]); } // NW if (i - 1 >= 0) { Tiles[i, j].AddNeighbor(Tiles[i - 1, j]); } } else { // NE if (i - 1 >= 0) { Tiles[i, j].AddNeighbor(Tiles[i - 1, j]); } // SE if (i + 1 < iHeight) { Tiles[i, j].AddNeighbor(Tiles[i + 1, j]); } // SW if ((i + 1 < iHeight) && (j - 1 >= 0)) { Tiles[i, j].AddNeighbor(Tiles[i + 1, j - 1]); } // NW if ((i - 1 >= 0) && (j - 1 >= 0)) { Tiles[i, j].AddNeighbor(Tiles[i - 1, j - 1]); } } } } // These values let the camera know what the maximum scroll area should be. GameState.Get().Camera.LevelMin = Tiles[0, 0].Position; GameState.Get().Camera.LevelMax = Tiles[iHeight - 1, iWidth - 1].Position; // Create the player's base and initial path for enemies if (BaseTile != null && SpawnTile != null) { BaseTile.Build(new Objects.Base(m_Game)); Pathfinder.Get().GlobalStartTile = SpawnTile; Pathfinder.Get().GlobalGoalTile = BaseTile; Pathfinder.Get().ComputeAStar(); GameState.Get().SetSelected(BaseTile); } }
public void Clear() { stack.Clear(); }
public void Clear() { data.Clear(); index.Clear(); }
public CRFResult Run(CRFGraph graph, IDictionary <IGWNode, int> startLabeling) { Graph = graph; graph.Nodes.Each(n => n.Data.IsChosen = false); var startPatch = (startLabeling != null) ? startLabeling.Keys.Cast <IGWNode>() : new List <IGWNode>(); var vertexQueue = computeQueue(graph.Nodes.Cast <IGWNode>().ToList(), startPatch).Cast <IGWNode <ICRFNodeData, ICRFEdgeData, ICRFGraphData> >().ToList(); //preparation int counter = 0; if (startLabeling != null) { foreach (IGWNode <ICRFNodeData, ICRFEdgeData, ICRFGraphData> item in startLabeling.Keys) { item.Data.IsChosen = true; } } foreach (var item in vertexQueue) { counter++; item.Data.UnchosenNeighboursTemp = item.Edges.Where(e => !item.Neighbour(e).Data.IsChosen).Count(); } //Create starting Combination { CRFLabelling newCombination = new CRFLabelling(); newCombination.AssignedLabels = new int[Graph.Nodes.Count() - startPatch.Count()]; var score = 0.0; if (startLabeling != null) { foreach (var item in startLabeling) { var key = item.Key as IGWNode <ICRFNodeData, ICRFEdgeData, ICRFGraphData>; score += key.Data.Score(item.Value); } foreach (var edge in graph.Edges) { if (edge.Head.Data.IsChosen && edge.Foot.Data.IsChosen) { score += edge.Score(edge.Head.GraphId, startLabeling[edge.Head], edge.Foot.GraphId, startLabeling[edge.Foot]); } } } newCombination.BorderFingerPrint = 0; Combinations.Add(newCombination); } Stopwatch watch = new Stopwatch(); watch.Start(); int counter2 = 0; foreach (var vertex in vertexQueue) { vertex.Data.IsChosen = true; var NewInnerVertices = ComputeNewBoundaryVertices(vertex); Barrier = DetermineBarrier(Combinations, vertex, NewInnerVertices.Count == 0, MaximalCombinationsUnderConsideration, RunsToDetermineBarrier); Do(Combinations, vertex, NewInnerVertices, comb => (comb.Score > Barrier || (comb.Score == Barrier && Random.NextDouble() > 0.5)), BoundaryVertices); //filter step two //this is needed, because of the heuristik the average combinations still grow if(NewInnerVertices == 1) if (NextGeneration.Count > MaximalCombinationsUnderConsideration) { var ng = NextGeneration.ToList(); var barrier2 = DetermineBarrierStep2(ng, MaximalCombinationsUnderConsideration, RunsToDetermineBarrier); NextGeneration = new LinkedList <CRFLabelling>(ng.Where(item => item.Score > barrier2 || (item.Score == barrier2 && Random.NextDouble() > 0.5))); } Combinations = NextGeneration.ToList(); NextGeneration.Clear(); counter2++; } watch.Stop(); //return result var result = new CRFResult(); result.Labeling = new int[vertexQueue.Count]; var winner = Combinations[0]; if (startLabeling != null) { foreach (var node in startLabeling) { result.Labeling[node.Key.GraphId] = node.Value; } } foreach (var node in vertexQueue) { result.Labeling[node.GraphId] = winner.AssignedLabels[node.GraphId]; } result.RunTime = watch.Elapsed; result.Score = winner.Score; return(result); }
public void DrawTriangle(IntVector2[] vertices, int triangleIndex) { if (Shader == null) { throw new Exception("First assign value to Shader field"); } for (int i = 0; i < vertices.Length; i++) { Shader.ForVertex(new Vector2(vertices[i].X, vertices[i].Y)); } Shader.StartTriangle(triangleIndex); Array.Sort(sortedVerticesIndexes, (int a, int b) => vertices[a].Y.CompareTo(vertices[b].Y)); int yMin = (int)vertices[sortedVerticesIndexes[0]].Y; int yMax = (int)vertices[sortedVerticesIndexes[sortedVerticesIndexes.Length - 1]].Y; int k = 0; for (int y = yMin + 1; y <= yMax; y++) { while (vertices[sortedVerticesIndexes[k]].Y == y - 1) { int prevIndex = (sortedVerticesIndexes[k] + vertices.Length - 1) % vertices.Length; int nextIndex = (sortedVerticesIndexes[k] + 1) % vertices.Length; if (vertices[prevIndex].Y > y - 1) { AET.AddLast( new AETData() { x = vertices[sortedVerticesIndexes[k]].X, antitangent = GetAntiTangent(vertices[sortedVerticesIndexes[k]], vertices[prevIndex]), yMax = vertices[prevIndex].Y }); } if (vertices[nextIndex].Y > y - 1) { AET.AddLast( new AETData() { x = vertices[sortedVerticesIndexes[k]].X, antitangent = GetAntiTangent(vertices[sortedVerticesIndexes[k]], vertices[nextIndex]), yMax = vertices[nextIndex].Y }); } k++; } foreach (var edge in AET) { edge.x += edge.antitangent; } AET.Sort((AETData edge1, AETData edge2) => edge1.x.CompareTo(edge2.x)); if (y >= 0 && y < bitmap.Height) { DrawOnScanLine(y); } RemoveFinishedEdges(y); } //foreach (Vector2 v in ToDraw) //{ // bitmap.RawSetPixel((int)v.X, (int)v.Y, Shader.ForFragment(v)); //} Parallel.ForEach(ToDraw, (v) => bitmap.RawSetPixel((int)v.X, (int)v.Y, Shader.ForFragment(v))); ToDraw.Clear(); }
public void Clear() { m_LinkedList.Clear(); m_Dictionary.Clear(); }
// Modified by Insthync protected virtual void Dispose(bool disposing) { try { m_disposing = true; if (!disposedValue) { if (disposing) { // 释放托管状态(托管对象)。 callbackHandle = null; acklist = null; buffer = null; } KcpSegment segment; while (snd_queue != null && (snd_queue.TryDequeue(out segment) || !snd_queue.IsEmpty) ) { try { KcpSegment.FreeHGlobal(segment); } catch (Exception) { //理论上这里没有任何异常; } } snd_queue = null; lock (snd_bufLock) { Dispose_FreeCollection(snd_buf); snd_buf?.Clear(); snd_buf = null; } lock (rcv_bufLock) { Dispose_FreeCollection(rcv_buf); rcv_buf?.Clear(); rcv_buf = null; } lock (rcv_queueLock) { Dispose_FreeCollection(rcv_queue); rcv_queue?.Clear(); rcv_queue = null; } disposedValue = true; } } finally { m_disposing = false; } }
/// <summary> /// TBD /// </summary> public void Clear() { _inner.Clear(); }
internal void Reset() { enemies.Clear(); }
/// <summary> /// Returns <c>true</c> if the given string is accepted by the automaton. /// <para/> /// Complexity: linear in the length of the string. /// <para/> /// <b>Note:</b> for full performance, use the <see cref="RunAutomaton"/> class. /// </summary> public static bool Run(Automaton a, string s) { if (a.IsSingleton) { return(s.Equals(a.singleton, StringComparison.Ordinal)); } if (a.deterministic) { State p = a.initial; for (int i = 0, cp = 0; i < s.Length; i += Character.CharCount(cp)) { State q = p.Step(cp = Character.CodePointAt(s, i)); if (q == null) { return(false); } p = q; } return(p.accept); } else { State[] states = a.GetNumberedStates(); LinkedList <State> pp = new LinkedList <State>(); LinkedList <State> pp_other = new LinkedList <State>(); OpenBitSet bb = new OpenBitSet(states.Length); OpenBitSet bb_other = new OpenBitSet(states.Length); pp.AddLast(a.initial); List <State> dest = new List <State>(); bool accept = a.initial.accept; for (int i = 0, c = 0; i < s.Length; i += Character.CharCount(c)) { c = Character.CodePointAt(s, i); accept = false; pp_other.Clear(); bb_other.Clear(0, bb_other.Length - 1); foreach (State p in pp) { dest.Clear(); p.Step(c, dest); foreach (State q in dest) { if (q.accept) { accept = true; } if (!bb_other.Get(q.number)) { bb_other.Set(q.number); pp_other.AddLast(q); } } } LinkedList <State> tp = pp; pp = pp_other; pp_other = tp; OpenBitSet tb = bb; bb = bb_other; bb_other = tb; } return(accept); } }
//clear list of instances public void Clear() { _instances.Clear(); _instanceNodes.Clear(); }
public static void Clear() { VariableCollection.Clear(); VariableChanged.Invoke(new VariableChangedEventArgs(ValueChangedType.Clear, null)); }
/// <summary> /// Computes the complete intersection of the given ray with the object. /// </summary> /// <param name="p0">Ray origin.</param> /// <param name="p1">Ray direction vector.</param> /// <returns>Sorted list of intersection records.</returns> public override LinkedList <Intersection> Intersect(Vector3d p0, Vector3d p1) { if (children == null || children.Count == 0) { return(null); } if (BoundingVolume != null) { countBoundingBoxes++; if (BoundingVolume.Intersect(p0, p1) < -0.5) { return(null); } } LinkedList <Intersection> result = null; LinkedList <Intersection> left = null; // I'm going to reuse these two.. bool leftOp = true; // the 1st pass => left operand foreach (ISceneNode child in children) { Vector3d origin = Vector3d.TransformPosition(p0, child.FromParent); Vector3d dir = Vector3d.TransformVector(p1, child.FromParent); // ray in local child's coords: [ origin, dir ] LinkedList <Intersection> partial = child.Intersect(origin, dir); if (partial == null) { partial = leftOp ? new LinkedList <Intersection>() : emptyResult; } else if (child is ISolid) { Intersection.countIntersections += partial.Count; } if (leftOp) { leftOp = false; result = partial; left = new LinkedList <Intersection>(); } else { if (trivial && partial.Count == 0) { continue; } // resolve one binary operation (result := left # partial): { LinkedList <Intersection> tmp = left; left = result; result = tmp; } // result .. empty so far result.Clear(); double lowestT = Double.NegativeInfinity; Intersection leftFirst = (left.First == null) ? null : left.First.Value; Intersection rightFirst = (partial.First == null) ? null : partial.First.Value; // initial inside status values: bool insideLeft = (leftFirst != null && !leftFirst.Enter); bool insideRight = (rightFirst != null && !rightFirst.Enter); bool insideResult = bop(insideLeft, insideRight); // merge behavior: bool minLeft = (leftFirst != null && leftFirst.T == lowestT); bool minRight = (rightFirst != null && rightFirst.T == lowestT); while (leftFirst != null || rightFirst != null) { double leftVal = (leftFirst != null) ? leftFirst.T : double.PositiveInfinity; double rightVal = (rightFirst != null) ? rightFirst.T : double.PositiveInfinity; lowestT = Math.Min(leftVal, rightVal); Debug.Assert(!Double.IsInfinity(lowestT)); minLeft = leftVal == lowestT; minRight = rightVal == lowestT; Intersection first = null; if (minRight) { first = rightFirst; partial.RemoveFirst(); rightFirst = (partial.First == null) ? null : partial.First.Value; insideRight = first.Enter; } if (minLeft) { first = leftFirst; left.RemoveFirst(); leftFirst = (left.First == null) ? null : left.First.Value; insideLeft = first.Enter; } bool newResult = bop(insideLeft, insideRight); if (newResult != insideResult) { first.Enter = insideResult = newResult; result.AddLast(first); } } } if (shortCurcuit && result.Count == 0) { break; } } return(result); }
public void Clear() { linkedList.Clear(); dictionary.Clear(); }
/// <summary> /// This function relocates all the instructions and pointers of the loading executable. /// </summary> /// <param name="Relocs"></param> protected void RelocateRelocs(IEnumerable<Elf.Reloc> Relocs) { var InstructionReader = new InstructionReader(ElfLoader.MemoryStream); /* Func<uint, Action<ref Instruction>> UpdateInstruction = (Address) => { }; */ //var Hi16List = new List<uint>(); ushort HiValue = 0; var DeferredHi16 = new LinkedList<uint>(); // We'll use this to relocate R_MIPS_HI16 when we get a R_MIPS_LO16 int Index = 0; foreach (var Reloc in Relocs) { //Console.WriteLine(Reloc.ToStringDefault()); //Console.WriteLine(" {0:X}", RelocatedAddress); // Check if R_TYPE is 0xFF (break code) and break the loop // immediately in order to avoid fetching non existent program headers. // Some games (e.g.: "Final Fantasy: Dissidia") use this kind of relocation // suggesting that the PSP's ELF Loader is capable of recognizing it and stop. if (Reloc.Type == Elf.Reloc.TypeEnum.StopRelocation) { break; } var PointerBaseOffset = (uint)ElfLoader.ProgramHeaders[Reloc.PointerSectionHeaderBase].VirtualAddress; var PointeeBaseOffset = (uint)ElfLoader.ProgramHeaders[Reloc.PointeeSectionHeaderBase].VirtualAddress; // Address of data to relocate var RelocatedPointerAddress = (uint)(BaseAddress + Reloc.PointerAddress + PointerBaseOffset); // Value of data to relocate var Instruction = InstructionReader[RelocatedPointerAddress]; var InstructionBefore = Instruction; var S = (uint)BaseAddress + PointeeBaseOffset; var GP_ADDR = (int)(BaseAddress + Reloc.PointerAddress); var GP_OFFSET = (int)GP_ADDR - ((int)BaseAddress & 0xFFFF0000); //Console.WriteLine(Reloc.Type); switch (Reloc.Type) { // Tested on PSP: R_MIPS_NONE just returns 0. case Elf.Reloc.TypeEnum.None: // 0 { } break; /* case Elf.Reloc.TypeEnum.Mips16: // 1 { Instruction.IMMU += S; } break; */ case Elf.Reloc.TypeEnum.Mips32: // 2 { Instruction.Value += S; } break; case Elf.Reloc.TypeEnum.MipsRel32: // 3; { throw (new NotImplementedException()); } case Elf.Reloc.TypeEnum.Mips26: // 4 { Instruction.JUMP_Real = Instruction.JUMP_Real + S; } break; case Elf.Reloc.TypeEnum.MipsHi16: // 5 { HiValue = (ushort)Instruction.IMMU; DeferredHi16.AddLast(RelocatedPointerAddress); } break; case Elf.Reloc.TypeEnum.MipsLo16: // 6 { uint A = Instruction.IMMU; Instruction.IMMU = ((uint)(HiValue << 16) | (uint)(A & 0x0000FFFF)) + S; // Process deferred R_MIPS_HI16 foreach (var data_addr2 in DeferredHi16) { var data2 = InstructionReader[data_addr2]; uint result = ((data2.Value & 0x0000FFFF) << 16) + A + S; // The low order 16 bits are always treated as a signed // value. Therefore, a negative value in the low order bits // requires an adjustment in the high order bits. We need // to make this adjustment in two ways: once for the bits we // took from the data, and once for the bits we are putting // back in to the data. if ((A & 0x8000) != 0) { result -= 0x10000; } if ((result & 0x8000) != 0) { result += 0x10000; } data2.IMMU = (result >> 16); InstructionReader[data_addr2] = data2; } DeferredHi16.Clear(); } break; case Elf.Reloc.TypeEnum.MipsGpRel16: // 7 { /* int A = Instruction.IMM; int result; if (A == 0) { result = (int)S - (int)GP_ADDR; } else { result = (int)S + (int)GP_OFFSET + (int)(((A & 0x00008000) != 0) ? (((A & 0x00003FFF) + 0x4000) | 0xFFFF0000) : A) - (int)GP_ADDR; } if ((result < -32768) || (result > 32768)) { Console.Error.WriteLine("Relocation overflow (R_MIPS_GPREL16) : '" + result + "'"); } Instruction.IMMU = (uint)result; */ } break; default: throw(new NotImplementedException("Handling " + Reloc.Type + " not implemented")); } if (RelocOutput != null) RelocOutput.WriteLine( "RELOC %06d : 0x%08X : 0x%08X -> 0x%08X".Sprintf( Index, RelocatedPointerAddress, InstructionBefore.Value, Instruction.Value ) ); /* log.error(String.format( "RELOC %06d : 0x%08X : 0x%08X -> 0x%08X\n", i, data_addr, data_prev, data )); */ InstructionReader[RelocatedPointerAddress] = Instruction; Index++; } }
public static void Show() { //1 内存连续存储,节约空间,可以索引访问,读取快,增删慢 #region Array { //Array:在内存上连续分配的,而且元素类型是一样的 //可以坐标访问 读取快--增删慢,长度不变 Console.WriteLine("***************Array******************"); int[] intArray = new int[3]; intArray[0] = 123; string[] stringArray = new string[] { "123", "234" };//Array } { //ArrayList 不定长的,连续分配的; //元素没有类型限制,任何元素都是当成object处理,如果是值类型,会有装箱操作 //读取快--增删慢 Console.WriteLine("***************ArrayList******************"); ArrayList arrayList = new ArrayList(); arrayList.Add("Eleven"); arrayList.Add("Is"); arrayList.Add(32);//add增加长度 //arrayList[4] = 26;//索引复制,不会增加长度 //删除数据 //arrayList.RemoveAt(4); var value = arrayList[2]; arrayList.RemoveAt(0); arrayList.Remove("Eleven"); } { //List:也是Array,内存上都是连续摆放;不定长;泛型,保证类型安全,避免装箱拆箱 //读取快--增删慢 Console.WriteLine("***************List<T>******************"); List <int> intList = new List <int>() { 1, 2, 3, 4 }; intList.Add(123); intList.Add(123); //intList.Add("123"); //intList[0] = 123; List <string> stringList = new List <string>(); //stringList[0] = "123";//异常的 foreach (var item in intList) { } } #endregion //2 非连续摆放,存储数据+地址,找数据的话就只能顺序查找,读取慢;增删快, #region 链表 { //LinkedList:泛型的特点;链表,元素不连续分配,每个元素都有记录前后节点 //节点值可以重复 //能不能下标访问?不能,找元素就只能遍历 查找不方便 //增删 就比较方便 Console.WriteLine("***************LinkedList<T>******************"); LinkedList <int> linkedList = new LinkedList <int>(); //linkedList[3] linkedList.AddFirst(123); linkedList.AddLast(456); bool isContain = linkedList.Contains(123); LinkedListNode <int> node123 = linkedList.Find(123); //元素123的位置 从头查找 linkedList.AddBefore(node123, 123); linkedList.AddBefore(node123, 123); linkedList.AddAfter(node123, 9); linkedList.Remove(456); linkedList.Remove(node123); linkedList.RemoveFirst(); linkedList.RemoveLast(); linkedList.Clear(); } { //Queue 就是链表 先进先出 放任务延迟执行,A不断写入日志任务 B不断获取任务去执行 Console.WriteLine("***************Queue<T>******************"); Queue <string> numbers = new Queue <string>(); numbers.Enqueue("one"); numbers.Enqueue("two"); numbers.Enqueue("three"); numbers.Enqueue("four"); numbers.Enqueue("four"); numbers.Enqueue("five"); foreach (string number in numbers) { Console.WriteLine(number); } Console.WriteLine($"Dequeuing '{numbers.Dequeue()}'"); Console.WriteLine($"Peek at next item to dequeue: { numbers.Peek()}"); Console.WriteLine($"Dequeuing '{numbers.Dequeue()}'"); Queue <string> queueCopy = new Queue <string>(numbers.ToArray()); foreach (string number in queueCopy) { Console.WriteLine(number); } Console.WriteLine($"queueCopy.Contains(\"four\") = {queueCopy.Contains("four")}"); queueCopy.Clear(); Console.WriteLine($"queueCopy.Count = {queueCopy.Count}"); } //队列是没瓶底的瓶子,栈是有瓶底的瓶子 { //Stack 就是链表 先进后出 解析表达式目录树的时候,先产生的数据后使用 //操作记录为命令,撤销的时候是倒序的 Console.WriteLine("***************Stack<T>******************"); Stack <string> numbers = new Stack <string>(); numbers.Push("one"); numbers.Push("two"); numbers.Push("three"); numbers.Push("four"); numbers.Push("five");//放进去 foreach (string number in numbers) { Console.WriteLine(number); } Console.WriteLine($"Pop '{numbers.Pop()}'"); //获取并移除 Console.WriteLine($"Peek at next item to dequeue: { numbers.Peek()}"); //获取不移除 Console.WriteLine($"Pop '{numbers.Pop()}'"); Stack <string> stackCopy = new Stack <string>(numbers.ToArray()); foreach (string number in stackCopy) { Console.WriteLine(number); } Console.WriteLine($"stackCopy.Contains(\"four\") = {stackCopy.Contains("four")}"); stackCopy.Clear(); Console.WriteLine($"stackCopy.Count = {stackCopy.Count}"); } #endregion //set纯粹的集合,容器,东西丢进去,唯一性 无序的 #region Set { //集合:hash分布,元素间没关系,动态增加容量 去重 //统计用户IP;IP投票 交叉并补--二次好友/间接关注/粉丝合集 Console.WriteLine("***************HashSet<string>******************"); HashSet <string> hashSet = new HashSet <string>(); hashSet.Add("123"); hashSet.Add("689"); hashSet.Add("456"); hashSet.Add("12435"); hashSet.Add("12435"); hashSet.Add("12435"); //hashSet[0]; foreach (var item in hashSet) { Console.WriteLine(item); } Console.WriteLine(hashSet.Count); Console.WriteLine(hashSet.Contains("12345")); { HashSet <string> hashSet1 = new HashSet <string>(); hashSet1.Add("123"); hashSet1.Add("689"); hashSet1.Add("789"); hashSet1.Add("12435"); hashSet1.Add("12435"); hashSet1.Add("12435"); hashSet1.SymmetricExceptWith(hashSet); //补 hashSet1.UnionWith(hashSet); //并 hashSet1.ExceptWith(hashSet); //差 hashSet1.IntersectWith(hashSet); //交 //风--亡五 找出共同的好友 } hashSet.ToList(); hashSet.Clear(); } { //排序的集合:去重 而且排序 //统计排名--每统计一个就丢进去集合 Console.WriteLine("***************SortedSet<string>******************"); SortedSet <string> sortedSet = new SortedSet <string>(); //IComparer<T> comparer 自定义对象要排序,就用这个指定 sortedSet.Add("123"); sortedSet.Add("689"); sortedSet.Add("456"); sortedSet.Add("12435"); sortedSet.Add("12435"); sortedSet.Add("12435"); foreach (var item in sortedSet) { Console.WriteLine(item); } Console.WriteLine(sortedSet.Count); Console.WriteLine(sortedSet.Contains("12345")); { SortedSet <string> sortedSet1 = new SortedSet <string>(); sortedSet1.Add("123"); sortedSet1.Add("689"); sortedSet1.Add("456"); sortedSet1.Add("12435"); sortedSet1.Add("12435"); sortedSet1.Add("12435"); sortedSet1.SymmetricExceptWith(sortedSet); //补 sortedSet1.UnionWith(sortedSet); //并 sortedSet1.ExceptWith(sortedSet); //差 sortedSet1.IntersectWith(sortedSet); //交 } sortedSet.ToList(); sortedSet.Clear(); } #endregion //读取&增删都快? 有 hash散列 字典 //key-value,一段连续有限空间放value(开辟的空间比用到的多,hash是用空间换性能),基于key散列计算得到地址索引,这样读取快 //增删也快,删除时也是计算位置,增加也不影响别人 //肯定会出现2个key(散列冲突),散列结果一致18,可以让第二次的+1, //可能会造成效率的降低,尤其是数据量大的情况下,以前测试过dictionary在3w条左右性能就开始下降的厉害 #region key-value { //Hashtable key-value 体积可以动态增加 拿着key计算一个地址,然后放入key - value //object-装箱拆箱 如果不同的key得到相同的地址,第二个在前面地址上 + 1 //查找的时候,如果地址对应数据的key不对,那就 + 1查找。。 //浪费了空间,Hashtable是基于数组实现 //查找个数据 一次定位; 增删 一次定位; 增删查改 都很快 //浪费空间,数据太多,重复定位定位,效率就下去了 Console.WriteLine("***************Hashtable******************"); Hashtable table = new Hashtable(); table.Add("123", "456"); table[234] = 456; table[234] = 567; table[32] = 4562; table[1] = 456; table["eleven"] = 456; foreach (DictionaryEntry objDE in table) { Console.WriteLine(objDE.Key.ToString()); Console.WriteLine(objDE.Value.ToString()); } //线程安全 Hashtable.Synchronized(table);//只有一个线程写 多个线程读 } { //字典:泛型;key - value,增删查改 都很快;有序的 // 字典不是线程安全 ConcurrentDictionary Console.WriteLine("***************Dictionary******************"); Dictionary <int, string> dic = new Dictionary <int, string>(); dic.Add(1, "HaHa"); dic.Add(5, "HoHo"); dic.Add(3, "HeHe"); dic.Add(2, "HiHi"); dic.Add(4, "HuHu1"); dic[4] = "HuHu"; dic.Add(4, "HuHu"); foreach (var item in dic) { Console.WriteLine($"Key:{item.Key}, Value:{item.Value}"); } } { Console.WriteLine("***************SortedDictionary******************"); SortedDictionary <int, string> dic = new SortedDictionary <int, string>(); dic.Add(1, "HaHa"); dic.Add(5, "HoHo"); dic.Add(3, "HeHe"); dic.Add(2, "HiHi"); dic.Add(4, "HuHu1"); dic[4] = "HuHu"; dic.Add(4, "HuHu"); foreach (var item in dic) { Console.WriteLine($"Key:{item.Key}, Value:{item.Value}"); } } { //"a".GetHashCode(); Console.WriteLine("***************SortedList******************"); SortedList sortedList = new SortedList();//IComparer sortedList.Add("First", "Hello"); sortedList.Add("Second", "World"); sortedList.Add("Third", "!"); sortedList["Third"] = "~~"; // sortedList.Add("Fourth", "!"); sortedList.Add("Fourth", "!"); //重复的Key Add会错 sortedList["Fourth"] = "!!!"; var keyList = sortedList.GetKeyList(); var valueList = sortedList.GetValueList(); sortedList.TrimToSize();//用于最小化集合的内存开销 sortedList.Remove("Third"); sortedList.RemoveAt(0); sortedList.Clear(); } #endregion { //ConcurrentQueue 线程安全版本的Queue //ConcurrentStack线程安全版本的Stack //ConcurrentBag线程安全的对象集合 //ConcurrentDictionary线程安全的Dictionary //BlockingCollection } { List <string> fruits = new List <string> { "apple", "passionfruit", "banana", "mango", "orange", "blueberry", "grape", "strawberry" }; IEnumerable <string> query = fruits.Where(fruit => fruit.Length < 6); foreach (var item in query)//遍历才会去查询比较 迭代器 yield { } IQueryable <string> queryable = fruits.AsQueryable <string>().Where(s => s.Length > 5); foreach (var item in queryable)//表达式目录树的解析,延迟到遍历的时候才去执行 EF的延迟查询 { } } }
private void InitializeGrid(ContentManager Content) { // Make the list of buttons for each type of grid. // This is super messy and should be more data-driven. But it works. // This is the position on the screen of the top left button on the grid Point StartPos = Point.Zero; StartPos.Y = GraphicsManager.Get().Height - m_LeftPanel.Height + 44; StartPos.X += 16; // These are used for the default and focus textures of the respective grid button Texture2D DefaultTex = null; Texture2D FocusTex = null; // These integers represent the row/column of the button in the grid; this is used // with the button size constant to know where a button should be. int iGridRow = 0; int iGridCol = 0; const int ButtonSize = 66; // This is the data used to store all of the grids Button b = null; int iBtnGrid = (int)eGridState.Default; m_BtnGrids[iBtnGrid] = new LinkedList<Button>(); LinkedList<TipData> tipdata = new LinkedList<TipData>(); // The default grid (nothing selected) has no buttons // So don't do anything here // Make the build button grid // This grid is when you click on a hex that doesn't have a building currently iGridRow = 0; iGridCol = 0; iBtnGrid = (int)eGridState.Build; m_BtnGrids[iBtnGrid] = new LinkedList<Button>(); // Projectile Tower button tipdata.Clear(); tipdata.AddLast(new TipData(eTipData.Keybind, eBindings.UI_ProjectileTower)); tipdata.AddLast(new TipData(eTipData.TowerBuildCost, eTowerType.Projectile)); tipdata.AddLast(new TipData(eTipData.TowerBuildTime, eTowerType.Projectile)); DefaultTex = Content.Load<Texture2D>("UI/Btn_Projectile_Default"); FocusTex = Content.Load<Texture2D>("UI/Btn_Projectile_Focus"); b = new Button(new Point(StartPos.X + iGridCol * ButtonSize, StartPos.Y + iGridRow * ButtonSize), DefaultTex, FocusTex, Build_ProjectileTower, "tip_projectiletower", tipdata); b.Enabled = false; m_Buttons.AddLast(b); m_BtnGrids[iBtnGrid].AddLast(b); iGridCol++; // Slow Tower button tipdata.Clear(); tipdata.AddLast(new TipData(eTipData.Keybind, eBindings.UI_SlowTower)); tipdata.AddLast(new TipData(eTipData.TowerBuildCost, eTowerType.Slow)); tipdata.AddLast(new TipData(eTipData.TowerBuildTime, eTowerType.Slow)); DefaultTex = Content.Load<Texture2D>("UI/Btn_Slow_Default"); FocusTex = Content.Load<Texture2D>("UI/Btn_Slow_Focus"); b = new Button(new Point(StartPos.X + iGridCol * ButtonSize, StartPos.Y + iGridRow * ButtonSize), DefaultTex, FocusTex, Build_SlowTower, "tip_slowtower", tipdata); b.Enabled = false; m_Buttons.AddLast(b); m_BtnGrids[iBtnGrid].AddLast(b); iGridCol++; // Make the Upgrade grid // This grid is when you click on a hex that has a building already (other than the base) iGridRow = 0; iGridCol = 0; iBtnGrid = (int)eGridState.Upgrade; m_BtnGrids[iBtnGrid] = new LinkedList<Button>(); // Upgrade button tipdata.Clear(); tipdata.AddLast(new TipData(eTipData.TowerName)); tipdata.AddLast(new TipData(eTipData.Keybind, eBindings.UI_Upgrade)); tipdata.AddLast(new TipData(eTipData.TowerLevel)); tipdata.AddLast(new TipData(eTipData.TowerUpgradeCost)); tipdata.AddLast(new TipData(eTipData.TowerUpgradeTime)); tipdata.AddLast(new TipData(eTipData.TowerUpgradeText)); DefaultTex = Content.Load<Texture2D>("UI/Btn_Upgrade_Default"); FocusTex = Content.Load<Texture2D>("UI/Btn_Upgrade_Focus"); b = new Button(new Point(StartPos.X + iGridCol * ButtonSize, StartPos.Y + iGridRow * ButtonSize), DefaultTex, FocusTex, Upgrade_Upgrade, "tip_upgrade", tipdata); b.Enabled = false; m_Buttons.AddLast(b); m_BtnGrids[iBtnGrid].AddLast(b); iGridCol++; // Cancel button iGridRow = 2; iGridCol = 3; tipdata.Clear(); tipdata.AddLast(new TipData(eTipData.Keybind, eBindings.UI_Delete)); tipdata.AddLast(new TipData(eTipData.TowerRefund)); DefaultTex = Content.Load<Texture2D>("UI/Btn_Cancel_Default"); FocusTex = Content.Load<Texture2D>("UI/Btn_Cancel_Focus"); b = new Button(new Point(StartPos.X + iGridCol * ButtonSize, StartPos.Y + iGridRow * ButtonSize), DefaultTex, FocusTex, Upgrade_Delete, "tip_delete", tipdata); b.Enabled = false; m_Buttons.AddLast(b); m_BtnGrids[iBtnGrid].AddLast(b); iGridCol++; }
public void Clear() { _memoryCache.Clear(); _recentlyUsed.Clear(); EstimatedMemorySize = 0; }
public void buttonRemoveSTL_Click(object sender, EventArgs e) { //STL stl = (STL)listSTLObjects.SelectedItem; //if (stl == null) return; LinkedList<STL> list = new LinkedList<STL>(); foreach (STL stl in listSTLObjects.SelectedItems) list.AddLast(stl); foreach (STL stl in list) { cont.models.Remove(stl); listSTLObjects.Items.Remove(stl); autosizeFailed = false; // Reset autoposition } list.Clear(); if (listSTLObjects.Items.Count > 0) listSTLObjects.SelectedIndex = 0; Main.main.threedview.UpdateChanges(); }
public void Clear() { _activeQueue.Clear(); _addedCache.Clear(); _deletedCache.Clear(); }
private void HandleData(Data data) { MinorityOutstandingSubscriptions--; if (data.MPR < MinPRInWindow) { MinPRInWindow = data.MPR; } if (data.Mark) { MinorityAccumulate = 0; if (MinorityWindowSize > 1) { MinorityWindowSize /= 2; } MinPRs.Clear(); MinPRInWindow = Int32.MaxValue; State = 0; } else { MinorityAccumulate++; while (MinorityAccumulate >= MinorityWindowSize) { MinorityAccumulate -= MinorityWindowSize; switch (State) { case 0: { if (MinPRInWindow >= WINDOW_SIZE_THRESHOLD) { State = 1; } else { MinorityWindowSize++; if (MinPRInWindow > 0) { State = 2; } } break; } case 1: { if (MinPRInWindow == 0) { MinorityWindowSize++; State = 0; } else { if (MinPRs.Count >= WINDOW_COUNT_THRESHOLD && MinPRs.All(x => x > 0)) { State = 3; } else if (MinPRInWindow < WINDOW_SIZE_THRESHOLD) { MinorityWindowSize++; State = 2; } } break; } case 2: { if (MinPRInWindow >= WINDOW_SIZE_THRESHOLD) { State = 1; } else if (MinPRInWindow == 0) { MinorityWindowSize++; State = 0; } else if (MinPRs.Count >= WINDOW_COUNT_THRESHOLD && MinPRs.All(x => x > 0)) { State = 3; } else { MinorityWindowSize++; } break; } case 3: { if (MinPRInWindow == 0) { State = 4; } break; } case 4: { if (MinPRInWindow > 0) { State = 3; } else if (MinPRs.Count >= WINDOW_COUNT_THRESHOLD && MinPRs.All(x => x == 0)) { MinorityWindowSize++; State = 0; } break; } } MinPRs.AddLast(MinPRInWindow); while (MinPRs.Count > WINDOW_COUNT_THRESHOLD) { MinPRs.RemoveFirst(); } MinPRInWindow = Int32.MaxValue; } } int count = MinorityWindowSize - MinorityOutstandingSubscriptions; if (count > 0) { SendInterest(count); MinorityOutstandingSubscriptions = MinorityWindowSize; } Console.WriteLine("{0},{1},{2},{3}", MinorityWindowSize, State, MinPRInWindow, data.Mark); }
public void Clear() { _items?.Clear(); }
public void Clear() { _cacheMap?.Clear(); _lruList?.Clear(); }
public void Clear() { Stop(); m_CommandList.Clear(); }