public IEnumerable<Frame> Mixin_scores(IEnumerable<Frame> frames, IEnumerable<int> scores) { return frames.Zip(scores, (f, s) => { f.Score = s; return f; }); }
/// <summary> /// Connects this power conversion element in Wye to <paramref name="connectTo"/>. Each phase of the /// <see cref="PowerConversionElement"/>in <paramref name="pcElementPhases"/> is connected to the phase of the same index in /// <paramref name="busPhases"/>. /// </summary> /// <param name="connectTo">The <see cref="Bus"/> to connect this <see cref="PowerConversionElement"/> to.</param> /// <param name="pcElementPhases">The phases of this element that should be connected.</param> /// <param name="busPhases">The phases of <paramref name="connectTo"/> to connect to.</param> public void ConnectWye(Bus connectTo, IEnumerable<int> pcElementPhases, IEnumerable<int> busPhases) { foreach (var phasePair in pcElementPhases.Zip(busPhases,(pcElementPhase,busPhase) => new {pcElementPhase,busPhase})) { Connect(phasePair.pcElementPhase, connectTo, phasePair.busPhase); } }
private static double Covariance(IEnumerable<double> xs, IEnumerable<double> ys) { var xAvg = xs.Average(); var yAvg = ys.Average(); var cov = xs.Zip(ys, (x, y) => (x - xAvg) * (y - yAvg)).Average(); return cov; }
public void LearnFrom(IEnumerable<char> english, IEnumerable<char> googlerese) { foreach (var tuple in googlerese.Zip(english, (x, y) => Tuple.Create(x, y))) { _charMapping[tuple.Item1] = tuple.Item2; } }
public static double Calculate(ISymbolicTimeSeriesPrognosisExpressionTreeInterpreter interpreter, ISymbolicExpressionTree solution, double lowerEstimationLimit, double upperEstimationLimit, ITimeSeriesPrognosisProblemData problemData, IEnumerable<int> rows, IntRange evaluationPartition, int horizon, bool applyLinearScaling) { var horizions = rows.Select(r => Math.Min(horizon, evaluationPartition.End - r)); IEnumerable<double> targetValues = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, rows.Zip(horizions, Enumerable.Range).SelectMany(r => r)); IEnumerable<double> estimatedValues = interpreter.GetSymbolicExpressionTreeValues(solution, problemData.Dataset, rows, horizions).SelectMany(x => x); OnlineCalculatorError errorState; double mse; if (applyLinearScaling && horizon == 1) { //perform normal evaluation and afterwards scale the solution and calculate the fitness value var mseCalculator = new OnlineMeanSquaredErrorCalculator(); CalculateWithScaling(targetValues, estimatedValues, lowerEstimationLimit, upperEstimationLimit, mseCalculator, problemData.Dataset.Rows * horizon); errorState = mseCalculator.ErrorState; mse = mseCalculator.MeanSquaredError; } else if (applyLinearScaling) { //first create model to perform linear scaling and afterwards calculate fitness for the scaled model var model = new SymbolicTimeSeriesPrognosisModel((ISymbolicExpressionTree)solution.Clone(), interpreter, lowerEstimationLimit, upperEstimationLimit); model.Scale(problemData); var scaledSolution = model.SymbolicExpressionTree; estimatedValues = interpreter.GetSymbolicExpressionTreeValues(scaledSolution, problemData.Dataset, rows, horizions).SelectMany(x => x); var boundedEstimatedValues = estimatedValues.LimitToRange(lowerEstimationLimit, upperEstimationLimit); mse = OnlineMeanSquaredErrorCalculator.Calculate(targetValues, boundedEstimatedValues, out errorState); } else { var boundedEstimatedValues = estimatedValues.LimitToRange(lowerEstimationLimit, upperEstimationLimit); mse = OnlineMeanSquaredErrorCalculator.Calculate(targetValues, boundedEstimatedValues, out errorState); } if (errorState != OnlineCalculatorError.None) return Double.NaN; else return mse; }
/// <summary> /// Convert the param XML element to Markdown safely. /// </summary> /// <param name="elements">The param XML element list.</param> /// <param name="paramTypes">The paramater type names.</param> /// <param name="memberKind">The member kind of the parent element.</param> /// <returns>The generated Markdown.</returns> /// <remarks> /// When the parameter (a.k.a <paramref name="elements"/>) list is empty: /// <para>If parent element kind is <see cref="MemberKind.Constructor"/> or <see cref="MemberKind.Method"/>, it returns a hint about "no parameters".</para> /// <para>If parent element kind is not the value mentioned above, it returns an empty string.</para> /// </remarks> internal static IEnumerable<string> ToMarkdown( IEnumerable<XElement> elements, IEnumerable<string> paramTypes, MemberKind memberKind) { if (!elements.Any()) { return memberKind != MemberKind.Constructor && memberKind != MemberKind.Method ? Enumerable.Empty<string>() : new[] { "##### Parameters", $"This {memberKind.ToLowerString()} has no parameters." }; } var markdowns = elements .Zip(paramTypes, (element, type) => new ParamUnit(element, type)) .SelectMany(unit => unit.ToMarkdown()); var table = new[] { "| Name | Type | Description |", "| ---- | ---- | ----------- |" } .Concat(markdowns); return new[] { "##### Parameters", string.Join("\n", table) }; }
private static IReadOnlyCollection<ClauseStates> Expand(IEnumerable<Clause> clauses, IEnumerable<ClauseStates> problem, int variable, bool value) { return clauses.Zip(problem, (clause, state) => new { Clause = clause, State = state }).Select( pair => { if (pair.State == ClauseStates.True) { return ClauseStates.True; } if (CanEliminateClause(pair.Clause, variable, value)) { return ClauseStates.True; } var state = pair.State; if (!state.HasFlag(ClauseStates.LeftFalse) && IsFalse(pair.Clause.Literal1, variable, value)) { state |= ClauseStates.LeftFalse; } if (!state.HasFlag(ClauseStates.RightFalse) && IsFalse(pair.Clause.Literal2, variable, value)) { state |= ClauseStates.RightFalse; } return state; }).ToArray(); }
static IEnumerable<MaraphoneEvent> CreateBets(IEnumerable<string> eventsNames, IEnumerable<ParsedEventData> eventsData) { Debug.Assert(eventsNames.Count() == eventsData.Count(), "Bets count and events count should match each other, but was " + eventsData.Count() + " vs " + eventsNames.Count()); return eventsNames.Zip(eventsData, (name, data) => new MaraphoneEvent(name, data.Coefficient, data.Specification)); }
public DiscountCard(int baseDiscount, IEnumerable<DiscountPoint> discountPoints) { Contract.Requires(baseDiscount >= 0); Contract.Requires(discountPoints.Zip(discountPoints.Skip(1), (a, b) => a.DiscountPrecents < b.DiscountPrecents && a.MinimumTotal < b.MinimumTotal).All(b => b), "Discount points sequence should be monotonically increasing"); points = (new[] { new DiscountPoint(0.0M, baseDiscount) }).Concat(discountPoints).Reverse().ToList(); }
private static void AssertEqual(IEnumerable<KeyValuePair<string, IEnumerable<string>>> expected, IEnumerable<KeyValuePair<string, IEnumerable<string>>> result) { Assert.Equal(expected.Count(), result.Count()); foreach (var value in expected.Zip(result, (e, r) => new { Expected = e, Result = r })) { Assert.Equal(value.Expected.Key, value.Result.Key); Assert.Equal(value.Expected.Value, value.Result.Value); } }
/// <summary> /// Constructs a new AxopatchDevice /// </summary> /// <param name="p">Axopatch instance</param> /// <param name="c">Symphony Controller instance</param> /// <param name="backgroundModes">Enumerable of operating modes</param> /// <param name="backgroundMeasurements">Corresponding background Measurement for each operating mode</param> public AxopatchDevice( IAxopatch p, Controller c, IEnumerable<AxopatchInterop.OperatingMode> backgroundModes, IEnumerable<IMeasurement> backgroundMeasurements) : this(p, c, backgroundModes.Zip(backgroundMeasurements, (k, v) => new {Key = k, Value = v}) .ToDictionary(x => x.Key, x => x.Value)) { }
private bool AreEquivalent(IEnumerable<LNode> First, IEnumerable<LNode> Second) { if (First.Count() != Second.Count()) { return false; } else { return First.Zip(Second, Pair.Create).All(item => AreEquivalent(item.Item1, item.Item2)); } }
public static IImmutableList<IImmutableList<int>> BuildDlxMatrix( IEnumerable<TetraStick> tetraSticks, IEnumerable<PlacedTetraStick> placedTetraSticks) { var tagToIndexDict = tetraSticks .Zip(Enumerable.Range(0, int.MaxValue), Tuple.Create) .ToImmutableDictionary(t => t.Item1.Tag, t => t.Item2); return placedTetraSticks .Select(placedTetraStick => BuildDlxMatrixRow(tagToIndexDict, placedTetraStick)) .ToImmutableList(); }
public Factory ToFactory(IEnumerable<Column> columns, TypeMapper typeMapper) { if (columns.Count() != _attributes.Count()) { throw new InvalidOperationException("Did not get equal number of Columns and Attributes"); } var readers = columns.Zip<Column, Attribute, Func<object[], object>>(_attributes, (column, attribute) => { var mapper = typeMapper.MappingFor(column, attribute); return (row) => mapper(column.Read(row)); }); return new Factory(_info, readers.ToArray()); }
public static IEnumerable<Rectangle> ArrangeBlocks(IEnumerable<SizeF> wordSizes, Rectangle clientRectangle) { var centers = GetCenters(0, clientRectangle.Width, 0, clientRectangle.Height); foreach (var sizeAndCenter in wordSizes.Zip(centers, (sz, center) => new {Size = sz, Center = center})) { var center = sizeAndCenter.Center; var size = sizeAndCenter.Size; var rect = new Rectangle(center.X - (int) size.Width / 2, center.Y - (int) size.Height / 2, (int) size.Width, (int) size.Height); yield return rect; } }
/// <summary> /// Connects the <see cref="PowerDeliveryElement"/> on the phases in <paramref name="bus1AndLinePhases"/> /// to the same phases on <paramref name="bus1"/>, and to the correspondingly-indexed phases <paramref name="bus2Phases"/> /// on <paramref name="bus2"/>. /// </summary> /// <example> /// The following code connects the <see cref="PowerDeliveryElement"/> to <paramref name="bus1"/> /// and <paramref name="bus2"/>, with the following phasing: /// <code> /// // key: line phase -> bus1 phase, bus2 phase /// // 1 -> 1, 2 /// // 2 -> 2, 3 /// // 3 -> 3, 1 /// myPowerDeliveryElement.Connect(bus1, new[] {1,2,3}, bus2, new[] {2,3,1}); /// </code></example> /// <param name="bus1">The first <see cref="Bus"/> to connect to. Shares common phases with the <see cref="PowerDeliveryElement"/>.</param> /// <param name="bus1AndLinePhases">The common phases to connect between the <see cref="PowerDeliveryElement"/> and the <see cref="Bus"/>.</param> /// <param name="bus2">The second <see cref="Bus"/> to connect to.</param> /// <param name="bus2Phases">Phase connections for <paramref name="bus2"/>.</param> public void Connect(Bus bus1, IEnumerable<int> bus1AndLinePhases, Bus bus2, IEnumerable<int> bus2Phases) { foreach (var phasePair in bus1AndLinePhases.Zip(bus2Phases, (phase1, phase2) => new { Bus1AndLinePhase = phase1, Bus2Phase = phase2 })) { NetworkElement.ConnectBetween(this, phasePair.Bus1AndLinePhase, bus1, phasePair.Bus1AndLinePhase, bus2, phasePair.Bus2Phase ); } }
private static IEnumerable<Tuple<PackageHeader, PackageVersion>> ListRequiredPackageVersions( IEnumerable<PackageHeader> headers, PackageVersion version) { return headers.Zip( version.full_dependency_versions, (header, v) => new Tuple<PackageHeader, string>(header, v)) .Select( (pair) => new Tuple<PackageHeader, PackageVersion>( pair.Item1, pair.Item1.versions.First(x => x.version == pair.Item2))); }
public async Task<List<string>> SendToastNotifications(string text1, string text2, IEnumerable<string> subscriberDeviceUris) { var payload = GetToastPayload(text1, text2); var tasks = subscriberDeviceUris .Select(deviceUri => SendToastNotification(payload, deviceUri)); bool[] succeses = await Task.WhenAll(tasks); var failedDeviceUris = subscriberDeviceUris .Zip(succeses, (deviceUri, success) => new { deviceUri, success }) .Where(pair => !pair.success) .Select(pair => pair.deviceUri) .ToList(); return failedDeviceUris; }
public async Task<List<string>> SendPushNotifications(FactTreeMemento factTree, IEnumerable<string> subscriberDeviceUris) { var payload = GetRawPayload(factTree); var tasks = subscriberDeviceUris .Select(deviceUri => SendRawNotification(payload, deviceUri)); bool[] succeses = await Task.WhenAll(tasks); var failedDeviceUris = subscriberDeviceUris .Zip(succeses, (deviceUri, success) => new { deviceUri, success }) .Where(pair => !pair.success) .Select(pair => pair.deviceUri) .ToList(); return failedDeviceUris; }
internal InfluxDbRecord(string name, IEnumerable<string> columns, IEnumerable<object> data, MetricTags tags, ConfigOptions config, Tuple<string, string>[] moreTags = null) : this(config) { var record = BuildRecordPreamble(name, tags, moreTags); var fieldKeypairs = new List<string>(); foreach (var pair in columns.Zip(data, (col, dat) => new { col, dat })) { fieldKeypairs.Add(string.Format("{0}={1}", Escape(pair.col), StringifyValue(pair.dat))); } record.Append(string.Join(",", fieldKeypairs)); LineProtocol = record.ToString(); }
public static bool AgreesAbsolute(IEnumerable<double> first, IEnumerable<double> second, double tolerance = 1e-6) { if (first.Count() != second.Count()) return false; Func<double, double, bool> passes = (f, s) => Math.Abs(f - s) < tolerance; var diffs = first.Zip(second, (f, s) => new { First = f, Second = s }).Where(d => !passes(d.First, d.Second)); if (diffs.Any()) { var builder = new StringBuilder(); builder.AppendLine(string.Format("Numbers of diffs: {0}", diffs.Count())); foreach (var item in diffs) { builder.AppendLine(string.Format("{0:F7} versus {1:F7} ({2:E1})", item.First, item.Second, item.First - item.Second)); } Console.WriteLine(builder.ToString()); } return !diffs.Any(); }
public static Mesh InstanceMerge( IEnumerable<Mesh> Meshes, IEnumerable<Matrix> Transformation) { var r = new Mesh(); var totalVerticies = Meshes.Sum(m => m.VertexCount); var totalIndicies = Meshes.Sum(m => m.indicies.Length); r.verticies = new Vertex[totalVerticies]; r.indicies = new short[totalIndicies]; int vertexInsertLocation = 0; int indexInsertLocation = 0; foreach (var instance in Meshes.Zip(Transformation, (m, t) => Tuple.Create(m,t))) { var mesh = instance.Item1; var transform = instance.Item2; for (int i = 0; i < mesh.VertexCount; ++i) { r.verticies[i + vertexInsertLocation].Position = Vector3.Transform(mesh.verticies[i].Position, transform); r.verticies[i + vertexInsertLocation].TextureCoordinate = mesh.verticies[i].TextureCoordinate; } Vector3 scale; Vector3 trans; Quaternion rot; transform.Decompose(out scale, out rot, out trans); for (int i = 0; i < mesh.VertexCount; ++i) { r.verticies[i + vertexInsertLocation].Normal = Vector3.Transform(mesh.verticies[i].Normal, rot); r.verticies[i + vertexInsertLocation].Tangent = Vector3.Transform(mesh.verticies[i].Tangent, rot); r.verticies[i + vertexInsertLocation].BiNormal = Vector3.Transform(mesh.verticies[i].BiNormal, rot); } for (int i = 0; i < mesh.indicies.Length; ++i) r.indicies[i + indexInsertLocation] = (short)(vertexInsertLocation + mesh.indicies[i]); vertexInsertLocation += mesh.VertexCount; indexInsertLocation += mesh.indicies.Length; } return r; }
internal static void AddArgumentSymbol(ISymbolicExpressionTreeGrammar originalGrammar, ISymbolicExpressionTreeGrammar grammar, IEnumerable<int> argumentIndexes, IEnumerable<CutPoint> argumentCutPoints) { foreach (var pair in argumentIndexes.Zip(argumentCutPoints, (a, b) => new { Index = a, CutPoint = b })) { var argSymbol = new Argument(pair.Index); grammar.AddSymbol(argSymbol); grammar.SetSubtreeCount(argSymbol, 0, 0); foreach (var symb in grammar.Symbols) { if (symb is ProgramRootSymbol || symb is StartSymbol) continue; if (originalGrammar.IsAllowedChildSymbol(symb, pair.CutPoint.Child.Symbol)) grammar.AddAllowedChildSymbol(symb, argSymbol); else { for (int i = 0; i < grammar.GetMaximumSubtreeCount(symb); i++) { if (originalGrammar.IsAllowedChildSymbol(symb, pair.CutPoint.Child.Symbol, i)) grammar.AddAllowedChildSymbol(symb, argSymbol, i); } } } } }
public static Move getMove(Board state, IEnumerable<Card> toBuy, IEnumerable<int> weights) { if (toBuy.Count() < 1) throw new Exception("BuySeeker.getMove called with no cards"); if (toBuy.Count() != weights.Count()) throw new Exception("Buyseeker called with the wrong number of weights"); Move target = new Move.BUY(toBuy.First()); if (target.isLegal(state)) return target; //Buy if possible target = new Move.RESERVE(toBuy.First()); if (state.notCurrentPlayer.canBuy(state, toBuy.First()) && target.isLegal(state)) return target; //Reserve if opponent can buy var zipped = toBuy.Zip(weights, (c, w) => new { cd = c, wt = w }); int[] needed = new int[5] { 0, 0, 0, 0, 0 }; foreach (var a in zipped) { Gem toAdd = neededGems(state, a.cd); for (int i = 0; i < 5; i++) needed[i] += toAdd[i] * a.wt; } Gem targetGems = new Gem(needed); Heuristic fn = Heuristic.colors(targetGems); return Greedy.getGreedyMove(state, fn); }
private static int Choose(IEnumerable<Clause> clauses, IEnumerable<ClauseStates> problem) { var clausesWithStates = clauses.Zip(problem, (clause, state) => new { Clause = clause, State = state }).ToArray(); foreach (var pair in clausesWithStates) { if (pair.State == ClauseStates.LeftFalse) { return pair.Clause.Literal2.Index; } if (pair.State == ClauseStates.RightFalse) { return pair.Clause.Literal1.Index; } } return clausesWithStates .First(x => x.State == ClauseStates.Undetermined) .Clause.Literal1.Index; }
private static double Gini(IEnumerable<double> original, IEnumerable<double> estimated, out OnlineCalculatorError errorState) { var pairs = estimated.Zip(original, (e, o) => new { e, o }) .OrderByDescending(p => p.e); if (pairs.Any()) errorState = OnlineCalculatorError.None; else errorState = OnlineCalculatorError.InsufficientElementsAdded; double giniSum = 0.0; double sumOriginal = 0.0; int n = 0; foreach (var p in pairs) { if (double.IsNaN(p.o) || double.IsNaN(p.e)) { errorState = OnlineCalculatorError.InvalidValueAdded; return double.NaN; } sumOriginal += p.o; giniSum += sumOriginal; n++; } giniSum /= sumOriginal; return (giniSum - ((n + 1) / 2.0)) / n; }
private static MethodInfo InferMethodInfo(MethodInfo methodInfo, IEnumerable<object> arguments) { if (methodInfo.ContainsGenericParameters) { var typeMap = arguments.Zip(methodInfo.GetParameters(), (argument, parameter) => ResolveGenericType(GetType(argument), parameter.ParameterType)) .SelectMany(x => x) .ToLookup(x => x.Item1, x => x.Item2); var actuals = methodInfo.GetGenericArguments() .Select(x => { if (!typeMap.Contains(x)) throw new TypeArgumentsCannotBeInferredException(methodInfo); return typeMap[x].Aggregate((t1, t2) => t1.IsAssignableFrom(t2) ? t2 : t1); }); return methodInfo.MakeGenericMethod(actuals.ToArray()); } return methodInfo; }
public IObservable<Unit> QueueBackgroundDownloads(IEnumerable<string> urls, IEnumerable<string> localPaths, IObserver<int> progress = null) { var fileCount = urls.Count(); double toIncrement = 100.0 / fileCount; progress = progress ?? new Subject<int>(); var ret = urls.Zip(localPaths, (u, p) => new { Url = u, Path = p }).ToObservable() .Select(x => Http.DownloadUrl(x.Url).Select(Content => new { x.Url, x.Path, Content })) .Merge(4) .SelectMany(x => Observable.Start(() => { var fi = fileSystem.GetFileInfo(x.Path); if (fi.Exists) fi.Delete(); using (var of = fi.OpenWrite()) { of.Write(x.Content, 0, x.Content.Length); } }, RxApp.TaskpoolScheduler)) .Multicast(new ReplaySubject<Unit>()); ret.Scan(0.0, (acc, _) => acc + toIncrement).Select(x => (int) x).Subscribe(progress); ret.Connect(); return ret.TakeLast(1).Select(_ => Unit.Default); }
public IEnumerable <DelaunatorEdge> CreateHull(IEnumerable <Vector> points) => points.Zip(points.Skip(1).Append(points.FirstOrDefault()), (a, b) => new DelaunatorEdge { Index = 0, P = a, Q = b }).OfType <DelaunatorEdge>();
private static bool ModificationListsMatch(IEnumerable <string> list1, IEnumerable <string> list2) { return(!list1.Zip(list2, ModificationsMatch).Contains(false)); }
public static Task <IEnumerable <TResult> > Zip <TSource, TSecond, TResult>(this IEnumerable <TSource> @this, IEnumerable <Task <TSecond> > second, Func <TSource, TSecond, TResult> func) => @this.Zip(second.AwaitAll(), func);
IEnumerable <KeyValuePair <string, T> > MakeEnumerable() { return(_arguments.Zip(_names, (arg, name) => new KeyValuePair <string, T>(name, arg))); }
public List<Island> CreateIslands(IEnumerable<Vector2> islandPositions, IEnumerable<int> initialGolds) { return islandPositions.Zip(initialGolds, (p, g) => this.CreateIsland(p, g)).ToList(); }
public static IEnumerable <Tuple <TSource1, TSource2> > Zip <TSource1, TSource2>(this IEnumerable <TSource1> source1, IEnumerable <TSource2> source2) { return(source1.Zip(source2, (e1, e2) => new Tuple <TSource1, TSource2>(e1, e2))); }
public static double ScalarMul(IEnumerable <double> v1, IEnumerable <double> v2) { return(v1.Zip(v2, (a, b) => a * b).Sum()); }
public static bool SameAs(this IEnumerable <IMusicable> list1, IEnumerable <IMusicable> list2) { return(list1?.Count() == list2?.Count() && list1.Zip(list2, (m1, m2) => m1.ToMusic().Equals(m2.ToMusic())).All(res => res)); }
/// <summary> /// 9. 与えられた2つの文字列コレクションから結合・加工したひとつの文字列コレクションを返す関数を作りなさい。2つの文字列は同じ要素番号を持つ者同士をコロンを用いて結合し、結合可能なもののみを返すこと。 /// </summary> /// <param name="_stringList1"></param> /// <param name="_stringList2"></param> /// <returns></returns> static IEnumerable <string> Q9(IEnumerable <string> _stringList1, IEnumerable <string> _stringList2) { return(_stringList1.Zip(_stringList2, (a, b) => $"{a}:{b}")); }
private static bool IsFullCombination(this IEnumerable <SyntaxNode> nodes, IEnumerable <string> expectedTags) { return(nodes.Zip(expectedTags, (a, b) => a.IsTag && a.TagName == b).All(p => p)); }
//private static T[] getdataOfType<T>(int datatype) where T : struct //{ // System.Type type; // switch (datatype) // { // case H5T.NATIVE_INT16: // type = Int16.; // break; // case nameof(Int32): // dataType = H5T.NATIVE_INT; // break; // case nameof(Int64): // dataType = H5T.NATIVE_INT64; // break; // case nameof(Double): // dataType = H5T.NATIVE_DOUBLE; // break; // case nameof(Boolean): // dataType = H5T.NATIVE_INT8; // break; // default: // throw new Exception(string.Format("Datatype {0} not supported", type)); // } // return type; //} public static bool Similar(this IEnumerable <double> first, IEnumerable <double> second, double precision = 1e-2) { var result = first.Zip(second, (f, s) => Math.Abs(f - s) < precision); return(result.All(r => r)); }
/// <summary> Combines numbers and fruits </summary> /// <param name="numbers">string sequience of numbers</param> /// <param name="fruits">string sequence of fruits</param> /// <returns> /// Returns new sequence of merged number and fruit items /// </returns> /// <example> /// {"one","two","three"}, {"apple", "bananas","pineapples"} => {"one apple","two bananas","three pineapples"} /// {"one"}, {"apple", "bananas","pineapples"} => {"one apple"} /// {"one","two","three"}, {"apple", "bananas" } => {"one apple","two bananas"} /// {"one","two","three"}, { } => { } /// { }, {"apple", "bananas" } => { } /// </example> public IEnumerable <string> CombineNumbersAndFruits(IEnumerable <string> numbers, IEnumerable <string> fruits) { // TODO : Implement CombinesNumbersAndFruits return(numbers.Zip(fruits, (num, fru) => string.Format("{0} {1}", num, fru))); }
/// <summary> /// Calcuates the sum of two vectors: /// (x1, x2, ..., xn) + (y1, y2, ..., yn) = (x1+y1, x2+y2, ..., xn+yn) /// </summary> /// <param name="vector1">source vector 1</param> /// <param name="vector2">source vector 2</param> /// <returns> /// Returns the sum of two vectors /// </returns> /// <example> /// { 1, 2, 3 } + { 10, 20, 30 } => { 11, 22, 33 } /// { 1, 1, 1 } + { -1, -1, -1 } => { 0, 0, 0 } /// </example> public IEnumerable <int> GetSumOfVectors(IEnumerable <int> vector1, IEnumerable <int> vector2) { // TODO : Implement GetSumOfVectors return(vector1.Zip(vector2, (x, y) => x + y)); }
private static IList <ColumnMappingBuilder> CreateMappings(IEnumerable <EdmProperty> columns, params string[] propertyNames) { var baseType = CreateMockType("Base").Object; return(columns.Zip(propertyNames, (t, p) => CreateColumnMapping(CreateMockType(p + "Type", baseType).Object, p, t)).ToList()); }
private (string Msg, AlertType LogType) AddWords(Book bookToAdd, Language from, Language to, IEnumerable <string> words, IEnumerable <string> translations, IEnumerable <string> descriptions = null) { var count1 = words?.Count(); var count2 = translations?.Count(); var count3 = descriptions?.Count(); var isInputCorrect = count1 != null && count1 == count2 && (count1 == count3 || count3 == null); if (!isInputCorrect) { return("Incorrect word format", AlertType.Error); } IEnumerable <(string Word, string Definition, string Description)> collection = descriptions != null? words.Zip(translations, (w, d) => (w, d)).Zip(descriptions, (tuple, ds) => (tuple.w, tuple.d, ds)) : words.Zip(translations, (w, d) => (w, d, "")); CreateTranslations(bookToAdd, from, to, collection); return($"Successfully added {count1} words!", AlertType.Success); }
public async Task <IActionResult> Index( int page = 1, int pageSize = 10, string mode = "", string region = "" ) { // Create the view model with initial values we already know. var vm = new LeaderboardViewModel { Page = page, PageSize = pageSize, SelectedMode = mode, SelectedRegion = region, GameModes = new List <string>() { "Solo", "Duo", "Trio" }, GameRegions = new List <string>() { "Milky Way", "Andromeda", "Pinwheel", "NGC 1300", "Messier 82", } }; try { // Fetch the total number of results in the background. var countItemsTask = _dbRespository.CountScoresAsync(mode, region); // Fetch the scores that match the current filter. IEnumerable <Score> scores = await _dbRespository.GetScoresAsync(mode, region, page, pageSize); // Wait for the total count. vm.TotalResults = await countItemsTask; // Fetch the user profile for each score. // This creates a list that's parallel with the scores collection. var profiles = new List <Task <Profile> >(); foreach (var score in scores) { profiles.Add(_dbRespository.GetProfileAsync(score.ProfileId)); } Task <Profile> .WaitAll(profiles.ToArray()); // Combine each score with its profile. vm.Scores = scores.Zip(profiles, (score, profile) => new ScoreProfile { Score = score, Profile = profile.Result }); return(View(vm)); } catch (Exception) { return(View(vm)); } }
/// <summary> /// Creates a map from telems to uelems. telems and uelems must have the same number of elements. /// </summary> /// <param name="telems"></param> /// <param name="uelems"></param> /// <typeparam name="T"></typeparam> /// <typeparam name="U"></typeparam> /// <returns></returns> public static Dictionary <T, U> Map <T, U>(IEnumerable <T> telems, IEnumerable <U> uelems) { return(telems.Zip(uelems).ToDictionary(x => x.Item1, x => x.Item2)); }
public CharRNNModel(CharRNNModelParameters parameters, bool training = true) { this.parameters = parameters ?? throw new ArgumentNullException(nameof(parameters)); if (!training) { this.parameters.BatchSize = 1; this.parameters.SeqLength = 1; } if (!ModelTypeToCellFunction.TryGetValue(parameters.ModelType, out this.cellFactory)) { throw new NotSupportedException(parameters.ModelType.ToString()); } for (int i = 0; i < parameters.LayerCount; i++) { RNNCell cell = this.cellFactory(parameters.RNNSize); if (training && (parameters.KeepOutputProbability < 1 || parameters.KeepInputProbability < 1)) { cell = new DropoutWrapper(cell, input_keep_prob: parameters.KeepInputProbability, output_keep_prob: parameters.KeepOutputProbability); } this.cells.Add(cell); } this.rnn = new MultiRNNCell(this.cells, state_is_tuple: true); this.inputData = tf.placeholder(tf.int32, new TensorShape(parameters.BatchSize, parameters.SeqLength)); this.targets = tf.placeholder(tf.int32, new TensorShape(parameters.BatchSize, parameters.SeqLength)); this.initialState = this.rnn.zero_state(parameters.BatchSize, tf.float32); Variable softmax_W = null, softmax_b = null; new variable_scope("rnnlm").UseSelf(_ => { softmax_W = tf.get_variable("softmax_w", new TensorShape(parameters.RNNSize, parameters.VocabularySize)); softmax_b = tf.get_variable("softmax_b", new TensorShape(parameters.VocabularySize)); }); Variable embedding = tf.get_variable("embedding", new TensorShape(parameters.VocabularySize, parameters.RNNSize)); Tensor input = tf.nn.embedding_lookup(embedding, this.inputData); // dropout beta testing: double check which one should affect next line if (training && parameters.KeepOutputProbability < 1) { input = tf.nn.dropout(input, parameters.KeepOutputProbability); } PythonList <Tensor> inputs = tf.split(input, parameters.SeqLength, axis: 1); inputs = inputs.Select(i => (Tensor)tf.squeeze(i, axis: 1)).ToPythonList(); dynamic Loop(dynamic prev, dynamic _) { prev = tf.matmul(prev, softmax_W) + softmax_b; var prevSymbol = tf.stop_gradient(tf.argmax(prev, 1)); return(tf.nn.embedding_lookup(embedding, prevSymbol)); } var decoder = tensorflow.contrib.legacy_seq2seq.legacy_seq2seq.rnn_decoder_dyn( decoder_inputs: inputs, initial_state: this.initialState.Items(), cell: this.rnn, loop_function: training ? null : PythonFunctionContainer.Of(new Func <dynamic, dynamic, dynamic>(Loop)), scope: "rnnlm"); var outputs = decoder.Item1; var lastState = (seq2seqState)decoder.Item2; dynamic contatenatedOutputs = tf.concat(outputs, 1); var output = tensorflow.tf.reshape(contatenatedOutputs, new[] { -1, parameters.RNNSize }); this.logits = tf.matmul(output, softmax_W) + softmax_b; this.probs = tf.nn.softmax(new[] { this.logits }); this.loss = tensorflow.contrib.legacy_seq2seq.legacy_seq2seq.sequence_loss_by_example_dyn( logits: new[] { this.logits }, targets: new[] { tf.reshape(this.targets, new[] { -1 }) }, weights: new[] { tf.ones(new[] { parameters.BatchSize *parameters.SeqLength }) }); Tensor cost = null; new name_scope("cost").UseSelf(_ => { cost = tf.reduce_sum(this.loss) / parameters.BatchSize / parameters.SeqLength; }); this.cost = cost; this.finalState = lastState; this.learningRate = new Variable(0.0, trainable: false); var tvars = tf.trainable_variables(); IEnumerable <object> grads = tf.clip_by_global_norm(tf.gradients(this.cost, tvars), parameters.GradientClip).Item1; AdamOptimizer optimizer = null; new name_scope("optimizer").UseSelf(_ => optimizer = new AdamOptimizer(this.learningRate)); this.trainOp = optimizer.apply_gradients(grads.Zip(tvars, (grad, @var) => (dynamic)(grad, @var))); tf.summary.histogram("logits", new[] { this.logits }); tf.summary.histogram("loss", new[] { this.loss }); tf.summary.histogram("train_loss", new[] { this.cost }); }
//public bool Matches(string functionName, IEnumerable<Type> argumentTypes) //{ // return functionName == Name && argumentTypes.Count() == ArgumentTypes.Count() && // argumentTypes.Zip(ArgumentTypes, (call, sig) => Typecasts.CanCastTo(call,sig)).All(r => r == true); //} public bool DynamicMatches(string functionName, IEnumerable <object> arguments) { return(functionName == Name && arguments.Count() == ArgumentTypes.Count() && arguments.Zip(ArgumentTypes, (call, sig) => Typecasts.CanCastTo(call, sig)).All(r => r == true)); }
/// <summary> /// Generate a sample sequence by sampling a function at the provided point sequence. /// </summary> public static IEnumerable <T> Map2Sequence <TA, TB, T>(IEnumerable <TA> pointsA, IEnumerable <TB> pointsB, Func <TA, TB, T> map) { return(pointsA.Zip(pointsB, map)); }
public IEnumerable <TargetSupportedIn> GetMatchingTargetsAndSupportedVersions(IEnumerable <Version> usedVersions) { var zipped = usedVersions.Zip(ReportingResult.Targets, (a, b) => { return(new TargetSupportedIn(b, a)); }); return(zipped); }
public static Task <IEnumerable <TResult> > Zip <TSource, TSecond, TResult>(this IEnumerable <TSource> @this, Task <IEnumerable <TSecond> > second, Func <TSource, TSecond, Task <TResult> > func) { return(@this.Zip(second, func)); }
private bool AreSubnetsEqual(IEnumerable <Subnet> subnets1, IEnumerable <Subnet> subnets2) { var subnetCollection = subnets1.Zip(subnets2, (s1, s2) => new { subnet1 = s1, subnet2 = s2 }); return(subnetCollection.All(subnets => AreSubnetsEqual(subnets.subnet1, subnets.subnet2))); }
public static IEnumerable <double> Times(this IEnumerable <double> xs, IEnumerable <double> ys) { return(xs.Zip(ys, (x, y) => x * y)); }
public IEnumerable <Guid> AddItem(IEnumerable <Product> products, IEnumerable <float> amounts) { return(products.Zip(amounts, (p, a) => AddItem(p, a))); }
public void NotNormalOrderedTest(bool pass, int nOrbitals, IEnumerable <int> ca, IEnumerable <int> idx) { var ladderOperators = ca.Zip(idx, (a, b) => (a == 0 ? RaisingLowering.d : RaisingLowering.u, (int)b)).ToLadderSequence(); Assert.Throws <ArgumentException>(() => new HermitianFermionTerm(ladderOperators)); }
/// <summary> /// Calcuates the product of two vectors: /// (x1, x2, ..., xn) + (y1, y2, ..., yn) = x1*y1 + x2*y2 + ... + xn*yn /// </summary> /// <param name="vector1">source vector 1</param> /// <param name="vector2">source vector 2</param> /// <returns> /// Returns the product of two vectors /// </returns> /// <example> /// { 1, 2, 3 } * { 1, 2, 3 } => 1*1 + 2*2 + 3*3 = 14 /// { 1, 1, 1 } * { -1, -1, -1 } => 1*-1 + 1*-1 + 1*-1 = -3 /// { 1, 1, 1 } * { 0, 0, 0 } => 1*0 + 1*0 +1*0 = 0 /// </example> public int GetProductOfVectors(IEnumerable <int> vector1, IEnumerable <int> vector2) { // TODO : Implement GetProductOfVectors return(vector1.Zip(vector2, (x, y) => x * y).Sum()); }
public static IEnumerable <double> Add(this IEnumerable <double> xs, IEnumerable <double> ys) { return(xs.Zip(ys, (x, y) => x + y)); }
private static bool ShouldBeEqual(IEnumerable<bool> isA, IEnumerable<bool> usedInEquals) { return isA.Zip(usedInEquals, (x, inEqual) => (inEqual && x) || !inEqual).All(x => x); }
public int Compare(IEnumerable <int> x, IEnumerable <int> y) { // TODO: throw ArgumentNullException return(x.Zip(y, (xItem, yItem) => xItem.CompareTo(yItem)) .Where(c => c != 0).FirstOrDefault()); }
private static IEnumerable <PlanSum> GetPlanSumsInScope(Patient patient, IEnumerable <string> planSumsInScopeCourseIds, IEnumerable <string> planSumsInScopeIds) => planSumsInScopeCourseIds?.Zip(planSumsInScopeIds ?? new string[0], (courseId, planSumId) => GetPlanSum(patient, courseId, planSumId));
public async Task <IActionResult> Index( int page = 1, int pageSize = 10, string mode = "", string region = "" ) { var configuration = new ConfigurationBuilder() .SetBasePath(Environment.CurrentDirectory) .AddEnvironmentVariables() .AddJsonFile("appsettings.json", true) .Build(); var configurationTest = configuration["TitleValue"]; // Create the view model with initial values we already know. var vm = new LeaderboardViewModel { Page = page, PageSize = pageSize, SelectedMode = mode, SelectedRegion = region, GameModes = new List <string>() { "Solo", "Duo", "Trio", configurationTest ?? string.Empty }, GameRegions = new List <string>() { "Milky Way", "Andromeda", "Pinwheel", "NGC 1300", "Messier 82", } }; try { // Form the query predicate. // This expression selects all scores that match the provided game // mode and region (map). // Select the score if the game mode or region is empty. Expression <Func <Score, bool> > queryPredicate = score => (string.IsNullOrEmpty(mode) || score.GameMode == mode) && (string.IsNullOrEmpty(region) || score.GameRegion == region); // Fetch the total number of results in the background. var countItemsTask = _scoreRepository.CountItemsAsync(queryPredicate); // Fetch the scores that match the current filter. IEnumerable <Score> scores = await _scoreRepository.GetItemsAsync( queryPredicate, // the predicate defined above score => score.HighScore, // sort descending by high score page - 1, // subtract 1 to make the query 0-based pageSize ); // Wait for the total count. vm.TotalResults = await countItemsTask; // Set previous and next hyperlinks. if (page > 1) { vm.PrevLink = $"/?page={page - 1}&pageSize={pageSize}&mode={mode}®ion={region}#leaderboard"; } if (vm.TotalResults > page * pageSize) { vm.NextLink = $"/?page={page + 1}&pageSize={pageSize}&mode={mode}®ion={region}#leaderboard"; } // Fetch the user profile for each score. // This creates a list that's parallel with the scores collection. var profiles = new List <Task <Profile> >(); foreach (var score in scores) { profiles.Add(_profileRespository.GetItemAsync(score.ProfileId)); } Task <Profile> .WaitAll(profiles.ToArray()); // Combine each score with its profile. vm.Scores = scores.Zip(profiles, (score, profile) => new ScoreProfile { Score = score, Profile = profile.Result }); return(View(vm)); } catch (Exception) { return(View(vm)); } }