Exemplo n.º 1
0
        /// <summary>
        /// Returns an option set with all the serializable option values prefetched for given <paramref name="languages"/>,
        /// while also retaining all the explicitly changed option values in this option set for any language.
        /// Note: All the provided <paramref name="languages"/> must be <see cref="RemoteSupportedLanguages.IsSupported(string)"/>.
        /// </summary>
        public SerializableOptionSet UnionWithLanguages(ImmutableHashSet <string> languages)
        {
            Debug.Assert(languages.All(RemoteSupportedLanguages.IsSupported));

            if (_languages.Value.IsSupersetOf(languages))
            {
                return(this);
            }

            // First create a base option set for the given languages.
            languages = languages.Union(_languages.Value);
            var newOptionSet = _workspaceOptionSet.OptionService.GetSerializableOptionsSnapshot(languages);

            // Then apply all the changed options from the current option set to the new option set.
            foreach (var changedOption in this.GetChangedOptions())
            {
                var valueInNewOptionSet         = newOptionSet.GetOption(changedOption);
                var changedValueInThisOptionSet = this.GetOption(changedOption);

                if (!Equals(changedValueInThisOptionSet, valueInNewOptionSet))
                {
                    newOptionSet = (SerializableOptionSet)newOptionSet.WithChangedOption(changedOption, changedValueInThisOptionSet);
                }
            }

            return(newOptionSet);
        }
Exemplo n.º 2
0
        public async Task <bool> Link(IImmutableSet <string> userIds)
        {
            List <LinkedAccount> linkedAccountEntries = await _collection
                                                        // .Find(l => l.UserIds.Intersect(userIds).Any())
                                                        .Find(Builders <LinkedAccount> .Filter.AnyIn(l => l.UserIds, userIds))
                                                        .ToListAsync();

            ImmutableHashSet <string> existingUserIds = linkedAccountEntries
                                                        .SelectMany(l => l.UserIds)
                                                        .ToImmutableHashSet();
            ImmutableHashSet <string> allUserIds = existingUserIds.Union(userIds);

            if (existingUserIds.Count == allUserIds.Count)
            {
                return(false); // already marked as linked
            }
            // don't bother patching existing documents, just delete all old ones and make a new one
            await _collection.InsertOneAsync(new LinkedAccount(string.Empty, allUserIds.ToHashSet()));

            foreach ((string id, _) in linkedAccountEntries)
            {
                await _collection.DeleteOneAsync(l => l.Id == id);
            }
            return(true);
        }
 internal static void AddRouteAllowList(IEnumerable <string> list)
 {
     if (list != null)
     {
         Allowlist = Allowlist.Union(list);
     }
 }
        private ImmutableHashSet <CounterElement> MergeElements(ImmutableHashSet <CounterElement> firstSet, ImmutableHashSet <CounterElement> secondSet)
        {
            var union            = firstSet.Union(secondSet);
            var filteredElements = union.Where(u => !union.Any(e => Equals(u.Node, e.Node) && u.Value < e.Value));

            return(filteredElements.ToImmutableHashSet());
        }
Exemplo n.º 5
0
        public Task <ImmutableHashSet <TChromosome> > SelectAsync(
            ImmutableHashSet <TChromosome> eliteOffspring,
            ImmutableHashSet <TChromosome> lastFront,
            int expectedOffspringCount,
            CancellationToken token)
        {
            var joined         = lastFront.Union(eliteOffspring);
            var remainingCount = expectedOffspringCount - eliteOffspring.Count;

            var measurable = SelectMeasurableOffspring(eliteOffspring, lastFront)
                             .ToDictionary(chromosome => chromosome, _ => 0d);

            foreach (var objective in _objectives)
            {
                var ordered = joined.OrderBy(chromosome =>
                                             _mapper.GetValue(objective, chromosome.Fitness))
                              .ThenBy(chromosome =>
                                      _objectives.Average(obj =>
                                                          _mapper.GetValue(obj, chromosome.Fitness)))
                              .ToImmutableArray();

                var first = ordered.First();
                var last  = ordered.Last();

                if (measurable.ContainsKey(first) || measurable.ContainsKey(last))
                {
                    var longestDistance = CalculateDistance(first, last);

                    if (measurable.ContainsKey(first))
                    {
                        measurable[first] += longestDistance;
                    }
                    if (measurable.ContainsKey(last))
                    {
                        measurable[last] += longestDistance;
                    }
                }

                for (var i = 1; i < ordered.Length - 1; i++)
                {
                    if (!measurable.ContainsKey(ordered[i]))
                    {
                        continue;
                    }
                    var lower    = ordered[i - 1];
                    var higher   = ordered[i + 1];
                    var distance = CalculateDistance(lower, higher);
                    measurable[ordered[i]] += distance;
                }
            }

            var selected = FilterMeasuredOffspring(
                eliteOffspring,
                measurable,
                expectedOffspringCount,
                remainingCount);

            return(Task.FromResult(selected));
        }
Exemplo n.º 6
0
        public void ImmutableSetAdapter_Ctor_Succeeds()
        {
            const int NumberOfMethods = 17;

            int[] methodsCalled            = new int[NumberOfMethods];
            ImmutableHashSet <int> realSet = ImmutableHashSet <int> .Empty;

            System.Collections.Immutable.IImmutableSet <int> backingSet =
                new MockSystemImmutableSet <int>(
                    addDelegate: x => { methodsCalled[0]++; return(realSet.Add(x)); },
                    clearDelegate: () => { methodsCalled[1]++; return(realSet.Clear()); },
                    containsDelegate: x => { methodsCalled[2]++; return(realSet.Contains(x)); },
                    countDelegate: () => { methodsCalled[3]++; return(realSet.Count); },
                    equalsDelegate: null,
                    exceptDelegate: x => { methodsCalled[4]++; return(realSet.Except(x)); },
                    getEnumeratorDelegate: () => { methodsCalled[5]++; return(realSet.GetEnumerator()); },
                    getHashCodeDelegate: null,
                    intersectDelegate: x => { methodsCalled[6]++; return(realSet.Intersect(x)); },
                    isProperSubsetOfDelegate: x => { methodsCalled[7]++; return(realSet.IsProperSubsetOf(x)); },
                    isProperSupersetOfDelegate: x => { methodsCalled[8]++; return(realSet.IsProperSupersetOf(x)); },
                    isSubsetOfDelegate: x => { methodsCalled[9]++; return(realSet.IsSubsetOf(x)); },
                    isSupersetOfDelegate: x => { methodsCalled[10]++; return(realSet.IsSupersetOf(x)); },
                    overlapsDelegate: x => { methodsCalled[11]++; return(realSet.Overlaps(x)); },
                    removeDelegate: x => { methodsCalled[12]++; return(realSet.Remove(x)); },
                    setEqualsDelegate: x => { methodsCalled[13]++; return(realSet.SetEquals(x)); },
                    symmetricExceptDelegate: x => { methodsCalled[14]++; return(realSet.SymmetricExcept(x)); },
                    toStringDelegate: null,
                    tryGetValueDelegate: (int x, out int y) => { methodsCalled[15]++; return(realSet.TryGetValue(x, out y)); },
                    unionDelegate: x => { methodsCalled[16]++; return(realSet.Union(x)); });

#pragma warning disable IDE0028 // Simplify collection initialization. Intentionally calling .Add separately for clarity
            ImmutableSetAdapter <int> set = new ImmutableSetAdapter <int>(backingSet);
#pragma warning restore IDE0028 // Simplify collection initialization.

            set.Add(12);
            set.Clear();
            set.Contains(12);
            _ = set.Count;
            set.Except(Array.Empty <int>());
            set.GetEnumerator();
            set.Intersect(Array.Empty <int>());
            set.IsProperSubsetOf(Array.Empty <int>());
            set.IsProperSupersetOf(Array.Empty <int>());
            set.IsSubsetOf(Array.Empty <int>());
            set.IsSupersetOf(Array.Empty <int>());
            set.Overlaps(Array.Empty <int>());
            set.Remove(12);
            set.SetEquals(Array.Empty <int>());
            set.SymmetricExcept(Array.Empty <int>());
            set.TryGetValue(12, out _);
            set.Union(Array.Empty <int>());

            for (int counter = 0; counter < NumberOfMethods; counter++)
            {
                Assert.AreEqual(1, methodsCalled[counter]);
            }
        }
Exemplo n.º 7
0
 protected override ImmutableHashSet <TChromosome> FilterMeasuredOffspring(
     ImmutableHashSet <TChromosome> elite,
     IReadOnlyDictionary <TChromosome, double> measured,
     int requiredCount,
     int remainingCount)
 {
     return(elite.Union(measured.OrderByDescending(kv => kv.Value)
                        .Take(remainingCount)
                        .Select(kv => kv.Key)));
 }
Exemplo n.º 8
0
        public static ImmutableHashSet <T> UnionAll <T>(this IEnumerable <ImmutableHashSet <T> > sets)
        {
            ImmutableHashSet <T> result = ImmutableHashSet <T> .Empty;

            foreach (var set in sets)
            {
                result = result.Union(set);
            }
            return(result);
        }
        public override void VisitPropertyBinding(ResolvedPropertyBinding propertyBinding)
        {
            var r = propertyBinding.Binding.Binding.GetProperty <RequiredRuntimeResourcesBindingProperty>(ErrorHandlingMode.ReturnNull);

            if (r != null)
            {
                requiredResources = requiredResources.Union(r.Resources);
            }
            base.VisitPropertyBinding(propertyBinding);
        }
Exemplo n.º 10
0
        protected override void Initialize()
        {
            using (UnconfiguredProjectAsynchronousTasksService.LoadedProject())
            {
                // this.IsApplicable may take a project lock, so we can't do it inline with this method
                // which is holding a private lock.  It turns out that doing it asynchronously isn't a problem anyway,
                // so long as we guard against races with the Dispose method.
                UnconfiguredProjectAsynchronousTasksService.LoadedProjectAsync(
                    async delegate
                {
                    await TaskScheduler.Default.SwitchTo(alwaysYield: true);
                    UnconfiguredProjectAsynchronousTasksService.
                    UnloadCancellationToken.ThrowIfCancellationRequested();

                    lock (SyncObject)
                    {
                        Verify.NotDisposed(this);

                        var intermediateBlock = new BufferBlock <
                            IProjectVersionedValue <
                                IProjectSubscriptionUpdate> >();

                        _projectSubscriptionLink = ProjectSubscriptionService.JointRuleSource.SourceBlock.LinkTo(
                            intermediateBlock,
                            ruleNames: UnresolvedReferenceRuleNames.Union(ResolvedReferenceRuleNames),
                            suppressVersionOnlyUpdates: false);

                        var actionBlock = new ActionBlock <
                            IProjectVersionedValue <
                                Tuple <IProjectSubscriptionUpdate,
                                       IProjectCatalogSnapshot,
                                       IProjectSharedFoldersSnapshot> > >
                                              (new Action <
                                                  IProjectVersionedValue <
                                                      Tuple <IProjectSubscriptionUpdate,
                                                             IProjectCatalogSnapshot,
                                                             IProjectSharedFoldersSnapshot> > >(
                                                  ProjectSubscriptionService_Changed),
                                              new ExecutionDataflowBlockOptions()
                        {
                            NameFormat = "ReferencesSubtree Input: {1}"
                        });

                        _projectSyncLink = ProjectDataSources.SyncLinkTo(
                            intermediateBlock.SyncLinkOptions(),
                            ProjectSubscriptionService.ProjectCatalogSource.SourceBlock.SyncLinkOptions(),
                            ProjectSubscriptionService.SharedFoldersSource.SourceBlock.SyncLinkOptions(),
                            actionBlock);
                    }
                },
                    registerFaultHandler: true);
            }
        }
Exemplo n.º 11
0
                private ImmutableHashSet <IIncrementalAnalyzer> Union(ImmutableHashSet <IIncrementalAnalyzer> analyzers)
                {
                    if (analyzers.IsEmpty)
                    {
                        return(Analyzers);
                    }

                    if (Analyzers.IsEmpty)
                    {
                        return(analyzers);
                    }

                    return(Analyzers.Union(analyzers));
                }
Exemplo n.º 12
0
        private void SubmissionSuccessfullyExecuted(RemoteExecutionResult result)
        {
            // only remember the submission if we compiled successfully, otherwise we
            // ignore it's id so we don't reference it in the next submission.
            _previousSubmissionProjectId = _currentSubmissionProjectId;

            // Grab any directive references from it
            var compilation = _workspace.CurrentSolution.GetProject(_previousSubmissionProjectId).GetCompilationAsync().Result;

            _references = _references.Union(compilation.DirectiveReferences);

            // update local search paths - remote paths has already been updated

            UpdateLocalPaths(result.NewReferencePaths, result.NewSourcePaths, result.NewWorkingDirectory);
        }
Exemplo n.º 13
0
        public CSharpEditorFormattingService()
        {
            _autoFormattingTriggerChars = ImmutableHashSet.CreateRange <char>(";}");

            // add all auto formatting trigger to supported char
            _supportedChars = _autoFormattingTriggerChars.Union("{}#nte:)");

            // set up multi words map
            _multiWordsMap = ImmutableDictionary.CreateRange(new[]
            {
                KeyValuePair.Create('n', ImmutableHashSet.Create(SyntaxKind.RegionKeyword, SyntaxKind.EndRegionKeyword)),
                KeyValuePair.Create('t', ImmutableHashSet.Create(SyntaxKind.SelectKeyword)),
                KeyValuePair.Create('e', ImmutableHashSet.Create(SyntaxKind.WhereKeyword)),
            });
        }
        public CSharpEditorFormattingService()
        {
            _autoFormattingTriggerChars = ImmutableHashSet.CreateRange<char>(";}");

            // add all auto formatting trigger to supported char
            _supportedChars = _autoFormattingTriggerChars.Union("{}#nte:)");

            // set up multi words map
            _multiWordsMap = ImmutableDictionary.CreateRange(new[]
            {
                KeyValuePair.Create('n', ImmutableHashSet.Create(SyntaxKind.RegionKeyword, SyntaxKind.EndRegionKeyword)),
                KeyValuePair.Create('t', ImmutableHashSet.Create(SyntaxKind.SelectKeyword)),
                KeyValuePair.Create('e', ImmutableHashSet.Create(SyntaxKind.WhereKeyword)),
            });
        }
Exemplo n.º 15
0
        /// <summary>
        /// This function is intended to provide a new immutability context that considers the conditional type parameters
        /// of the ConditionallyImmutable type being checked as immutable. It is important this is only used in those cases,
        /// and not for instance while validating type arguments to an [Immutable] type parameter.
        /// </summary>
        /// <param name="type">The ConditionallyImmutable type definition being checked</param>
        /// <returns></returns>
        public ImmutabilityContext WithConditionalTypeParametersAsImmutable(
            INamedTypeSymbol type
            )
        {
            if (!m_annotationsContext.Objects.ConditionallyImmutable.IsDefined(type))
            {
                throw new InvalidOperationException($"{nameof( WithConditionalTypeParametersAsImmutable )} should only be called on ConditionallyImmutable types");
            }

            var conditionalTypeParameters = type.TypeParameters.Where(p => m_annotationsContext.Objects.OnlyIf.IsDefined(p));

            return(new ImmutabilityContext(
                       annotationsContext: m_annotationsContext,
                       extraImmutableTypes: m_extraImmutableTypes,
                       knownImmutableReturns: m_knownImmutableReturns,
                       conditionalTypeParamemters: m_conditionalTypeParameters.Union(conditionalTypeParameters)
                       ));
        }
        private static double MinPrice(ImmutableHashSet <Node> nodesIn, Graph graph,
                                       ImmutableHashSet <Node> prohibitedNodes, int setSize)
        {
            ImmutableDictionary <Node, double> priceOfNode = ImmutableDictionary <Node, double> .Empty;
            var usedNodes = nodesIn.Union(prohibitedNodes);

            foreach (var node in nodesIn)
            {
                var price = 0.0;
                foreach (var adjacentNode in nodesIn)
                {
                    if (!node.Equals(adjacentNode))
                    {
                        price += graph.Weights[node][adjacentNode];
                    }
                }

                price += graph.Weights[node].RemoveKeys(usedNodes).Values.PartialSort(setSize - nodesIn.Count).Sum();

                priceOfNode = priceOfNode.Add(node, price);
            }
            foreach (var graphNode in graph.Nodes)
            {
                if (!usedNodes.Contains(graphNode))
                {
                    var price = 0.0;
                    foreach (var adjacentNode in nodesIn)
                    {
                        price += graph.Weights[graphNode][adjacentNode];
                    }
                    if (setSize > nodesIn.Count)
                    {
                        price += graph.Weights[graphNode].RemoveKeys(usedNodes).Values.PartialSort(setSize - nodesIn.Count - 1).Sum();
                    }

                    priceOfNode = priceOfNode.Add(graphNode, price);
                }
            }

            double inPrice   = nodesIn.Sum(n => priceOfNode[n]) / 2.0;
            double restPrice = priceOfNode.RemoveRange(nodesIn).Values.PartialSort(setSize - nodesIn.Count).Sum() / 2.0;

            return(inPrice + restPrice);
        }
Exemplo n.º 17
0
        private static IEnumerable <ImmutableHashSet <T> > FindCliques(
            IGraph <T> graph,
            ImmutableHashSet <T> potential_clique,
            ImmutableHashSet <T> remaining_nodes,
            ImmutableHashSet <T> skip_nodes)
        {
            if (potential_clique.IsEmpty && skip_nodes.IsEmpty)
            {
                yield return(remaining_nodes);
            }
            else
            {
                var choices = potential_clique.Union(skip_nodes);
                ImmutableHashSet <T> pivoted;

                if (choices.Count > 0)
                {
                    var pivotVertex = choices.Shuffle().First();
                    pivoted = potential_clique.Except(graph.Neigbours(pivotVertex));
                }
                else
                {
                    pivoted = potential_clique;
                }

                foreach (var v in pivoted)
                {
                    var neighborsOfV = graph.Neigbours(v);
                    var sub          = FindCliques(
                        graph,
                        potential_clique.Intersect(neighborsOfV),
                        remaining_nodes.Add(v),
                        skip_nodes.Intersect(neighborsOfV));

                    foreach (var s in sub)
                    {
                        yield return(s);
                    }

                    potential_clique = potential_clique.Remove(v);
                    skip_nodes       = skip_nodes.Add(v);
                }
            }
        }
Exemplo n.º 18
0
        public void Process(ImmutableHashSet <EvalStack> set)
        {
            if (G == null)
            {
                throw new NullReferenceException("Need to init G for node " + _id);
            }

            var x = set.Except(_I);

            if (!x.IsEmpty)
            {
                _I = _I.Union(x);
                _O = _I.Select(s => G(s)).ToImmutableHashSet();
                foreach (var n in _targets)
                {
                    n.Process(_O);
                }
            }
        }
Exemplo n.º 19
0
        public async Task <ExecutionResult> ExecuteCodeAsync(string text)
        {
            try
            {
                if (InteractiveCommands.InCommand)
                {
                    var cmdResult = InteractiveCommands.TryExecuteCommand();
                    if (cmdResult != null)
                    {
                        return(await cmdResult.ConfigureAwait(false));
                    }
                }

                var result = await _interactiveHost.ExecuteAsync(text).ConfigureAwait(false);

                if (result.Success)
                {
                    // We are not executing a command (the current content type is not "Interactive Command"),
                    // so the source document should not have been removed.
                    Debug.Assert(_workspace.CurrentSolution.GetProject(_currentSubmissionProjectId).HasDocuments);

                    // only remember the submission if we compiled successfully, otherwise we
                    // ignore it's id so we don't reference it in the next submission.
                    _previousSubmissionProjectId = _currentSubmissionProjectId;

                    // Grab any directive references from it
                    var compilation = await _workspace.CurrentSolution.GetProject(_previousSubmissionProjectId).GetCompilationAsync().ConfigureAwait(false);

                    _references = _references.Union(compilation.DirectiveReferences);

                    // update local search paths - remote paths has already been updated
                    UpdateResolvers(result);
                }

                return(new ExecutionResult(result.Success));
            }
            catch (Exception e) when(FatalError.Report(e))
            {
                throw ExceptionUtilities.Unreachable;
            }
        }
Exemplo n.º 20
0
            private static ImmutableHashSet <RemoteObserver> GatherObservers
                (IDictionary <string, ImmutableList <Subscription> > dictionary,
                string[] ids)
            {
                ImmutableHashSet <RemoteObserver> result = null;

                if (ids != null)
                {
                    result = ImmutableHashSet <RemoteObserver> .Empty;

                    foreach (string id in ids)
                    {
                        if (dictionary.TryGetValue(id, out ImmutableList <Subscription> subscriptions))
                        {
                            result = result.Union(subscriptions.Select(x => x.Observer));
                        }
                    }
                }

                return(result);
            }
        /// <summary>
        ///     Constructs validator with custom set of allowed and restricted characters.
        /// </summary>
        /// <param name="configAction">
        ///     Delegate to configure validator. Used for setting allowed characters and add additional restricted characters.
        /// </param>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="configAction" /> is null.</exception>
        /// <exception cref="ArgumentException">Thrown if you set same characters for allowed and restricted.</exception>
        public NoSpecialCharactersValidator(Action <INoSpecialCharactersConfigurationExpression> configAction) : this()
        {
            if (configAction == null)
            {
                throw new ArgumentNullException(nameof(configAction));
            }

            var builder = new NoSpecialCharactersConfigurationBuilder();

            configAction(builder);
            _configuration = builder.Build();

            if (_configuration.AllowedChars != null && _configuration.AllowedChars.Count > 0)
            {
                _restrictedCharacters = _restrictedCharacters.Except(_configuration.AllowedChars);
            }

            if (_configuration.RestrictedChars != null && _configuration.RestrictedChars.Count > 0)
            {
                _restrictedCharacters = _restrictedCharacters.Union(_configuration.RestrictedChars);
            }
        }
Exemplo n.º 22
0
        internal ProjectDependencyGraph WithAdditionalProjects(IEnumerable <ProjectId> projectIds)
        {
            // Track the existence of some new projects. Note this call only adds new ProjectIds, but doesn't add any references. Any caller who wants to add a new project
            // with references will first call this, and then call WithAdditionalProjectReferences to add references as well.

            // Since we're adding a new project here, there aren't any references to it, or at least not yet. (If there are, they'll be added
            // later with WithAdditionalProjectReferences). Thus, the new projects aren't topologically sorted relative to any other project
            // and form their own dependency set. Thus, sticking them at the end is fine.
            var newTopologicallySortedProjects = _lazyTopologicallySortedProjects;

            if (!newTopologicallySortedProjects.IsDefault)
            {
                newTopologicallySortedProjects = newTopologicallySortedProjects.AddRange(projectIds);
            }

            var newDependencySets = _lazyDependencySets;

            if (!newDependencySets.IsDefault)
            {
                var builder = newDependencySets.ToBuilder();

                foreach (var projectId in projectIds)
                {
                    builder.Add(ImmutableArray.Create(projectId));
                }

                newDependencySets = builder.ToImmutable();
            }

            // The rest of the references map is unchanged, since no new references are added in this call.
            return(new ProjectDependencyGraph(
                       _projectIds.Union(projectIds),
                       referencesMap: _referencesMap,
                       reverseReferencesMap: _lazyReverseReferencesMap,
                       transitiveReferencesMap: _transitiveReferencesMap,
                       reverseTransitiveReferencesMap: _reverseTransitiveReferencesMap,
                       topologicallySortedProjects: newTopologicallySortedProjects,
                       dependencySets: newDependencySets));
        }
        public ComputationalComplexityMetrics Union(ComputationalComplexityMetrics other)
        {
            if (ReferenceEquals(this, Default))
            {
                return(other);
            }
            else if (ReferenceEquals(other, Default))
            {
                return(this);
            }

            return(new ComputationalComplexityMetrics(
                       effectiveLinesOfCode: EffectiveLinesOfCode + other.EffectiveLinesOfCode,
                       operatorUsageCounts: _operatorUsageCounts + other._operatorUsageCounts,
                       symbolUsageCounts: _symbolUsageCounts + other._symbolUsageCounts,
                       constantUsageCounts: _constantUsageCounts + other._constantUsageCounts,
                       distinctOperatorKinds: _distinctOperatorKinds.Union(other._distinctOperatorKinds),
                       distinctBinaryOperatorKinds: _distinctBinaryOperatorKinds.Union(other._distinctBinaryOperatorKinds),
                       distinctUnaryOperatorKinds: _distinctUnaryOperatorKinds.Union(other._distinctUnaryOperatorKinds),
                       distinctCaseKinds: _distinctCaseKinds.Union(other._distinctCaseKinds),
                       distinctReferencedSymbols: _distinctReferencedSymbols.Union(other._distinctReferencedSymbols),
                       distinctReferencedConstants: _distinctReferencedConstants.Union(other._distinctReferencedConstants)));
        }
Exemplo n.º 24
0
 public TestComposition AddAssemblies(IEnumerable <Assembly>?assemblies)
 => WithAssemblies(Assemblies.Union(assemblies ?? Array.Empty <Assembly>()));
Exemplo n.º 25
0
        public Task <ImmutableHashSet <TChromosome> > SelectAsync(
            ImmutableHashSet <TChromosome> eliteOffspring,
            ImmutableHashSet <TChromosome> lastFront,
            int expectedOffspringCount,
            CancellationToken token)
        {
            var joined         = lastFront.Union(eliteOffspring);
            var remainingCount = expectedOffspringCount - eliteOffspring.Count;

            var measurable = SelectMeasurableOffspring(eliteOffspring, lastFront)
                             .ToDictionary(chromosome => chromosome, _ => 0d);

            foreach (var objective in _objectives)
            {
                var orderedGrouped = joined.GroupBy(chromosome =>
                                                    _mapper.GetValue(objective, chromosome.Fitness))
                                     .OrderBy(group => group.Key)
                                     .ToImmutableArray();

                if (orderedGrouped.Length == 1)
                {
                    continue;
                }

                var longestDistance = Math.Abs(orderedGrouped.First().Key - orderedGrouped.Last().Key);
                var firstLast       = orderedGrouped.First().Union(orderedGrouped.Last());

                foreach (var chromosome in firstLast)
                {
                    if (!measurable.ContainsKey(chromosome))
                    {
                        continue;
                    }
                    measurable[chromosome] += longestDistance;
                }

                if (orderedGrouped.Length == 2)
                {
                    continue;
                }

                for (var i = 1; i < orderedGrouped.Length - 1; i++)
                {
                    var lower    = orderedGrouped[i - 1].Key;
                    var higher   = orderedGrouped[i + 1].Key;
                    var distance = Math.Abs(higher - lower);

                    foreach (var chromosome in orderedGrouped[i])
                    {
                        if (!measurable.ContainsKey(chromosome))
                        {
                            continue;
                        }
                        measurable[chromosome] += distance;
                    }
                }
            }

            var selected = FilterMeasuredOffspring(
                eliteOffspring,
                measurable,
                expectedOffspringCount,
                remainingCount);

            return(Task.FromResult(selected));
        }
Exemplo n.º 26
0
 public TestComposition AddParts(IEnumerable <Type>?types)
 => WithParts(Parts.Union(types ?? Array.Empty <Type>()));
Exemplo n.º 27
0
 public override ImmutableHashSet <ValueTag> Merge(ImmutableHashSet <ValueTag> first, ImmutableHashSet <ValueTag> second)
 {
     return(first.Union(second));
 }
Exemplo n.º 28
0
		public ImmutableHashSet<Point> PlacePiece(Piece piece, ImmutableHashSet<Point> gameField)
		{
			return
				gameField.Union(piece.Coordinates);
		}
Exemplo n.º 29
0
        private bool TryCreateImportDefinition(Type importingType, ICustomAttributeProvider member, ImmutableHashSet <IImportSatisfiabilityConstraint> importConstraints, [NotNullWhen(true)] out ImportDefinition?importDefinition)
        {
            Requires.NotNull(importingType, nameof(importingType));
            Requires.NotNull(member, nameof(member));

            var importAttribute     = member.GetFirstAttribute <ImportAttribute>();
            var importManyAttribute = member.GetFirstAttribute <ImportManyAttribute>();

            // Importing constructors get implied attributes on their parameters.
            if (importAttribute == null && importManyAttribute == null && member is ParameterInfo)
            {
                importAttribute = new ImportAttribute();
            }

            var sharingBoundaries        = ImmutableHashSet.Create <string>();
            var sharingBoundaryAttribute = member.GetFirstAttribute <SharingBoundaryAttribute>();

            if (sharingBoundaryAttribute != null)
            {
                Verify.Operation(importingType.IsExportFactoryTypeV2(), Strings.IsExpectedOnlyOnImportsOfExportFactoryOfT, typeof(SharingBoundaryAttribute).Name);
                sharingBoundaries = sharingBoundaries.Union(sharingBoundaryAttribute.SharingBoundaryNames);
            }

            if (member is PropertyInfo importingMember && importingMember.SetMethod == null)
            {
                // MEFv2 quietly ignores such importing members.
                importDefinition = null;
                return(false);
            }

            if (importAttribute != null)
            {
                this.ThrowOnInvalidImportingMemberOrParameter(member, isImportMany: false);

                Type contractType = GetTypeIdentityFromImportingType(importingType, importMany: false);
                if (contractType.IsAnyLazyType() || contractType.IsExportFactoryTypeV2())
                {
                    contractType = contractType.GetTypeInfo().GetGenericArguments()[0];
                }

                importConstraints = importConstraints
                                    .Union(this.GetMetadataViewConstraints(importingType, importMany: false))
                                    .Union(GetExportTypeIdentityConstraints(contractType));
                importDefinition = new ImportDefinition(
                    string.IsNullOrEmpty(importAttribute.ContractName) ? GetContractName(contractType) : importAttribute.ContractName,
                    importAttribute.AllowDefault ? ImportCardinality.OneOrZero : ImportCardinality.ExactlyOne,
                    GetImportMetadataForGenericTypeImport(contractType),
                    importConstraints,
                    sharingBoundaries);
                return(true);
            }
            else if (importManyAttribute != null)
            {
                this.ThrowOnInvalidImportingMemberOrParameter(member, isImportMany: true);

                Type contractType = GetTypeIdentityFromImportingType(importingType, importMany: true);
                importConstraints = importConstraints
                                    .Union(this.GetMetadataViewConstraints(importingType, importMany: true))
                                    .Union(GetExportTypeIdentityConstraints(contractType));
                importDefinition = new ImportDefinition(
                    string.IsNullOrEmpty(importManyAttribute.ContractName) ? GetContractName(contractType) : importManyAttribute.ContractName,
                    ImportCardinality.ZeroOrMore,
                    GetImportMetadataForGenericTypeImport(contractType),
                    importConstraints,
                    sharingBoundaries);
                return(true);
            }
            else
            {
                importDefinition = null;
                return(false);
            }
        }
Exemplo n.º 30
0
 public TestComposition AddExcludedPartTypes(IEnumerable <Type>?types)
 => WithExcludedPartTypes(ExcludedPartTypes.Union(types ?? Array.Empty <Type>()));
Exemplo n.º 31
0
 /// <inheritdoc />
 public IImmutableSet <T> Union(IEnumerable <T> other)
 {
     return(new SetEqualedReadOnlySet <T>(_set.Union(other)));
 }
 public static ImmutableHashSet <T> AddRange <T>(this ImmutableHashSet <T> set, IEnumerable <T> values)
 {
     return(set.Union(values));
 }
Exemplo n.º 33
0
        /// <summary>
        /// Invoked by <see cref="InteractiveHost"/> when a new process is being started.
        /// </summary>
        private void ProcessStarting(bool initialize)
        {
            if (!Dispatcher.CheckAccess())
            {
                Dispatcher.BeginInvoke(new Action(() => ProcessStarting(initialize)));
                return;
            }

            // Freeze all existing classifications and then clear the list of
            // submission buffers we have.
            FreezeClassifications();
            _submissionBuffers.Clear();

            // We always start out empty
            _workspace.ClearSolution();
            _currentSubmissionProjectId = null;
            _previousSubmissionProjectId = null;

            var metadataService = _workspace.CurrentSolution.Services.MetadataService;
            var mscorlibRef = metadataService.GetReference(typeof(object).Assembly.Location, MetadataReferenceProperties.Assembly);
            var interactiveHostObjectRef = metadataService.GetReference(typeof(InteractiveScriptGlobals).Assembly.Location, MetadataReferenceProperties.Assembly);

            _references = ImmutableHashSet.Create<MetadataReference>(mscorlibRef, interactiveHostObjectRef);
            _rspImports = ImmutableArray<string>.Empty;
            _initialScriptFileOpt = null;
            ReferenceSearchPaths = ImmutableArray<string>.Empty;
            SourceSearchPaths = ImmutableArray<string>.Empty;

            if (initialize && File.Exists(_responseFilePath))
            {
                // The base directory for relative paths is the directory that contains the .rsp file.
                // Note that .rsp files included by this .rsp file will share the base directory (Dev10 behavior of csc/vbc).
                var rspDirectory = Path.GetDirectoryName(_responseFilePath);
                var args = this.CommandLineParser.Parse(new[] { "@" + _responseFilePath }, rspDirectory, RuntimeEnvironment.GetRuntimeDirectory(), null);

                if (args.Errors.Length == 0)
                {
                    var metadataResolver = CreateMetadataReferenceResolver(metadataService, args.ReferencePaths, rspDirectory);
                    var sourceResolver = CreateSourceReferenceResolver(args.SourcePaths, rspDirectory);

                    // ignore unresolved references, they will be reported in the interactive window:
                    var rspReferences = args.ResolveMetadataReferences(metadataResolver).Where(r => !(r is UnresolvedMetadataReference));

                    _initialScriptFileOpt = args.SourceFiles.IsEmpty ? null : args.SourceFiles[0].Path;

                    ReferenceSearchPaths = args.ReferencePaths;
                    SourceSearchPaths = args.SourcePaths;

                    _references = _references.Union(rspReferences);
                    _rspImports = CommandLineHelpers.GetImports(args);
                }
            }

            _metadataReferenceResolver = CreateMetadataReferenceResolver(metadataService, ReferenceSearchPaths, _initialWorkingDirectory);
            _sourceReferenceResolver = CreateSourceReferenceResolver(SourceSearchPaths, _initialWorkingDirectory);

            // create the first submission project in the workspace after reset:
            if (_currentSubmissionBuffer != null)
            {
                AddSubmission(_currentTextView, _currentSubmissionBuffer, this.LanguageName);
            }
        }