/// <summary> /// Determines whether two enumerables have common items. @ref <see cref="IsSubsetOf{T}(IList{T}, IEnumerable{T}, IEqualityComparer{T})"/> /// </summary> /// <returns> /// `true` if <paramref name="source"/> and <paramref name="other"/> have common items; otherwise, `false`. /// </returns> public static bool Overlaps <T>(this IList <T> source, IEnumerable <T> other, IEqualityComparer <T> comparer) { if (source == null) { throw new ArgumentNullException(nameof(source)); } if (other == null) { throw new ArgumentNullException(nameof(other)); } // empty set is always overlaps with non-empty sets if (other.Any()) { if (source.Count == 0) { return(false); } } else if (source.Count == 0) { return(true); } // better perf than hashset if (comparer == null) { return(source.Intersect(other).Any()); } else { return(source.Intersect(other, comparer).Any()); } }
public IList <T> Intersect <T>(IList <T> data1, IList <T> data2, IEqualityComparer <T> Ecomparer = null) { if (Ecomparer == null) { return(data1.Intersect(data2).ToList()); } else { return(data1.Intersect(data2, Ecomparer).ToList()); } }
private static bool HashSufficientPermissions(IList <Role> collectionRoles, IList <Role> requiredRoles) { foreach (var requiredRole in requiredRoles) { switch (requiredRole) { case Role.Viewer: if (!collectionRoles.Intersect(new[] { Role.Viewer, Role.Analyst, Role.Admin }).Any()) { return(false); } break; case Role.DataProducer: if (!collectionRoles.Intersect(new[] { Role.DataProducer, Role.Analyst, Role.Admin }).Any()) { return(false); } break; case Role.Analyst: if (!collectionRoles.Contains(Role.Analyst) && !collectionRoles.Contains(Role.Admin) && (!collectionRoles.Contains(Role.Viewer) || !collectionRoles.Contains(Role.DataProducer))) { return(false); } break; case Role.UserManager: if (!collectionRoles.Intersect(new[] { Role.UserManager, Role.Admin }).Any()) { return(false); } break; case Role.Admin: if (!collectionRoles.Contains(Role.Admin)) { return(false); } break; default: throw new ArgumentOutOfRangeException(); } } return(true); }
/// <summary> /// Compares two collections and returns a score.<para> </para> /// Ideally, you'd set a carefully selected threshold of equality (such as 0.75f), but NOT 100%.<para> </para> /// The resulting equality score is a <c>float</c> value between [0;1] where <c>0</c> is completely different and <c>1</c> entirely identical.<para> </para> /// Duplicate values are stripped from both collections before comparison. /// </summary> /// <param name="collection1">Collection 1</param> /// <param name="collection2">Collection 2</param> /// /// <typeparam name="T"><see cref="ICollection{T}"/> type parameter.</typeparam> /// <returns>The resulting equality score: a value between [0;1] where 0 is completely different and 1 entirely identical.</returns> public static float Compare <T>(this IEnumerable <T> collection1, IEnumerable <T> collection2) { IList <T> l1 = collection1.Distinct().OrderBy(e => e).ToList(); IList <T> l2 = collection2.Distinct().OrderBy(e => e).ToList(); int c1 = l1.Count; int c2 = l2.Count; if (c1 != c2) { IList <T> smaller = c1 < c2 ? l1 : l2; IList <T> bigger = c1 > c2 ? l1 : l2; do { smaller.Add(default(T)); }while (smaller.Count != bigger.Count); l1 = smaller; l2 = bigger; c1 = l1.Count; c2 = l2.Count; if (c1 != c2) { throw new SystemException(); } } return((float)l1.Intersect(l2).Count() / c1); }
public ShootResult CheckShot(Point point, IList <GeneratedShip> generatedShips, IList <Point> shoots) { Point shoot = shoots.FirstOrDefault(p => p.X == point.X && p.Y == point.Y); if (shoot != null) { if (GetAllShipsCoordinates(generatedShips).Any(p => p.X == point.X && p.Y == point.Y)) { if (GetAllShipsCoordinates(generatedShips).Intersect(shoots, new PointEqualityComparer()).Count() == GetAllShipsCoordinates(generatedShips).Count) { return(ShootResult.SinkAllShips); } IList <Point> hitShipPoints = generatedShips.First(generatedShip => generatedShip.Points.Any(shipPoint => shipPoint.X == point.X && shipPoint.Y == point.Y)).Points; if (hitShipPoints.Intersect(shoots, new PointEqualityComparer()).Count() == hitShipPoints.Count) { return(ShootResult.HitAndSink); } return(ShootResult.Hit); } else { return(ShootResult.Miss); } } return(ShootResult.WrongShoot); }
public void GetValueTestMethod() { var capacity = 10; _factory.GetLruCache(capacity); // init static content to null as singleton _rand1 = new Random(); for (int i = 0; i < 100; i++) { _valuesToCache.Add(new KeyValuePair <int, int>(rand.Next(), _rand1.Next())); } _loops = rand.Next(10, 100); for (int i = 0; i < _loops; i++) // exercise cache { _currCacheVal = LRUCache.ValuesT.Cast <int?>().Where(s => s != null).ToList(); LRUCache.Set(_valuesToCache[i].Key, _valuesToCache[i].Value); _newCacheVal = LRUCache.ValuesT.Cast <int?>().Where(s => s != null).ToList(); if (_currCacheVal.Count == 10 && _newCacheVal.Count == 10) { _delCacheVal = _currCacheVal.Except(_newCacheVal).Cast <int>().ToList(); if (_delCacheVal.Count == 1) { _delCount++; } } } _cacheValList = LRUCache.ValuesT.Cast <int?>().ToList(); _tocacheValList = _valuesToCache.Select(s => s.Value).Cast <int?>().ToList(); _cachedValues = _cacheValList.Intersect(_tocacheValList).ToList(); Assert.AreEqual(_cacheValList.Count, _cachedValues.Count); Assert.AreEqual(_loops, _delCount); }
/// <summary> /// Checks to see if any of the given disk paths exist in the db already /// </summary> /// <param name="diskPaths"></param> /// <returns></returns> public static bool ContainsDisks(IList <string> diskPaths) { var allDisks = from d in DBContext.Instance.Disks select d.Path.ToLower(); return(diskPaths.Intersect(allDisks).Count() > 0); }
public static List <int[]> ChooseSets(IList <int[]> sets, IList <int> universe) { var result = new List <int[]>(); var allSets = new HashSet <int[]>(sets); while (universe.Count != 0) { allSets = new HashSet <int[]>(allSets.OrderByDescending(s => s.Intersect(universe).Count()).ThenBy(s => s.Length)); var currentSet = allSets.FirstOrDefault(); var setContainsElements = universe.Intersect(currentSet); if (setContainsElements.Any()) { result.Add(currentSet); foreach (var element in currentSet) { universe.Remove(element); } } allSets.Remove(currentSet); } return(result); }
/// <summary> /// EditRequiresFeatureAttribute prüfen /// </summary> /// <param name="logedInUserApplicationFeatureList">Applications Features List des eingeloggten Benuters</param> /// <param name="originalUser"></param> /// <param name="postData"></param> public static void CheckEditRequiresFeatureAttribute(IList <ApplicationFeature> logedInUserApplicationFeatureList, User originalUser, User postData) { foreach (var propertyInfo in typeof(User).GetProperties()) { var originalWert = propertyInfo.GetValue(originalUser); var neuerWert = propertyInfo.GetValue(postData); if (originalWert.IsEquivalent(neuerWert)) { continue; } var requiredFeatureAttribute = propertyInfo.GetCustomAttributes(typeof(EditRequiresFeatureAttribute), false) .OfType <EditRequiresFeatureAttribute>().FirstOrDefault(); if (requiredFeatureAttribute == null) { continue; } if (!logedInUserApplicationFeatureList.Intersect(requiredFeatureAttribute.RequiredFeatures).Any()) { throw new ForbiddenException( $"Es wurde versucht, das Feld {propertyInfo.Name} vom Wert {originalWert} zum Wert {neuerWert} zu aktualisieren. Dafür wird das Feature {string.Join(" ", requiredFeatureAttribute.RequiredFeatures)} benötigt, welches Sie nicht haben."); } } }
public static void UpdateFilterInfo(this IEnumerable <Feature> features, IList <FilterInfoDisplay> filterInfoToUpdate, bool resetFilters = false) { var comparer = new FilterInfoDisplayEqualityComparer(); foreach (var change in features .SelectMany(GetFilterInfo) .Distinct(comparer) .Select(f => new { Update = filterInfoToUpdate.Intersect(new [] { f }, comparer).FirstOrDefault(), Item = f })) { if (change.Update == null) { filterInfoToUpdate.Add(change.Item); if (change.Item.Name == "Airspace") { change.Item.Visible = false; } } else { change.Update.Name = change.Item.Name; change.Update.ParentName = change.Item.ParentName; change.Update.Active = change.Item.Active; change.Update.Property = change.Item.Property; if (resetFilters) { change.Update.Visible = change.Item.Name != "Airspace" && change.Item.Visible; } } } }
private void ReadBaseModels(IList <string> allFields, Dictionary <string, object>[] records) { Debug.Assert(allFields != null); Debug.Assert(records != null); //本尊及各个关联到基类模型的字段已经读出来了,现在读各个基类模型 foreach (var bm in this.Inheritances) { var baseModel = (IModel)this.DbDomain.GetResource(bm.BaseModel); var baseFieldsToRead = allFields.Intersect(baseModel.Fields.Keys).ToArray(); var baseIds = records.Select(r => (long)r[bm.RelatedField]).ToArray(); var baseRecords = baseModel.ReadInternal(baseIds, baseFieldsToRead); //合并到结果中 for (int i = 0; i < baseRecords.Length; i++) { foreach (var baseField in baseRecords[i]) { if (!records[i].ContainsKey(baseField.Key)) { records[i].Add(baseField.Key, baseField.Value); } } } } }
public IList <Symbol> GetImpureSymbolsIn(Sentence sentence) { IList <Symbol> allNegatives = this.GetNegativeSymbolsIn(sentence); IList <Symbol> allPositives = this.GetPositiveSymbolsIn(sentence); return(new List <Symbol>(allPositives.Intersect(allNegatives))); }
public void PrepareForUpdateChildrenMasterPages(PageProperties page, Guid?masterPageId, out IList <Guid> newMasterIds, out IList <Guid> oldMasterIds, out IList <Guid> childrenPageIds, out IList <MasterPage> existingChildrenMasterPages) { if ((page.MasterPage != null && page.MasterPage.Id != masterPageId) || (page.MasterPage == null && masterPageId.HasValue)) { newMasterIds = masterPageId.HasValue ? GetPageMasterPageIds(masterPageId.Value) : new List <Guid>(0); oldMasterIds = page.MasterPage != null && page.MasterPages != null?page.MasterPages.Select(mp => mp.Master.Id).Distinct().ToList() : new List <Guid>(0); var intersectingIds = newMasterIds.Intersect(oldMasterIds).ToArray(); foreach (var id in intersectingIds) { oldMasterIds.Remove(id); newMasterIds.Remove(id); } var updatingIds = newMasterIds.Union(oldMasterIds).Distinct().ToList(); existingChildrenMasterPages = GetChildrenMasterPagesToUpdate(page, updatingIds, out childrenPageIds); } else { newMasterIds = null; oldMasterIds = null; childrenPageIds = null; existingChildrenMasterPages = null; } }
/// <summary> /// /// </summary> /// <param name="node1"></param> /// <param name="node2"></param> /// <returns> /// A list of elements directly connecting both the nodes. /// If node1 is equal to node2 (i.e. they are the same nodes), then all the elements connected to that node will be returned. /// </returns> public IList <IFiniteElement> GetAllElementsDirectlyConnecting(IFiniteElementNode node1, IFiniteElementNode node2) { Guard.AgainstNullArgument(node1, "node1"); Guard.AgainstNullArgument(node2, "node2"); IList <IFiniteElement> connectingElements; int currentValidHashForCache = this.GetHashCode(); ElementRepository.NodeTuple keyForCache = new ElementRepository.NodeTuple(node1, node2); return(this.cacheConnectingElements.GetOrCreateAndSave(keyForCache, currentValidHashForCache, () => { IList <IFiniteElement> elementsConnectedToNode1 = this.GetAllElementsConnectedTo(node1); if (node1.Equals(node2)) { connectingElements = elementsConnectedToNode1; } else { IList <IFiniteElement> elementsConnectedToNode2 = this.GetAllElementsConnectedTo(node2); connectingElements = elementsConnectedToNode1.Intersect(elementsConnectedToNode2).ToList(); } return connectingElements; })); }
/// <summary> /// The method to get the suggested friend list of the all database /// </summary> /// <param name="username">the user name</param> /// <param name="userTagIDs">the user tags id</param> /// <param name="pendingRequests">the user pending requests</param> /// <returns>a list with suggested friends</returns> private async Task <List <string> > GetAllFriendsSuggested(string username, IList <int> userTagIDs, List <string> pendingRequests) { List <string> suggestedFriends = new List <string>(); List <string> allUsers = await GetAllUsers(username); foreach (string item in pendingRequests) { if (allUsers.Contains(item)) { allUsers.Remove(item); } } List <string> allUsersId = FindFriendIds(allUsers); foreach (string friendId in allUsersId) { IList <int> friendTagIds = (from userToTag in db.UsersTags where (userToTag.UserID == friendId) select userToTag.TagID).ToList(); if (userTagIDs.Intersect(friendTagIds).ToList().Count > 0) { ApplicationUser friend = db.Users.Find(friendId); suggestedFriends.Add(friend.UserName); } } if (suggestedFriends.Count == 0) { suggestedFriends = allUsers; } return(suggestedFriends); }
//testStudents = new List<NetworkStatus>(); /// <summary> /// 开始比较从数据库读取到的数据集IList和上一次读取结果保存的值是否一致,一致则改变网络状态为offline,不一致则覆盖这次读到的数据 /// </summary> /// <param name="networkstatus_old"></param> /// <param name="networkstatus_new"></param> private void startCompare(IList <NetworkStatus> networkstatus_old, IList <NetworkStatus> networkstatus_new) { try { var jiaoji = networkstatus_old.Intersect(networkstatus_new, new StudentListEquality2()).ToList();//交集 //var ChaJi = networkstatus_new.Except(testStudents).ToList();//差集 jiaoji.ForEach(x => { networkstatus_new.Clear(); for (int i = 0; i < dt1.Rows.Count; i++) { networkstatus_new.Add(new NetworkStatus(dt1.Rows[i][0].ToString(), dt1.Rows[i][1].ToString())); } //如果version没变化,则改变网络状态 UpdateNetworkStatus = "DECLARE @flag AS int begin tran select @flag=Versions from AllStatus where DeviceId='" + x.DeviceId.ToString() + "' update AllStatus set NetworkStatus='offline'WHERE DeviceId='" + x.DeviceId.ToString() + "' and Versions=@flag commit TRAN"; int ii = db.ExecuteNonQuery(UpdateNetworkStatus); }); networkstatus_new.Clear(); for (int i = 0; i < dt1.Rows.Count; i++) { networkstatus_new.Add(new NetworkStatus(dt1.Rows[i][0].ToString(), dt1.Rows[i][1].ToString())); } } catch (Exception ex) { } }
/// <summary> /// The method that determines if a given possible value matches the current values /// of all cascading properties using the attribute specified for each property. /// Cascading properties with blank values are ignored, i.e. a blank value /// is considered to match any value. /// This method is used as part of the default filter function <see cref="IsAllowed"/>, /// but can also be used separately as part of a custom filter function. /// </summary> /// <param name="h">The possible value to match against cascading properties. /// It should have the same attributes as specified for each cascading property.</param> /// <returns>True, if the specified value matches the current value(s) of all cascading properties, /// false otherwise.</returns> public virtual bool MatchesCascadingProperties(Header h) { foreach (string attr in cascadingProperties.Keys) { DataProperty p = cascadingProperties[attr]; object pv = p.InternalValue; object hv = p.ResolveValue(h[attr], ValueFormat.Internal); if (p.IsNull() || p.IsValueNull(hv, ValueFormat.Internal)) { continue; } IList <object> hvl = hv as IList <object>; IList <object> pvl = pv as IList <object>; bool match; if (hvl != null) { match = (pvl != null) ? pvl.Intersect(hvl).Count() > 0 : hvl.Contains(pv); } else { match = (pvl != null) ? pvl.Contains(hv) : hv.Equals(pv); } if (!match) { return(false); } } return(true); }
/// <summary> /// Disjoins the given lists. The common elements are captured in a new list that is returned. /// The commom elements are taken from the list that is the target of the extension invocation. /// The elements are only taken from the target lists if they're not read-only /// The disjoin operation uses the Equals definition of the given IEqualityComparer /// </summary> /// <typeparam name="T">The type of object in the lists</typeparam> /// <param name="a">the target list</param> /// <param name="b">the list to disjoin with</param> /// <param name="equalityComparer"> a specified IEqualityComparer of T that will be used in the comparison of objects during the disjoin operation</param> /// <returns>a list of the elements in common taken fron the target list</returns> public static ICollection <T> Disjoin <T>(this IList <T> a, IList <T> b, IEqualityComparer <T> equalityComparer) { var intersection = a.Intersect(b, equalityComparer).ToSet(); Action <IList <T>, T> removeAction = (list, item) => { for (int i = 0; i < list.Count; i++) { if (equalityComparer.Equals(list[i], item)) { list.RemoveAt(i); break; } } }; Action <IList <T>, T> emptyAction = (list, item) => { }; var aListAction = a.IsReadOnly ? emptyAction : removeAction; var bListAction = b.IsReadOnly ? emptyAction : removeAction; if (!a.IsReadOnly || !b.IsReadOnly) { foreach (var obj in intersection) { aListAction(a, obj); bListAction(b, obj); } } return(intersection); }
public bool AddDialogVariableConditions(DialogVariableConditions variableConditions) { bool variablesChanged = false; var conditionsGroupsByVariable = variableConditions.VariableConditions.Where(condition => condition.Comparison == ConditionComparison.Equals).GroupBy(condition => condition.Variable); foreach (var conditionGroup in conditionsGroupsByVariable) { var variable = conditionGroup.Key; IList <string> previousValues = null; if (VariablesValues.ContainsKey(variable)) { previousValues = VariablesValues[variable]; } IList <string> newValues = null; if (conditionGroup.Count() > 1 && variableConditions.Operator == ConditionOperator.Or) { newValues = conditionGroup.Select(condition => condition.Value).ToList(); } else { newValues = new List <string>(1); newValues.Add(conditionGroup.First().Value); } VariablesValues[variable] = newValues; if (previousValues == null || previousValues.Count != newValues.Count || previousValues.Intersect(newValues).Count() < previousValues.Count) { variablesChanged = true; } } return(variablesChanged); }
public static bool ListEquals <T>(IList <T> x, IList <T> y) { if (x.Count == y.Count) { return(x.Intersect(y).Count() == x.Count); } return(false); }
public static IList <long> IntersectIfNotNull(IList <long> list1, IList <long> list2) { if (list1 == null) { return(list2); } return(list1.Intersect(list2).ToList()); }
public ActionResult Filtrar(FiltroPelicula collection) { try { PeliculaCEN cen = new PeliculaCEN(); IList <PeliculaEN> res = null, aux = null; // TODO: Add delete logic here res = cen.ReadAll(0, int.MaxValue); if (!(collection.anyobol == false || collection.anyomin <= 0 || collection.anyomax <= 0 || collection.anyomax <= collection.anyomin)) { aux = cen.Filtroanyo(collection.anyomin, collection.anyomax); res = res.Intersect(aux).ToList(); } if (collection.Nombrebol == true && collection.Nombre != null) { aux = cen.Filtronombre(collection.Nombre); res = res.Intersect(aux).ToList(); } if (collection.generobol == true && collection.genero != null) { aux = cen.Filtrogenero(collection.genero); res = res.Intersect(aux).ToList(); } if (collection.Valoracionbol == true && collection.Valoracion > 0 && collection.Valoracion < 6) { aux = cen.Filtrovalor((SMPGenNHibernate.Enumerated.SMP.ValoracionEnum)collection.Valoracion); res = res.Intersect(aux).ToList(); } AssemblerPelicula ass = new AssemblerPelicula(); IList <Pelicula> listart = ass.ConvertListENToModel(res); System.Web.HttpContext.Current.Session["resu"] = listart; return(RedirectToAction("Resultadobusqueda", "Pelicula", null)); } catch { return(View()); } }
private bool IsResourceCoveredByAssignedProfile(IList <string> assignedProfiles, string resourceItemName) { // is the resource items name sent in covered by an assigned profile? return(assignedProfiles.Intersect( _profileResourceNamesProvider.GetProfileResourceNames() .Where(x => x.ResourceName.EqualsIgnoreCase(resourceItemName)) .Select(z => z.ProfileName)) .Any()); }
public void IntersectOperator() { var result = _strList1.Intersect(_strList2); foreach (var str in result) { Console.WriteLine(str); } }
public void Bla(string desc, IList <int> left, IList <int> right, IList <int> add, IList <int> remove) { var intersect = left.Intersect(right).ToList(); var toAdd = right.Except(intersect).ToList(); var toRemove = left.Except(intersect).ToList(); Assert.Equal(add, toAdd); Assert.Equal(remove, toRemove); }
public static decimal calculateGenreSimilarity(Movie movieA, Movie movieB) { IList <Genre> genresA = movieA.Genres; IList <Genre> genresB = movieB.Genres; decimal intersection = genresA.Intersect(genresB).Count(); decimal joined = genresA.Count() + genresB.Count(); return(2 * intersection / joined); }
public void intersect() { var result = StringList1.Intersect(StringList2); Console.WriteLine("-----Intersect-------------"); foreach (string str in result) { Console.WriteLine(str); } }
public static List <string> IntersectOnRowKeys(ref Matrix <string, string, double> m1, ref Matrix <string, string, double> m2) { IList <string> var2 = m2.RowKeys; IList <string> var1 = m1.RowKeys; List <string> var = var2.Intersect(var1).ToList(); m1 = m1.SelectRowsView(var); //.AsShoMatrix(); m2 = m2.SelectRowsView(var); //.AsShoMatrix(); return(var); }
public static IList <long> RemoveIntersect(IList <long> list1, IList <long> list2) { var intersectList = list1.Intersect(list2).ToList(); foreach (var item in intersectList) { list1.Remove(item); } return(list1); }
public static void Intersect() { var result = strList1.Intersect(strList2); Console.WriteLine("intersect-----------------------"); foreach (string str in result) { Console.WriteLine(str); } }
/// <summary>Online evaluation for rankings of items</summary> /// <remarks> /// The evaluation protocol works as follows: /// For every test user, evaluate on the test items, and then add the those test items to the training set and perform an incremental update. /// The sequence of users is random. /// </remarks> /// <param name="recommender">the item recommender to be evaluated</param> /// <param name="test">test cases</param> /// <param name="training">training data (must be connected to the recommender's training data)</param> /// <param name="test_users">a list of all test user IDs</param> /// <param name="candidate_items">a list of all candidate item IDs</param> /// <param name="candidate_item_mode">the mode used to determine the candidate items</param> /// <returns>a dictionary containing the evaluation results (averaged by user)</returns> static public ItemRecommendationEvaluationResults EvaluateOnline( this IRecommender recommender, IPosOnlyFeedback test, IPosOnlyFeedback training, IList<int> test_users, IList<int> candidate_items, CandidateItems candidate_item_mode) { var incremental_recommender = recommender as IIncrementalItemRecommender; if (incremental_recommender == null) throw new ArgumentException("recommender must be of type IIncrementalItemRecommender"); candidate_items = Items.Candidates(candidate_items, candidate_item_mode, test, training); test_users.Shuffle(); var results_by_user = new Dictionary<int, ItemRecommendationEvaluationResults>(); foreach (int user_id in test_users) { if (candidate_items.Intersect(test.ByUser[user_id]).Count() == 0) continue; // prepare data var current_test_data = new PosOnlyFeedback<SparseBooleanMatrix>(); foreach (int index in test.ByUser[user_id]) current_test_data.Add(user_id, test.Items[index]); // evaluate user var current_result = Items.Evaluate(recommender, current_test_data, training, current_test_data.AllUsers, candidate_items, CandidateItems.EXPLICIT); results_by_user[user_id] = current_result; // update recommender var tuples = new List<Tuple<int, int>>(); foreach (int index in test.ByUser[user_id]) tuples.Add(Tuple.Create(user_id, test.Items[index])); incremental_recommender.AddFeedback(tuples); // TODO candidate_items should be updated properly } var results = new ItemRecommendationEvaluationResults(); foreach (int u in results_by_user.Keys) foreach (string measure in Items.Measures) results[measure] += results_by_user[u][measure]; foreach (string measure in Items.Measures) results[measure] /= results_by_user.Count; results["num_users"] = results_by_user.Count; results["num_items"] = candidate_items.Count; results["num_lists"] = results_by_user.Count; return results; }
private bool ValidateGrammar(IList<string> terminals, IList<Production> productions) { var declaredNonTerminals = productions.Select(x => x.ProductionHead).Distinct().ToList(); var grammarSymbolsInTails = productions.SelectMany(x => x.ProductionTail).Distinct().ToList(); //check if there are any declared terminals that are used //as the head of a production. var v = terminals.Intersect(declaredNonTerminals).ToList(); if(v.Count > 0) { return false; } //check if there are any symbols used in a production that are not a terminal //and are not the head of some production. v = grammarSymbolsInTails.Except(terminals).Except(declaredNonTerminals).ToList(); if(v.Count > 0) { return false; } //check if there are any declared terminals that are not used in any production. v = terminals.Except(grammarSymbolsInTails).ToList(); if(v.Count > 0) { return false; } //check that there is only one nonterminal that does not appear in a production //this nonterminal is the root of the grammar. v = declaredNonTerminals.Except(grammarSymbolsInTails).ToList(); if(v.Count != 1) { return false; } return false; }
private static void FailDifferentObjects(IList<string> expectedFields, IList<string> actualFields, JObject expectedObject, JObject actualObject) { var commonFields = new HashSet<string>(expectedFields.Intersect(actualFields)); expectedFields = expectedFields.Select(f => commonFields.Contains(f) ? f : "**" + f + "**").ToList(); actualFields = actualFields.Select(f => commonFields.Contains(f) ? f : "**" + f + "**").ToList(); var writer = new StringWriter(); writer.WriteLine("Different fields found in object{0}", expectedObject.Path.WithLeadingWhitespace()); writer.WriteLine(" expected: {0}", string.Join(", ", expectedFields)); writer.WriteLine(" but was: {0}", string.Join(", ", actualFields)); writer.WriteLine(); writer.WriteLine(" expected object:"); writer.WriteLine(expectedObject.ToString(Formatting.Indented)); writer.WriteLine(" actual object:"); writer.WriteLine(actualObject.ToString(Formatting.Indented)); throw new AssertionException(writer.ToString()); }
/// <summary> /// Checks to see if a list of coordinates intersects /// with another list of objects /// </summary> /// <param name="objA">List of coordinates</param> /// <param name="objB">List of coordinates to compare with</param> /// <returns></returns> public static Boolean Detect(IList<Coord> objA, IList<Coord> objB) { return objA.Intersect(objB).Any(); }
private void EditList(string name, IList<string> listToEdit) { ListEditor editor = new ListEditor(name, listToEdit); List<string> original = listToEdit.ToList<string>(); editor.ShowDialog(); int commonCount = listToEdit.Intersect(original).Count<string>(); if (commonCount != listToEdit.Count || commonCount != original.Count) { TitleChanges(null, null); } }
private static void CompareListsNew(IList<Article> list1, List<Article> list2, ListBox lb1, ListBox lb2, ListBox lb3) { lb1.BeginUpdate(); lb2.BeginUpdate(); lb3.BeginUpdate(); lb1.Items.AddRange(list1.Except(list2).ToArray()); lb2.Items.AddRange(list2.Except(list1).ToArray()); lb3.Items.AddRange(list1.Intersect(list2).ToArray()); lb1.EndUpdate(); lb2.EndUpdate(); lb3.EndUpdate(); }
/// <summary> /// this function performs compacting that is bringing in last sitting group to front as so on /// </summary> /// <param name="_theatreList"></param> /// <returns></returns> public IList<Section> Compacting(IList<Customer> customerList) { for (int i = 0; i < _theatreList.Count; i++) { for (int j = _theatreList.Count - 1; j >= i; j--) { if (_theatreList[i].EmpltySeats >= _theatreList[j]. OccupiedSeats && _theatreList[j].OccupiedSeats > 0) { _theatreList[i].AllocateThisSection(_theatreList[j]. GivenTo.ToArray(), _theatreList[j].OccupiedSeats); _theatreList[j].DeallocateThisAllocation(); var customers = customerList.Intersect(_theatreList[i].GivenTo); customers.ToList().ForEach(x => x.AllocateSeat(_theatreList[i].Rownumber, _theatreList[i].SectionId)); } } } return _theatreList; }
/// <summary> /// Set the roles that are being exported by a port /// </summary> /// <param name="portInfo">the portinfo object of the port</param> /// <param name="roles">the list of roles to bind</param> /// <param name="module">the module that own the port</param> public void SetRoles(VPortInfo vPortInfo, IList<VRole> roles, VModule module) { PortInfo storedPortInfo = config.GetMatchingPortInfo(vPortInfo); if (storedPortInfo == null) throw new Exception(vPortInfo + " not found!"); IList<VRole> oldList = storedPortInfo.GetRoles(); bool roleListChanged = (roles.Count != oldList.Count || roles.Count != roles.Intersect(oldList).Count()); storedPortInfo.SetRoles(roles); //update the configuration if (roleListChanged) config.UpdateRoleList(storedPortInfo); }
public void PrepareForUpdateChildrenMasterPages(PageProperties page, Guid? masterPageId, out IList<Guid> newMasterIds, out IList<Guid> oldMasterIds, out IList<Guid> childrenPageIds, out IList<MasterPage> existingChildrenMasterPages) { if ((page.MasterPage != null && page.MasterPage.Id != masterPageId) || (page.MasterPage == null && masterPageId.HasValue)) { newMasterIds = masterPageId.HasValue ? GetPageMasterPageIds(masterPageId.Value) : new List<Guid>(0); oldMasterIds = page.MasterPage != null && page.MasterPages != null ? page.MasterPages.Select(mp => mp.Master.Id).Distinct().ToList() : new List<Guid>(0); var intersectingIds = newMasterIds.Intersect(oldMasterIds).ToArray(); foreach (var id in intersectingIds) { oldMasterIds.Remove(id); newMasterIds.Remove(id); } var updatingIds = newMasterIds.Union(oldMasterIds).Distinct().ToList(); existingChildrenMasterPages = GetChildrenMasterPagesToUpdate(page, updatingIds, out childrenPageIds); } else { newMasterIds = null; oldMasterIds = null; childrenPageIds = null; existingChildrenMasterPages = null; } }