private static decimal CalculateDictionary(ImmutableDictionary <string, int> dictionary, decimal totalSoFar)
        {
            if (dictionary.Count == 0)
            {
                return(totalSoFar);
            }
            if (dictionary.Count == 1)
            {
                return(totalSoFar + UndiscountedPriceOfBooks(dictionary.First()));
            }

            var differentBooks = dictionary.Keys;

            Func <KeyValuePair <string, int>, KeyValuePair <string, int> > decrementBookCount = kvp => new KeyValuePair <string, int>(kvp.Key, kvp.Value - 1);
            Func <KeyValuePair <string, int>, bool> bookCountIsPositive = kvp => kvp.Value > 0;

            var reducedDictionary = dictionary
                                    .Select(decrementBookCount)
                                    .Where(bookCountIsPositive)
                                    .ToImmutableDictionary();

            var subTotal = totalSoFar + DiscountedPriceOfBooks(differentBooks);

            return(CalculateDictionary(reducedDictionary, subTotal));
        }
示例#2
0
 public Settings Merge(Settings userSettings)
 {
     return(new(ImmutableDictionary.CreateRange(userSettings._settings.Select(settingNamePair => {
         (SettingNames name, SettingBase setting) = settingNamePair;
         KeyValuePair <SettingNames, SettingBase> serverSetting = _settings.First(serverSettingItem => name == serverSettingItem.Key);
         return new KeyValuePair <SettingNames, SettingBase>(name, setting.Merge(serverSetting.Value));
     }))));
 }
示例#3
0
        /// <summary>
        /// <see cref="IActiveDebugFrameworkServices.GetConfiguredProjectForActiveFrameworkAsync"/>
        /// </summary>
        public async Task <ConfiguredProject?> GetConfiguredProjectForActiveFrameworkAsync()
        {
#pragma warning disable CS0618 // Type or member is obsolete
            ImmutableDictionary <string, ConfiguredProject>?configProjects = await _activeConfiguredProjectsProvider.GetActiveConfiguredProjectsMapAsync();

#pragma warning restore CS0618 // Type or member is obsolete

            if (configProjects == null)
            {
                return(null);
            }

            // If there is only one we are done
            if (configProjects.Count == 1)
            {
                return(configProjects.First().Value);
            }

            string?activeFramework = await GetActiveDebuggingFrameworkPropertyAsync();

            if (!Strings.IsNullOrWhiteSpace(activeFramework))
            {
                if (configProjects.TryGetValue(activeFramework, out ConfiguredProject? configuredProject))
                {
                    return(configuredProject);
                }
            }

            // We can't just select the first one. If activeFramework is not set we must pick the first one as defined by the
            // targetFrameworks property. So we need the order as returned by GetProjectFrameworks()
            List <string>?frameworks = await GetProjectFrameworksAsync();

            if (frameworks?.Count > 0)
            {
                if (configProjects.TryGetValue(frameworks[0], out ConfiguredProject? configuredProject))
                {
                    return(configuredProject);
                }
            }

            // All that is left is to return the first one.
            return(configProjects.First().Value);
        }
示例#4
0
 /// <summary>
 /// Creates a new <see cref="FixMultipleContext"/>.
 /// Use this overload when applying fix multiple diagnostics with a source location.
 /// </summary>
 /// <param name="diagnosticsToFix">Specific set of diagnostics to fix. Must be a non-empty set.</param>
 /// <param name="codeFixProvider">Underlying <see cref="CodeFixes.CodeFixProvider"/> which triggered this fix all.</param>
 /// <param name="codeActionEquivalenceKey">The <see cref="CodeAction.EquivalenceKey"/> value expected of a <see cref="CodeAction"/> participating in this fix all.</param>
 /// <param name="cancellationToken">Cancellation token for fix all computation.</param>
 public static FixMultipleContext Create(
     ImmutableDictionary<Project, ImmutableArray<Diagnostic>> diagnosticsToFix,
     CodeFixProvider codeFixProvider,
     string codeActionEquivalenceKey,
     CancellationToken cancellationToken)
 {
     var triggerProject = diagnosticsToFix.First().Key;
     var diagnosticIds = GetDiagnosticsIds(diagnosticsToFix.Values);
     var diagnosticProvider = new FixMultipleDiagnosticProvider(diagnosticsToFix);
     return new FixMultipleContext(triggerProject, codeFixProvider, codeActionEquivalenceKey, diagnosticIds, diagnosticProvider, cancellationToken);
 }
示例#5
0
        private static ImmutableArray <string> BuildPath(ImmutableDictionary <Point, char> map)
        {
            var output = ImmutableArray.CreateBuilder <string>();
            var robot  = map.First(k => k.Value == '^').Key;

            var pos       = robot;
            var direction = Direction.North;
            var count     = 1;

            while (true)
            {
                var adjacent = GetAdjacentScaffold(pos, map);

                if (adjacent[direction] is Point nextAdjacent)
                {
                    count++;
                    pos = nextAdjacent;
                }
                else if (adjacent[direction.Left()] is Point nextLeft)
                {
                    if (count > 1)
                    {
                        output.AddRange(count.ToString());
                    }

                    output.Add("L");
                    direction = direction.Left();
                    count     = 1;
                    pos       = nextLeft;
                }
                else if (adjacent[direction.Right()] is Point nextRight)
                {
                    if (count > 1)
                    {
                        output.AddRange(count.ToString());
                    }
                    output.Add("R");
                    direction = direction.Right();
                    count     = 1;
                    pos       = nextRight;
                }
                else
                {
                    if (count > 1)
                    {
                        output.AddRange(count.ToString());
                    }
                    break;
                }
            }

            return(output.ToImmutable());
        }
示例#6
0
        /// <summary>
        /// Creates a new <see cref="FixMultipleContext"/>.
        /// Use this overload when applying fix multiple diagnostics with a source location.
        /// </summary>
        /// <param name="diagnosticsToFix">Specific set of diagnostics to fix. Must be a non-empty set.</param>
        /// <param name="codeFixProvider">Underlying <see cref="CodeFixes.CodeFixProvider"/> which triggered this fix all.</param>
        /// <param name="codeActionEquivalenceKey">The <see cref="CodeAction.EquivalenceKey"/> value expected of a <see cref="CodeAction"/> participating in this fix all.</param>
        /// <param name="cancellationToken">Cancellation token for fix all computation.</param>
        public static FixMultipleContext Create(
            ImmutableDictionary <Document, ImmutableArray <Diagnostic> > diagnosticsToFix,
            CodeFixProvider codeFixProvider,
            string codeActionEquivalenceKey,
            CancellationToken cancellationToken)
        {
            var triggerDocument    = diagnosticsToFix.First().Key;
            var diagnosticIds      = GetDiagnosticsIds(diagnosticsToFix.Values);
            var diagnosticProvider = new FixMultipleDiagnosticProvider(diagnosticsToFix);

            return(new FixMultipleContext(triggerDocument, codeFixProvider, codeActionEquivalenceKey, diagnosticIds, diagnosticProvider, cancellationToken));
        }
示例#7
0
        /// <summary>
        /// Creates a new <see cref="FixAllContext"/>.
        /// Use this overload when applying fix multiple diagnostics with no source location.
        /// </summary>
        /// <param name="diagnosticsToFix">Specific set of diagnostics to fix. Must be a non-empty set.</param>
        /// <param name="codeFixProvider">Underlying <see cref="CodeFixes.CodeFixProvider"/> which triggered this fix all.</param>
        /// <param name="codeActionEquivalenceKey">The <see cref="CodeAction.EquivalenceKey"/> value expected of a <see cref="CodeAction"/> participating in this fix all.</param>
        /// <param name="cancellationToken">Cancellation token for fix all computation.</param>
        internal static FixAllContext Create(
            ImmutableDictionary <Project, ImmutableArray <Diagnostic> > diagnosticsToFix,
            CodeFixProvider codeFixProvider,
            string codeActionEquivalenceKey,
            CancellationToken cancellationToken)
        {
            var triggerProject     = diagnosticsToFix.First().Key;
            var diagnosticIds      = GetDiagnosticsIds(diagnosticsToFix.Values);
            var diagnosticProvider = new FixMultipleDiagnosticProvider(diagnosticsToFix);

            return(new FixAllContext(triggerProject, codeFixProvider, FixAllScope.Custom, codeActionEquivalenceKey, diagnosticIds, diagnosticProvider, cancellationToken));
        }
示例#8
0
 public static VersionVector Create(ImmutableDictionary <UniqueAddress, long> versions)
 {
     if (versions.IsEmpty)
     {
         return(VersionVector.Empty);
     }
     if (versions.Count == 1)
     {
         var v = versions.First();
         return(new SingleVersionVector(v.Key, v.Value));
     }
     return(new MultiVersionVector(versions));
 }
示例#9
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ExceptionlessSplatLogger"/> class.
        /// </summary>
        /// <param name="sourceType">The type being tracked.</param>
        /// <param name="exceptionlessClient">The exceptionless client instance to use.</param>
        public ExceptionlessSplatLogger(
            Type sourceType,
            ExceptionlessClient exceptionlessClient)
        {
            _sourceType          = sourceType.FullName;
            _exceptionlessClient = exceptionlessClient ?? throw new ArgumentNullException(nameof(exceptionlessClient));
            _exceptionlessClient.Configuration.Changed += OnInnerLoggerReconfigured;

            if (_exceptionlessClient.Configuration.Settings.TryGetValue("@@log:*", out var logLevel))
            {
                var l = global::Exceptionless.Logging.LogLevel.FromString(logLevel);
                Level = _mappingsDictionary.First(x => x.Value == l).Key;
            }
        }
 internal static FixAllState Create(
     FixAllProvider fixAllProvider,
     ImmutableDictionary<Project, ImmutableArray<Diagnostic>> diagnosticsToFix,
     CodeFixProvider codeFixProvider,
     string codeActionEquivalenceKey)
 {
     var triggerProject = diagnosticsToFix.First().Key;
     var diagnosticIds = GetDiagnosticsIds(diagnosticsToFix.Values);
     var diagnosticProvider = new FixMultipleDiagnosticProvider(diagnosticsToFix);
     return new FixAllState(
         fixAllProvider,
         triggerProject, codeFixProvider,
         FixAllScope.Custom, codeActionEquivalenceKey,
         diagnosticIds, diagnosticProvider);
 }
        public Solution GetFix(
            ImmutableDictionary<Project, ImmutableArray<Diagnostic>> diagnosticsToFix,
            Workspace workspace,
            CodeFixProvider fixProvider,
            FixAllProvider fixAllProvider,
            string equivalenceKey,
            string waitDialogTitle,
            string waitDialogMessage,
            CancellationToken cancellationToken)
        {
            var fixMultipleState = FixAllState.Create(fixAllProvider, diagnosticsToFix, fixProvider, equivalenceKey);
            var triggerDiagnostic = diagnosticsToFix.First().Value.First();

            var suggestedAction = GetSuggestedAction(fixMultipleState, triggerDiagnostic, workspace, waitDialogTitle, waitDialogMessage, showPreviewChangesDialog: false, cancellationToken: cancellationToken);
            return suggestedAction.GetChangedSolution(cancellationToken);
        }
        public Solution GetFix(
            ImmutableDictionary <Project, ImmutableArray <Diagnostic> > diagnosticsToFix,
            Workspace workspace,
            CodeFixProvider fixProvider,
            FixAllProvider fixAllProvider,
            string equivalenceKey,
            string waitDialogTitle,
            string waitDialogMessage,
            CancellationToken cancellationToken)
        {
            var fixMultipleContext = FixAllContext.Create(diagnosticsToFix, fixProvider, equivalenceKey, cancellationToken);
            var triggerDiagnostic  = diagnosticsToFix.First().Value.First();

            var suggestedAction = GetSuggestedAction(fixMultipleContext, triggerDiagnostic, workspace, fixAllProvider, waitDialogTitle, waitDialogMessage, showPreviewChangesDialog: false, cancellationToken: cancellationToken);

            return(suggestedAction.GetChangedSolution(cancellationToken));
        }
        public Solution GetFix(
            ImmutableDictionary<Document, ImmutableArray<Diagnostic>> diagnosticsToFix,
            Workspace workspace,
            CodeFixProvider fixProvider,
            FixAllProvider fixAllProvider,
            string equivalenceKey,
            string waitDialogTitle,
            string waitDialogMessage,
            CancellationToken cancellationToken)
        {
            var fixMultipleState = FixAllState.Create(fixAllProvider, diagnosticsToFix, fixProvider, equivalenceKey);
            var triggerDiagnostic = diagnosticsToFix.First().Value.First();

            var result = GetFixedSolution(
                fixMultipleState, triggerDiagnostic, workspace,
                waitDialogTitle, waitDialogMessage, cancellationToken);
            return result;
        }
示例#14
0
        public Solution GetFix(
            ImmutableDictionary <Project, ImmutableArray <Diagnostic> > diagnosticsToFix,
            Workspace workspace,
            CodeFixProvider fixProvider,
            FixAllProvider fixAllProvider,
            string equivalenceKey,
            string waitDialogTitle,
            string waitDialogMessage,
            CancellationToken cancellationToken)
        {
            var fixMultipleState  = FixAllState.Create(fixAllProvider, diagnosticsToFix, fixProvider, equivalenceKey);
            var triggerDiagnostic = diagnosticsToFix.First().Value.First();

            var result = GetFixedSolution(
                fixMultipleState, triggerDiagnostic, workspace,
                waitDialogTitle, waitDialogMessage, cancellationToken);

            return(result);
        }
示例#15
0
        private static BoundLambda GuessBestBoundLambda <T>(ImmutableDictionary <T, BoundLambda> candidates)
        {
            switch (candidates.Count)
            {
            case 0:
                return(null);

            case 1:
                return(candidates.First().Value);

            default:
                // Prefer candidates with fewer diagnostics.
                IEnumerable <KeyValuePair <T, BoundLambda> > minDiagnosticsGroup = candidates.GroupBy(lambda => lambda.Value.Diagnostics.Length).OrderBy(group => group.Key).First();

                // If multiple candidates have the same number of diagnostics, order them by delegate type name.
                // It's not great, but it should be stable.
                return(minDiagnosticsGroup
                       .OrderBy(lambda => GetLambdaSortString(lambda.Value.Symbol))
                       .FirstOrDefault()
                       .Value);
            }
        }
示例#16
0
        /// <summary>
        ///     Creates a <see cref="AggregateCrossTargetProjectContext"/>.
        /// </summary>
        /// <returns>
        ///     The created <see cref="AggregateCrossTargetProjectContext"/>.
        /// </returns>
        public async Task <AggregateCrossTargetProjectContext> CreateProjectContextAsync()
        {
            // Get the set of active configured projects ignoring target framework.
#pragma warning disable CS0618 // Type or member is obsolete
            ImmutableDictionary <string, ConfiguredProject>?configuredProjectsMap = await _activeConfiguredProjectsProvider.GetActiveConfiguredProjectsMapAsync();

#pragma warning restore CS0618 // Type or member is obsolete

            if (configuredProjectsMap == null)
            {
                throw new InvalidOperationException("There are no active configured projects.");
            }

            ProjectConfiguration activeProjectConfiguration            = _commonServices.ActiveConfiguredProject.ProjectConfiguration;
            ImmutableArray <TargetFramework> .Builder targetFrameworks = ImmutableArray.CreateBuilder <TargetFramework>(initialCapacity: configuredProjectsMap.Count);
            TargetFramework activeTargetFramework = TargetFramework.Empty;

            foreach ((string tfm, ConfiguredProject configuredProject) in configuredProjectsMap)
            {
                TargetFramework targetFramework = await GetTargetFrameworkAsync(tfm, configuredProject);

                targetFrameworks.Add(targetFramework);

                if (activeTargetFramework.Equals(TargetFramework.Empty) &&
                    configuredProject.ProjectConfiguration.Equals(activeProjectConfiguration))
                {
                    activeTargetFramework = targetFramework;
                }
            }

            bool isCrossTargeting = !(configuredProjectsMap.Count == 1 && string.IsNullOrEmpty(configuredProjectsMap.First().Key));

            return(new AggregateCrossTargetProjectContext(
                       isCrossTargeting,
                       targetFrameworks.MoveToImmutable(),
                       configuredProjectsMap,
                       activeTargetFramework,
                       _targetFrameworkProvider));
        }
示例#17
0
        public async Task <AggregateCrossTargetProjectContext> CreateProjectContextAsync()
        {
            // Get the set of active configured projects ignoring target framework.
#pragma warning disable CS0618 // Type or member is obsolete
            ImmutableDictionary <string, ConfiguredProject> configuredProjectsMap = await _activeConfiguredProjectsProvider.GetActiveConfiguredProjectsMapAsync();

#pragma warning restore CS0618 // Type or member is obsolete
            ProjectConfiguration activeProjectConfiguration             = _commonServices.ActiveConfiguredProject.ProjectConfiguration;
            ImmutableArray <ITargetFramework> .Builder targetFrameworks = ImmutableArray.CreateBuilder <ITargetFramework>(initialCapacity: configuredProjectsMap.Count);
            ITargetFramework activeTargetFramework = TargetFramework.Empty;

            foreach ((string tfm, ConfiguredProject configuredProject) in configuredProjectsMap)
            {
                ProjectProperties    projectProperties = configuredProject.Services.ExportProvider.GetExportedValue <ProjectProperties>();
                ConfigurationGeneral configurationGeneralProperties = await projectProperties.GetConfigurationGeneralPropertiesAsync();

                ITargetFramework targetFramework = await GetTargetFrameworkAsync(tfm, configurationGeneralProperties);

                targetFrameworks.Add(targetFramework);

                if (activeTargetFramework.Equals(TargetFramework.Empty) &&
                    configuredProject.ProjectConfiguration.Equals(activeProjectConfiguration))
                {
                    activeTargetFramework = targetFramework;
                }
            }

            bool isCrossTargeting = !(configuredProjectsMap.Count == 1 && string.IsNullOrEmpty(configuredProjectsMap.First().Key));

            return(new AggregateCrossTargetProjectContext(
                       isCrossTargeting,
                       targetFrameworks.MoveToImmutable(),
                       configuredProjectsMap,
                       activeTargetFramework,
                       _targetFrameworkProvider));
        }
        private async Task <AggregateCrossTargetProjectContext> CreateProjectContextAsyncCore()
        {
            ProjectData projectData = GetProjectData();

            // Get the set of active configured projects ignoring target framework.
#pragma warning disable CS0618 // Type or member is obsolete
            ImmutableDictionary <string, ConfiguredProject> configuredProjectsMap = await _activeConfiguredProjectsProvider.GetActiveConfiguredProjectsMapAsync().ConfigureAwait(true);

#pragma warning restore CS0618 // Type or member is obsolete
            ProjectConfiguration activeProjectConfiguration = _commonServices.ActiveConfiguredProject.ProjectConfiguration;
            ImmutableDictionary <ITargetFramework, ITargetedProjectContext> .Builder innerProjectContextsBuilder = ImmutableDictionary.CreateBuilder <ITargetFramework, ITargetedProjectContext>();
            ITargetFramework activeTargetFramework = TargetFramework.Empty;

            foreach (KeyValuePair <string, ConfiguredProject> kvp in configuredProjectsMap)
            {
                ConfiguredProject    configuredProject = kvp.Value;
                ProjectProperties    projectProperties = configuredProject.Services.ExportProvider.GetExportedValue <ProjectProperties>();
                ConfigurationGeneral configurationGeneralProperties = await projectProperties.GetConfigurationGeneralPropertiesAsync().ConfigureAwait(true);

                ITargetFramework targetFramework = await GetTargetFrameworkAsync(kvp.Key, configurationGeneralProperties).ConfigureAwait(false);

                if (!TryGetConfiguredProjectState(configuredProject, out ITargetedProjectContext targetedProjectContext))
                {
                    // Get the target path for the configured project.
                    string targetPath = (string)await configurationGeneralProperties.TargetPath.GetValueAsync().ConfigureAwait(true);

                    string displayName = GetDisplayName(configuredProject, projectData, targetFramework.FullName);

                    targetedProjectContext = new TargetedProjectContext(targetFramework, projectData.FullPath, displayName, targetPath)
                    {
                        // By default, set "LastDesignTimeBuildSucceeded = false" until first design time
                        // build succeeds for this project.
                        LastDesignTimeBuildSucceeded = false
                    };
                    AddConfiguredProjectState(configuredProject, targetedProjectContext);
                }

                innerProjectContextsBuilder.Add(targetFramework, targetedProjectContext);

                if (activeTargetFramework.Equals(TargetFramework.Empty) &&
                    configuredProject.ProjectConfiguration.Equals(activeProjectConfiguration))
                {
                    activeTargetFramework = targetFramework;
                }
            }

            bool isCrossTargeting = !(configuredProjectsMap.Count == 1 && string.IsNullOrEmpty(configuredProjectsMap.First().Key));
            return(new AggregateCrossTargetProjectContext(isCrossTargeting,
                                                          innerProjectContextsBuilder.ToImmutable(),
                                                          configuredProjectsMap,
                                                          activeTargetFramework,
                                                          _targetFrameworkProvider));
        }
示例#19
0
        /// <summary>
        /// Returns latests stable version which is an aggregate of the least values of all known remote versions times for individual replica id.
        /// </summary>
        private static VClock UpdateStableVersion(ImmutableDictionary <ReplicaId, VClock> versions)
        {
            var first = versions.First().Value;

            return(versions.Values.Aggregate(first, (c1, c2) => c1.MergeMin(c2)));
        }
示例#20
0
 public static eHero ToHero(this string source) => tokens.First(x => x.Value.ToUpper() == source.ToUpper()).Key;
示例#21
0
 internal static FixAllState Create(
     FixAllProvider fixAllProvider,
     ImmutableDictionary<Project, ImmutableArray<Diagnostic>> diagnosticsToFix,
     CodeFixProvider codeFixProvider,
     string codeActionEquivalenceKey)
 {
     var triggerProject = diagnosticsToFix.First().Key;
     var diagnosticIds = GetDiagnosticsIds(diagnosticsToFix.Values);
     var diagnosticProvider = new FixMultipleDiagnosticProvider(diagnosticsToFix);
     return new FixAllState(
         fixAllProvider,
         triggerProject, codeFixProvider, 
         FixAllScope.Custom, codeActionEquivalenceKey, 
         diagnosticIds, diagnosticProvider);
 }
示例#22
0
 public static eArmorType ToArmorType(this string source) => tokens.First(x => x.Value.ToUpper() == source.ToUpper()).Key;
示例#23
0
 /// <summary>
 /// Get AssignmentObjectTypeId by Name
 /// </summary>
 public int GetMetadataType(string typeName) => MetadataTypes.First(mt => mt.Value == typeName).Key;
示例#24
0
 public (Point Position, Entity Entity) FindPortal(string identifier)
 {
     var(pos, entity) = _mapArr.First(x => x.Value.Identifier.Equals(identifier, StringComparison.OrdinalIgnoreCase));
     return(pos, entity);
 }
示例#25
0
        public static CH_Polyhedron Make(ImmutableList <CH_Polygon> facesAway, Vertex3 v)
        {
            ImmutableList <CH_Polygon> facesAway1 = facesAway;

            foreach (CH_Polygon face in facesAway1)
            {
                if (!(face.Plane.Includes(v)))
                {
                    throw new ArgumentException("Polygons must face away from new point");
                }
            }

            DualIndexedSet <Tuple <Vertex3, Vertex3> > edgeMap    = new DualIndexedSet <Tuple <Vertex3, Vertex3> >(x => new Tuple <Vertex3, Vertex3>(x.Item2, x.Item1));
            ImmutableDictionary <int, int>             edgeToFace = ImmutableDictionary <int, int> .Empty;
            int iEnd = facesAway1.Count;

            for (int i = 0; i < iEnd; ++i)
            {
                foreach (CH_Polygon.Edge edge in facesAway1[i].Edges)
                {
                    var(edgeMap2, eIndex, isNew) = edgeMap.EnsureAdded(new Tuple <Vertex3, Vertex3>(edge.Start, edge.End));
                    edgeMap = edgeMap2;
                    if (edgeToFace.ContainsKey(eIndex))
                    {
                        throw new ArgumentException("Invalid polyhedron (edge traversed in same direction by more than one face)");
                    }
                    edgeToFace = edgeToFace.Add(eIndex, i);
                }
            }
            ImmutableDictionary <Vertex3, int> startToEdge = ImmutableDictionary <Vertex3, int> .Empty;
            int iEnd2 = edgeMap.Count;

            for (int i = 0; i < iEnd2; ++i)
            {
                if (!(edgeToFace.ContainsKey(i)))
                {
                    startToEdge = startToEdge.Add(edgeMap[i].Item1, i);
                }
                if (!(edgeToFace.ContainsKey(~i)))
                {
                    startToEdge = startToEdge.Add(edgeMap[~i].Item1, ~i);
                }
            }

            ImmutableList <int> edges = ImmutableList <int> .Empty;

            edges = edges.Add(startToEdge.First().Value);
            int sentinel = startToEdge.Count;

            while (true)
            {
                Vertex3 end = edgeMap[edges[edges.Count - 1]].Item2;
                if (!(startToEdge.ContainsKey(end)))
                {
                    throw new ArgumentException("Unable to walk loose edges");
                }
                int nextEdge = startToEdge[end];
                if (nextEdge == edges[0])
                {
                    break;
                }
                edges = edges.Add(nextEdge);
                --sentinel;
                if (sentinel < 0)
                {
                    throw new InvalidOperationException("Loose edges don't loop properly");
                }
            }
            if (edges.Count != startToEdge.Count)
            {
                throw new InvalidOperationException("Not all loose edges were used");
            }

            sentinel = edges.Count;
            Func <int, int, bool> inSamePlane = delegate(int edge1, int edge2)
            {
                Tuple <Vertex3, Vertex3> e1 = edgeMap[edge1];
                Tuple <Vertex3, Vertex3> e2 = edgeMap[edge2];
                Plane3 p = Plane3.FromThreePoints(e1.Item1, e1.Item2, v);
                return(p.Contains(e2.Item1) && p.Contains(e2.Item2));
            };

            while (true)
            {
                if (!inSamePlane(edges[0], edges[edges.Count - 1]))
                {
                    break;
                }
                int x = edges[0];
                edges = edges.RemoveAt(0).Add(x);
                --sentinel;
                if (sentinel < 0)
                {
                    throw new InvalidOperationException("Loose edges all lie in the same plane as the vertex (?!)");
                }
            }

            ImmutableList <CH_Polygon> newPolys = ImmutableList <CH_Polygon> .Empty;
            ImmutableList <Vertex3>    corners  = ImmutableList <Vertex3> .Empty;
            int?lastEdge = null;

            Action flush = delegate()
            {
                corners  = corners.Add(edgeMap[lastEdge.Value].Item2).Add(v);
                newPolys = newPolys.Add(new CH_Polygon(corners));
            };

            Action <int> addEdge = delegate(int edge)
            {
                if (lastEdge == null || inSamePlane(edge, lastEdge.Value))
                {
                    corners  = corners.Add(edgeMap[edge].Item1);
                    lastEdge = edge;
                }
                else
                {
                    flush();
                    corners = ImmutableList <Vertex3> .Empty
                              .Add(edgeMap[edge].Item1);

                    lastEdge = edge;
                }
            };

            foreach (int edge in edges)
            {
                addEdge(edge);
            }
            flush();

            return(new CH_Polyhedron(newPolys.AddRange(facesAway1)));
        }
示例#26
0
        /// <summary>
        /// Initializes a new instance of the <see cref="OptionPositionCollection"/> class
        /// </summary>
        /// <param name="positions">All positions</param>
        /// <param name="rights">Index of position symbols by option right</param>
        /// <param name="sides">Index of position symbols by position side (short/long/none)</param>
        /// <param name="strikes">Index of position symbols by strike price</param>
        /// <param name="expirations">Index of position symbols by expiration</param>
        public OptionPositionCollection(
            ImmutableDictionary <Symbol, OptionPosition> positions,
            ImmutableDictionary <OptionRight, ImmutableHashSet <Symbol> > rights,
            ImmutableDictionary <PositionSide, ImmutableHashSet <Symbol> > sides,
            ImmutableSortedDictionary <decimal, ImmutableHashSet <Symbol> > strikes,
            ImmutableSortedDictionary <DateTime, ImmutableHashSet <Symbol> > expirations
            )
        {
            _sides       = sides;
            _rights      = rights;
            _strikes     = strikes;
            _positions   = positions;
            _expirations = expirations;

            if (_rights.Count != 2)
            {
                // ensure we always have both rights indexed, even if empty
                ImmutableHashSet <Symbol> value;
                if (!_rights.TryGetValue(OptionRight.Call, out value))
                {
                    _rights = _rights.SetItem(OptionRight.Call, ImmutableHashSet <Symbol> .Empty);
                }
                if (!_rights.TryGetValue(OptionRight.Put, out value))
                {
                    _rights = _rights.SetItem(OptionRight.Put, ImmutableHashSet <Symbol> .Empty);
                }
            }

            if (_sides.Count != 3)
            {
                // ensure we always have all three sides indexed, even if empty
                ImmutableHashSet <Symbol> value;
                if (!_sides.TryGetValue(PositionSide.None, out value))
                {
                    _sides = _sides.SetItem(PositionSide.None, ImmutableHashSet <Symbol> .Empty);
                }
                if (!_sides.TryGetValue(PositionSide.Short, out value))
                {
                    _sides = _sides.SetItem(PositionSide.Short, ImmutableHashSet <Symbol> .Empty);
                }
                if (!_sides.TryGetValue(PositionSide.Long, out value))
                {
                    _sides = _sides.SetItem(PositionSide.Long, ImmutableHashSet <Symbol> .Empty);
                }
            }

            if (!positions.IsEmpty)
            {
                // assumption here is that 'positions' includes the underlying equity position and
                // ONLY option contracts, so all symbols have the underlying equity symbol embedded
                // via the Underlying property, except of course, for the underlying itself.
                var underlying = positions.First().Key;
                if (underlying.HasUnderlying)
                {
                    underlying = underlying.Underlying;
                }

                // OptionPosition is struct, so no worry about null ref via .Quantity
                var underlyingQuantity = positions.GetValueOrDefault(underlying).Quantity;
                UnderlyingPosition = new OptionPosition(underlying, underlyingQuantity);
            }
#if DEBUG
            var errors = Validate().ToList();
            if (errors.Count > 0)
            {
                throw new ArgumentException("OptionPositionCollection validation failed: "
                                            + Environment.NewLine + string.Join(Environment.NewLine, errors)
                                            );
            }
#endif
        }