static void Main(string[] args) { var letters = new HashSet<char>("the quick brown fox"); Console.WriteLine(letters.Contains('t')); // true Console.WriteLine(letters.Contains('j')); // false foreach (char c in letters) { Console.Write(c); // the quickbrownfx } letters.IntersectWith("aeiou"); foreach (char c in letters) { Console.Write(c); // euio } var letters2 = new HashSet<char>("the quick brown fox"); letters2.ExceptWith("aeiou"); foreach (char c in letters2) { Console.Write(c); // th qckbrwnfx } var letters3 = new HashSet<char>("the quick brown fox"); letters3.SymmetricExceptWith("the lazy brown fox"); foreach (char c in letters3) { Console.Write(c); // quicklazy } }
internal override void OnCycle() { ad++; if (ad == 10) { if (_currentCustomer == null) _unit.MoveTo(_unit.GetRoom().GetGameMap().getRandomWalkableSquare()); ad = 0; } if (_currentCustomer != null && _unit.Coordinate == _currentCustomer.SquareInFront) { _unit.Chat("Don't drink it all in one go, savour the flavor!", true); _currentCustomer = null; } RoomUnitManager unitManager = _unit.GetRoom().GetRoomUserManager(); List<Point> area = GetCustomerArea(); List<int> currentCustomers = new List<int>(); foreach (Point p in area) { RoomUser customer = unitManager.GetUnitForSquare(p.X, p.Y) as RoomUser; if (customer == null) continue; currentCustomers.Add(customer.VirtualID); if (!_customers.Contains(customer.VirtualID)) // New customer { _customers.Add(customer.VirtualID); _unit.Chat(string.Format("Hello, {0}", customer.Name), true); } } var test = new HashSet<int>(_customers); test.SymmetricExceptWith(currentCustomers); List<int> toRemove = new List<int>(); foreach (int customerID in test) { if (!currentCustomers.Contains(customerID)) // A customer left { _customers.Remove(customerID); //toRemove.Add(customerID); _unit.Chat(string.Format("Bye, {0}", unitManager.GetRoomUnitByVirtualId(customerID).Name), true); } } // Remove old customers //foreach (int customerID in toRemove) // _customers.Remove(customerID); }
public override System.Collections.IEnumerator Execute(UTContext context) { var theFirstListProperty = firstListProperty.EvaluateIn (context); if (string.IsNullOrEmpty (theFirstListProperty)) { throw new UTFailBuildException ("You must specify the property holding the first list.", this); } var theSecondListProperty = secondListProperty.EvaluateIn (context); if (string.IsNullOrEmpty (theFirstListProperty)) { throw new UTFailBuildException ("You must specify the property holding the second list.", this); } var theOutputProperty = outputProperty.EvaluateIn (context); if (string.IsNullOrEmpty (theFirstListProperty)) { throw new UTFailBuildException ("You must specify the output property.", this); } var firstEnumerable = context [theFirstListProperty]; if (!(firstEnumerable is IEnumerable)) { if (firstEnumerable == null) { throw new UTFailBuildException ("Property '" + theFirstListProperty + "' has a null value. Cannot combine this.", this); } throw new UTFailBuildException ("Property '" + theFirstListProperty + "' is of type '" + firstEnumerable.GetType () + "'. Cannot combine this.", this); } var secondEnumerable = context [theSecondListProperty]; if (!(secondEnumerable is IEnumerable)) { if (secondEnumerable == null) { throw new UTFailBuildException ("Property '" + theSecondListProperty + "' has a null value. Cannot combine this.", this); } throw new UTFailBuildException ("Property '" + theSecondListProperty + "' is of type '" + secondEnumerable.GetType () + "'. Cannot combine this.", this); } var firstListAsSet = new HashSet<object> (); foreach (var obj in (IEnumerable)firstEnumerable) { firstListAsSet.Add (obj); } var secondListAsSet = new HashSet<object> (); foreach (var obj in (IEnumerable)secondEnumerable) { secondListAsSet.Add (obj); } var theListOperationType = listOperationType.EvaluateIn (context); switch (theListOperationType) { case UTCombineListOperation.Union: firstListAsSet.UnionWith (secondListAsSet); break; case UTCombineListOperation.Intersect: firstListAsSet.IntersectWith (secondListAsSet); break; case UTCombineListOperation.Subtract: firstListAsSet.ExceptWith (secondListAsSet); break; case UTCombineListOperation.ExclusiveOr: firstListAsSet.SymmetricExceptWith (secondListAsSet); break; } context [theOutputProperty] = firstListAsSet; yield return ""; }
internal override void CheckSyntax() { if (GroupByClause != null) { if (!Columns.Aggregates.Any()) throw new SqlException("At least one aggregate function must be present along with a GROUP BY clause.\n"); var groupByKeys = GroupByClause.GroupByItems.Select(g => g.Id.LookupId); var nonAggregateSelectKeys = Columns.ColumnSources.Where(c => !(c is AggregateNode)).Select(c => c.Id.LookupId); var difference = new HashSet<string>(groupByKeys, StringComparer.OrdinalIgnoreCase); difference.SymmetricExceptWith(nonAggregateSelectKeys); if (difference.Count > 0) throw new SqlException(string.Format("The query contains the field '{0}' that is not matched between the select list and group by clause.", difference.First())); } else if (Columns.Aggregates.Any() && !Columns.IsAggregateOnlyQuery) throw new SqlException("Your query contains fields and aggregates but no GROUP BY clause.\n"); if ((Columns.Distinct || GroupByClause != null) && OrderByClause != null) { var selectFields = Columns.FieldList; foreach (OrderByItem item in OrderByClause.OrderByItems) { if (!selectFields.Contains(item.Id.LookupId, StringComparer.OrdinalIgnoreCase)) throw new SqlException(string.Format("The query specifies DISTINCT or GROUP BY but contains an ORDER BY field '{0}' that is not included in the result list.", item.Id.LookupId)); } } base.CheckSyntax(); }
private void btnHashSet_Click(object sender, EventArgs e) { clearList(); var letters = new HashSet<char>("teerapong"); string result = ""; foreach (char c in letters) result += c; lsvResult.Items.Add(result); result = ""; lsvResult.Items.Add(letters.Contains('t')); lsvResult.Items.Add(letters.Contains('z')); letters = new HashSet<char>("teerapong"); letters.IntersectWith("aeiou"); foreach (char c in letters) result += c; lsvResult.Items.Add(result); result = ""; letters = new HashSet<char>("teerapong"); letters.ExceptWith("aeiou"); foreach (char c in letters) result += c; lsvResult.Items.Add(result); result = ""; letters = new HashSet<char>("teerapong"); letters.SymmetricExceptWith("teerapongs" ); foreach (char c in letters) result += c; lsvResult.Items.Add(result); result = ""; HashSet<int> first = new HashSet<int>(); HashSet<int> second = new HashSet<int>(); for (var i = 1; i <= 5; i++) { first.Add(5 * i); } for (var j = 1; j <= 5; j++) { second.Add(10 * j); } lsvResult.Items.Add("The table of 5 is:"); foreach (var n in first) { lsvResult.Items.Add(n); } lsvResult.Items.Add("The table of 10 is:"); foreach (var n in second) { lsvResult.Items.Add(n); } }
/// <summary> /// Searches the given directory for plugins. /// </summary> /// <param name="directory">The directory to search.</param> /// <exception cref="ArgumentNullException"> /// Thrown if <paramref name="directory"/> is <see langword="null" />. /// </exception> /// <exception cref="DirectoryNotFoundException"> /// Thrown if <paramref name="directory"/> does not exist. /// </exception> public void SearchDirectory(string directory) { { Lokad.Enforce.Argument(() => directory); } m_Diagnostics.Log( LevelToLog.Info, HostConstants.LogPrefix, string.Format( CultureInfo.InvariantCulture, Resources.Plugins_LogMessage_Detector_FileScanStarted_WithDirectory, directory)); IEnumerable<string> files = Enumerable.Empty<string>(); try { files = m_FileSystem.Directory.GetFiles(directory, "*.dll", SearchOption.AllDirectories); } catch (UnauthorizedAccessException e) { // Something went wrong with the file IO. That probably means we don't have a complete list // so we just exit to prevent any issues from occuring. m_Diagnostics.Log( LevelToLog.Error, HostConstants.LogPrefix, string.Format( CultureInfo.InvariantCulture, Resources.Plugins_LogMessage_Detector_FileScanFailed_WithDirectoryAndException, directory, e)); return; } catch (IOException e) { // Something went wrong with the file IO. That probably means we don't have a complete list // so we just exit to prevent any issues from occuring. m_Diagnostics.Log( LevelToLog.Error, HostConstants.LogPrefix, string.Format( CultureInfo.InvariantCulture, Resources.Plugins_LogMessage_Detector_FileScanFailed_WithDirectoryAndException, directory, e)); return; } var knownFiles = m_Repository.KnownPluginFiles(); var changedKnownFiles = knownFiles .Where(p => files.Exists(f => string.Equals(p.Path, f, StringComparison.OrdinalIgnoreCase))) .Where(p => m_FileSystem.File.GetLastWriteTimeUtc(p.Path) > p.LastWriteTimeUtc) .Select(p => p.Path); var changedFilePaths = new HashSet<string>(files); changedFilePaths.SymmetricExceptWith(knownFiles.Select(p => p.Path)); var newFiles = changedFilePaths.Where(file => m_FileSystem.File.Exists(file)); RemoveDeletedPlugins(changedFilePaths); StorePlugins(changedKnownFiles.Concat(newFiles)); m_Diagnostics.Log( LevelToLog.Info, HostConstants.LogPrefix, string.Format( CultureInfo.InvariantCulture, Resources.Plugins_LogMessage_Detector_FileScanCompleted, directory)); }
static void Main(string[] args) { Console.WriteLine("Combining two collections with no duplicates:"); List<string> colors = new List<string> { "red", "orange", "yellow" }; string[] moreColors = { "orange", "yellow", "green", "blue", "violet" }; // Want to combine but without any duplicates. // Following is just the first stage ... HashSet<string> combined = new HashSet<string>(colors); // ... now for the second stage. // UnionWith() collects items in both lists that aren't duplicated, // resulting in a combined collection whose members are all unique. combined.UnionWith(moreColors); foreach (string color in combined) { Console.WriteLine(color); } Console.WriteLine("\nConverting the combined set to a list:"); // Initialize a new List from combined. List<string> spectrum = new List<string>(combined); foreach(string color in spectrum) { Console.WriteLine("{0}", color); } Console.WriteLine("\nFinding the overlap in two lists:"); List<string> presidentialCandidates = new List<string> { "Clinton", "Edwards", "Giuliani", "McCain", "Obama", "Romney" }; List<string> senators = new List<string> { "Alexander", "Boxer", "Clinton", "McCain", "Obama", "Snowe" }; // Following set hasn't yet weeded out non-Senators ... HashSet<string> senatorsRunning = new HashSet<string>(presidentialCandidates); // ... but IntersectWith() collects items that appear only in both lists, // effectively eliminating the non-Senators. senatorsRunning.IntersectWith(senators); foreach (string senator in senatorsRunning) { Console.WriteLine(senator); } Console.WriteLine("\nExcluding items from a list:"); // Initialize a Queue from an array. Queue<int> queue = new Queue<int>(new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 17 }); // Create a set containing small prime numbers. This is stage 1 of 2. HashSet<int> unique = new HashSet<int> { 1, 3, 5, 7, 9, 11, 13, 15 }; // ExceptWith() removes any items in remainder that are // also in queue: 1, 3, 5, 7, // leaving remainder with 9, 11, 13, 15. Stage 2 of 2. unique.ExceptWith(queue); foreach (int n in unique) { Console.WriteLine(n.ToString()); } Console.WriteLine("\nFinding just the non-overlapping items in two lists:"); Stack<int> stackOne = new Stack<int>(new int[] { 1, 2, 3, 4, 5, 6, 7, 8 }); Stack<int> stackTwo = new Stack<int>(new int[] { 2, 4, 6, 7, 8, 10, 12 }); HashSet<int> nonoverlapping = new HashSet<int>(stackOne); // SymmetricExceptWith() collects items that are in one collection but not // the other: the items that don't overlap. nonoverlapping.SymmetricExceptWith(stackTwo); foreach(int n in nonoverlapping) { Console.WriteLine(n.ToString()); } Console.WriteLine("Press Enter to terminate..."); Console.Read(); }
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("wxw"); arrayList.Add("Is"); arrayList.Add(32);//add增加长度 //arrayList[4] = 26;//索引复制,不会增加长度 //删除数据 //arrayList.RemoveAt(4); var value = arrayList[2]; arrayList.RemoveAt(0); arrayList.Remove("wxw"); } { //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()}'"); //在队列的头部读取和删除一个元素,注意,这里读取元素的同时也删除了这个元素。 numbers.TrimExcess(); //重新设置队列的容量,因为调用Dequeue方法读取删除元素后不会重新设置队列的容量 Queue <string> queueCopy = new Queue <string>(numbers.ToArray()); //ToArray():返回一个包含元素的新数组 // queueCopy.CopyTo(numbers.ToArray(), 1); //CopyTo():把元素队列复制到一个已有的数组中 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 Pop: { 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 HashSet { //集合: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的延迟查询 { } } }
internal IEnumerable <MemberResult> GetMemberResults( IEnumerable <AnalysisValue> vars, InterpreterScope scope, GetMemberOptions options ) { IList <AnalysisValue> namespaces = new List <AnalysisValue>(); foreach (var ns in vars) { if (ns != null) { namespaces.Add(ns); } } if (namespaces.Count == 1) { // optimize for the common case of only a single namespace var newMembers = namespaces[0].GetAllMembers(GlobalScope.InterpreterContext); if (newMembers == null || newMembers.Count == 0) { return(new MemberResult[0]); } return(SingleMemberResult(GetPrivatePrefix(scope), options, newMembers)); } Dictionary <string, IEnumerable <AnalysisValue> > memberDict = null; Dictionary <string, IEnumerable <AnalysisValue> > ownerDict = null; HashSet <string> memberSet = null; int namespacesCount = namespaces.Count; foreach (AnalysisValue ns in namespaces) { if (ProjectState._noneInst == ns) { namespacesCount -= 1; continue; } var newMembers = ns.GetAllMembers(GlobalScope.InterpreterContext); // IntersectMembers(members, memberSet, memberDict); if (newMembers == null || newMembers.Count == 0) { continue; } if (memberSet == null) { // first namespace, add everything memberSet = new HashSet <string>(newMembers.Keys); memberDict = new Dictionary <string, IEnumerable <AnalysisValue> >(); ownerDict = new Dictionary <string, IEnumerable <AnalysisValue> >(); foreach (var kvp in newMembers) { var tmp = new List <AnalysisValue>(kvp.Value); memberDict[kvp.Key] = tmp; ownerDict[kvp.Key] = new List <AnalysisValue> { ns }; } } else { // 2nd or nth namespace, union or intersect HashSet <string> toRemove; IEnumerable <string> adding; if (options.Intersect()) { adding = new HashSet <string>(newMembers.Keys); // Find the things only in memberSet that we need to remove from memberDict // toRemove = (memberSet ^ adding) & memberSet toRemove = new HashSet <string>(memberSet); toRemove.SymmetricExceptWith(adding); toRemove.IntersectWith(memberSet); // intersect memberSet with what we're adding memberSet.IntersectWith(adding); // we're only adding things they both had adding = memberSet; } else { // we're adding all of newMembers keys adding = newMembers.Keys; toRemove = null; } // update memberDict foreach (var name in adding) { IEnumerable <AnalysisValue> values; List <AnalysisValue> valueList; if (!memberDict.TryGetValue(name, out values)) { memberDict[name] = values = new List <AnalysisValue>(); } if ((valueList = values as List <AnalysisValue>) == null) { memberDict[name] = valueList = new List <AnalysisValue>(values); } valueList.AddRange(newMembers[name]); if (!ownerDict.TryGetValue(name, out values)) { ownerDict[name] = values = new List <AnalysisValue>(); } if ((valueList = values as List <AnalysisValue>) == null) { ownerDict[name] = valueList = new List <AnalysisValue>(values); } valueList.Add(ns); } if (toRemove != null) { foreach (var name in toRemove) { memberDict.Remove(name); ownerDict.Remove(name); } } } } if (memberDict == null) { return(new MemberResult[0]); } if (options.Intersect()) { // No need for this information if we're only showing the // intersection. Setting it to null saves lookups later. ownerDict = null; } return(MemberDictToResultList(GetPrivatePrefix(scope), options, memberDict, ownerDict, namespacesCount)); }
public static string Generico <T>(T dato) { var serializador = new XmlSerializer(typeof(T)); using (var sw = new StringWriter()) { using (var escritor = XmlWriter.Create(sw)) { serializador.Serialize(escritor, dato); return(sw.ToString()); } } Stack <int> os = new Stack <int>(); os.Push(8); os.Push(6); int valor = os.Pop(); HashSet <int> conjunto1 = new HashSet <int>(); conjunto1.Add(5); conjunto1.Add(6); conjunto1.Add(5);// no se inserta porque ya existe HashSet <int> conjunto2 = new HashSet <int>(); conjunto1.Add(5); conjunto1.Add(8); // se obtiene 5,6 y 8 HashSet <int> union_set1_set2 = new HashSet <int>(conjunto1); union_set1_set2.UnionWith(conjunto2); // se obtiene solo el 5 HashSet <int> interseccion_set1_set2 = new HashSet <int>(conjunto1); interseccion_set1_set2.IntersectWith(conjunto2); // se obtiene solo el 6 HashSet <int> diferencia_set1_set2 = new HashSet <int>(conjunto1); diferencia_set1_set2.ExceptWith(conjunto2); // se obtiene solo el 6 y 8 HashSet <int> diferencia_simetrica_set1_set2 = new HashSet <int>(conjunto1); diferencia_simetrica_set1_set2.SymmetricExceptWith(conjunto2); // eliminar numeros repetidos List <int> numeros = new List <int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 34, 5, 6, 8 }; numeros = new HashSet <int>(numeros).ToList(); string[] arregloStr = new string[] { "uno", "dos", "tres", "cuatro", "cinco" }; Array.Resize <string>(ref arregloStr, 6); arregloStr[5] = "seis"; // Arreglo bidimensional int[,] matrixi = new int[3, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 } }; string[,] matrix = new string[3, 2] { { "valor1", "valor2" }, { "valor3", "valor4" }, { "valor5", "valor6" }, }; var filas = matrix.GetLength(0); var columnas = matrix.GetLength(1); var str = string.Join(",", matrix); }
public void CanCombineSnapshots() { ViewDefinition vd = Context.ViewProcessor.ViewDefinitionRepository.GetViewDefinition(@"Demo Equity Option Test View"); var snapshotManager = Context.MarketDataSnapshotManager; Tuple<ManageableMarketDataSnapshot, ManageableMarketDataSnapshot> snaps; using (var proc = snapshotManager.CreateFromViewDefinition(vd.Name)) { var snapshot = proc.Snapshot; snaps = Halve(snapshot); snaps.Item1.Name = TestUtils.GetUniqueName(); snaps.Item2.Name = TestUtils.GetUniqueName(); Context.MarketDataSnapshotMaster.Add(new MarketDataSnapshotDocument(null, snaps.Item1)); Context.MarketDataSnapshotMaster.Add(new MarketDataSnapshotDocument(null, snaps.Item2)); } try { var snapOptions = ExecutionOptions.GetSingleCycle(new CombinedMarketDataSpecification(new UserMarketDataSpecification(snaps.Item2.UniqueId), new UserMarketDataSpecification(snaps.Item1.UniqueId))); var withSnapshot = GetFirstResult(snapOptions, vd.Name); var options = ExecutionOptions.SingleCycle; IViewComputationResultModel withoutSnapshot = GetFirstResult(options, vd.Name); var withoutCount = CountResults(withoutSnapshot); var withCount = CountResults(withSnapshot); if (withoutCount != withCount) { var withSpecs = new HashSet<ValueSpecification>(withSnapshot.AllResults.Select(r => r.ComputedValue.Specification)); var withoutSpecs = new HashSet<ValueSpecification>(withoutSnapshot.AllResults.Select(r => r.ComputedValue.Specification)); withoutSpecs.SymmetricExceptWith(withSpecs); Assert.True(false, string.Format("Running snapshot of {0} only had {1}, live had {2}", vd.Name, withCount, withoutCount)); } Assert.Equal(withoutCount, withCount); } finally { Context.MarketDataSnapshotMaster.Remove(snaps.Item1.UniqueId); Context.MarketDataSnapshotMaster.Remove(snaps.Item2.UniqueId); } }
public void CanCreateAndRunFromView(ViewDefinition vd) { var snapshotManager = Context.MarketDataSnapshotManager; using (var proc = snapshotManager.CreateFromViewDefinition(vd.Name)) { proc.Snapshot.Name = TestUtils.GetUniqueName(); var uid = Context.MarketDataSnapshotMaster.Add(new MarketDataSnapshotDocument(null, proc.Snapshot)).UniqueId; try { var snapOptions = ExecutionOptions.Snapshot(proc.Snapshot.UniqueId); var withSnapshot = GetFirstResult(snapOptions, vd.Name); var options = ExecutionOptions.SingleCycle; IViewComputationResultModel withoutSnapshot = GetFirstResult(options, vd.Name); var withoutCount = CountResults(withoutSnapshot); var withCount = CountResults(withSnapshot); if (withoutCount != withCount) { var withSpecs = new HashSet<ValueSpecification>(withSnapshot.AllResults.Select(r => r.ComputedValue.Specification)); var withoutSpecs = new HashSet<ValueSpecification>(withoutSnapshot.AllResults.Select(r => r.ComputedValue.Specification)); withoutSpecs.SymmetricExceptWith(withSpecs); Assert.True(false, string.Format("Running snapshot of {0} only had {1}, live had {2}", vd.Name, withCount, withoutCount)); } Assert.Equal(withoutCount, withCount); } finally { Context.MarketDataSnapshotMaster.Remove(uid); } } }
private void DragCheck() { Camera cam = SceneView.lastActiveSceneView.camera; limitFaceDragCheckToSelection = pb_Preferences_Internal.GetBool(pb_Constant.pbDragCheckLimit); pbUndo.RecordSelection(selection, "Drag Select"); switch(selectionMode) { case SelectMode.Vertex: { if(!shiftKey && !ctrlKey) ClearFaceSelection(); // profiler.BeginSample("Drag Select Vertices"); for(int i = 0; i < selection.Length; i++) { pb_Object pb = selection[i]; if(!pb.isSelectable) continue; // profiler.BeginSample("Create HashSet"); HashSet<int> selectedTriangles = new HashSet<int>(pb.SelectedTriangles); // profiler.EndSample(); // selection[i].ToMesh(); // selection[i].Refresh(); // Vector3[] normals = selection[i].msh.normals; // selection[i].Optimize(); // Vector3 camDirLocal = -selection[i].transform.InverseTransformDirection(cam.transform.forward); for(int n = 0; n < m_uniqueIndices[i].Length; n++) { Vector3 v = m_verticesInWorldSpace[i][m_uniqueIndices[i][n]]; // profiler.BeginSample("Contains"); bool contains = selectionRect.Contains(HandleUtility.WorldToGUIPoint(v)); // profiler.EndSample(); if(contains) { // if point is behind the camera, ignore it. // profiler.BeginSample("WorldToScreenPoint"); if(cam.WorldToScreenPoint(v).z < 0) { // profiler.EndSample(); continue; } // profiler.EndSample(); // profiler.BeginSample("backface culling"); // Vector3 nrm = normals[m_uniqueIndices[i][n]]; // float dot = Vector3.Dot(camDirLocal, nrm); // if(!pref_backfaceSelect && (dot < 0 || pb_HandleUtility.PointIsOccluded(cam, selection[i], v))) if( !pref_backfaceSelect && pb_HandleUtility.PointIsOccluded(cam, selection[i], v) ) { // profiler.EndSample(); continue; } // profiler.EndSample(); // Check if index is already selected, and if not add it to the pot // profiler.BeginSample("selected triangles contains"); contains = selectedTriangles.Contains(m_uniqueIndices[i][n]); // profiler.EndSample(); // profiler.BeginSample("add / remove"); if( contains ) selectedTriangles.Remove(m_uniqueIndices[i][n]); else selectedTriangles.Add(m_uniqueIndices[i][n]); // profiler.EndSample(); } } // profiler.BeginSample("SetSelectedTriangles"); pb.SetSelectedTriangles(selectedTriangles.ToArray()); // profiler.EndSample(); } // profiler.EndSample(); if(!vertexSelectionMask) DragObjectCheck(true); UpdateSelection(false); } break; case SelectMode.Face: { if(!shiftKey && !ctrlKey) ClearFaceSelection(); pb_Object[] pool = limitFaceDragCheckToSelection ? selection : (pb_Object[])FindObjectsOfType(typeof(pb_Object)); List<pb_Face> selectedFaces; for(int i = 0; i < pool.Length; i++) { pb_Object pb = pool[i]; selectedFaces = new List<pb_Face>(pb.SelectedFaces); if(!pb.isSelectable) continue; Vector3[] verticesInWorldSpace = m_verticesInWorldSpace[i]; bool addToSelection = false; for(int n = 0; n < pb.faces.Length; n++) { pb_Face face = pb.faces[n]; /// face is behind the camera if( cam.WorldToScreenPoint(verticesInWorldSpace[face.indices[0]]).z < 0 )//|| (!pref_backfaceSelect && Vector3.Dot(dir, nrm) > 0f)) continue; // only check the first index per quad, and if it checks out, then check every other point if(selectionRect.Contains(HandleUtility.WorldToGUIPoint(verticesInWorldSpace[face.indices[0]]))) { bool nope = false; for(int q = 1; q < face.distinctIndices.Length; q++) { if(!selectionRect.Contains(HandleUtility.WorldToGUIPoint(verticesInWorldSpace[face.distinctIndices[q]]))) { nope = true; break; } } if(!nope) { if( pref_backfaceSelect || !pb_HandleUtility.PointIsOccluded(cam, pool[i], pb_Math.Average(pbUtil.ValuesWithIndices(verticesInWorldSpace, face.distinctIndices))) ) { int indx = selectedFaces.IndexOf(face); if( indx > -1 ) { selectedFaces.RemoveAt(indx); } else { addToSelection = true; selectedFaces.Add(face); } } } } } pb.SetSelectedFaces(selectedFaces.ToArray()); if(addToSelection) AddToSelection(pb.gameObject); } DragObjectCheck(true); UpdateSelection(false); } break; case SelectMode.Edge: { if(!shiftKey && !ctrlKey) ClearFaceSelection(); for(int i = 0; i < selection.Length; i++) { Vector3 v0 = Vector3.zero, v1 = Vector3.zero, cen = Vector3.zero; pb_Object pb = selection[i]; Vector3[] vertices = m_verticesInWorldSpace[i]; pb_IntArray[] sharedIndices = pb.sharedIndices; HashSet<pb_Edge> inSelection = new HashSet<pb_Edge>(); for(int n = 0; n < m_universalEdges[i].Length; n++) { v0 = vertices[sharedIndices[m_universalEdges[i][n].x][0]]; v1 = vertices[sharedIndices[m_universalEdges[i][n].y][0]]; cen = (v0+v1)*.5f; bool behindCam = cam.WorldToScreenPoint(cen).z < 0; if( behindCam ) continue; bool rectContains = selectionRect.Contains( HandleUtility.WorldToGUIPoint(cen) ); if( rectContains ) { bool occluded = !pref_backfaceSelect && pb_HandleUtility.PointIsOccluded(cam, pb, cen); if(!occluded) { inSelection.Add( new pb_Edge(m_universalEdges[i][n]) ); } } } pb_Edge[] curSelection = pb_Edge.GetUniversalEdges(pb.SelectedEdges, m_sharedIndicesLookup[i]); inSelection.SymmetricExceptWith(curSelection); pb_Edge[] selected = inSelection.ToArray(); for(int n = 0; n < selected.Length; n++) { selected[n].x = sharedIndices[selected[n].x][0]; selected[n].y = sharedIndices[selected[n].y][0]; } pb.SetSelectedEdges( selected ); } if(!vertexSelectionMask) { DragObjectCheck(true); } UpdateSelection(false); } break; default: DragObjectCheck(false); break; } SceneView.RepaintAll(); }
private async Task VerifyReporting(AccessType access, Action <FileAccessManifest> populateManifest, params ExpectedReportEntry[] expectedExplicitReports) { // We need a process which will generate the expected accesses. var testProcess = CreateTestProcess(access, expectedExplicitReports); var pathTable = Context.PathTable; var info = ToProcessInfo(testProcess, "FileAccessExplicitReportingTest"); info.FileAccessManifest.ReportFileAccesses = false; info.FileAccessManifest.ReportUnexpectedFileAccesses = true; info.FileAccessManifest.FailUnexpectedFileAccesses = false; populateManifest(info.FileAccessManifest); using (ISandboxedProcess process = await StartProcessAsync(info)) { SandboxedProcessResult result = await process.GetResultAsync(); XAssert.AreEqual(0, result.ExitCode, "\r\ncmd: {0} \r\nStandard out: '{1}' \r\nStandard err: '{2}'.", info.Arguments, await result.StandardOutput.ReadValueAsync(), await result.StandardError.ReadValueAsync()); XAssert.IsNotNull(result.ExplicitlyReportedFileAccesses); Dictionary <AbsolutePath, ExpectedReportEntry> pathsToExpectations = expectedExplicitReports.ToDictionary( e => e.File.Path, e => e); var verifiedPaths = new HashSet <AbsolutePath>(); foreach (var actualReport in result.ExplicitlyReportedFileAccesses) { string actualReportedPathString = actualReport.GetPath(pathTable); XAssert.AreEqual( FileAccessStatus.Allowed, actualReport.Status, "Incorrect status for path " + actualReportedPathString); if (!TryVerifySingleReport(pathTable, actualReport, access, pathsToExpectations, out var actualReportPath)) { if ((actualReport.RequestedAccess & RequestedAccess.Enumerate) != 0) { // To account for 'explicitly reported' enumerations globally, we need to be lenient about unexpected enumerations. // Alternatively instead opt-in to enumeration reports under certain scopes. } else { AbsolutePath actualReportedPath = AbsolutePath.Create(pathTable, actualReportedPathString); XAssert.Fail("No expectations for an explicitly reported path {0}", actualReportedPath.ToString(pathTable)); } } else { verifiedPaths.Add(actualReportPath); } } foreach (var actualReport in result.AllUnexpectedFileAccesses) { XAssert.AreEqual(FileAccessStatus.Denied, actualReport.Status); if (TryVerifySingleReport(pathTable, actualReport, access, pathsToExpectations, out var actualReportPath)) { verifiedPaths.Add(actualReportPath); } // Note that we allow extra unexpected file accesses for the purposes of these tests. } var expectedPathsSet = new HashSet <AbsolutePath>(pathsToExpectations.Keys); var disagreeingPaths = new HashSet <AbsolutePath>(verifiedPaths); disagreeingPaths.SymmetricExceptWith(expectedPathsSet); if (disagreeingPaths.Any()) { var disagreeingReports = "Disagreeing reports:" + string.Join(string.Empty, disagreeingPaths .Select(p => (tag: expectedPathsSet.Contains(p) ? "Missing" : "Unexpected", path: p)) .Select(t => $"{Environment.NewLine} {t.tag} report for path {t.path.ToString(pathTable)}")); var expectedReports = "Expected reports:" + string.Join(string.Empty, pathsToExpectations.Keys .Select(p => $"{Environment.NewLine} {p.ToString(pathTable)}")); var verifiedReports = "Verified reports:" + string.Join(string.Empty, verifiedPaths .Select(p => $"{Environment.NewLine} {p.ToString(pathTable)}")); XAssert.Fail(string.Join(Environment.NewLine, disagreeingReports, expectedReports, verifiedReports)); } } }
public static double GetDiffScore(string a, string b) { // first iteration is to take all distinct values from a and b // then compare the actual content and score it. // second iteration takes words into consideration var c1 = a.ToLower().ToCharArray(); var c2 = b.ToLower().ToCharArray(); var diff = new HashSet <char>(c1); diff.SymmetricExceptWith(c2); var changes = diff.ToArray(); // c1.Intersect(c2).ToArray(); var score = 0.0; // different chars have different scoring // letters are 1.0 // numbers are 0.75 // brackets and paranthesis are 0.5 // spaces are 0.1 foreach (var change in changes) { if (change == '[' || change == ']' || change == '(' || change == ')') { score += 0.5; } else if (char.IsDigit(change)) { score += 0.75; } else if (change == ' ') { score += 0.1; } else { score += 1.0; } } var l0 = new HashSet <string>(); a.ToLower().Split(new[] { '.', ' ' }, StringSplitOptions.RemoveEmptyEntries).ForEach(x => l0.Add(x)); if (l0.Count > 1) { l0.Remove(a.ToLower()); } var l1 = new HashSet <string>(); b.ToLower().Split(new[] { '.', ' ' }, StringSplitOptions.RemoveEmptyEntries).ForEach(x => l1.Add(x)); if (l1.Count > 1) { l1.Remove(b.ToLower()); } var l2 = new HashSet <string>(); l2.UnionWith(l0); l2.UnionWith(l1); for (var i = 0; i < l2.Count; i++) { if (!l0.Contains(l2.ElementAt(i))) { score++; } if (!l1.Contains(l2.ElementAt(i))) { score++; } } return(score); }
internal IEnumerable<MemberResult> GetMemberResults( IEnumerable<AnalysisValue> vars, InterpreterScope scope, GetMemberOptions options ) { IList<AnalysisValue> namespaces = new List<AnalysisValue>(); foreach (var ns in vars) { if (ns != null) { namespaces.Add(ns); } } if (namespaces.Count == 1) { // optimize for the common case of only a single namespace var newMembers = namespaces[0].GetAllMembers(GlobalScope.InterpreterContext, options); if (newMembers == null || newMembers.Count == 0) { return new MemberResult[0]; } return SingleMemberResult(GetPrivatePrefix(scope), options, newMembers); } Dictionary<string, IEnumerable<AnalysisValue>> memberDict = null; Dictionary<string, IEnumerable<AnalysisValue>> ownerDict = null; HashSet<string> memberSet = null; int namespacesCount = namespaces.Count; foreach (AnalysisValue ns in namespaces) { if (ProjectState._noneInst == ns) { namespacesCount -= 1; continue; } var newMembers = ns.GetAllMembers(GlobalScope.InterpreterContext, options); // IntersectMembers(members, memberSet, memberDict); if (newMembers == null || newMembers.Count == 0) { continue; } if (memberSet == null) { // first namespace, add everything memberSet = new HashSet<string>(newMembers.Keys); memberDict = new Dictionary<string, IEnumerable<AnalysisValue>>(); ownerDict = new Dictionary<string, IEnumerable<AnalysisValue>>(); foreach (var kvp in newMembers) { var tmp = new List<AnalysisValue>(kvp.Value); memberDict[kvp.Key] = tmp; ownerDict[kvp.Key] = new List<AnalysisValue> { ns }; } } else { // 2nd or nth namespace, union or intersect HashSet<string> toRemove; IEnumerable<string> adding; if (options.Intersect()) { adding = new HashSet<string>(newMembers.Keys); // Find the things only in memberSet that we need to remove from memberDict // toRemove = (memberSet ^ adding) & memberSet toRemove = new HashSet<string>(memberSet); toRemove.SymmetricExceptWith(adding); toRemove.IntersectWith(memberSet); // intersect memberSet with what we're adding memberSet.IntersectWith(adding); // we're only adding things they both had adding = memberSet; } else { // we're adding all of newMembers keys adding = newMembers.Keys; toRemove = null; } // update memberDict foreach (var name in adding) { IEnumerable<AnalysisValue> values; List<AnalysisValue> valueList; if (!memberDict.TryGetValue(name, out values)) { memberDict[name] = values = new List<AnalysisValue>(); } if ((valueList = values as List<AnalysisValue>) == null) { memberDict[name] = valueList = new List<AnalysisValue>(values); } valueList.AddRange(newMembers[name]); if (!ownerDict.TryGetValue(name, out values)) { ownerDict[name] = values = new List<AnalysisValue>(); } if ((valueList = values as List<AnalysisValue>) == null) { ownerDict[name] = valueList = new List<AnalysisValue>(values); } valueList.Add(ns); } if (toRemove != null) { foreach (var name in toRemove) { memberDict.Remove(name); ownerDict.Remove(name); } } } } if (memberDict == null) { return new MemberResult[0]; } if (options.Intersect()) { // No need for this information if we're only showing the // intersection. Setting it to null saves lookups later. ownerDict = null; } return MemberDictToResultList(GetPrivatePrefix(scope), options, memberDict, ownerDict, namespacesCount); }
/// <inheritdoc /> public void SymmetricExceptWith(IEnumerable <T> other) { using (LockObject.EnterWriteLock()) _setData.SymmetricExceptWith(other); }
/// ------------------------------------------------------------------------------------ /// <summary> /// Selections the changed. /// </summary> /// <param name="prootb">The prootb.</param> /// <param name="sel">The sel.</param> /// ------------------------------------------------------------------------------------ protected override void HandleSelectionChange(IVwRootBox prootb, IVwSelection sel) { CheckDisposed(); if (m_fInChangeSelectedObjects) return; m_fInChangeSelectedObjects = true; try { int cvsli = 0; // Out variables for AllTextSelInfo. int ihvoRoot = 0; int tagTextProp = 0; int cpropPrevious = 0; int ichAnchor = 0; int ichEnd = 0; int ws = 0; bool fAssocPrev = false; int ihvoEnd = 0; ITsTextProps ttpBogus = null; SelLevInfo[] rgvsli = new SelLevInfo[0]; List<int> newSelectedObjects = new List<int>(4); newSelectedObjects.Add(XmlVc.FocusHvo); if (sel != null) { cvsli = sel.CLevels(false) - 1; // Main array of information retrived from sel that made combo. rgvsli = SelLevInfo.AllTextSelInfo(sel, cvsli, out ihvoRoot, out tagTextProp, out cpropPrevious, out ichAnchor, out ichEnd, out ws, out fAssocPrev, out ihvoEnd, out ttpBogus); for (int i = 0; i < cvsli; i++) { newSelectedObjects.Add(rgvsli[i].hvo); } } var changed = new HashSet<int>(m_xmlVc.SelectedObjects); changed.SymmetricExceptWith(newSelectedObjects); if (changed.Count != 0) { m_xmlVc.SelectedObjects = newSelectedObjects; // Generate propChanged calls that force the relevant parts of the view to redraw // to indicate which command icons should be visible. foreach (int hvo in changed) m_rootb.PropChanged(hvo, XmlVc.IsObjectSelectedTag, 0, 1, 1); if (sel != null && !sel.IsValid) { // we wiped it out by regenerating parts of the display in our PropChanged calls! Restore it if we can. sel = m_rootb.MakeTextSelection(ihvoRoot, cvsli, rgvsli, tagTextProp, cpropPrevious, ichAnchor, ichEnd, ws, fAssocPrev, ihvoEnd, ttpBogus, true); } } } finally { m_fInChangeSelectedObjects = false; } base.HandleSelectionChange(prootb, sel); }
public void SymmetricExceptWith(IEnumerable <T> other) => self.SymmetricExceptWith(other);
public void simulate(int n, int T) { HashSet<string> first = new HashSet<string>(); HashSet<string> second = new HashSet<string>(); for (int multiply = 1; multiply <= 10; multiply *= 10) { HashSet<string> found = new HashSet<string>(); for (int t = 0; t < T * multiply; t++) { List<List<int>> towers = new List<List<int>>(); int numTowers = 0; int howManyTowers = rand.Next(1, ((n + 1) * n) / 2 + 1); for (int i = 0; i < n; i++) { if (howManyTowers >= n - i) { howManyTowers -= (n - i); towers.Add(new List<int>() { 1 }); numTowers++; } } double[] prob = new double[numTowers]; double sum = 0; for (int i = 0; i < numTowers; i++) { prob[i] = rand.NextDouble(); if (i == 0) prob[i] = 1 - prob[i] * prob[i]; sum += prob[i]; } for (int i = 0; i < numTowers; i++) { prob[i] /= sum; } for (int i = 0; i < n - numTowers; i++) { double towerToChangeRandom = rand.NextDouble(); List<int> towerToChange = towers[0]; for (int j = 0; j < numTowers; j++) { if (towerToChangeRandom < prob[j]) { towerToChange = towers[j]; break; } towerToChangeRandom -= prob[j]; } if (towerToChange[towerToChange.Count - 1] == 2 || rand.Next(0, 5) <= 2) { towerToChange.Add(1); } else { towerToChange[towerToChange.Count - 1] = 2; } } found.Add(canonical(towers)); } int total = found.Count; printHashSet(found, total); if (multiply == 1) { first.UnionWith(found); } else { second.UnionWith(found); } } second.SymmetricExceptWith(first); printHashSet(second, second.Count); }
/// ------------------------------------------------------------------------------------ /// <summary> /// Selections the changed. /// </summary> /// <param name="prootb">The prootb.</param> /// <param name="sel">The sel.</param> /// ------------------------------------------------------------------------------------ protected override void HandleSelectionChange(IVwRootBox prootb, IVwSelection sel) { CheckDisposed(); if (m_fInChangeSelectedObjects) { return; } m_fInChangeSelectedObjects = true; try { int cvsli = 0; // Out variables for AllTextSelInfo. int ihvoRoot = 0; int tagTextProp = 0; int cpropPrevious = 0; int ichAnchor = 0; int ichEnd = 0; int ws = 0; bool fAssocPrev = false; int ihvoEnd = 0; ITsTextProps ttpBogus = null; SelLevInfo[] rgvsli = new SelLevInfo[0]; List <int> newSelectedObjects = new List <int>(4); newSelectedObjects.Add(XmlVc.FocusHvo); if (sel != null) { cvsli = sel.CLevels(false) - 1; // Main array of information retrived from sel that made combo. rgvsli = SelLevInfo.AllTextSelInfo(sel, cvsli, out ihvoRoot, out tagTextProp, out cpropPrevious, out ichAnchor, out ichEnd, out ws, out fAssocPrev, out ihvoEnd, out ttpBogus); for (int i = 0; i < cvsli; i++) { newSelectedObjects.Add(rgvsli[i].hvo); } } var changed = new HashSet <int>(m_xmlVc.SelectedObjects); changed.SymmetricExceptWith(newSelectedObjects); if (changed.Count != 0) { m_xmlVc.SelectedObjects = newSelectedObjects; // Generate propChanged calls that force the relevant parts of the view to redraw // to indicate which command icons should be visible. foreach (int hvo in changed) { m_rootb.PropChanged(hvo, XmlVc.IsObjectSelectedTag, 0, 1, 1); } if (sel != null && !sel.IsValid) { // we wiped it out by regenerating parts of the display in our PropChanged calls! Restore it if we can. sel = m_rootb.MakeTextSelection(ihvoRoot, cvsli, rgvsli, tagTextProp, cpropPrevious, ichAnchor, ichEnd, ws, fAssocPrev, ihvoEnd, ttpBogus, true); } } } finally { m_fInChangeSelectedObjects = false; } base.HandleSelectionChange(prootb, sel); }
public void NumberOfResultsIsConsistent(ViewDefinition defn) { const int cyclesCount = 5; using (var remoteViewClient = Context.ViewProcessor.CreateClient()) using (var mre = new ManualResetEvent(false)) { var cycles = new BlockingCollection<IEngineResourceReference<IViewCycle>>(); var listener = new EventViewResultListener(); listener.ProcessCompleted += delegate { mre.Set(); }; listener.ViewDefinitionCompilationFailed += delegate { mre.Set(); }; listener.CycleExecutionFailed += delegate { mre.Set(); }; listener.CycleCompleted += (sender, e) => { cycles.Add(remoteViewClient.CreateCycleReference(e.FullResult.ViewCycleId)); remoteViewClient.TriggerCycle(); }; remoteViewClient.SetResultListener(listener); remoteViewClient.SetViewCycleAccessSupported(true); var sequence = ArbitraryViewCycleExecutionSequence.Create(Enumerable.Range(0, cyclesCount).Select(i => DateTimeOffset.Now + TimeSpan.FromHours(i))); var options = new ExecutionOptions(sequence, ViewExecutionFlags.TriggersEnabled | ViewExecutionFlags.AwaitMarketData, null, new ViewCycleExecutionOptions(default(DateTimeOffset), ExecutionOptions.GetDefaultMarketDataSpec())); remoteViewClient.AttachToViewProcess(defn.UniqueID, options); TimeSpan timeout = TimeSpan.FromMinutes(5); if (! mre.WaitOne(timeout)) { throw new TimeoutException(string.Format("Failed to get result in {0}", timeout)); } Assert.Equal(cyclesCount, cycles.Count); var specs = cycles.Select(GetAllSpecs).ToList(); var inconsistent = specs.Zip(specs.Skip(1), Tuple.Create).SelectMany( t => { var diff = new HashSet<Tuple<string, ValueSpecification>>(t.Item1); diff.SymmetricExceptWith(t.Item2); return diff; }).Distinct(); if (inconsistent.Any()) { var counts = string.Join(",", specs.Select(c => c.Count.ToString())); var inconsistentStrings = specs.Select(s => string.Join(",", s.Where(x => inconsistent.Contains(x)).Select(x => x.ToString()))); string inconsistentString = string.Join(Environment.NewLine, inconsistentStrings); throw new Exception(string.Format("Inconsistent number of results for {0} {1}: {2}", defn.Name, counts, inconsistentString)); } } }
public void SymmetricExceptWith(IEnumerable <T> other) { _hashset.SymmetricExceptWith(other); }
internal IEnumerable<MemberResult> GetMemberResults(IEnumerable<Namespace> vars, bool intersectMultipleResults = true) { IList<Namespace> namespaces = new List<Namespace>(); foreach (var ns in vars) { if (ns != null) { namespaces.Add(ns); } } if (namespaces.Count == 1) { // optimize for the common case of only a single namespace var newMembers = namespaces[0].GetAllMembers(GlobalScope.ShowClr); if (newMembers == null || newMembers.Count == 0) { return new MemberResult[0]; } return SingleMemberResult(newMembers); } Dictionary<string, List<Namespace>> memberDict = null; HashSet<string> memberSet = null; foreach (Namespace ns in namespaces) { if (ProjectState._noneInst == ns) { continue; } var newMembers = ns.GetAllMembers(GlobalScope.ShowClr); // IntersectMembers(members, memberSet, memberDict); if (newMembers == null || newMembers.Count == 0) { continue; } if (memberSet == null) { // first namespace, add everything memberSet = new HashSet<string>(newMembers.Keys); memberDict = new Dictionary<string, List<Namespace>>(); foreach (var kvp in newMembers) { var tmp = new List<Namespace>(kvp.Value); memberDict[kvp.Key] = tmp; } } else { // 2nd or nth namespace, union or intersect HashSet<string> toRemove; IEnumerable<string> adding; if (intersectMultipleResults) { adding = new HashSet<string>(newMembers.Keys); // Find the things only in memberSet that we need to remove from memberDict // toRemove = (memberSet ^ adding) & memberSet toRemove = new HashSet<string>(memberSet); toRemove.SymmetricExceptWith(adding); toRemove.IntersectWith(memberSet); // intersect memberSet with what we're adding memberSet.IntersectWith(adding); // we're only adding things they both had adding = memberSet; } else { // we're adding all of newMembers keys adding = newMembers.Keys; toRemove = null; } // update memberDict foreach (var name in adding) { List<Namespace> values; if (!memberDict.TryGetValue(name, out values)) { memberDict[name] = values = new List<Namespace>(); } values.AddRange(newMembers[name]); } if (toRemove != null) { foreach (var name in toRemove) { memberDict.Remove(name); } } } } if (memberDict == null) { return new MemberResult[0]; } return MemberDictToResultList(memberDict); }
private ValidationResult ValidateInternal(string[] ruleSets) { var result = new ValidationResult { IsValid = true }; var binderPropsOrFieldsOfT = this.TypeProperties.Keys; foreach (var rule in ruleSets) { var strictMode = Faker.DefaultStrictMode; this.StrictModes.TryGetValue(rule, out strictMode); //If strictMode is not enabled, skip and move on to the next ruleSet. if (!strictMode) { continue; } this.Actions.TryGetValue(rule, out var populateActions); var userSet = new HashSet <string>(StringComparer.OrdinalIgnoreCase); if (populateActions != null) { userSet.UnionWith(populateActions.Keys); } //Get the set properties or fields that are only //known to the binder, while removing //items in userSet that are known to both the user and binder. userSet.SymmetricExceptWith(binderPropsOrFieldsOfT); //What's left in userSet is the set of properties or fields //that the user does not know about + .Rule() methods. if (userSet.Count > 0) { foreach (var propOrFieldOfT in userSet) { if (populateActions.TryGetValue(propOrFieldOfT, out var populateAction)) { // Very much a .Rules() action if (populateAction.ProhibitInStrictMode) { result.ExtraMessages.Add( $"When StrictMode is set to True the Faker<{typeof(T).Name}>.Rules(...) method cannot verify that all properties have rules. You need to use Faker<{typeof(T).Name}>.RuleFor( x => x.Prop, ...) for each property to ensure each property has an associated rule when StrictMode is true; otherwise, set StrictMode to False in order to use Faker<{typeof(T).Name}>.Rules() method."); result.IsValid = false; } } else //The user doesn't know about this property or field. Log it as a validation error. { result.MissingRules.Add(propOrFieldOfT); result.IsValid = false; } } } } return(result); }
public void SymmetricExceptWithTest() { var set=new HashSet<int>(); var arr = new int[100]; for (int i = 0; i < 100; i++) { set.Add(i); arr[i] = i + 50; } set.SymmetricExceptWith(arr); Assert.AreEqual(set.Count, 100); for (int i = 0,j=100; i < 50 && j<150; i++,j++) { Assert.IsTrue(set.Contains(i) && set.Contains(j)); } }
public void SymmetricExceptWith() { var set = new HashSet<int>(); Assert.That(() => set.SymmetricExceptWith(null), Throws.TypeOf(typeof(ArgumentNullException))); set.SymmetricExceptWith(new[] { 3, 9, 11 }); Assert.IsTrue(set.SetEquals(new[] { 3, 9, 11 })); set.SymmetricExceptWith(Enumerable.Range(0, 10)); Assert.IsTrue(set.SetEquals(new[] { 0, 1, 2, 4, 5, 6, 7, 8, 11 })); set.SymmetricExceptWith(set); Assert.IsTrue(set.SetEquals(new int[0])); }
private void RemoveCachedRoutesForChangedSubscriptions(IEnumerable<Subscription> subscriptions) { _routes.Keys.ToList().Each(type => { // This list of subscriptions is generally pretty small (less than 100), // so multiple enumerations over the collection shouldn't be a big deal. var existingSubscriptions = _subscriptions.Where(x => x.Matches(type)); var newSubscriptions = subscriptions.Where(x => x.Matches(type)); var differences = new HashSet<Subscription>(existingSubscriptions); differences.SymmetricExceptWith(newSubscriptions); if (differences.Any()) { _routes.Remove(type); } }); }
static void Main(string[] args) { var set=new MySet.HashSet<int>(); var micrset=new HashSet<int>(); var watch = new Stopwatch(); var rnd = new Random(); watch.Start(); for (int i = 0; i < 100000; i++) { set.Add(rnd.Next(0, 100000)); } watch.Stop(); Console.WriteLine(watch.Elapsed); watch.Reset(); watch.Start(); for (int i = 0; i < 100000; i++) { micrset.Add(rnd.Next(50000, 150000)); } watch.Stop(); Console.WriteLine(watch.Elapsed); watch.Reset(); watch.Start(); micrset.SymmetricExceptWith(set); watch.Stop(); Console.WriteLine("\n\n"+watch.Elapsed+"\n\n"); watch.Reset(); var words = GetWords(); watch.Restart(); var my = GetTable(words); watch.Stop(); Console.WriteLine(watch.Elapsed); watch.Restart(); var notmy = GetDictionary(words); watch.Stop(); Console.WriteLine(watch.Elapsed); Console.WriteLine(); var notnot=new HashSet<int>(); Console.ReadKey(); }
static void Main(string[] args) { var BigCities = new HashSet<string> { "New York", "Manchester", "Sheffield", "Paris" }; string[] citiesInUK = { "Sheffield", "Ripon", "Truro", "Manchester" }; //// Generic code to find intersecting values. //BigCities.IntersectWith(citiesInUK); //foreach (string city in BigCities) //{ // Console.WriteLine(city); //} // Linq method // The linq method does create a new array. var IntersectCities = BigCities.Intersect(citiesInUK); foreach (string city in IntersectCities) { Console.WriteLine(city); } Console.WriteLine(); // Union takes elements that are in either set and puts every element out once. var UnionCities = BigCities.Union(citiesInUK); foreach (string city in UnionCities) { Console.WriteLine(city); } Console.WriteLine(); // Every element that is in the first set, but not in the second set. var ExceptCities = BigCities.Except(citiesInUK); foreach (string city in ExceptCities) { Console.WriteLine(city); } Console.WriteLine(); // Which elements appear in either one but not in both collections. BigCities.SymmetricExceptWith(citiesInUK); foreach (string city in BigCities) { Console.WriteLine(city); } }
public void BuildersAreSymmetric(TypeDefinition type) { if (type.Name == "ValuePropertiesBuilder") { //This builder is too clever for its own good return; } if (type.BaseType != null && type.BaseType.Name.StartsWith("BuilderBase")) { var methods = type.Methods.Cast<MethodDefinition>(); Assert.NotEmpty(methods); var serialize = methods.SingleOrDefault(m => m.Name == "SerializeImpl"); var deserialize = methods.SingleOrDefault(m => m.Name == "DeserializeImpl"); Assert.NotNull(deserialize); if (IsUseful(deserialize) && IsUseful(serialize)) { var deserializeStrings = new HashSet<string>(GetStaticStrings(deserialize)); var serializeStrings = new HashSet<string>(GetStaticStrings(serialize)); if (! deserializeStrings.SetEquals(serializeStrings)) { deserializeStrings.SymmetricExceptWith(serializeStrings); throw new Exception(string.Format("Mismatched strings: {0}", string.Join(",", deserializeStrings))); } } } }
void OnItemSelected(Selection newSelection) { Fx.Assert(newSelection != null, "newSelection is null"); IList<ModelItem> newSelectionObjects = newSelection.SelectedObjects as IList<ModelItem>; IList<ModelItem> oldSelectionObjects = oldSelection.SelectedObjects as IList<ModelItem>; //Call notifyPropertyChanged for IsPrimarySelection attached property. if (newSelection.PrimarySelection != null && !newSelection.PrimarySelection.Equals(oldSelection.PrimarySelection)) { isPrimarySelectionProperty.NotifyPropertyChanged(oldSelection.PrimarySelection); isPrimarySelectionProperty.NotifyPropertyChanged(newSelection.PrimarySelection); } else if (newSelection.PrimarySelection == null) { isPrimarySelectionProperty.NotifyPropertyChanged(oldSelection.PrimarySelection); } //call NotifyPropertyChanged for IsSelection property on ModelItems that were added or removed from selection. HashSet<ModelItem> selectionChangeSet = new HashSet<ModelItem>(oldSelectionObjects); selectionChangeSet.SymmetricExceptWith(newSelectionObjects); foreach (ModelItem selectionChangeMI in selectionChangeSet) { isSelectionProperty.NotifyPropertyChanged(selectionChangeMI); } if (helpService != null) { if (oldSelection.PrimarySelection != null) { helpService.RemoveContextAttribute(string.Empty, GetF1HelpTypeKeyword(oldSelection.PrimarySelection.ItemType)); } if (newSelection.PrimarySelection != null) { helpService.AddContextAttribute(string.Empty, GetF1HelpTypeKeyword(newSelection.PrimarySelection.ItemType), HelpKeywordType.F1Keyword); } } oldSelection = newSelection; }
public void AppendDifferential(Differential differential, DocumentState originatingState) { var contextChangeIndices = new HashSet<int>(_activeDifferentialIndices); contextChangeIndices.SymmetricExceptWith(originatingState.ActiveDifferentialIndices); }
static void Main() { #if DEBUG Console.SetIn(new System.IO.StreamReader("../../input.txt")); #endif var date = DateTime.Now; double maxRange = double.Parse(Console.ReadLine()); decoded = Enumerable.Range(0, int.Parse(Console.ReadLine())) .Select(i => Console.ReadLine().Split()) .ToDictionary(parts => parts[0], parts => int.Parse(parts[1])); var coords = Enumerable.Range(0, int.Parse(Console.ReadLine())) .Select(i => Console.ReadLine().Split()) .Select(parts => new Tuple<int, int>( ParseCoordinate(parts[0]), ParseCoordinate(parts[1]) ) ).ToArray(); #if DEBUG Console.WriteLine(DateTime.Now - date); #endif graph = Enumerable.Range(0, coords.Length) .Select(i => new HashSet<int>()).ToArray(); for (int i = 0; i < graph.Length; i++) { for (int j = 0; j < graph.Length; j++) { if (i == j) continue; if (Distance(coords[i], coords[j]) <= maxRange) { graph[i].Add(j); graph[j].Add(i); } } } var remaining = new HashSet<int>(Enumerable.Range(0, graph.Length)); int groups = 0; while (remaining.Count != 0) { int next = remaining.First(); Dfs(next); remaining.SymmetricExceptWith(visited); visited.Clear(); groups++; } Console.WriteLine(groups); #if DEBUG Console.WriteLine(DateTime.Now - date); #endif }
public void SymmetricExceptWith(IEnumerable <T> other) { _set.SymmetricExceptWith(other); Set2List(); }