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); }
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)); }
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); }
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); }); }
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))); }
public static IEnumerable <Vec2> HaltonControlPoints() { var i = 1; return(EnumerableExt.Generate <Vec2> (() => new Vec2(FMath.Halton(2, i), FMath.Halton(3, i++)))); }
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)); }
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); }
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)); }
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); }); }
/// <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)); }
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(); }
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)); }
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>()); }
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); }
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))))); }
public void IsNullOrEmpty_CollectionIsNull_ReturnsTrue() { IEnumerable <string> collection = null; bool actual = EnumerableExt.IsNullOrEmpty(collection); Assert.IsTrue(actual); }
public void combined_promise_is_resolved_if_there_are_no_promises() { var all = Promise.All(EnumerableExt.Empty <IPromise>()); var completed = 0; all.Then(() => ++ completed); }
public void IsEmpty_CollectionIsEmpty_ReturnsTrue() { IEnumerable <string> collection = new List <string>(); bool actual = EnumerableExt.IsEmpty(collection); Assert.IsTrue(actual); }
public IEnumerable <CodePoint> LookupRelatedCharacters(CodePoint point) { return(EnumerableExt.IntersperseSequencesWith(new[] { kanaProperties.FindSimilar(point), confused.FindSimilar(point) }, null as CodePoint)); }
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); }
public void IsEmpty_CollectionIsNotEmpty_ReturnsFalse() { IEnumerable <string> collection = new List <string> { "test" }; bool actual = EnumerableExt.IsEmpty(collection); Assert.IsFalse(actual); }
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))); }
/// <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); }
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))); }
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))); }
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)); }
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); }
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); }); }
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); }