コード例 #1
0
ファイル: Promise`1.cs プロジェクト: smdx24/CPI-Source-Code
        public static IPromise <IEnumerable <PromisedT> > All(IEnumerable <IPromise <PromisedT> > promises)
        {
            IPromise <PromisedT>[] array = promises.ToArray();
            if (array.Length == 0)
            {
                return(Promise <IEnumerable <PromisedT> > .Resolved(EnumerableExt.Empty <PromisedT>()));
            }
            int remainingCount = array.Length;

            PromisedT[] results = new PromisedT[remainingCount];
            Promise <IEnumerable <PromisedT> > resultPromise = new Promise <IEnumerable <PromisedT> >();

            resultPromise.WithName("All");
            array.Each(delegate(IPromise <PromisedT> promise, int index)
            {
                promise.Catch(delegate(Exception ex)
                {
                    if (resultPromise.CurState == PromiseState.Pending)
                    {
                        resultPromise.Reject(ex);
                    }
                }).Then(delegate(PromisedT result)
                {
                    results[index] = result;
                    remainingCount--;
                    if (remainingCount <= 0)
                    {
                        resultPromise.Resolve(results);
                    }
                }).Done();
            });
            return(resultPromise);
        }
コード例 #2
0
        public static Geometry <V> ExtrudeToScale <V> (this Geometry <V> plane, float depth, float targetScale,
                                                       float steepness, int numSteps, bool includeFrontFace = true, bool includeBackFace = true,
                                                       Vec3 scaleAround = new Vec3())
            where V : struct, IVertex3D
        {
            if (depth <= 0f)
            {
                throw new ArgumentException(
                          "Depth needs to be greater than zero.", "depth");
            }
            if (steepness <= 0)
            {
                throw new ArgumentException(
                          "Steepness parameter needs to be greater than zero.", "steepness");
            }

            var normal     = plane.Vertices[0].normal;
            var step       = depth / numSteps;
            var scaleRange = 1f - targetScale;
            var exponent   = scaleRange < 0 ? 1f / steepness : steepness;
            var transforms =
                from s in EnumerableExt.Range(step, depth, step)
                let factor                       = (1f - (s / depth).Pow(exponent)) * scaleRange + targetScale
                                        let offs = -normal * s
                                                   select Mat.Translation <Mat4> (offs.X, offs.Y, offs.Z) *
                                                   Mat.ScalingPerpendicularTo(normal, new Vec2(factor)).RelativeTo(scaleAround);

            return(plane.Stretch(transforms, includeFrontFace, includeBackFace));
        }
コード例 #3
0
        public void chain_multiple_promises_using_all_and_convert_to_non_value_promise()
        {
            var promise         = new Promise <string>();
            var chainedPromise1 = new Promise();
            var chainedPromise2 = new Promise();

            var completed = 0;

            promise
            .ThenAll(i => EnumerableExt.FromItems(chainedPromise1, chainedPromise2).Cast <IPromise>())
            .Then(() =>
            {
                ++completed;
            });

            Assert.Equal(0, completed);

            promise.Resolve("hello");

            Assert.Equal(0, completed);

            chainedPromise1.Resolve();

            Assert.Equal(0, completed);

            chainedPromise2.Resolve();

            Assert.Equal(1, completed);
        }
コード例 #4
0
        public void combined_promise_is_resolved_when_children_are_resolved()
        {
            var promise1 = new Promise <int>();
            var promise2 = new Promise <int>();

            TestHelpers.VerifyDoesntThrowUnhandledException(() =>
            {
                var all = Promise <int> .All(EnumerableExt.FromItems <IPromise <int> >(promise1, promise2));

                var completed = 0;

                all.Then(v =>
                {
                    ++completed;

                    var values = v.ToArray();
                    Assert.Equal(2, values.Length);
                    Assert.Equal(1, values[0]);
                    Assert.Equal(2, values[1]);
                });

                promise1.Resolve(1);
                promise2.Resolve(2);

                Assert.Equal(1, completed);
            });
        }
コード例 #5
0
        public static IEnumerable <V> RandomControlPoints <V> (int seed)
            where V : struct, IVec <V, float>
        {
            var random = new System.Random(seed);

            return(EnumerableExt.Generate <V> (() => Vec.Random <V> (random, 0f, 1f)));
        }
コード例 #6
0
        public static IEnumerable <Vec2> HaltonControlPoints()
        {
            var i = 1;

            return(EnumerableExt.Generate <Vec2> (() =>
                                                  new Vec2(FMath.Halton(2, i), FMath.Halton(3, i++))));
        }
コード例 #7
0
        protected virtual string GetTitleLocalisationsContent(string line, string gameId)
        {
            IEnumerable <Localisation> titleLocalisations = localisations.TryGetValue(gameId);

            if (EnumerableExt.IsNullOrEmpty(titleLocalisations))
            {
                return(null);
            }

            string        indentation = Regex.Match(line, "^(\\s*)" + gameId + "\\s*=\\s*\\{.*$").Groups[1].Value + "    ";
            List <string> lines       = new List <string>();

            foreach (Localisation localisation in titleLocalisations.OrderBy(x => x.LanguageGameId))
            {
                string normalisedName = nameNormaliser.ToWindows1252(localisation.Name);
                string lineToAdd      = $"{indentation}{localisation.LanguageGameId} = \"{normalisedName}\"";

                if (Settings.Output.AreVerboseCommentsEnabled)
                {
                    lineToAdd += $" # Language={localisation.LanguageId}";
                }

                if (!string.IsNullOrWhiteSpace(localisation.Comment))
                {
                    lineToAdd += $" # {nameNormaliser.ToWindows1252(localisation.Comment)}";
                }

                lines.Add(lineToAdd);
            }

            return(string.Join(Environment.NewLine, lines));
        }
コード例 #8
0
        public void chain_multiple_promises_using_all()
        {
            var promise         = new Promise();
            var chainedPromise1 = new Promise();
            var chainedPromise2 = new Promise();

            var completed = 0;

            promise
            .ThenAll(() => EnumerableExt.FromItems(chainedPromise1, chainedPromise2).Cast <IPromise>())
            .Then(() => ++ completed);

            Assert.Equal(0, completed);

            promise.Resolve();

            Assert.Equal(0, completed);

            chainedPromise1.Resolve();

            Assert.Equal(0, completed);

            chainedPromise2.Resolve();

            Assert.Equal(1, completed);
        }
コード例 #9
0
        public IEnumerable <JGram.Entry> Lookup(string key)
        {
            int limit = 50;

            var(start, end) = index.EqualRange(key, kvp => kvp.Key);
            var outOfBoundLimit = (limit - (end - start)) / 2;

            start = Math.Max(0, start - outOfBoundLimit);
            end   = Math.Min(entries.Count, end + outOfBoundLimit);
            var mid = (start + end) / 2;

            var resultEntries = EnumerableExt.Range(start, end - start)
                                .OrderBy(i => Math.Abs(i - mid))
                                .Select(i => index[i])
                                .Select(indexEntry =>
            {
                var indexKey   = indexEntry.Key;
                var entryKey   = indexEntry.Value;
                var(entry, id) = entries.BinarySearch(entryKey, e => e.Id);
                return((indexKey, entry).SomeWhen(_ => id != -1));
            })
                                .Values()
                                .OrderByDescending(r => CommonPrefixLength(r.indexKey, key))
                                .Where(r => CommonPrefixLength(r.indexKey, key) != 0)
                                .Select(r => r.entry);

            return(EnumerableExt.DistinctBy(resultEntries, entry => entry.Id));
        }
コード例 #10
0
        public void chain_multiple_promises_using_all()
        {
            var promise         = new Promise();
            var chainedPromise1 = new Promise();
            var chainedPromise2 = new Promise();

            var completed = 0;

            TestHelpers.VerifyDoesntThrowUnhandledException(() =>
            {
                promise
                .ThenAll(() => EnumerableExt.FromItems(chainedPromise1, chainedPromise2)
                         .Cast <IPromise>())
                .Then(() => ++ completed);

                Assert.Equal(0, completed);

                promise.Resolve();

                Assert.Equal(0, completed);

                chainedPromise1.Resolve();

                Assert.Equal(0, completed);

                chainedPromise2.Resolve();

                Assert.Equal(1, completed);
            });
        }
コード例 #11
0
        /// <summary>
        /// Crée un scénario cible à partir d'un autre scénario, initial ou cible.
        /// </summary>
        /// <param name="context">Le contexte.</param>
        /// <param name="projectId">L'identifiant du projet.</param>
        /// <param name="sourceScenarioId">L'identifiant du scénario source.</param>
        /// <param name="natureCode">Le code de la nature.</param>
        /// <param name="save"><c>true</c> pour sauvegarder le scénario créé.</param>
        /// <returns>
        /// Le scénario créé
        /// </returns>
        public static async Task <Scenario> CreateDerivatedScenario(KsmedEntities context, int projectId, int sourceScenarioId, string natureCode, bool save)
        {
            Scenario fromScenario;

            using (var tempContext = ContextFactory.GetNewContext())
            {
                // Charger les référentiels
                var referentialsUsed = await SharedScenarioActionsOperations.GetReferentialsUse(context, projectId);

                await Queries.LoadAllReferentialsOfProject(context, projectId, referentialsUsed);

                var videos = await context.Projects
                             .Include(nameof(Project.Process))
                             .Include($"{nameof(Project.Process)}.{nameof(Procedure.Videos)}")
                             .Where(p => p.ProjectId == projectId)
                             .SelectMany(p => p.Process.Videos)
                             .ToArrayAsync();

                fromScenario = await context.Scenarios.FirstAsync(s => s.ScenarioId == sourceScenarioId);

                await Queries.LoadScenariosDetails(context, EnumerableExt.Concat(fromScenario), referentialsUsed);
            }

            return(await CreateDerivatedScenario(context, fromScenario, natureCode, save));
        }
コード例 #12
0
ファイル: FighterGeometry.cs プロジェクト: johtela/Compose3D
        public FighterGeometry()
        {
            var nose            = new Nose(0.5f, 0.6f, 26, 0.4f);
            var cockpitFuselage = new CockpitFuselage(nose, 1.2f, 1.2f, 3f);
            var mainFuselage    = new MainFuselage(cockpitFuselage);
            var intake          = new EngineIntake(cockpitFuselage);
            var underside       = new Underside(intake);
            var canopy          = new Canopy(0.65f, 0.5f, 3f, 16);
            var wing            = new Wing(4.5f, 4.5f);
            var rear            = new Rear(mainFuselage, underside);
            var tailFin         = new TailFin();
            var stabilizer      = new Stabilizer();
            var exhaust         = new Exhaust(rear, 0.6f);
            var bottomFin       = new BottomFin();

            var path      = exhaust.FlangeEndXSection;
            var graySlide = new Vec3(1f).Interpolate(new Vec3(0f), path.Vertices.Length);

            path.Vertices.Color(graySlide);
            Paths = EnumerableExt.Enumerate(path);

            Fighter = Composite.Create(Stacking.StackBackward(cockpitFuselage.Fuselage, mainFuselage.Fuselage)
                                       .Concat(EnumerableExt.Enumerate(intake.Intake, intake.Belly, underside.Geometry, canopy.Geometry,
                                                                       wing.Geometry, wing.Geometry.ReflectX(), rear.Geometry, exhaust.Geometry,
                                                                       exhaust.StabilizerFlange, exhaust.StabilizerFlange.ReflectX(),
                                                                       tailFin.Geometry, stabilizer.Geometry, stabilizer.Geometry.ReflectX(),
                                                                       bottomFin.Geometry, bottomFin.Geometry.ReflectX())))
                      .Smoothen(0.85f)
                      .Center();
        }
コード例 #13
0
    public override Translation With(
        string?originalText                = null,
        string?translatedText              = null,
        IEnumerable <GlossNote>?glosses    = null,
        IEnumerable <TranslatorNote>?notes = null,
        IEnumerable <TranslatedText>?alternativeTranslations = null)
    {
        var clone = GetJson();

        clone.Source = originalText ?? clone.Source;
        clone.Target = translatedText ?? clone.Target;
        if (notes != null)
        {
            clone.Notes = clone.Notes
                          .Select(n => n.Uuid)
                          .Concat(EnumerableExt.Repeat("infinity").Select(_ => System.Guid.NewGuid()))
                          .Zip(
                notes,
                (id, note) => new NoteJson()
            {
                Uuid    = id,
                Content = note.Text
            })
                          .ToList();
        }

        return(new TextEntryTranslation(clone));
    }
コード例 #14
0
        public async Task <Option <RichFormatting> > Answer(Request request)
        {
            try
            {
                var rich       = new RichFormatting();
                var paragraphs = ReadParagraphs(path);
                if (paragraphs != null)
                {
                    await paragraphs.Where(paragraph => paragraph.Contains(request.QueryText)).ForEachAsync(paragraph =>
                    {
                        var text = new TextParagraph(
                            StringExt.HighlightWords(paragraph, request.QueryText)
                            .Select(p => new Text(p.text, emphasis: p.highlight)));
                        rich.Paragraphs.Add(text);
                    });

                    return(Option.Some(rich));
                }
            }
            catch (FileNotFoundException)
            {
                var text = "This data source looks for a custom_notes.txt file in the data directory. Currently no such file exists.";
                var rich = new RichFormatting(
                    EnumerableExt.OfSingle(
                        new TextParagraph(
                            EnumerableExt.OfSingle(
                                new Text(text)))));
                return(Option.Some(rich));
            }

            return(Option.None <RichFormatting>());
        }
コード例 #15
0
        public bool Match(byte[] machineHash)
        {
            _traceManager?.TraceDebug("MachineIdentifierProvider.Match(stored hash: {0})",
                                      machineHash != null ? Convert.ToBase64String(machineHash) : "null");

            var identifiers = EnumerableExt.Concat(NewMachineIdentifier).Concat(OldMachineIdentifiersCheck);

            using (MemoryStream stream = new MemoryStream(machineHash))
            {
                byte[] hash = new byte[16];
                if (stream.Read(hash, 0, 16) != 16)
                {
                    return(false);
                }

                foreach (var identifier in identifiers)
                {
                    if (identifier.Match(hash))
                    {
                        return(true);
                    }
                }
            }

            return(false);
        }
コード例 #16
0
        public IEnumerable <IGrouping <string, CodePoint> > FindRelated(CodePoint codePoint)
        {
            similar.TryGetValue(codePoint.ToString(), out var resultList);
            IEnumerable <string> result = resultList ?? Enumerable.Empty <string>();

            return(EnumerableExt.OfSingle(new CategoryGrouping <CodePoint>("Similar Kanji",
                                                                           result.Select(r => CodePoint.FromString(r)))));
        }
コード例 #17
0
        public void IsNullOrEmpty_CollectionIsNull_ReturnsTrue()
        {
            IEnumerable <string> collection = null;

            bool actual = EnumerableExt.IsNullOrEmpty(collection);

            Assert.IsTrue(actual);
        }
コード例 #18
0
        public void combined_promise_is_resolved_if_there_are_no_promises()
        {
            var all = Promise.All(EnumerableExt.Empty <IPromise>());

            var completed = 0;

            all.Then(() => ++ completed);
        }
コード例 #19
0
        public void IsEmpty_CollectionIsEmpty_ReturnsTrue()
        {
            IEnumerable <string> collection = new List <string>();

            bool actual = EnumerableExt.IsEmpty(collection);

            Assert.IsTrue(actual);
        }
コード例 #20
0
 public IEnumerable <CodePoint> LookupRelatedCharacters(CodePoint point)
 {
     return(EnumerableExt.IntersperseSequencesWith(new[]
     {
         kanaProperties.FindSimilar(point),
         confused.FindSimilar(point)
     },
                                                   null as CodePoint));
 }
コード例 #21
0
 public void TestFromLowerTriangularIndex()
 {
     var r1 = EnumerableExt.FromLowerTriangularIndex(2);
     var r2 = EnumerableExt.FromLowerTriangularIndex(5);
     var r3 = EnumerableExt.FromLowerTriangularIndex(8);
     var r4 = EnumerableExt.FromLowerTriangularIndex(12);
     var r5 = EnumerableExt.FromLowerTriangularIndex(14);
     var r6 = EnumerableExt.FromLowerTriangularIndex(16);
 }
コード例 #22
0
        public void IsEmpty_CollectionIsNotEmpty_ReturnsFalse()
        {
            IEnumerable <string> collection = new List <string> {
                "test"
            };

            bool actual = EnumerableExt.IsEmpty(collection);

            Assert.IsFalse(actual);
        }
コード例 #23
0
ファイル: ColorMapEdit.cs プロジェクト: johtela/Compose3D
 public ColorMapEdit(float domainMin, float domainMax, float knobWidth, float minVisualLength,
                     ColorMap <Vec3> colorMap, Reaction <ColorMap <Vec3> > changed)
     : base(VisualDirection.Horizontal, HAlign.Left, VAlign.Top, false, false,
            Enumerable.Empty <Control> ())
 {
     _bar = new ColorMapBar(domainMin, domainMax, knobWidth, minVisualLength, colorMap, changed,
                            React.By <int?> (ItemSelected));
     _picker = new ColorPicker(VisualDirection.Vertical, knobWidth, minVisualLength - (3f * knobWidth),
                               Color.Black, true, React.By <Color> (ColorChanged));
     Controls.AddRange(EnumerableExt.Enumerate <Control> (_bar, _picker)
                       .Select(c => new Tuple <Control, Reaction <Control> > (c, null)));
 }
コード例 #24
0
        /// <summary>
        /// Returns a promise that resolves when all of the promises in the enumerable argument have resolved.
        /// Returns a promise of a collection of the resolved results.
        /// </summary>
        public static IPromise <IEnumerable <PromisedT> > All(IEnumerable <IPromise <PromisedT> > promises)
        {
            var promisesArray = promises.ToArray();

            if (promisesArray.Length == 0)
            {
                return(Promise <IEnumerable <PromisedT> > .Resolved(EnumerableExt.Empty <PromisedT>()));
            }

            var remainingCount = promisesArray.Length;
            var results        = new PromisedT[remainingCount];
            var progress       = new float[remainingCount];
            /// ADDED: Progress ripped from 3.0
            var resultPromise = new Promise <IEnumerable <PromisedT> >();

            resultPromise.WithName("All");

            promisesArray.Each((promise, index) =>
            {
                promise
                /// ADDED: Progress ripped from 3.0
                .Progress(v =>
                {
                    progress[index] = v;
                    resultPromise.ReportProgress(progress.Average());
                })
                .Catch(ex =>
                {
                    if (resultPromise.CurState == PromiseState.Pending)
                    {
                        // If a promise errorred and the result promise is still pending, reject it.
                        resultPromise.Reject(ex);
                    }
                })
                .Then(result =>
                {
                    /// ADDED: Progress ripped from 3.0
                    progress[index] = 1f;
                    results[index]  = result;

                    --remainingCount;
                    if (remainingCount <= 0)
                    {
                        // This will never happen if any of the promises errorred.
                        resultPromise.Resolve(results);
                    }
                })
                .Done();
            });

            return(resultPromise);
        }
コード例 #25
0
        public Task <Option <RichFormatting> > Answer(Request request, CancellationToken token)
        {
            var rich    = new RichFormatting();
            var text    = request.AllText();
            var glosses = autoglosser.Gloss(text);

            rich.Paragraphs.Add(
                new TextParagraph(EnumerableExt.OfSingle(new Text(Descriptor.AcknowledgementText))));
            var s = string.Join("\n", glosses.Select(gloss => $"- {gloss.Foreign}:\n{string.Join("\n", gloss.GlossCandidates.Select(c => $"    - {c}"))}"));

            rich.Paragraphs.Add(new TextParagraph(EnumerableExt.OfSingle(new Text(s))));
            return(Task.FromResult(Option.Some(rich)));
        }
コード例 #26
0
        public static bool AreCoplanar <V> (this IEnumerable <V> vertices)
            where V : struct, IVertex <Vec3>
        {
            if (vertices.Count() < 4)
            {
                return(true);
            }
            var first  = EnumerableExt.Next(ref vertices).position;
            var ab     = EnumerableExt.Next(ref vertices).position - first;
            var ac     = EnumerableExt.Next(ref vertices).position - first;
            var normal = ab.Cross(ac);

            return(vertices.All(v => normal.Dot(v.position - first).ApproxEquals(0f, 0.1f)));
        }
コード例 #27
0
        public static Geometry <EntityVertex> SineS()
        {
            var range   = MathHelper.PiOver2;
            var step    = MathHelper.Pi / 20f;
            var contour =
                (from x in EnumerableExt.Range(-range, range, step)
                 select new Vec2(x, x.Sin() + 1f))
                .Concat(
                    from x in EnumerableExt.Range(range, -range, -step)
                    select new Vec2(x, x.Sin() - 1f)).ToArray();

            return(Polygon <EntityVertex> .FromVec2s(contour)
                   .Extrude(2f, true)
                   .Smoothen(0.9f));
        }
コード例 #28
0
        public void combined_promise_is_resolved_if_there_are_no_promises()
        {
            var all = Promise <int> .All(EnumerableExt.Empty <IPromise <int> >());

            var completed = 0;

            all.Then(v =>
            {
                ++completed;

                Assert.Empty(v);
            });

            Assert.Equal(1, completed);
        }
コード例 #29
0
        public void combined_promise_is_resolved_when_all_promises_are_already_resolved()
        {
            var promise1 = Promise.Resolved();
            var promise2 = Promise.Resolved();

            TestHelpers.VerifyDoesntThrowUnhandledException(() =>
            {
                var all = Promise.All(EnumerableExt.FromItems(promise1, promise2));

                var completed = 0;

                all.Then(() => ++ completed);

                Assert.Equal(1, completed);
            });
        }
コード例 #30
0
        public void combined_promise_is_resolved_when_all_promises_are_already_resolved()
        {
            var promise1 = Promise.Resolved();
            var promise2 = Promise.Resolved();

            var all = Promise.All(EnumerableExt.FromItems(promise1, promise2));

            var completed = 0;

            all.Then(() =>
            {
                ++completed;
            });

            Assert.Equal(1, completed);
        }