private static void ResolveImportResources(LGFile start, HashSet <LGFile> resourcesFound, ImportResolverDelegate importResolver) { var resourceIds = start.Imports.Select(lg => lg.Id); resourcesFound.Add(start); foreach (var id in resourceIds) { try { var(content, path) = importResolver(start.Id, id); if (resourcesFound.All(u => u.Id != path)) { var childResource = ParseText(content, path, importResolver); ResolveImportResources(childResource, resourcesFound, importResolver); } } catch (LGException err) { throw err; } catch (Exception err) { throw new LGException(err.Message, new List <Diagnostic> { BuildDiagnostic(err.Message, source: start.Id) }); } } }
static long Second(string inputFile) { var map = IntMapParser.Instance.ReadMap(inputFile); HashSet <Octopus> set = Setup(map); for (int step = 1; step <= 10000; step++) { foreach (var octopus in set) { octopus.Increase(); } foreach (var octopus in set) { octopus.DoTurn(step, false); } foreach (var octopus in set) { octopus.Reset(step); } if (set.All(oct => oct.Energy == 0)) { return(step); } } return(-1); }
public static IEnumerable <TSource> DistinctBy <TSource, TKey>(this IEnumerable <TSource> source, Func <TSource, TKey> keySelector, IEqualityComparer <TKey> comparer) { HashSet <TKey> seenKeys = new HashSet <TKey>(); foreach (TSource element in source) { if (seenKeys.Any()) { if (seenKeys.All(t => !comparer.Equals(t, keySelector(element)))) { if (seenKeys.Add(keySelector(element))) { yield return(element); } } } else { if (seenKeys.Add(keySelector(element))) { yield return(element); } } } }
static void Run(string filepath) { var lines = File.ReadAllLines(filepath); var passports = Parse(lines); var mandatory = new HashSet <string> { "byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid" }; int valid = 0; foreach (var passport in passports) { if (mandatory.All(x => passport.ContainsKey(x))) { valid++; } } Console.WriteLine($"valid passports: {valid}"); valid = 0; foreach (var passport in passports) { if (Validators.All(v => passport.ContainsKey(v.Key) && v.Value(passport[v.Key]))) { valid++; } } Console.WriteLine($"B valid {valid}"); }
public static void HasValueCollectionOverlapThrow <T>( StringBuilder sb, T[][] arr1, T[][] arr2, string name1, string name2, IEqualityComparer <T> comparer, string source) { var l = Math.Min(arr1.Length, arr2.Length); for (int i = 0; i < l; i++) { if (new HashSet <T>(arr1[i], comparer).Overlaps( new HashSet <T>(arr2[i], comparer))) { var common = new HashSet <T>(arr1[i], comparer); common.IntersectWith(new HashSet <T>(arr2[i], comparer)); var sbTemp = new StringBuilder(); common.All(x => sbTemp.Append(x).Append(", ") != null); sb.Append(name1).Append(" and ").Append(name2).Append(" ") .Append("can't have value collections on the same ") .Append(" index (i = ").Append(i).Append(") ") .Append("that have any value in common in ") .Append(source) .Append(". Common elements: ") .AppendLine(sbTemp.ToString().Trim(' ', ',')); } } }
private void OnStart(int port, int ws_port) { ListenerPort = port; timer = Context.System.Scheduler.ScheduleTellRepeatedlyCancelable(0, 5000, Context.Self, new Timer(), ActorRefs.NoSender); if ((port > 0 || ws_port > 0) && localAddresses.All(p => !p.IsIPv4MappedToIPv6 || IsIntranetAddress(p)) && UPnP.Discover()) { try { localAddresses.Add(UPnP.GetExternalIP()); if (port > 0) { UPnP.ForwardPort(port, ProtocolType.Tcp, "BHP"); } if (ws_port > 0) { UPnP.ForwardPort(ws_port, ProtocolType.Tcp, "BHP WebSocket"); } } catch { } } if (port > 0) { tcp_manager.Tell(new Tcp.Bind(Self, new IPEndPoint(IPAddress.Any, port), options: new[] { new Inet.SO.ReuseAddress(true) })); } if (ws_port > 0) { ws_host = new WebHostBuilder().UseKestrel().UseUrls($"http://*:{ws_port}").Configure(app => app.UseWebSockets().Run(ProcessWebSocketAsync)).Build(); ws_host.Start(); } }
public void RemoteRouter_must_let_remote_deployment_be_overridden_by_remote_configuration() { var probe = CreateTestProbe(masterActorSystem); var router = masterActorSystem.ActorOf(new RoundRobinPool(2).Props(Props.Create<Echo>()) .WithDeploy( new Deploy(new RemoteScope(intendedRemoteAddress))), "remote-override"); router.Path.Address.ShouldBe(intendedRemoteAddress); var replies = new HashSet<ActorPath>(); for (var i = 0; i < 5; i++) { router.Tell("", probe.Ref); var expected = probe.ExpectMsg<IActorRef>(GetTimeoutOrDefault(null)); replies.Add(expected.Path); } Assert.Equal(4, replies.Count); var parents = replies.Select(x => x.Parent).Distinct().ToList(); parents.Count.ShouldBe(1); parents.Head().Address.ShouldBe(new Address("akka.tcp", sysName, "localhost", port)); Assert.True(replies.All(x => x.Address.Equals(intendedRemoteAddress))); masterActorSystem.Stop(router); }
public void behavior_configurator_should_work() { var behaviorStore = new Mock <IBehaviorStore>(); var behaviorsTypes = new HashSet <Type> { typeof(NotifyPropertyChangedBehavior), typeof(DataErrorInfoBehavior), typeof(EditableBehavior) }; behaviorStore.Setup(bs => bs.GetBehaviorsForType(typeof(A))) .Returns(behaviorsTypes); var additionalInterfaces = new[] { typeof(IDataErrorInfo), typeof(INotifyPropertyChanged), typeof(IEditableObject), typeof(IWellKnownProxy) }; var behaviorToProxyResolver = new BehaviorConfigurator(behaviorStore.Object); var proxyInfo = behaviorToProxyResolver.GetProxyInformation(typeof(A)); behaviorsTypes.All(b => proxyInfo.Interceptors.Contains(b)).Should().Be.True(); additionalInterfaces.All(i => proxyInfo.AdditionalInterfaces.Contains(i)).Should().Be.True(); }
async Task <IEnumerable <Uri> > GetPages(string keyPhrase) { const string resPrefix = "/url?q="; const string protocolPrefix = "http"; var webClient = new WebClient(); var html = await webClient.DownloadStringTaskAsync($"https://www.google.com/search?q=\"{keyPhrase}\""); var parser = new HtmlParser(); var document = parser.ParseDocument(html); var result = document .QuerySelectorAll("a") .Select(p => p.GetAttribute("href")) .Where(p => p.StartsWith(resPrefix + protocolPrefix)) .Select(p => new Uri(p.Substring(resPrefix.Length, p.IndexOf("&") - resPrefix.Length))) .Where(p => ExcludesInUrl.All(e => !p.Host.Contains(e))); if (result.Any()) { _badUrls ??= _dbContext.BadCollectionUrls.Select(p => p.InUrl).ToHashSet(); result = result.Where(p => _badUrls.All(url => !p.Host.Contains(url, StringComparison.OrdinalIgnoreCase))); } return(result); }
public override bool Equals(object obj) { if (this.GetType() != obj.GetType()) { return(false); } AuthorizationRule authorizationRule = (AuthorizationRule)obj; if (!string.Equals(this.IssuerName, authorizationRule.IssuerName, StringComparison.OrdinalIgnoreCase) || !string.Equals(this.ClaimType, authorizationRule.ClaimType, StringComparison.OrdinalIgnoreCase) || !string.Equals(this.ClaimValue, authorizationRule.ClaimValue, StringComparison.OrdinalIgnoreCase)) { return(false); } if (this.Rights != null && authorizationRule.Rights == null || this.Rights == null && authorizationRule.Rights != null) { return(false); } if (this.Rights == null || authorizationRule.Rights == null) { return(true); } HashSet <AccessRights> accessRights = new HashSet <AccessRights>(this.Rights); HashSet <AccessRights> accessRights1 = new HashSet <AccessRights>(authorizationRule.Rights); if (accessRights1.Count != accessRights.Count) { return(false); } return(accessRights.All <AccessRights>(new Func <AccessRights, bool>(accessRights1.Contains))); }
public override BoundNode VisitBaseReference(BoundBaseReference node) { var syntax = node.Syntax; var rewrittenThis = GenerateThisReference(node); var baseType = node.Type; HashSet <DiagnosticInfo> unusedUseSiteDiagnostics = null; var conversion = _conversions.ClassifyImplicitConversionFromExpression(rewrittenThis, baseType, ref unusedUseSiteDiagnostics); Debug.Assert(unusedUseSiteDiagnostics == null || !conversion.IsValid || unusedUseSiteDiagnostics.All(d => d.Severity < DiagnosticSeverity.Error)); // It would be nice if we could just call BoundConversion.Synthesized, but it doesn't seem worthwhile to // introduce a bunch of new overloads to accommodate isBaseConversion. return(new BoundConversion( syntax, rewrittenThis, conversion, isBaseConversion: true, @checked: false, explicitCastInCode: false, constantValueOpt: null, type: baseType, hasErrors: !conversion.IsValid) { WasCompilerGenerated = true }); }
//Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) //{ // throw new NotImplementedException(); //} private static string ImportsFor(HashSet<string> namespaces) { StringBuilder builder = new StringBuilder(); namespaces.All(s => { builder.AppendFormat("using {0};{1}", s, Environment.NewLine); return true; }); return builder.ToString(); }
public void FilterData(List<DoorkeeperJson> doorkeeperResult, ObservableCollection<AllEventsInfo> allEventsInfo, HashSet<string> ngWordsList, HashSet<string> cities) { if (doorkeeperResult != null) { var doorkeeperInfo = from evnt in doorkeeperResult join city in cities on SpecifyCity.GetCity(evnt._event.address) equals city where evnt._event.starts_at <= DateTime.Now.AddMonths(5) where evnt._event.starts_at > DateTime.Now where ngWordsList.All(word => !evnt._event.title.Contains(word)) select new AllEventsInfo { Site = "site_doorkeeper.png", Title = evnt._event.title, Event_uri = evnt._event.public_url, Start_at = evnt._event.starts_at, End_at = evnt._event.ends_at, Description = evnt._event.description, Overview = HtmlToString.GetString(evnt._event.description, 50), Address = evnt._event.address, City = SpecifyCity.GetCity(evnt._event.address), Accepted = evnt._event.participants, Limit = evnt._event.ticket_limit, Organizer = [email protected], }; foreach (var item in doorkeeperInfo) { allEventsInfo.Add(item); } } }
/// <summary> /// Extracts mediators from a graph /// </summary> public void ExtractMediators(HashSet <Node <T> > orderedNodes) { HashSet <Node <T> > mediatorSet = new HashSet <Node <T> >(); HashSet <Community <T> > connectedCommunities = new HashSet <Community <T> >(); while (connectedCommunities.Count < _graph.Communities.Count && orderedNodes.Count != 0) { Node <T> node = orderedNodes.First(); foreach (Community <T> community in _graph.GetIncidentCommunitiesOfNode(node)) { if (connectedCommunities.All(x => x.Id != community.Id)) { if (mediatorSet.All(x => x.Id != node.Id)) { mediatorSet.Add(node); } connectedCommunities.Add(community); } } orderedNodes.Remove(node); } foreach (Node <T> node in mediatorSet) { if (node.Role == 0) { node.Role = Role.Mediator; } } }
public void FilterData(ZusaarJson zusaarResult, ObservableCollection<AllEventsInfo> allEventsInfo, HashSet<string> ngWordsList, HashSet<string> cities) { if (zusaarResult != null) { var zusaaarInfo = from evnt in zusaarResult._event where evnt.started_at <= DateTime.Now.AddMonths(5) where evnt.started_at > DateTime.Now join city in cities on SpecifyCity.GetCity(evnt.address) equals city where ngWordsList.All(word => !evnt.title.Contains(word)) select new AllEventsInfo { Site = "site_zusaar.png", Title = evnt.title, Event_uri = evnt.event_url, Start_at = evnt.started_at, End_at = evnt.ended_at, Description = evnt.description, Overview = HtmlToString.GetString(evnt.description, 50), Address = evnt.address, City = SpecifyCity.GetCity(evnt.address), Accepted = evnt.accepted, Limit = evnt.limit, Organizer = evnt.owner_nickname, }; foreach (var item in zusaaarInfo) { allEventsInfo.Add(item); } } }
private static void Main(string[] args) { var lines = File.ReadAllText("input.txt"); var passports = lines.Split("\n\n"); // Part A var mandatory = new HashSet <string> { "byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid" }; var validsA = new List <string>(); foreach (var passport in passports) { var fields = string.Join(" ", passport.Split("\n")) .Split(' ') .Select(x => x.Split(':')[0]); if (!mandatory.All(x => fields.Contains(x))) { continue; } validsA.Add(passport); } Console.WriteLine(validsA.Count); // 254 // Part B var actions = new Dictionary <string, Func <string, bool> > { { "byr", x => x.All(char.IsDigit) && int.Parse(x) >= 1920 && int.Parse(x) <= 2002 },
/// <summary> /// Topological Sorting (Kahn's algorithm) /// </summary> /// <remarks>https://en.wikipedia.org/wiki/Topological_sorting</remarks> /// <typeparam name="T"></typeparam> /// <param name="nodes">All nodes of directed acyclic graph.</param> /// <param name="edges">All edges of directed acyclic graph.</param> /// <returns>Sorted node in topological order.</returns> public static List <T> Sort <T>(HashSet <T> nodes, HashSet <Tuple <T, T> > edges) where T : IEquatable <T> { // Empty list that will contain the sorted elements var L = new List <T>(); // Set of all nodes with no incoming edges var S = new HashSet <T>(nodes.Where(n => edges.All(e => !e.Item2.Equals(n)))); // while S is non-empty do while (S.Any()) { // remove a node n from S var n = S.First(); S.Remove(n); // add n to tail of L L.Add(n); // for each node m with an edge e from n to m do foreach (var e in edges.Where(e => e.Item1.Equals(n)).ToList()) { var m = e.Item2; // remove edge e from the graph edges.Remove(e); // if m has no other incoming edges then if (edges.All(me => !me.Item2.Equals(m))) { // insert m into S S.Add(m); } } } // if graph has edges then if (edges.Any()) { // return error (graph has at least one cycle) return(new List <T>()); } else { // return L (a topologically sorted order) return(L); } }
/// <summary> /// Updates <see cref="ActiveDocumentMetadata"/> to reflect the documents /// in the method argument. Does not update the value of /// <see cref="DocumentMetadata.ActivatedAt"/> for existing metadata; sets /// as the current time in UTC for new metadata. /// </summary> /// <param name="documents"> /// <see cref="Documents"/> that <see cref="ActiveDocumentMetadata"/> /// should reflect /// </param> /// <param name="setUsageOrder"> /// true to update <see cref="DocumentMetadata.UsageOrder"/> for every /// <see cref="DocumentMetadata"/> in <see cref="ActiveDocumentMetadata"/> /// after Synchronization, false otherwise /// </param> public void Synchronize(Documents documents, bool setUsageOrder) { // DocumentMetadataInfo for each Document in 'documents' var documentsInfoSet = new HashSet <DocumentMetadataInfo>(); // Add documents unique to method parameter collection try { foreach (var obj in documents) { var document = (Document)obj; if (document.ActiveWindow == null) { continue; } var info = new DocumentMetadataInfo { FullName = document.FullName, ProjectDisplayName = document.ProjectItem.ContainingProject.Name, ProjectFullName = document.ProjectItem.ContainingProject.FullName }; documentsInfoSet.Add(info); Add(info); } } catch (COMException) { // COMException is thrown during enumeration of 'documents' // when a project is closed in Visual Studio. Do nothing: this // will result in the active documents metadata collection // being emptied, which is appropriate } // Remove documents not in method parameter collection for (int i = 0; i < _activeDocumentMetadata.Count; i++) { var removeMetadata = documentsInfoSet.All(info => !_documentMetadataEqualityService.Compare( info, _activeDocumentMetadata[i])); if (removeMetadata) { _activeDocumentMetadata.RemoveAt(i); i--; } } if (setUsageOrder) { _normalizedUsageOrderService.SetUsageOrder( _activeDocumentMetadata, _userPreferences); } }
private static bool ContainsAll <E>(HashSet <E> self, HashSet <E> other) { if (self.Count < other.Count) { return(false); } return(other.All(self.Contains)); }
internal static IEnumerable <FilePath> Normalize(IEnumerable <FilePath> directories) { var directorySet = new HashSet <FilePath> (directories); return(directorySet.Where(d => { return directorySet.All(other => !d.IsChildPathOf(other)); })); }
public void HashSetExtensions_All_ReturnsTrueIfHashSetIsEmpty() { var set = new HashSet<Int32>(); var result = set.All(x => x % 2 == 0); TheResultingValue(result).ShouldBe(true); }
public void HashSetExtensions_All_ReturnsTrueIfAllItemsMatchPredicate() { var set = new HashSet<Int32>() { 2, 4, 6 }; var result = set.All(x => x % 2 == 0); TheResultingValue(result).ShouldBe(true); }
public void HashSetExtensions_All_ReturnsFalseIfOneItemDoesNotMatchPredicate() { var set = new HashSet<Int32>() { 1, 2, 4, 6 }; var result = set.All(x => x % 2 == 0); TheResultingValue(result).ShouldBe(false); }
protected void ProcessUnwatchRemote(IActorRef watchee, IActorRef watcher) { if (!Equals(watcher, Self)) { _log.Debug("Unwatching: [{0} -> {1}]", watcher.Path, watchee.Path); _watching.Remove(Tuple.Create(watchee, watcher)); // clean up self watch when no more watchers of this watchee if (_watching.All(t => !Equals(t.Item1, watchee) || Equals(t.Item2, Self))) { _log.Debug("Cleanup self watch of [{0}]", watchee.Path); Context.Unwatch(watchee); _watching.Remove(Tuple.Create(watchee, Self)); } CheckLastUnwatchOfNode(watchee.Path.Address); } }
public void HashSetExtensions_All_ReturnsTrueIfHashSetIsEmpty() { var set = new HashSet <Int32>(); var result = set.All(x => x % 2 == 0); TheResultingValue(result).ShouldBe(true); }
public override bool Equals(object obj) { LibraryDependencyType other = obj as LibraryDependencyType; return(other != null && _keywords.All(other.Contains) && other._keywords.All(_keywords.Contains)); }
//Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) //{ // throw new NotImplementedException(); //} private static string ImportsFor(HashSet <string> namespaces) { StringBuilder builder = new StringBuilder(); namespaces.All(s => { builder.AppendFormat("using {0};{1}", s, Environment.NewLine); return(true); }); return(builder.ToString()); }
/// <summary> /// Invalidate cache object for collection of keys. /// </summary> /// <param name="key"></param> public Task InvalidateCacheAsync(string key) { if (_cacheKeys.All(x => x == key)) { AddOrRemoveCacheKey(key, false); } return(Task.CompletedTask); }
private async Task Start() { CurrentPhase = Phase.Running; if (_users.Count <= 1) { foreach (var user in _users) { if (user.Bet > 0) { await _currency.AddAsync(user.UserId, "Race refund", user.Bet).ConfigureAwait(false); } } var _sf = OnStartingFailed?.Invoke(this); CurrentPhase = Phase.Ended; return; } var _ = OnStarted?.Invoke(this); var _t = Task.Run(async() => { var rng = new NadekoRandom(); while (!_users.All(x => x.Progress >= 60)) { foreach (var user in _users) { user.Progress += rng.Next(1, 11); if (user.Progress >= 60) { user.Progress = 60; } } var finished = _users.Where(x => x.Progress >= 60 && !FinishedUsers.Contains(x)) .Shuffle(); FinishedUsers.AddRange(finished); var _ignore = OnStateUpdate?.Invoke(this); await Task.Delay(2500).ConfigureAwait(false); } var win_amount = 0; foreach (var u in FinishedUsers) { win_amount += (int)u.Bet; } if (FinishedUsers[0].Bet > 0) { await _currency.AddAsync(FinishedUsers[0].UserId, "Won a Race", win_amount) .ConfigureAwait(false); } var _ended = OnEnded?.Invoke(this); }); }
public void All() { Assert.IsTrue(list.All(always)); Assert.IsTrue(list.All(never)); Assert.IsTrue(list.All(even)); list.Add(0); Assert.IsTrue(list.All(always)); Assert.IsFalse(list.All(never)); Assert.IsTrue(list.All(even)); list.Add(5); Assert.IsTrue(list.All(always)); Assert.IsFalse(list.All(never)); Assert.IsFalse(list.All(even)); }
public void cytoscape_script_from_topdown() { Sweet.lollipop = new Lollipop(); ProteoformCommunity community = TestProteoformFamilies.construct_community_with_td_proteoforms(-1); Sweet.lollipop.target_proteoform_community = community; TopDownProteoform td = ConstructorsForTesting.TopDownProteoform("ASDF", 1000, 50); td.gene_name = new GeneName(new List <Tuple <string, string> > { new Tuple <string, string>("genename", "genename") }); ProteoformFamily fam = new ProteoformFamily(td); fam.construct_family(); CytoscapeScript.write_cytoscape_script(new List <ProteoformFamily>() { fam }, new List <ProteoformFamily>() { fam }, TestContext.CurrentContext.TestDirectory, "", "test", null, false, false, CytoscapeScript.color_scheme_names[0], Lollipop.edge_labels[0], Lollipop.node_labels[0], CytoscapeScript.node_label_positions[0], Lollipop.node_positioning[0], 2, true, Lollipop.gene_name_labels[1]); string[] edge_lines = File.ReadAllLines(Path.Combine(TestContext.CurrentContext.TestDirectory, CytoscapeScript.edge_file_prefix + "test" + CytoscapeScript.edge_file_extension)); HashSet <string> shared_pf_names_edges = new HashSet <string>(); for (int i = 1; i < edge_lines.Length; i++) { if (edge_lines[i] == "") { break; } string[] line = edge_lines[i].Split(new char[] { '\t' }); shared_pf_names_edges.Add(line[0]); shared_pf_names_edges.Add(line[2]); } string[] node_lines = File.ReadAllLines(Path.Combine(TestContext.CurrentContext.TestDirectory, CytoscapeScript.node_file_prefix + "test" + CytoscapeScript.node_file_extension)); HashSet <string> shared_pf_names_nodes = new HashSet <string>(); for (int i = 1; i < node_lines.Length; i++) { if (node_lines[i] == "") { break; } string[] line = node_lines[i].Split(new char[] { '\t' }); shared_pf_names_nodes.Add(line[0]); } Assert.True(shared_pf_names_nodes.All(name => shared_pf_names_edges.Contains(name))); Assert.True(shared_pf_names_edges.All(name => shared_pf_names_nodes.Contains(name))); Assert.AreEqual(2, shared_pf_names_nodes.Count); Assert.AreEqual(2, shared_pf_names_edges.Count); }
private void button4_Click(object sender, EventArgs e) { var currentSet = new HashSet <Node>(); var initial = new HashSet <string>(); initial.Add((string)comboBox1.SelectedItem); currentSet.Add(new Node(initial, null, null)); Node sourceNode = null; while (true) { var nextSet = new HashSet <Node>(); foreach (var node in currentSet) { var activeRules = rules .Where(r => !selectedFacts.Contains(r.Consequent) && node.Set.Contains(r.Consequent)); foreach (var r in activeRules) { var set = new HashSet <string>(node.Set); set.Remove(r.Consequent); foreach (var f in r.Antecedents) { set.Add(f); } var newNode = new Node(set, node, r); nextSet.Add(newNode); if (set.All(f => selectedFacts.Contains(f))) { sourceNode = newNode; goto found; } } } if (currentSet.SetEquals(nextSet)) { break; } currentSet = nextSet; } found: if (null == sourceNode) { MessageBox.Show("Вывод невозможен"); return; } MessageBox.Show("Вывод с вероятностью " + sourceNode.Rule.K.ToString()); var inference = new List <Rule>(); while (null != sourceNode.Parent) { inference.Add(sourceNode.Rule); sourceNode = sourceNode.Parent; } listBox4.DataSource = inference; }
public override bool Match(List <string> key, Dictionary <string, object> attributes = null, ISplitClient splitClient = null) { if (key == null || itemsToCompare.Count == 0) { return(false); } return(itemsToCompare.All(i => key.Contains(i))); }
public HashSet <Node <UserDto> > ExtractNodesFromEdges(HashSet <Edge <UserDto> > edges) { HashSet <Node <UserDto> > vertices = new HashSet <Node <UserDto> >(); foreach (Edge <UserDto> edge in edges) { if (vertices.All(x => x.Id != edge.Node1.Id)) { vertices.Add(edge.Node1); } else if (vertices.All(y => y.Id != edge.Node2.Id)) { vertices.Add(edge.Node2); } } return(new HashSet <Node <UserDto> >(vertices.Distinct().ToList())); }
public bool Equals(HashSet <int> x, HashSet <int> y) { if (x.Count != y.Count) { return(false); } return(x.All(t => y.Contains(t))); }
public GlobalVarHidingProofGenerator(ProofGenerationParams i_pgp, GlobalVariableHidingStrategyDecl i_strategy) : base(i_pgp, true) { strategy = i_strategy; hiddenVariables = new HashSet <string>(strategy.Variables); if (hiddenVariables.All(varName => pgp.symbolsLow.Globals.Lookup(varName).varType == ArmadaVarType.Ghost)) { canHideTau = false; } }
public bool IsInGeneratedCodeDocument([NotNull] ISymbol symbol, CancellationToken cancellationToken) { Guard.NotNull(symbol, nameof(symbol)); // Return false when not all locations have generated comment; for example, partial classes. IEnumerable<Location> locations = symbol.Locations.Where(location => location.IsInSource); var trees = new HashSet<SyntaxTree>(locations.Select(location => location.SourceTree)); return trees.Any() && trees.All(tree => IsGeneratedCodeDocument(tree, cancellationToken)); }
public void RemoteRouter_must_let_remote_deployment_router_be_overriden_by_local_configuration() { var probe = CreateTestProbe(masterActorSystem); var router = masterActorSystem.ActorOf(new RoundRobinPool(2).Props(Props.Create<Echo>()) .WithDeploy( new Deploy(new RemoteScope(intendedRemoteAddress.Copy()))), "local-blub2"); // This line was subject to a bug in the original Akka - this router should be locally-deployed. router.Path.Address.ToString().ShouldBe(string.Format("akka://{0}", masterActorSystem.Name)); var replies = new HashSet<ActorPath>(); for (var i = 0; i < 5; i++) { router.Tell("", probe.Ref); var expected = probe.ExpectMsg<ActorRef>(); replies.Add(expected.Path); } Assert.Equal(4, replies.Count); var parents = replies.Select(x => x.Parent).Distinct().ToList(); parents.Head().Address.ShouldBe(new Address("akka.tcp", sysName, "localhost", port)); Assert.True(replies.All(x => x.Address.Equals(intendedRemoteAddress))); masterActorSystem.Stop(router); }
/// <summary> /// Build a dictionary of mixins /// </summary> /// <param name="finalMixins">a list of mixins</param> /// <returns>a dictionary of all the necessary mixins</returns> private Dictionary<string, ModuleMixin> BuildMixinDictionary(IEnumerable<ModuleMixin> finalMixins) { var allMixins = new HashSet<ModuleMixin>(); foreach (var mixin in finalMixins) { if (allMixins.All(x => x.MixinName != mixin.MixinName)) allMixins.Add(mixin); } return allMixins.ToDictionary(x => x.MixinName, x => x); }
private static bool Assignable(HashSet<int> arg) { return arg.All(a => !arg.Contains(-a)); }
public void RemoteRouter_must_deploy_remote_routers_based_on_explicit_deployment() { var probe = CreateTestProbe(masterActorSystem); var router = masterActorSystem.ActorOf(new RoundRobinPool(2).Props(Props.Create<Echo>()) .WithDeploy( new Deploy(new RemoteScope(intendedRemoteAddress))), "remote-blub2"); router.Path.Address.ShouldBe(intendedRemoteAddress); var replies = new HashSet<ActorPath>(); for (var i = 0; i < 5; i++) { router.Tell("", probe.Ref); var expected = probe.ExpectMsg<IActorRef>(GetTimeoutOrDefault(null)); replies.Add(expected.Path); } Assert.Equal(2, replies.Count); var parents = replies.Select(x => x.Parent).Distinct().ToList(); parents.Head().ShouldBe(router.Path); Assert.True(replies.All(x => x.Address.Equals(intendedRemoteAddress))); masterActorSystem.Stop(router); }
public void RemoteRouter_must_deploy_its_children_on_remote_host_driven_by_programmatic_definition() { var probe = CreateTestProbe(masterActorSystem); var router = masterActorSystem.ActorOf(new RemoteRouterConfig(new RoundRobinPool(2), new[] { new Address("akka.tcp", sysName, "localhost", port) }) .Props(Props.Create<Echo>()), "blub2"); var replies = new HashSet<ActorPath>(); for (var i = 0; i < 5; i++) { router.Tell("", probe.Ref); var expected = probe.ExpectMsg<IActorRef>(GetTimeoutOrDefault(null)); replies.Add(expected.Path); } Assert.Equal(2, replies.Count); Assert.Equal(1, replies.Select(x => x.Parent).Distinct().Count()); Assert.True(replies.All(x => x.Address.Equals(intendedRemoteAddress))); masterActorSystem.Stop(router); }
/// <summary> /// Combines several collections of <see cref="IPHostEntry"/> objects into one deduplicated list /// </summary> /// <param name="collections">Collections to combine</param> /// <returns>Deduplicated list of <see cref="IPHostEntry"/> objects</returns> private static ICollection<IPHostEntry> Combine(IEnumerable<ICollection<IPHostEntry>> collections) { var result = new HashSet<IPHostEntry>(); if (collections == null) return result; foreach (var collection in collections.Where(collection => collection != null)) foreach (var host in collection.Where(host => host != null)) { if (String.IsNullOrEmpty(host.HostName)) { if (host.AddressList == null || !host.AddressList.Any()) continue; // We only have one or more IP addresses - no HostName. We consider this host the same as a host we // already have in our result, when at least one IP address in this host equals one IP address of the result host. host.HostName = String.Empty; host.AddressList = host.AddressList.Where(address => address != null).ToArray(); var alreadyPresentHost = result.FirstOrDefault(presentHost => presentHost.AddressList.Intersect(host.AddressList).Any()); if (alreadyPresentHost == null) result.Add(host); else alreadyPresentHost.AddressList = alreadyPresentHost.AddressList.Union(host.AddressList).ToArray(); } else { host.HostName = host.HostName.ToUpperInvariant(); if (host.AddressList == null || !host.AddressList.Any()) { // We only have a HostName - no IP addresses. We consider this host the same as a host we already have in our // result, wenn the HostName is the same host.AddressList = new IPAddress[0]; if (result.All(presentHost => presentHost.HostName != host.HostName)) result.Add(host); } else { // We have both, HostName and one or more IP addresses. // If there is already a host with the same HostName, we combine the IP addresses. // If there is a host with a different HostName, but at least one identical IP address, // if the already present HostName is String.Empty, we replace the empty string with the new HostName // and combine the IP addresses; // if the already present HostName is not String.Empty, we log a warning, // combine the IP addresses of the already present host and discard the HostName of the new host. // If there is no host with the same HostName and no host with one or more identical IP addresses, we // add the new host to the result. host.AddressList = host.AddressList.Where(address => address != null).ToArray(); var alreadyPresentHost = result.FirstOrDefault(presentHost => presentHost.HostName == host.HostName); if (alreadyPresentHost != null) alreadyPresentHost.AddressList = alreadyPresentHost.AddressList.Union(host.AddressList).ToArray(); else { alreadyPresentHost = result.FirstOrDefault(presentHost => presentHost.AddressList.Intersect(host.AddressList).Any()); if (alreadyPresentHost != null) { if (alreadyPresentHost.HostName == String.Empty) { alreadyPresentHost.HostName = host.HostName; alreadyPresentHost.AddressList = alreadyPresentHost.AddressList.Union(host.AddressList).ToArray(); } else { ServiceRegistration.Get<ILogger>().Warn("NeighborhoodBrowserService: Found two computers with different HostNames but at least one identical IP-Address:"); ServiceRegistration.Get<ILogger>().Warn("NeighborhoodBrowserService: HostName: '{0}', IP-Addresses {1}", alreadyPresentHost.HostName, String.Join(" / ", alreadyPresentHost.AddressList.Select(adress => adress.ToString()))); ServiceRegistration.Get<ILogger>().Warn("NeighborhoodBrowserService: HostName: '{0}', IP-Addresses {1}", host.HostName, String.Join(" / ", host.AddressList.Select(adress => adress.ToString()))); ServiceRegistration.Get<ILogger>().Warn("NeighborhoodBrowserService: Discarding the second HostName and adding its IP-Addresses to the first host."); alreadyPresentHost.AddressList = alreadyPresentHost.AddressList.Union(host.AddressList).ToArray(); } } else result.Add(host); } } } } return result; }
private List<IPackage> GetRootPackagesInDependencyOrder() { var packagesInOrder = new List<IPackage>(); // Get all packages var packages = new HashSet<IPackage>(); foreach (var package in LocalRepository.GetPackages().OrderBy(p => p.Id).ThenByDescending(p => p.Version)) { if (packages.All(p => p.Id != package.Id)) { packages.Add(package); } } while (packages.Count > 0) { var nextPackage = packages.FirstOrDefault(); AddPackageRecursive(packagesInOrder, packages, nextPackage); } return packagesInOrder; }
/// <summary> /// Unite filename casing between git index and host OS /// </summary> /// <param name="repo"></param> /// <param name="gitPathInfo"></param> /// <param name="folders"></param> private static void UniteFilenameCasing(this UniteRepository repo, DirectoryInfo gitPathInfo, List<DirectoryInfo> folders) { var files = folders.GetAllFileInfos(gitPathInfo); var filesFullPathMap = new HashSet<String>(files.ConvertAll(s => s.FullName)); var indexFileEntries = repo.Index.Where(f => filesFullPathMap.All(s => s.Replace(repo.Info.WorkingDirectory, string.Empty) != f.Path)); foreach (var entry in indexFileEntries) { var sourcePath = repo.Info.WorkingDirectory + entry.Path; // Match host OS filename based on full pathname ignoring case var target = files.FirstOrDefault(f => String.Equals(f.FullName, sourcePath, StringComparison.CurrentCultureIgnoreCase)); if (target == null) continue; // Unite the git index with the correct OS folder repo.Unite(sourcePath, target.FullName); } }
public static void Main(string[] args) { if (args.Count() != 6) { Console.WriteLine("usage DependencyDumper assemblyFolder assemblyName typePattern minDepth roots absoluteOutputPath"); Console.WriteLine("you provided: " + Environment.CommandLine); Console.ReadLine(); return; } string assemblyFolder = args[0]; string assemblyName = args[1]; Regex typePattern = new Regex(args[2]); int minDepth = int.Parse(args[3]); string[] roots = string.IsNullOrEmpty(args[4]) ? new string[] { } : args[4].Split(','); string outputPath = args[5]; RegisterAssemblyResolveHandler(assemblyFolder); types = new HashSet<Type>(); dependencies = new HashSet<Tuple<Type, Type>>(); allTypes = new HashSet<Type>(); Console.WriteLine("dumping dependencies of " + assemblyName + " and all its referenced assemblies."); Console.WriteLine("using assemblies from folder " + assemblyFolder); Console.WriteLine("using only types matching " + typePattern); Console.WriteLine("dumping only dependency chains longer or equal to " + minDepth); Console.WriteLine("treating the following classes as roots (even if they are used by other classes): " + string.Join(", ", roots)); Console.WriteLine("writing output to (should be a .tgf file)" + outputPath); Console.WriteLine(); Console.WriteLine(); Console.WriteLine("loading types from assemblies..."); Assembly assembly = Assembly.LoadFrom(Path.Combine(assemblyFolder, assemblyName)); var allAssemblies = new List<Assembly>(); AddAssemblies(assembly, allAssemblies); foreach (var a in allAssemblies) { var t = a.GetTypes(); foreach (var type in t) { if (typePattern.IsMatch(type.FullName)) { if (!type.Name.Contains("__")) { allTypes.Add(type); } } } } Console.WriteLine(); Console.WriteLine("processing types:"); foreach (Type type in allTypes) { Console.WriteLine("processing type " + type.FullName); Step(type); } // explicit roots Console.WriteLine(); Console.WriteLine("processing explicit roots:"); foreach (string root in roots) { Console.WriteLine("removing dependencies on " + root); var regex = new Regex(root); var toBreak = dependencies.Where(t => t.Item2.FullName != null && regex.IsMatch(t.Item2.FullName)).ToList(); foreach (Tuple<Type, Type> tuple in toBreak) { dependencies.Remove(tuple); } } Console.WriteLine(); Console.WriteLine("calculating dependency depths"); Dictionary<Type, int> levels = CalculateNodeDepth(); Console.WriteLine(); Console.WriteLine("removing types that are not in a deep enough dependency chain:"); List<Type> remove = new List<Type>(); do { remove.Clear(); foreach (Type type in types) { // root type and not enough depth if (dependencies.All(t => t.Item2 != type) && levels[type] < minDepth) { remove.Add(type); } } foreach (Type type in remove) { Console.WriteLine("removing type " + type); types.Remove(type); dependencies.RemoveWhere(t => t.Item1 == type); } } while (remove.Count > 0); Console.WriteLine(); Console.WriteLine("writing output file..."); var list = new List<Type>(types); using (StreamWriter writer = new StreamWriter(outputPath)) { foreach (var type in list) { var i = levels.ContainsKey(type) ? levels[type] : 0; writer.WriteLine(new List<Type>(types).IndexOf(type) + " " + type.NameToString() + " " + i); } writer.WriteLine("#"); foreach (var dependency in dependencies) { if (list.IndexOf(dependency.Item1) >= 0 && list.IndexOf(dependency.Item2) >= 0) { writer.WriteLine( list.IndexOf(dependency.Item1) + " " + list.IndexOf(dependency.Item2)); } } } Console.WriteLine(); Console.WriteLine(@"opening yEd (C:\Program Files (x86)\yWorks\yEd\yEd.exe)"); Process yEd = new Process { StartInfo = { FileName = @"C:\Program Files (x86)\yWorks\yEd\yEd.exe", Arguments = outputPath } }; yEd.Start(); Console.WriteLine("done. Output file is at " + outputPath); }
/// <summary> /// Returns a sequence of ModulePaths for all modules importable from /// the specified library. /// </summary> public static IEnumerable<ModulePath> GetModulesInLib( string interpreterPath, string libraryPath, string sitePath = null, bool requireInitPyFiles = true ) { if (File.Exists(interpreterPath)) { interpreterPath = Path.GetDirectoryName(interpreterPath); } if (!Directory.Exists(libraryPath)) { return Enumerable.Empty<ModulePath>(); } if (string.IsNullOrEmpty(sitePath)) { sitePath = Path.Combine(libraryPath, "site-packages"); } var pthDirs = ExpandPathFiles(sitePath); var excludedPthDirs = new HashSet<string>() { sitePath, libraryPath }; // Get modules in stdlib var modulesInStdLib = GetModulesInPath(libraryPath, true, true, requireInitPy: requireInitPyFiles); // Get files in site-packages var modulesInSitePackages = GetModulesInPath(sitePath, true, false, requireInitPy: requireInitPyFiles); // Get directories in site-packages // This is separate from getting files to ensure that each package // gets its own library path. var packagesInSitePackages = GetModulesInPath(sitePath, false, true, requireInitPy: requireInitPyFiles); // Get modules in DLLs directory IEnumerable<ModulePath> modulesInDllsPath; // Get modules in interpreter directory IEnumerable<ModulePath> modulesInExePath; if (Directory.Exists(interpreterPath)) { modulesInDllsPath = GetModulesInPath(Path.Combine(interpreterPath, "DLLs"), true, false); modulesInExePath = GetModulesInPath(interpreterPath, true, false); excludedPthDirs.Add(interpreterPath); excludedPthDirs.Add(Path.Combine(interpreterPath, "DLLs")); } else { modulesInDllsPath = Enumerable.Empty<ModulePath>(); modulesInExePath = Enumerable.Empty<ModulePath>(); } // Get directories referenced by pth files var modulesInPath = GetModulesInPath( pthDirs.Where(p1 => excludedPthDirs.All(p2 => !PathUtils.IsSameDirectory(p1, p2))), true, true, requireInitPy: requireInitPyFiles ); return modulesInPath .Concat(modulesInDllsPath) .Concat(modulesInStdLib) .Concat(modulesInExePath) .Concat(modulesInSitePackages) .Concat(packagesInSitePackages); }
internal override FunctionUpdateCommand Translate( UpdateTranslator translator, ExtractedStateEntry stateEntry) { var mapping = GetFunctionMapping(stateEntry); StorageEntityTypeModificationFunctionMapping typeMapping = mapping.Item1; StorageModificationFunctionMapping functionMapping = mapping.Item2; EntityKey entityKey = stateEntry.Source.EntityKey; var stateEntries = new HashSet<IEntityStateEntry> { stateEntry.Source }; // gather all referenced association ends var collocatedEntries = // find all related entries corresponding to collocated association types from end in functionMapping.CollocatedAssociationSetEnds join candidateEntry in translator.GetRelationships(entityKey) on end.CorrespondingAssociationEndMember.DeclaringType equals candidateEntry.EntitySet.ElementType select Tuple.Create(end.CorrespondingAssociationEndMember, candidateEntry); var currentReferenceEnds = new Dictionary<AssociationEndMember, IEntityStateEntry>(); var originalReferenceEnds = new Dictionary<AssociationEndMember, IEntityStateEntry>(); foreach (var candidate in collocatedEntries) { ProcessReferenceCandidate(entityKey, stateEntries, currentReferenceEnds, originalReferenceEnds, candidate.Item1, candidate.Item2); } // create function object FunctionUpdateCommand command; // consider the following scenario, we need to loop through all the state entries that is correlated with entity2 and make sure it is not changed. // entity1 <-- Independent Association <-- entity2 <-- Fk association <-- entity 3 // | // entity4 <-- Fk association <-- if (stateEntries.All(e => e.State == EntityState.Unchanged)) { // we shouldn't update the entity if it is unchanged, only update when referenced association is changed. // if not, then this will trigger a fake update for principal end as describe in bug 894569. command = null; } else { command = new FunctionUpdateCommand(functionMapping, translator, stateEntries.ToList().AsReadOnly(), stateEntry); // bind all function parameters BindFunctionParameters(translator, stateEntry, functionMapping, command, currentReferenceEnds, originalReferenceEnds); // interpret all result bindings if (null != functionMapping.ResultBindings) { foreach (StorageModificationFunctionResultBinding resultBinding in functionMapping.ResultBindings) { PropagatorResult result = stateEntry.Current.GetMemberValue(resultBinding.Property); command.AddResultColumn(translator, resultBinding.ColumnName, result); } } } return command; }
public void RemoteRouter_must_deploy_remote_routers_based_on_configuration() { var probe = CreateTestProbe(masterActorSystem); var router = masterActorSystem.ActorOf(Props.Create<Echo>().WithRouter(FromConfig.Instance), "remote-blub"); router.Path.Address.ShouldBe(intendedRemoteAddress); var replies = new HashSet<ActorPath>(); for (var i = 0; i < 5; i++) { router.Tell("", probe.Ref); var expected = probe.ExpectMsg<ActorRef>(); replies.Add(expected.Path); } Assert.Equal(2, replies.Count); var parents = replies.Select(x => x.Parent).Distinct().ToList(); parents.Head().ShouldBe(router.Path); Assert.True(replies.All(x => x.Address.Equals(intendedRemoteAddress))); masterActorSystem.Stop(router); }
private static void EnsureFieldsAreInCache(IndexSearcherHolder.IndexSearcherHoldingState state, HashSet<string> fieldsToRead, IndexReader reader) { if (fieldsToRead.All(state.IsInCache)) return; state.Lock.ExitReadLock(); state.Lock.EnterWriteLock(); try { var fieldsNotInCache = fieldsToRead.Where(field => state.IsInCache(field) == false).ToList(); if (fieldsToRead.Count > 0) FillCache(state, fieldsNotInCache, reader); } finally { state.Lock.ExitWriteLock(); } state.Lock.EnterReadLock(); }
// Looks up a member of given name and arity in a particular type. private LookupResult MemberLookup(TypeSymbol type, string name, int arity, bool invoked) { LookupResult result; switch (type.TypeKind) { case TypeKind.RefType: return MemberLookup(((RefTypeSymbol)type).ReferencedType, name, arity, invoked); case TypeKind.TypeParameter: result = MemberLookupInTypeParameter(type, name, arity, invoked); break; case TypeKind.Interface: result = MemberLookupInInterface(type, name, arity, invoked); break; case TypeKind.Class: case TypeKind.Struct: case TypeKind.Enum: case TypeKind.Delegate: case TypeKind.ArrayType: result = MemberLookupInClass(type, name, arity, invoked); break; case TypeKind.Error: case TypeKind.PointerType: return LookupResult.Empty; case TypeKind.Unknown: default: Debug.Fail("Unknown type kind"); return LookupResult.Empty; } // TODO: Diagnose ambiguity problems here, and conflicts between non-method and method? Or is that // done in the caller? return result; #if SLOW // A member lookup is the process whereby the meaning of a name in the context of // a type is determined. A member lookup can occur as part of evaluating a // simple-name or a member-access in an expression. If the // simple-name or member-access occurs as the simple-expression of an // invocation-expression, the member is said to be invoked. // If a member is a method or event, or if it is a constant, field or property // of a delegate type, then the member is said to be invocable. // Member lookup considers not only the name of a member but also the number of // type parameters the member has and whether the member is accessible. For the // purposes of member lookup, generic methods and nested generic types have the // number of type parameters indicated in their respective declarations and all // other members have zero type parameters. // A member lookup of a name N with K type parameters in a type T is processed as follows: // First, a set of accessible members named N is determined. // If T is a type parameter, then the set is the union of the sets of accessible // members named N in each of the types specified as a primary constraint or secondary // constraint for T, along with the set of accessible members named N in object. // Otherwise, the set consists of all accessible members named N in T, // including inherited members and the accessible members named N in object. If T is // a constructed type, the set of members is obtained by substituting type arguments // as described in §10.3.2. Members that include an override modifier are excluded // from the set. var results = new HashSet<Symbol>(); var inaccessible = new HashSet<Symbol>(); var notInvocable = new HashSet<Symbol>(); var hidden1 = new HashSet<Symbol>(); var hidden2 = new HashSet<Symbol>(); var types = new HashSet<TypeSymbol>(type.TypeAndAllBaseTypes()); types.Add(System_Object); foreach (TypeSymbol t in types) { results.UnionWith( from s in t.GetMembers(name) where !s.IsOverride select s); } inaccessible.UnionWith(from s in results where !IsMemberAccessible(s) select s); results.ExceptWith(inaccessible); var badArity = new HashSet<Symbol>(); // Next, if K is zero, all nested types whose declarations include type parameters are removed. // If K is not zero, all members with a different number of type parameters are removed. // Note that when K is zero, methods having type parameters are not removed, since the // type inference process might be able to infer the type arguments. if (arity == 0) { badArity.UnionWith(from s in results where s.IsNestedType() && ((NamedTypeSymbol)s).Arity != 0 select s); } else { badArity.UnionWith(from s in results where s is NamedTypeSymbol && ((NamedTypeSymbol)s).Arity != arity select s); badArity.UnionWith(from s in results where s is MethodSymbol && ((MethodSymbol)s).TypeParameters.Count != arity select s); } results.ExceptWith(badArity); // Next, if the member is invoked, all non-invocable members are removed from the set. if (invoked) { notInvocable.UnionWith(from s in results where !IsInvocable(s) select s); } results.ExceptWith(notInvocable); // Next, members that are hidden by other members are removed from the set. // For every member S.M in the set, where S is the type in which the member M is declared, // the following rules are applied: foreach (var member in results) { var declaringType = member.ContainingType; // If M is a constant, field, property, event, or enumeration member, // then all members declared in a base type of S are removed from the set. if (member is FieldSymbol || member is PropertySymbol /* UNDONE || member is EventSymbol */) { foreach (var baseType in declaringType.AllBaseTypeDefinitions()) { hidden1.UnionWith( from s in results where s.ContainingType.OriginalDefinition == baseType select s); } } else if (member is NamedTypeSymbol) { // If M is a type declaration, then all non-types declared in a base type of S // are removed from the set, and all type declarations with the same number of // type parameters as M declared in a base type of S are removed from the set. foreach (var baseType in declaringType.AllBaseTypeDefinitions()) { hidden1.UnionWith( from s in results where s.ContainingType.OriginalDefinition == baseType where !(s is NamedTypeSymbol) || ((NamedTypeSymbol)s).Arity == ((NamedTypeSymbol)member).Arity select s); } } else if (member is MethodSymbol) { // If M is a method, then all non-method members declared in a base type of S // are removed from the set. foreach (var baseType in declaringType.AllBaseTypeDefinitions()) { hidden1.UnionWith( from m in results where m.ContainingType.OriginalDefinition == baseType && !(m is MethodSymbol) select m); } } } results.ExceptWith(hidden1); // Next, interface members that are hidden by class members are removed from the set. // This step only has an effect if T is a type parameter and T has both an effective base // class other than object and a non-empty effective interface set. For every // member S.M in the set, where S is the type in which the member M is declared, the // following rules are applied if S is a class declaration other than object: foreach (var member in results) { var declaringType = member.ContainingType; if (!declaringType.IsClassType() || declaringType == System_Object) { continue; } // If M is a constant, field, property, event, enumeration member, or type declaration, // then all members declared in an interface declaration are removed from the set. if (member is FieldSymbol || member is PropertySymbol /* UNDONE || member is EventSymbol */ || member is NamedTypeSymbol) { hidden2.UnionWith( from m in results where m.ContainingType.IsInterfaceType() select m); } else if (member is MethodSymbol) { // If M is a method, then all non-method members declared in an interface declaration // are removed from the set, and all methods with the same signature as M declared // in an interface declaration are removed from the set. hidden2.UnionWith( from m in results where m.ContainingType.IsInterfaceType() && (!(m is MethodSymbol) || HaveSameSignature((MethodSymbol)m, (MethodSymbol)member)) select m); } } results.ExceptWith(hidden2); hidden1.UnionWith(hidden2); // Finally, having removed hidden members, the result of the lookup is determined: // If the set consists of a single member that is not a method, then this member is the result of the lookup. // Otherwise, if the set contains only methods, then this group of methods is the result of the lookup. // Otherwise, the lookup is ambiguous, and a compile-time error occurs. // For member lookups in types other than type parameters and interfaces, and member lookups in interfaces // that are strictly single-inheritance (each interface in the inheritance chain has exactly zero or one direct // base interface), the effect of the lookup rules is simply that derived members hide base members with the // same name or signature. Such single-inheritance lookups are never ambiguous. The ambiguities that can possibly // arise from member lookups in multiple-inheritance interfaces are described in §13.2.5. // UNDONE: Make this match what the original compiler does. if (results.Count == 0 || (results.Count > 1 && !results.All(m => m is MethodSymbol))) { if (inaccessible.Count != 0) { return LookupResult.Inaccessible(inaccessible.First()); } else if (badArity.Count != 0) { return LookupResult.WrongArity(badArity.First(), null); } else { return LookupResult.Bad((DiagnosticInfo)null); } } else { return LookupResult.ForSymbols(results); } #endif }
private static bool AllOrNoneInThisSet(HashSet<Activity> activities, HashSet<Activity> set) => activities.All(set.Contains) || !set.Any(activities.Contains);
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)); }
//if the activities has any relation where they are the target and the source is not in activities private static bool HasIngoingConnections(DcrGraph graph, HashSet<Activity> activities) => graph.IncludeExcludes.Any(keyValuePair => activities.All(a => !Equals(a, keyValuePair.Key)) && activities.Any(a => keyValuePair.Value.ContainsKey(a))) || graph.Conditions.Any(keyValuePair => activities.All(a => !Equals(a, keyValuePair.Key)) && activities.Any(a => keyValuePair.Value.Contains(a))) || graph.Responses.Any(keyValuePair => activities.All(a => !Equals(a, keyValuePair.Key)) && activities.Any(a => keyValuePair.Value.Contains(a))) || graph.Milestones.Any(keyValuePair => activities.All(a => !Equals(a, keyValuePair.Key)) && activities.Any(a => keyValuePair.Value.Contains(a)));
public void RemoveWhere() { var set = new HashSet<int>(Enumerable.Range(0, 10)); Assert.That(() => { set.RemoveWhere(null); }, Throws.TypeOf(typeof(ArgumentNullException))); set.RemoveWhere(i => i % 2 == 0); Assert.AreEqual(5, set.Count); Assert.IsTrue(set.All(i => i % 2 == 1)); }
public void Execute() { //We only want to run the base query once, so we capture all of the facet-ing terms then run the query // once through the collector and pull out all of the terms in one shot var allCollector = new GatherAllCollector(); var facetsByName = new Dictionary<string, Dictionary<string, FacetValue>>(); using (var currentState = Database.IndexStorage.GetCurrentStateHolder(Index)) { var currentIndexSearcher = currentState.IndexSearcher; var baseQuery = Database.IndexStorage.GetLuceneQuery(Index, IndexQuery, Database.IndexQueryTriggers); currentIndexSearcher.Search(baseQuery, allCollector); var fields = Facets.Values.Select(x => x.Name) .Concat(Ranges.Select(x => x.Key)); var fieldsToRead = new HashSet<string>(fields); FieldTermVector fieldTermVector; var allVectoredTerms = fieldsToRead.All(s => indexDefinition.TermVectors.TryGetValue(s, out fieldTermVector) && fieldTermVector != FieldTermVector.No); if (allVectoredTerms) { IndexedTerms.ReadEntriesForFieldsFromTermVectors(currentState, fieldsToRead, allCollector.Documents, (field,value, doc) => HandleFacets(field,value, facetsByName, doc)); } else { IndexedTerms.ReadEntriesForFields(currentState, fieldsToRead, allCollector.Documents, (field, value, doc) => HandleFacets(field,value, facetsByName, doc)); } UpdateFacetResults(facetsByName); CompleteFacetCalculationsStage1(currentState, allVectoredTerms); CompleteFacetCalculationsStage2(); } }
public void RemoteRouter_must_deploy_dynamic_resizable_number_of_children_on_remote_host_driven_by_configuration () { var probe = CreateTestProbe(masterActorSystem); var router = masterActorSystem.ActorOf(Props.Create<Echo>().WithRouter(FromConfig.Instance), "elastic-blub"); var replies = new HashSet<ActorPath>(); for (var i = 0; i < 5000; i++) { router.Tell("", probe.Ref); var expected = probe.ExpectMsg<IActorRef>(GetTimeoutOrDefault(null)); replies.Add(expected.Path); } Assert.True(replies.Count >= 2); Assert.Equal(1, replies.Select(x => x.Parent).Distinct().Count()); Assert.True(replies.All(x => x.Address.Equals(intendedRemoteAddress))); masterActorSystem.Stop(router); }
public void RemoteRouter_must_deploy_its_children_on_remote_host_driven_by_configuration() { var probe = CreateTestProbe(masterActorSystem); var router = masterActorSystem.ActorOf(new RoundRobinPool(2).Props(Props.Create<Echo>()), "blub"); var replies = new HashSet<ActorPath>(); for (var i = 0; i < 5; i++) { router.Tell("", probe.Ref); var expected = probe.ExpectMsg<ActorRef>(); replies.Add(expected.Path); } Assert.Equal(2, replies.Count); Assert.Equal(1, replies.Select(x => x.Parent).Distinct().Count()); Assert.True(replies.All(x => x.Address.Equals(intendedRemoteAddress))); masterActorSystem.Stop(router); }
public bool CreatePMRoom(HashSet<int> newUsers, int creator, out string error) { error = ""; bool result = false; lock(managerLock) { Log("Enter createpmroom lock", MyExtensions.Logging.LogLevel.Locks); if (newUsers.Count < 2) { error = "There's not enough people to make the room"; } else if (rooms.Any(x => x.Value.Users.SetEquals(newUsers))) { error = "There's already a room with this exact set of people!"; } else if (!newUsers.All(x => users.ContainsKey(x))) { error = "One or more of the given users doesn't exist!"; } /*else if (newUsers.Any(x => users[x].IrcUser)) { error = "You can't include IRC users in a PM room!"; }*/ else if (!users.ContainsKey(creator)) { error = "You don't seem to exist... I'm not sure how to create the room"; } else if (users[creator].Banned || users[creator].Blocked) { error = "You are banned or blocked and cannot create a room"; } else { PMRoom newRoom = new PMRoom(newUsers, creator, TimeSpan.FromDays(1)); rooms.Add(newRoom.Name, newRoom); result = true; } Log("Exit createpmroom lock", MyExtensions.Logging.LogLevel.Locks); } if (result) BroadcastUserList(); return result; }