public void TrimExcess() { var set = new HashSet <int>(); foreach (int item in Enumerable.Range(100, 1000)) { set.Add(item); } Assert.AreEqual(1000, set.Count); set.TrimExcess(); Assert.AreEqual(1000, set.Count); foreach (int item in Enumerable.Range(100, 1000)) { Assert.IsTrue(set.Contains(item)); } foreach (int item in Enumerable.Range(100, 1000).Where(i => i % 2 == 0)) { set.Remove(item); } set.TrimExcess(); Assert.AreEqual(500, set.Count); Assert.IsTrue(set.All(i => i % 2 == 1)); }
internal void ClearAndTrim() { using (Lock.WriterLock()) { HashSet.Clear(); HashSet.TrimExcess(); } }
private static void SetExpirationTimer() { if (_expirationTimerSetted) { return; } _expirationTimerSetted = true; _globalExpirationTimer?.Dispose(); _globalExpirationTimer = new Timer(i => { if (_runningTimer) { return; } try { _runningTimer = true; StorageItemMeta[] metasToRemove; lock (LockPad) { metasToRemove = AllMetas.Where(m => m.IsExpired).ToArray(); foreach (var meta in metasToRemove) { if (AllMetas.Remove(meta)) { _currentCount--; } } } foreach (var meta in metasToRemove) { try { meta?.FireOnExpire(); } catch (Exception ex) { Core.Log.Write(ex); } } if (metasToRemove.Length > 0 && _registeredCount > 0 && (double)_currentCount / _registeredCount < 0.6) { lock (LockPad) AllMetas.TrimExcess(); GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce; GC.Collect(); _registeredCount = _currentCount; } } catch (Exception ex) { Core.Log.Write(ex); } finally { _runningTimer = false; } }, null, 5000, 5000); }
public void MoneyAPI_Exit() { foreach (Client player in SaveList) { SaveWallet(player, true); } SaveList.Clear(); SaveList.TrimExcess(); }
public void HashSet_Generic_TrimExcess_Repeatedly(int setLength) { HashSet <T> set = (HashSet <T>)GenericISetFactory(setLength); List <T> expected = set.ToList(); set.TrimExcess(); set.TrimExcess(); set.TrimExcess(); Assert.True(set.SetEquals(expected)); }
private static void SetExpirationTimer() { if (Interlocked.CompareExchange(ref _expirationTimerSetted, 1, 0) == 1) { return; } _globalExpirationTimer?.Dispose(); _globalExpirationTimer = new Timer(i => { if (Interlocked.CompareExchange(ref _runningTimer, 1, 0) == 1) { return; } try { StorageItemMeta[] metasToRemove; lock (LockPad) { metasToRemove = AllMetas.Where(m => m.IsExpired).ToArray(); foreach (var meta in metasToRemove) { if (AllMetas.Remove(meta)) { _currentCount--; } } } foreach (var meta in metasToRemove) { try { meta?.FireOnExpire(); } catch (Exception ex) { Core.Log.Write(ex); } } if (metasToRemove.Length > 0 && _registeredCount > 0 && (double)_currentCount / _registeredCount < 0.6) { lock (LockPad) AllMetas.TrimExcess(); _registeredCount = _currentCount; } } catch (Exception ex) { Core.Log.Write(ex); } finally { Interlocked.Exchange(ref _runningTimer, 0); } }, null, 5000, 5000); }
internal void ClearAndTrim() { Lock.EnterWriteLock(); try { HashSet.Clear(); HashSet.TrimExcess(); } finally { Lock.ExitWriteLock(); } }
private void CheckMsgBuff() { while (true) { try { HashSet <AsyncUserToken> RemoveList = new HashSet <AsyncUserToken>(); lock (locker1) { foreach (AsyncUserToken x in connList) { TimeSpan timeSpan = DateTime.Now - x.EndMsgTime; if (x.Buffer.Count > 0 && timeSpan.TotalSeconds > 10) //大于10秒认为设备不会再回消息了 { RemoveList.Add(x); } } foreach (AsyncUserToken x in RemoveList) { byte[] rev = x.Buffer.GetRange(0, x.Buffer.Count).ToArray(); string da = System.Text.Encoding.Default.GetString(rev).Trim(); if (!string.IsNullOrEmpty(da)) { Xml_codec.StaticOutputLog(LogInfoType.EROR, string.Format("清除设备[{0}:{1}]缓存消息。", x.IPAddress.ToString(), x.Port), "DeviceList"); Xml_codec.StaticOutputLog(LogInfoType.DEBG, string.Format("清除消息内容:\n{0}", da), "DeviceList"); } rev = null; da = null; x.Buffer.Clear(); x.Buffer.TrimExcess(); } connList.TrimExcess(); RemoveList.Clear(); RemoveList.TrimExcess(); } Thread.Sleep(10000); } catch (Exception e) { Xml_codec.StaticOutputLog(LogInfoType.EROR, string.Format("线程[CheckMsgBuff]出错。错误码:{0}", e.Message), "DeviceList"); } } }
public static void TrimExcess_Test3() { HashSet<int> hashSet; int[] values; hashSet = new HashSet<int>(); AddItemsInt(hashSet, 197, out values); hashSet.Clear(); hashSet.TrimExcess(); hashSet.TrimExcess(); HashSetTestSupport<int>.VerifyHashSet(hashSet, new int[0], EqualityComparer<int>.Default); }
public static void TrimExcess_Test3() { HashSet <int> hashSet; int[] values; hashSet = new HashSet <int>(); AddItemsInt(hashSet, 197, out values); hashSet.Clear(); hashSet.TrimExcess(); hashSet.TrimExcess(); HashSetTestSupport <int> .VerifyHashSet(hashSet, new int[0], EqualityComparer <int> .Default); }
public void HashSet_Generic_TrimExcess_AfterClearingAndAddingAllElementsBack(int setLength) { if (setLength > 0) { HashSet <T> set = (HashSet <T>)GenericISetFactory(setLength); set.TrimExcess(); set.Clear(); set.TrimExcess(); Assert.Equal(0, set.Count); AddToCollection(set, setLength); set.TrimExcess(); Assert.Equal(setLength, set.Count); } }
internal void ReplaceWith(IEnumerable<T> items) { Lock.EnterWriteLock(); try { HashSet.Clear(); foreach (T item in items) { HashSet.Add(item); } HashSet.TrimExcess(); } finally { Lock.ExitWriteLock(); } }
public Form3() { CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture; InitializeComponent(); selected_windows_to_save.Clear(); selected_windows_to_save.TrimExcess(); sw_txtBox.KeyPress += (s, e) => { if (e.KeyChar == (char)13) { if (Find_selected_windows_to_save() == true) { Save_selected_windows(); this.Hide(); } } }; }
static void Main() { //<snippet02> HashSet <int> Numbers = new HashSet <int>(); for (int i = 0; i < 10; i++) { Numbers.Add(i); } Console.Write("Numbers contains {0} elements: ", Numbers.Count); DisplaySet(Numbers); Numbers.Clear(); Numbers.TrimExcess(); Console.Write("Numbers contains {0} elements: ", Numbers.Count); DisplaySet(Numbers); void DisplaySet(HashSet <int> set) { Console.Write("{"); foreach (int i in set) { Console.Write(" {0}", i); } Console.WriteLine(" }"); } /* This example produces output similar to the following: * Numbers contains 10 elements: { 0 1 2 3 4 5 6 7 8 9 } * Numbers contains 0 elements: { } */ //</snippet02> }
public void EmptySetTrimExcessTest() { var set = new HashSet <int>(); set.TrimExcess(); Assert.AreEqual(set.Count, 0); }
public int lruCacheMisses_int(int num, List <int> pages, int maxCacheSize) { // If the max cache size is zero. Then every element will be a new item. if (maxCacheSize == 0) { return (pages.Count); } HashSet <int> cache = new HashSet <int>(); int count = 0; foreach (int page in pages) { if (cache.Contains(page)) { // Move the element to the end. cache.Remove(page); cache.TrimExcess(); cache.Add(page); } else { if (cache.Count == maxCacheSize) { // If cache is full, then get the first element and remove from cache int first = cache.First(); cache.Remove(first); } cache.Add(page); count++; } } return(count); }
/// <summary> /// Reset this instance. /// </summary> public void Reset() { Name = ""; segmentsSet.Clear(); segmentsSet.TrimExcess(); route.Clear(); }
private async Task ParseActiveTrades() { if (string.IsNullOrEmpty(Bot.BotConfig.SteamApiKey)) { return; } HashSet <Steam.TradeOffer> tradeOffers = Bot.ArchiWebHandler.GetTradeOffers(); if ((tradeOffers == null) || (tradeOffers.Count == 0)) { return; } tradeOffers.RemoveWhere(tradeoffer => tradeoffer.State != Steam.TradeOffer.ETradeOfferState.Active); tradeOffers.TrimExcess(); if (tradeOffers.Count == 0) { return; } await tradeOffers.ForEachAsync(ParseTrade).ConfigureAwait(false); await Bot.AcceptConfirmations(true, Confirmation.ConfirmationType.Trade).ConfigureAwait(false); }
public void TrimExcess() { lock (this.LockObject) { _hashSet.TrimExcess(); } }
public void TrimExcess() { lock (this.ThisLock) { _hashSet.TrimExcess(); } }
private async Task ParseActiveTrades() { if (string.IsNullOrEmpty(Bot.BotConfig.SteamApiKey)) { return; } HashSet <Steam.TradeOffer> tradeOffers = Bot.ArchiWebHandler.GetTradeOffers(); if ((tradeOffers == null) || (tradeOffers.Count == 0)) { return; } if (tradeOffers.RemoveWhere(tradeoffer => (tradeoffer.State != Steam.TradeOffer.ETradeOfferState.Active) || IgnoredTrades.Contains(tradeoffer.TradeOfferID)) > 0) { tradeOffers.TrimExcess(); if (tradeOffers.Count == 0) { return; } } List <Task <ParseTradeResult> > tasks = tradeOffers.Select(ParseTrade).ToList(); ParseTradeResult[] results = await Task.WhenAll(tasks).ConfigureAwait(false); if (results.Any(result => result == ParseTradeResult.AcceptedWithItemLose)) { await Task.Delay(1000).ConfigureAwait(false); // Sometimes we can be too fast for Steam servers to generate confirmations, wait a short moment HashSet <ulong> tradeIDs = new HashSet <ulong>(tradeOffers.Select(tradeOffer => tradeOffer.TradeOfferID)); await Bot.AcceptConfirmations(true, Steam.ConfirmationDetails.EType.Trade, 0, tradeIDs).ConfigureAwait(false); } }
public void HashSet_Generic_TrimExcess_AfterRemovingOneElement(int setLength) { if (setLength > 0) { HashSet <T> set = (HashSet <T>)GenericISetFactory(setLength); List <T> expected = set.ToList(); T elementToRemove = set.ElementAt(0); set.TrimExcess(); Assert.True(set.Remove(elementToRemove)); expected.Remove(elementToRemove); set.TrimExcess(); Assert.True(set.SetEquals(expected)); } }
static Helpers() { TypesWriteableByPrimitiveWriter = new HashSet <Type>( typeof(PrimitiveWriter).GetMethods().Where(x => x.Name == "Write").Select(x => x.GetParameters()[0].ParameterType).Where(x => x != typeof(string) && x != typeof(byte[]))); TypesWriteableByPrimitiveWriter.TrimExcess(); AttrbuteIsDefinedLookup = new ConcurrentDictionary <Type, bool>(); }
public Ignores(IEnumerable <string> ignoreSources) { if (ignoreSources != null) { ignores = new HashSet <string>(ignoreSources, StringComparer.OrdinalIgnoreCase); ignores.TrimExcess(); } }
/// <summary> /// 检测Ap在线状态 /// </summary> private void CheckApStatusThread() { long upTime = 0; HashSet <AsyncUserToken> toKenList = new HashSet <AsyncUserToken>(); HashSet <AsyncUserToken> RemovList = new HashSet <AsyncUserToken>(); while (true) { try { if (DeviceType != null && ((DateTime.Now.Ticks - upTime) / 10000000) > 60) { upTime = DateTime.Now.Ticks; //报到线程状态 FrmMainController.write_monitor_status(DeviceType + "_STATUS"); } MyDeviceList.CopyConnList(ref toKenList); foreach (AsyncUserToken x in toKenList) { TimeSpan timeSpan = DateTime.Now - x.EndMsgTime; if (timeSpan.TotalSeconds > DataController.ApOnLineTime) //大于180秒认为设备下线 { RemovList.Add(x); } } //删除已下线的AP foreach (AsyncUserToken x in RemovList) { string MainControllerStatus = MyDeviceList.GetMainControllerStatus(x); if (string.IsNullOrEmpty(MainControllerStatus)) { MainControllerStatus = "unknown"; } int i = MyDeviceList.remov(x); if (i != -1) { CloseToken(x); OnOutputLog(LogInfoType.INFO, string.Format("Ap[{0}:{1}]下线了!!!", x.IPAddress, x.Port.ToString())); Send2main_OnOffLine(OffLine, i, x, MainControllerStatus); } } //OnOutputLog(LogInfoType.DEBG, "当前在线Ap数量为:" + MyDeviceList.GetCount().ToString() + "台 !"); toKenList.Clear(); toKenList.TrimExcess(); RemovList.Clear(); RemovList.TrimExcess(); Thread.Sleep(3000); } catch (Exception e) { OnOutputLog(LogInfoType.EROR, string.Format("线程[CheckApStatusThread]出错。错误码:{0}", e.Message)); } } }
public static void TrimExcess_Test1() { HashSet <int> hashSet; hashSet = new HashSet <int>(); hashSet.TrimExcess(); HashSetTestSupport <int> .VerifyHashSet(hashSet, new int[0], EqualityComparer <int> .Default); }
public void TrimExcess() { lock (mHashSet) { HashSet <T> copy = GetCopy(); copy.TrimExcess(); mHashSet = copy; } }
public static void TrimExcess_Test1() { HashSet<int> hashSet; hashSet = new HashSet<int>(); hashSet.TrimExcess(); HashSetTestSupport<int>.VerifyHashSet(hashSet, new int[0], EqualityComparer<int>.Default); }
/// <summary> /// Sets the capacity to the actual number of elements in the BinaryHeap, /// if that number is less than a threshold value. /// </summary> /// <remarks> /// The current threshold value is 90% (.NET 3.5), but might change in a future release. /// </remarks> public void TrimExcess() { mKeys.TrimExcess(); mItems.TrimExcess(); if (mUseHashSet) { mHash.TrimExcess(); } }
public void EnumerableBreakAfterTrimExcess() { var set = new HashSet <int>(Enumerable.Range(0, 10)); foreach (var item in set) { set.TrimExcess(); } }
public void TrimToBaseCapacity() { while (Capacity > BaseCapacity && m_unused.Count > 0) { m_unused.Pop(); } m_unused.TrimExcess(); m_active.TrimExcess(); m_marked.TrimExcess(); Debug.Assert(Capacity == BaseCapacity, "Could not trim to base capacity (possibly due to active objects)."); }
public void ImmutabilityAfterTrimExcessTest() { var set = new HashSet <int>(Enumerable.Range(0, 100)); set.TrimExcess(); Assert.AreEqual(set.Count, 100); for (int i = 0; i < 100; i++) { Assert.IsTrue(set.Contains(i)); } }
public static void TrimExcess_Test4() { HashSet<int> hashSet; HashSet<int> hashSet2; int[] values; List<int> remainingValues; hashSet = new HashSet<int>(); AddItemsInt(hashSet, 198, out values); remainingValues = new List<int>(values); hashSet.Remove(0); remainingValues.Remove(0); hashSet.TrimExcess(); hashSet2 = new HashSet<int>(); AddItemsInt(hashSet2, 197); HashSetTestSupport<int>.VerifyHashSet(hashSet, remainingValues, EqualityComparer<int>.Default); }
public void EnumerableBreakAfterTrimExcess() { var set = new HashSet<int>(Enumerable.Range(0, 10)); foreach (var item in set) { set.TrimExcess(); } }
public string RemoveInterjections(string text) { if (_interjectionList == null) { var interjectionList = new HashSet<string>(); foreach (var s in Configuration.Settings.Tools.Interjections.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)) { if (s.Length > 0) { interjectionList.Add(s); var upper = s.ToUpper(); interjectionList.Add(upper); var lower = s.ToLower(); interjectionList.Add(lower); interjectionList.Add(lower.CapitalizeFirstLetter()); } } _interjectionList = new List<string>(interjectionList); interjectionList.Clear(); interjectionList.TrimExcess(); _interjectionList.Sort(CompareLength); } string oldText = text; bool doRepeat = true; while (doRepeat) { doRepeat = false; foreach (string s in _interjectionList) { if (text.Contains(s)) { var regex = new Regex("\\b" + Regex.Escape(s) + "\\b"); var match = regex.Match(text); if (match.Success) { int index = match.Index; string temp = text.Remove(index, s.Length); while (index == 0 && temp.StartsWith("... ", StringComparison.Ordinal)) { temp = temp.Remove(3, 1); } while (index == 3 && temp.StartsWith("<i>... ", StringComparison.Ordinal)) { temp = temp.Remove(6, 1); } while (index > 2 && (" \r\n".Contains(text.Substring(index - 1, 1))) && temp.Substring(index).StartsWith("... ", StringComparison.Ordinal)) { temp = temp.Remove(index + 3, 1); } if (temp.Remove(0, index) == " —" && temp.EndsWith("— —", StringComparison.Ordinal)) { temp = temp.Remove(temp.Length - 3); if (temp.EndsWith(Environment.NewLine + "—", StringComparison.Ordinal)) temp = temp.Remove(temp.Length - 1).TrimEnd(); } else if (temp.Remove(0, index) == " —" && temp.EndsWith("- —", StringComparison.Ordinal)) { temp = temp.Remove(temp.Length - 3); if (temp.EndsWith(Environment.NewLine + "-", StringComparison.Ordinal)) temp = temp.Remove(temp.Length - 1).TrimEnd(); } else if (index == 2 && temp.StartsWith("- —", StringComparison.Ordinal)) { temp = temp.Remove(2, 2); } else if (index == 2 && temp.StartsWith("- —", StringComparison.Ordinal)) { temp = temp.Remove(2, 1); } else if (index == 0 && temp.StartsWith(" —", StringComparison.Ordinal)) { temp = temp.Remove(0, 2); } else if (index == 0 && temp.StartsWith('—')) { temp = temp.Remove(0, 1); } else if (index > 3 && (temp.Substring(index - 2) == ". —" || temp.Substring(index - 2) == "! —" || temp.Substring(index - 2) == "? —")) { temp = temp.Remove(index - 2, 1).Replace(" ", " "); } string pre = string.Empty; if (index > 0) doRepeat = true; bool removeAfter = true; if (index > s.Length) { if (temp.Length > index - s.Length + 3) { int subIndex = index - s.Length + 1; string subTemp = temp.Substring(subIndex, 3); if (subTemp == ", !" || subTemp == ", ?" || subTemp == ", .") { temp = temp.Remove(subIndex, 2); removeAfter = false; } } if (removeAfter && temp.Length > index - s.Length + 2) { int subIndex = index - s.Length; string subTemp = temp.Substring(subIndex, 3); if (subTemp == ", !" || subTemp == ", ?" || subTemp == ", .") { temp = temp.Remove(subIndex, 2); removeAfter = false; } else { subTemp = temp.Substring(subIndex); if (subTemp.StartsWith(", -—", StringComparison.Ordinal)) { temp = temp.Remove(subIndex, 3); removeAfter = false; } else if (subTemp.StartsWith(", --", StringComparison.Ordinal)) { temp = temp.Remove(subIndex, 2); removeAfter = false; } else if (index > 2 && subTemp.StartsWith("- —", StringComparison.Ordinal)) { temp = temp.Remove(subIndex + 2, 2).Replace(" ", " "); removeAfter = false; } } } if (removeAfter && temp.Length > index - s.Length + 2) { int subIndex = index - s.Length + 1; string subTemp = temp.Substring(subIndex, 2); if (subTemp == "-!" || subTemp == "-?" || subTemp == "-.") { temp = temp.Remove(subIndex, 1); removeAfter = false; } subTemp = temp.Substring(subIndex); if (subTemp == " !" || subTemp == " ?" || subTemp == " .") { temp = temp.Remove(subIndex, 1); removeAfter = false; } } } if (index > 3 && index - 2 < temp.Length) { string subTemp = temp.Substring(index - 2); if (subTemp.StartsWith(", —", StringComparison.Ordinal) || subTemp.StartsWith(", —", StringComparison.Ordinal)) { temp = temp.Remove(index - 2, 1); index--; } if (subTemp.StartsWith("- ...", StringComparison.Ordinal)) { removeAfter = false; } } if (removeAfter) { if (index == 0) { if (temp.StartsWith('-')) temp = temp.Remove(0, 1).Trim(); } else if (index == 3 && temp.StartsWith("<i>-", StringComparison.Ordinal)) { temp = temp.Remove(3, 1); } else if (index > 0 && temp.Length > index) { pre = text.Substring(0, index); temp = temp.Remove(0, index); if (temp.StartsWith('-') && pre.EndsWith('-')) temp = temp.Remove(0, 1); if (temp.StartsWith('-') && pre.EndsWith("- ", StringComparison.Ordinal)) temp = temp.Remove(0, 1); } if (temp.StartsWith("...")) { pre = pre.Trim(); } else { while (temp.Length > 0 && " ,.?!".Contains(temp[0])) { temp = temp.Remove(0, 1); doRepeat = true; } } if (temp.Length > 0 && s[0].ToString(CultureInfo.InvariantCulture) != s[0].ToString(CultureInfo.InvariantCulture).ToLower()) { temp = char.ToUpper(temp[0]) + temp.Substring(1); doRepeat = true; } if (temp.StartsWith('-') && pre.EndsWith(' ')) temp = temp.Remove(0, 1); if (temp.StartsWith('—') && pre.EndsWith(',')) pre = pre.TrimEnd(',') + " "; temp = pre + temp; } if (temp.EndsWith(Environment.NewLine + "- ", StringComparison.Ordinal)) temp = temp.Remove(temp.Length - 2).TrimEnd(); var st = new StrippableText(temp); if (st.StrippedText.Length == 0) return string.Empty; if (temp.StartsWith('-') && !temp.Contains(Environment.NewLine) && text.Contains(Environment.NewLine)) temp = temp.Remove(0, 1).Trim(); text = temp; } } } } var lines = text.SplitToLines(); if (lines.Length == 2 && text != oldText) { if (lines[0] == "-" && lines[1] == "-") return string.Empty; if (lines[0].Length > 1 && lines[0][0] == '-' && lines[1].Trim() == "-") return lines[0].Remove(0, 1).Trim(); if (lines[1].Length > 1 && lines[1][0] == '-' && lines[0].Trim() == "-") return lines[1].Remove(0, 1).Trim(); if (lines[1].Length > 4 && lines[1].StartsWith("<i>-", StringComparison.Ordinal) && lines[0].Trim() == "-") return "<i>" + lines[1].Remove(0, 4).Trim(); if (lines[0].Length > 1 && lines[1] == "-" || lines[1] == "." || lines[1] == "!" || lines[1] == "?") { if (lines[0].StartsWith('-') && oldText.Contains(Environment.NewLine + "-")) lines[0] = lines[0].Remove(0, 1); return lines[0].Trim(); } var noTags0 = HtmlUtil.RemoveHtmlTags(lines[0]).Trim(); var noTags1 = HtmlUtil.RemoveHtmlTags(lines[1]).Trim(); if (noTags0 == "-") { if (noTags1 == noTags0) return string.Empty; if (lines[1].Length > 1 && lines[1][0] == '-') return lines[1].Remove(0, 1).Trim(); if (lines[1].Length > 4 && lines[1].StartsWith("<i>-", StringComparison.Ordinal)) return "<i>" + lines[1].Remove(0, 4).Trim(); return lines[1]; } if (noTags1 == "-") { if (lines[0].Length > 1 && lines[0][0] == '-') return lines[0].Remove(0, 1).Trim(); if (lines[0].Length > 4 && lines[0].StartsWith("<i>-", StringComparison.Ordinal)) { if (!lines[0].Contains("</i>") && lines[1].Contains("</i>")) return "<i>" + lines[0].Remove(0, 4).Trim() + "</i>"; return "<i>" + lines[0].Remove(0, 4).Trim(); } return lines[0]; } } if (lines.Length == 2) { if (string.IsNullOrWhiteSpace(lines[1].Replace(".", string.Empty).Replace("?", string.Empty).Replace("!", string.Empty).Replace("-", string.Empty).Replace("—", string.Empty))) { text = lines[0]; lines = text.SplitToLines(); } else if (string.IsNullOrWhiteSpace(lines[0].Replace(".", string.Empty).Replace("?", string.Empty).Replace("!", string.Empty).Replace("-", string.Empty).Replace("—", string.Empty))) { text = lines[1]; lines = text.SplitToLines(); } } if (lines.Length == 1 && text != oldText && Utilities.GetNumberOfLines(oldText) == 2) { if ((oldText.StartsWith('-') || oldText.StartsWith("<i>-", StringComparison.Ordinal)) && (oldText.Contains("." + Environment.NewLine) || oldText.Contains(".</i>" + Environment.NewLine) || oldText.Contains("!" + Environment.NewLine) || oldText.Contains("!</i>" + Environment.NewLine) || oldText.Contains("?" + Environment.NewLine) || oldText.Contains("?</i>" + Environment.NewLine))) { if (text.StartsWith("<i>-", StringComparison.Ordinal)) text = "<i>" + text.Remove(0, 4).TrimStart(); else text = text.TrimStart('-').TrimStart(); } else if ((oldText.Contains(Environment.NewLine + "-") || oldText.Contains(Environment.NewLine + "<i>-")) && (oldText.Contains("." + Environment.NewLine) || oldText.Contains(".</i>" + Environment.NewLine) || oldText.Contains("!" + Environment.NewLine) || oldText.Contains("!</i>" + Environment.NewLine) || oldText.Contains("?" + Environment.NewLine) || oldText.Contains("?</i>" + Environment.NewLine))) { if (text.StartsWith("<i>-", StringComparison.Ordinal)) text = "<i>" + text.Remove(0, 4).TrimStart(); else text = text.TrimStart('-').TrimStart(); } } if (oldText != text) { text = text.Replace(Environment.NewLine + "<i>" + Environment.NewLine, Environment.NewLine + "<i>"); text = text.Replace(Environment.NewLine + "</i>" + Environment.NewLine, "</i>" + Environment.NewLine); if (text.StartsWith("<i>" + Environment.NewLine)) { text = text.Remove(3, Environment.NewLine.Length); } if (text.EndsWith(Environment.NewLine + "</i>")) { text = text.Remove(text.Length - (Environment.NewLine.Length + 4), Environment.NewLine.Length); } text = text.Replace(Environment.NewLine + "</i>" + Environment.NewLine, "</i>" + Environment.NewLine); } return text; }
private void UpdateChildren( DataGridContext dataGridContext, TableViewColumnVirtualizationManager columnVirtualizationManager, VirtualizingCellCollection parentRowCells ) { //Prevent reentrance if( m_parentRowCells.AlreadyUpdating ) return; m_parentRowCells.AlreadyUpdating = true; if( dataGridContext == null ) throw new DataGridInternalException( "DataGridContext is null for FixedCellPanel" ); if( columnVirtualizationManager == null ) throw new DataGridInternalException( "ColumnVirtualizationManager is null for FixedCellPanel" ); if( parentRowCells == null ) return; this.ClearPermanentScrollingFieldNames(); List<string> currentFieldsName = new List<string>(); currentFieldsName.AddRange( columnVirtualizationManager.FixedFieldNames ); currentFieldsName.AddRange( columnVirtualizationManager.ScrollingFieldNames ); HashSet<Cell> unusedCells = new HashSet<Cell>( parentRowCells.BindedCells ); //Idenfity the binded cells that aren't needed anymore. foreach( string fieldName in currentFieldsName ) { ColumnBase column = dataGridContext.Columns[ fieldName ]; Cell cell; if( parentRowCells.TryGetCell( column, out cell ) ) { //Certain non recyclable cells like StatCells need their content binding to be updated when they become (or stay) in view. cell.AddContentBinding(); unusedCells.Remove( cell ); } } currentFieldsName.Clear(); currentFieldsName.TrimExcess(); //Release the unused binded cells now in order to minimize the number of cell's creation. foreach( Cell cell in unusedCells ) { bool release = this.CanReleaseCell( cell ); //We move the unused cell into the scrolling panel since there is more chance it will be reused there in the future. this.MoveCellToScrollingPanel( cell, release ); if( release ) { parentRowCells.Release( cell ); } //Since the cell cannot be released, it will not be collapsed. We must keep the field name in order to let the scrolling sub-panel measure and arrange the cell out of view. else { //Certain non recyclable cells like StatCells needs their content binding to be removed when they become out of view. cell.RemoveContentBinding(); this.AddPermanentScrollingFieldNames( cell.FieldName ); } } unusedCells.Clear(); unusedCells.TrimExcess(); //Add the missing cells to the fixed region. foreach( string fieldName in columnVirtualizationManager.FixedFieldNames ) { //The cell is created if it is missing. Cell cell = parentRowCells[ fieldName ]; //Make sure the cell is in the appropriate panel. this.MoveCellToFixedPanel( cell ); } //Add the missing cells to the scrolling region. foreach( string fieldName in columnVirtualizationManager.ScrollingFieldNames ) { //The cell is created if it is missing. Cell cell = parentRowCells[ fieldName ]; //Make sure the cell is in the appropriate panel. this.MoveCellToScrollingPanel( cell ); } if( m_clearUnusedCellsDispatcherOperation == null ) { m_clearUnusedCellsDispatcherOperation = this.Dispatcher.BeginInvoke( new Action( this.ClearUnusedCells ), DispatcherPriority.ApplicationIdle ); } m_fixedPanel.InvalidateMeasure(); m_scrollingCellsDecorator.InvalidateMeasure(); m_scrollingPanel.InvalidateMeasure(); m_parentRowCells.AlreadyUpdating = false; }
protected static ICollection<Symbol> ConstructFreeVariables(SCode body, Symbol [] formals) { HashSet<Symbol> freeVariableSet = new HashSet<Symbol> (); body.CollectFreeVariables (freeVariableSet); foreach (Symbol formal in formals) freeVariableSet.Remove (formal); freeVariableSet.TrimExcess (); return freeVariableSet; }
public void TrimExcess() { var set = new HashSet<int>(); foreach (int item in Enumerable.Range(100, 1000)) set.Add(item); Assert.AreEqual(1000, set.Count); set.TrimExcess(); Assert.AreEqual(1000, set.Count); foreach (int item in Enumerable.Range(100, 1000)) Assert.IsTrue(set.Contains(item)); foreach (int item in Enumerable.Range(100, 1000).Where(i => i % 2 == 0)) set.Remove(item); set.TrimExcess(); Assert.AreEqual(500, set.Count); Assert.IsTrue(set.All(i => i % 2 == 1)); }
public static void TrimExcess_Test6() { HashSet<int> hashSet; HashSet<int> hashSet2; int[] values; hashSet = new HashSet<int>(); AddItemsInt(hashSet, 17519); hashSet.Clear(); AddItemsInt(hashSet, 8419, out values); hashSet.TrimExcess(); hashSet2 = new HashSet<int>(); AddItemsInt(hashSet2, 8419); HashSetTestSupport<int>.VerifyHashSet(hashSet, values, EqualityComparer<int>.Default); }
static CollectionMetaToken() { var speciallySerializedTypes = new [] { typeof(List<>), typeof(ReadOnlyCollection<>), typeof(Dictionary<,>), typeof(HashSet<>), typeof(Queue<>), typeof(Stack<>), typeof(BlockingCollection<>), typeof(Hashtable) }; SpeciallySerializedCollections = new HashSet<Type>(speciallySerializedTypes); SpeciallySerializedCollections.TrimExcess(); SpeciallySerializedCollectionsAQNs = new HashSet<string>(speciallySerializedTypes.Select(x => x.AssemblyQualifiedName)); SpeciallySerializedCollectionsAQNs.TrimExcess(); }
public void EmptySetTrimExcessTest() { var set=new HashSet<int>(); set.TrimExcess(); Assert.AreEqual(set.Count, 0); }
public void ImmutabilityAfterTrimExcessTest() { var set = new HashSet<int>(Enumerable.Range(0, 100)); set.TrimExcess(); Assert.AreEqual(set.Count, 100); for (int i = 0; i < 100; i++) { Assert.IsTrue(set.Contains(i)); } }