Beispiel #1
0
        void AssertEquals(IList<IList<int>> firstList, IList<IList<int>> secondList)
        {
            Assert.AreEqual(firstList.Count(), secondList.Count());

            firstList = firstList
                .OrderBy(list => list[0])
                .ThenBy(list => list[1])
                .ThenBy(list => list[2])
                .ToList();

            secondList = secondList
                .OrderBy(list => list[0])
                .ThenBy(list => list[1])
                .ThenBy(list => list[2])
                .ToList();

            Assert.IsTrue(firstList
                .Zip(secondList
                    , (firstSubList, secondeSubList) =>
                        firstSubList
                            .Zip(secondeSubList
                                , (first, second) =>
                                    first == second)
                            .All(item => item))
                .All(item => item)); ;
        }
Beispiel #2
0
 private static void CompareEvents(IList<Events.Base> events1, IList<Events.Base> events2)
 {
     Assert.That(events1.Count, Is.EqualTo(events2.Count));
     foreach (var pair in events1.Zip(events2, Tuple.Create))
     {
         Assert.That(pair.Item1, Is.TypeOf(pair.Item2.GetType()));
         var nodeEvent1 = pair.Item1 as Events.Node;
         if (nodeEvent1 == null)
             continue;
         var nodeEvent2 = (Events.Node) pair.Item2;
         Assert.That(nodeEvent1.Anchor, Is.EqualTo(nodeEvent2.Anchor));
         var cstart1 = nodeEvent1 as Events.CollectionStart;
         if (cstart1 != null)
         {
             Assert.That(cstart1.Tag, Is.EqualTo(((Events.CollectionStart)nodeEvent2).Tag));
             continue;
         }
         var scalar1 = nodeEvent1 as Events.Scalar;
         if (scalar1 == null)
             continue;
         var scalar2 = (Events.Scalar) nodeEvent2;
         if (scalar1.ImplicitLevel != ScalarImplicitLevel.Plain &&
             scalar2.ImplicitLevel != ScalarImplicitLevel.Plain)
             Assert.That(scalar1.Tag, Is.EqualTo(scalar2.Tag));
         Assert.That(scalar1.Value, Is.EqualTo(scalar2.Value));
     }
 }
        void AssertEquals(IList<int> subject, IList<int> @object)
        {
            Assert.AreEqual(subject.Count, @object.Count);

            Assert.IsTrue(subject
                .Zip(@object
                    , (first, second) => first == second)
                .All(item => item));
        }
Beispiel #4
0
        public override bool DeepEquals(ISymbolStore otherStore)
        {
            var other = otherStore as SymbolServer;

            return(other != null && IsCache == other.IsCache &&
                   _stores.Count == other._stores.Count &&
                   _stores.Zip(other._stores, (a, b) => Tuple.Create(a, b))
                   .All(x => x.Item1.DeepEquals(x.Item2)));
        }
        /// <summary>
        /// Gets the OData <see cref="ETag"/> from the given request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="entityTagHeaderValue">The entity tag header value.</param>
        /// <returns>The parsed <see cref="ETag"/>.</returns>
        public static ETag GetETag(this HttpRequestMessage request, EntityTagHeaderValue entityTagHeaderValue)
        {
            if (request == null)
            {
                throw Error.ArgumentNull("request");
            }

            if (entityTagHeaderValue != null)
            {
                if (entityTagHeaderValue.Equals(EntityTagHeaderValue.Any))
                {
                    return(new ETag {
                        IsAny = true
                    });
                }

                HttpConfiguration configuration = request.GetConfiguration();
                if (configuration == null)
                {
                    throw Error.InvalidOperation(SRResources.RequestMustContainConfiguration);
                }

                // get the etag handler, and parse the etag
                IDictionary <string, object> properties =
                    configuration.GetETagHandler().ParseETag(entityTagHeaderValue) ?? new Dictionary <string, object>();
                IList <object> parsedETagValues = properties.Select(property => property.Value).AsList();

                // get property names from request
                ODataPath     odataPath = request.ODataProperties().Path;
                IEdmModel     model     = request.ODataProperties().Model;
                IEdmEntitySet entitySet = odataPath.NavigationSource as IEdmEntitySet;
                if (model != null && entitySet != null)
                {
                    IList <string> concurrencyPropertyNames =
                        model.GetConcurrencyProperties(entitySet).OrderBy(c => c.Name).Select(c => c.Name).AsList();
                    ETag etag = new ETag();

                    if (parsedETagValues.Count != concurrencyPropertyNames.Count)
                    {
                        etag.IsWellFormed = false;
                    }

                    IEnumerable <KeyValuePair <string, object> > nameValues = concurrencyPropertyNames.Zip(
                        parsedETagValues,
                        (name, value) => new KeyValuePair <string, object>(name, value));
                    foreach (var nameValue in nameValues)
                    {
                        etag[nameValue.Key] = nameValue.Value;
                    }

                    return(etag);
                }
            }

            return(null);
        }
        private static double Distance(IList<int> aChromosone, IEnumerable<int> anotherChromosone)
        {
            var numberOfIdenticalBits =
                aChromosone
                    .Zip(anotherChromosone,
                        (x, y) => new { first = x, second = y })
                    .Count(tuple => tuple.first == tuple.second);

            return numberOfIdenticalBits / (double)aChromosone.Count();
        }
Beispiel #7
0
 static byte[] ParseContent(Stream stream, IEnumerable <long> offsets)
 {
     using var content = new MemoryStream();
     foreach (var(length, offset) in fields.Zip(offsets, (l, o) => (l, o)))
     {
         stream.Position = offset;
         stream.CopyTo(content, length);
     }
     return(content.ToArray());
 }
        /// <typeparam name="T">The data type of the Matrix. It can be either: double, float, Complex, or Complex32.</typeparam>
        public static void Write <T>(string filePath, IList <Matrix <T> > matrices, IList <string> names)
            where T : struct, IEquatable <T>, IFormattable
        {
            if (matrices.Count != names.Count)
            {
                throw new ArgumentException("Each matrix must have a name. Number of matrices must equal to the number of names.");
            }

            Store(filePath, matrices.Zip(names, Pack));
        }
Beispiel #9
0
        private void calcSubTotals()
        {
            // Using Zip to combine quantities and unit prices. Result is stored in subTotals list
            var results = quantities.Zip(unitPrices, (a, b) => a * b);

            foreach (var result in results)
            {
                subTotals.Add((double)result);
            }
        }
 public Substitution(IList <LVar> fvs, IList <ITerm> vts)
     : this()
 {
     Debug.Assert(fvs.Count == vts.Count);
     Debug.Assert(fvs.Zip(vts, (x, y) => new Tuple <LVar, ITerm>(x, y)).All(t => t.Item1.type.isEquivalent(t.Item2.type)));
     for (var i = 0; i < fvs.Count; i++)
     {
         termMap[fvs[i]] = vts[i];
     }
 }
 protected virtual void ShowMashup(IList <object> values)
 {
     shownValues = values;
     foreach (var pair in values.Zip(
                  Mashups.Select(xs => (DialogTypeVisualizer)xs.Visualizer).Prepend(this),
                  (value, visualizer) => Tuple.Create(value, visualizer)))
     {
         pair.Item2.Show(pair.Item1);
     }
 }
        public void TestNews()
        {
            try
            {
                driver.Url = "https://news.ycombinator.com/";
                string actual = driver.Url;
                driver.Manage().Window.Maximize();
                Thread.Sleep(2000);
                IList <IWebElement>      header = driver.FindElements(By.ClassName("storylink"));
                IList <IWebElement>      point  = driver.FindElements(By.ClassName("score"));
                Dictionary <string, int> dict   = new Dictionary <string, int>();
                List <string>            mylist = new List <string>();
                List <int> pointlist            = new List <int>();
                foreach (var items in header.Zip(point, (a, b) => new { A = a, B = b }))
                {
                    var    a    = items.A;
                    var    b    = items.B;
                    string text = a.Text;
                    mylist.Add(text);
                    Console.WriteLine(text);
                    Console.WriteLine(b.Text);
                }

                var mostRepeatedWord = mylist.SelectMany(x => x.Split(new[] { " " },
                                                                      StringSplitOptions.RemoveEmptyEntries))
                                       .GroupBy(x => x).OrderByDescending(x => x.Count())
                                       .Select(x => x.Key).FirstOrDefault();
                Console.WriteLine("most repeated word" + "---->" + mostRepeatedWord);


                foreach (var items in point)
                {
                    string text         = items.Text;
                    string filteredText = text.Replace("points", " ");
                    pointlist.Add(int.Parse(filteredText));
                }

                for (int i = 0; i < mylist.Count; i++)
                {
                    dict.Add(mylist[i], pointlist[i]);
                }
                Console.WriteLine("max points and headlines" + "-->" + dict.Keys.Max() + "----->" + dict.Values.Max());
                string expectedUrl = ("https://news.ycombinator.com/");
                Assert.AreEqual(expectedUrl, actual);
                Thread.Sleep(3000);
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception.Message);
            }
            finally
            {
                driver.Quit();
            }
        }
Beispiel #13
0
        public UnitsProvider(IList <string> vkKeys, IProxyProvider proxyProvider, IList <string> userAgents)
        {
            if (!vkKeys.Any() || !userAgents.Any())
            {
                throw new Exception("Inproper initialization.");
            }

            _pool.AddRange(vkKeys.Zip(proxyProvider.RetrieveProxyList(), (x, y) => new UnitRequestor {
                Proxy = y, VkKey = x, UserAgent = userAgents[_rnd.Next(userAgents.Count)]
            }));
        }
Beispiel #14
0
        public List <List <SlamPoint> > Compute(IList <SlamPoint> items)
        {
            var detector = new PlanesDetector();
            var indexes  = detector.FindPlanes(new PointsList(items.Select(ToNative)), _settings);

            return(items.Zip(indexes, (point, i) => (point, i))
                   .Where(z => z.i != 0)
                   .GroupBy(v => v.i)
                   .Select(g => g.Select(v => v.point).ToList())
                   .ToList());
        }
Beispiel #15
0
 private bool CompareState()
 {
     foreach (var i in state.Zip(container.items, (a, b) => new { a, b }))
     {
         if (!ItemsEqual(i.a, i.b))
         {
             return(false);
         }
     }
     return(true);
 }
Beispiel #16
0
        public override void Load(TagCompound tag)
        {
            damage   = tag.GetInt("damage");
            itemType = tag.GetString("itemType");
            parts    = tag.GetList <string>("parts").ToList();
            IList <string> effectKeys   = tag.GetList <string>("effectKeys");
            IList <int>    effectValues = tag.GetList <int>("effectValues");

            effects = effectKeys.Zip(effectValues, (k, v) => new { k, v }).ToDictionary(x => x.k, x => x.v);
            SetDefaults();
        }
Beispiel #17
0
    public void UpdateContactPoints(IList <Vector3> contactPoints)
    {
        // PERF: THIS

        if (contactPoints.Count < 2)
        {
            _lineRenderer.enabled = false;
            return;
        }

        _lineRenderer.enabled = true;

        var segmentLengths = contactPoints.Zip(contactPoints.Skip(1), Vector3.Distance).ToArray();
        var totalLen       = segmentLengths.Sum();

        var stress = Mathf.SmoothStep(0f, 1f, Mathf.Clamp01((totalLen - RestLength) / (MaxVisualStretchLength - RestLength)));

        var lenAcc    = 0.0f;
        var keyFrames = segmentLengths.Select((sLen, sId) =>
        {
            lenAcc       += sLen;
            var kfTime    = lenAcc / totalLen;
            var sEndPoint = contactPoints[sId + 1];
            return(new[] { new Keyframe(kfTime, sEndPoint.x), new Keyframe(kfTime, sEndPoint.y), new Keyframe(kfTime, sEndPoint.z), });
        }).Prepend(new [] { new Keyframe(0, contactPoints[0].x), new Keyframe(0, contactPoints[0].y), new Keyframe(0, contactPoints[0].z) }).ToArray();

        // Why the hell can't we avoid ToArray calls here??? #rigged #iwantrust
        var xPosCurve = new AnimationCurve(keyFrames.Select(kfs => kfs[0]).ToArray());
        var yPosCurve = new AnimationCurve(keyFrames.Select(kfs => kfs[1]).ToArray());
        var zPosCurve = new AnimationCurve(keyFrames.Select(kfs => kfs[2]).ToArray());

        for (int i = 0; i < RenderPoints; i++)
        {
            var t = (float)i / (float)(RenderPoints - 1);

            _worldPoints[i] = new Vector3(xPosCurve.Evaluate(t), yPosCurve.Evaluate(t), zPosCurve.Evaluate(t));

            _widthKeyframes[i] = new Keyframe(t, BaseThiccness.Evaluate(t) * Mathf.Lerp(1f, StressThiccness.Evaluate(t), stress));
        }

        _lineRenderer.widthCurve = new AnimationCurve(_widthKeyframes);

        var midpointColor = Color.Lerp(RestColor, StressColor, stress);

        _colorKeys[1] = new GradientColorKey(midpointColor, 0.5f);
        _alphaKeys[1] = new GradientAlphaKey(midpointColor.a, 0.5f);
        var gradient = new Gradient();

        gradient.colorKeys          = _colorKeys;
        gradient.alphaKeys          = _alphaKeys;
        _lineRenderer.colorGradient = gradient;

        _lineRenderer.SetPositions(_worldPoints.ToArray());
    }
Beispiel #18
0
        public void CommitInventory()
        {
            int settingOffset            = Properties.Settings.Default.activeSlot;
            IList <InventoryArea> source = (IList <InventoryArea>)((ListCollectionView)Application.Current.Resources["InventoryAreaCollectionView"])
                                           .SourceCollection;

            foreach ((var Area, var Properties) in source.Zip(InventoryArea.AreaSet, (i1, i2) => (i1, i2)))
            {
                Area.Serialize().ToArray().CopyTo(saveFile.data, PlayerOffset[settingOffset] + Properties.localoffset);
            }
        }
Beispiel #19
0
        public void Run()
        {
            // get results
            IList <Result> exactResults  = null;
            var            sw1           = Stopwatch.StartNew();
            var            exactRunCount = 0;

            while (sw1.ElapsedMilliseconds < 10)
            {
                ++exactRunCount;
                exactResults = instances.Select(instance => exactSolver.Solve(instance)).ToList().AsReadOnly();
            }

            sw1.Stop();

            IList <Result> results  = Enumerable.Empty <Result>().ToArray();
            var            sw2      = Stopwatch.StartNew();
            var            runCount = 0;

            while (sw2.ElapsedMilliseconds < 5000)
            {
                ++runCount;
                var newResults = instances.Select(instance => solver.Solve(instance)).ToList().AsReadOnly();
                results = results.Concat(newResults).ToArray();
            }

            sw1.Stop();

            // handle all results
            var relativeDivergences =
                exactResults
                .Zip(results, (er, r) => new { er, r })
                .Select(i => (i.er.Price - i.r.Price) / (double)i.er.Price).ToList().AsReadOnly();
            var averageRelativeDivergence = relativeDivergences.Average(x => x);
            var maxRelativeDivergence     = relativeDivergences.Max(x => x);

            ////var time1 = new TimeSpan((long)(sw1.ElapsedMilliseconds * 10000 / (double)exactRunCount));
            var time2 = new TimeSpan((long)(sw2.ElapsedMilliseconds * 10000 / (double)runCount));

            ////foreach (var x in exactResults
            ////        .Zip(results, (er, r) => new { a = er.Price, b = r.Price }))
            ////{
            ////    Console.WriteLine($"{x.a} - {x.b} = {x.a - x.b}");
            ////}

            //Console.WriteLine();
            Console.WriteLine($"Average relative divergence: {averageRelativeDivergence}");
            Console.WriteLine($"    Max relative divergence: {maxRelativeDivergence}");
            ////Console.WriteLine($"             Exact Run Time: {time1}\t(run {exactRunCount} times)");
            Console.WriteLine($"                   Run Time: {time2}\t(run {runCount} times)");
            ////Console.WriteLine($"                      Ratio: {time1.Ticks / (double)time2.Ticks:P2}");
            Console.WriteLine();
        }
Beispiel #20
0
        /// <summary>
        /// This method is used to combine two list name list and address list into a single list
        /// </summary>
        /// <returns>single list of company data</returns>
        private IList <string> Result()
        {
            foreach (var word in _mCompanyNames.Zip(_mCompanyAddress, (companyNamesObj, companyAddressObj) => new { companyNamesObj, companyAddressObj }))
            {
                CompanyData.Add(_mSerialNum + ". " + "Company Name =>" + word.companyNamesObj);
                CompanyData.Add("Address =>" + word.companyAddressObj + "\n");

                _mSerialNum++;
            }

            return(CompanyData);
        }
Beispiel #21
0
 public static bool IsEqualTo <T>(this IList <T> list, IList <T> other)
 {
     if (list == null || other == null)
     {
         throw new ArgumentNullException();
     }
     if (list.Count != other.Count)
     {
         return(false);
     }
     return(list.Zip(other, (v1, v2) => v1.Equals(v2)).All(x => x));
 }
Beispiel #22
0
        private void AssertRecordsAreEqual(IList<Record> actualRecords, params string[] expectedRecords)
        {
            Assert.That(actualRecords, Is.Not.Null, "actualRecords");
            Assert.That(actualRecords.Count, Is.EqualTo(expectedRecords.Length));

            IEnumerable<object> expectedRecordsAsRecords = expectedRecords.Select(ParseRecord);

            var pairs = actualRecords.Zip(expectedRecordsAsRecords, (actual, expected) => new {Actual = actual, Expected = expected});
            foreach (var pair in pairs) {
                Assert.That(pair.Actual, Is.EqualTo(pair.Expected));
            }
        }
        private IList <int> MACrosses(IList <Rate> rates, int frame)
        {
            var rates1  = rates.Zip(rates.Skip(1), (f, s) => new { f = f.PriceAvg, s = s.PriceAvg, ma = f.PriceCMALast }).ToArray();
            var crosses = new int[0].ToConcurrentQueue();

            Partitioner.Create(Enumerable.Range(0, rates.Count - frame).ToArray(), true).AsParallel()
            .ForAll(i => {
                var rates2 = rates1.ToArray(frame);
                Array.Copy(rates1, i, rates2, 0, frame);
                crosses.Enqueue(rates2.Count(r => r.f.Sign(r.ma) != r.s.Sign(r.ma)));
            });
            return(crosses.ToArray());
        }
Beispiel #24
0
        public static double Covariance(IList <double> seqX, IList <double> seqY) // "Pearson" covariance
        {
            Guard.NotNull(seqX, nameof(seqX));
            Guard.NotNull(seqY, nameof(seqY));
            Guard.Requires(seqX.Any(), $"The sequence {nameof(seqX)} must not be empty.");
            Guard.Requires(seqY.Any(), $"The sequence {nameof(seqY)} must not be empty.");
            Guard.Requires(seqX.Count == seqY.Count, $"The count of {nameof(seqX)} ({seqX.Count}) must be equal to the count of {nameof(seqY)} ({seqY.Count}).");

            double meanX = ArithmeticMean(seqX);
            double meanY = ArithmeticMean(seqY);

            return(seqX.Zip(seqY, (x, y) => (x - meanX) * (y - meanY)).Sum() / seqX.Count);
        }
 public static ModelShip FromCsvRecord(IList<string> header, IList<string> row)
 {
     var keyedRow = header.Zip(row, (h, r) => new { h, r }).ToDictionary(a => a.h, a => a.r);
     return new ModelShip()
     {
         No = keyedRow["No"].ToInt32(),
         ClassOfShip = keyedRow["ClassOfShip"],
         Name = keyedRow["Name"],
         TaxIncludedPrice = keyedRow["TaxIncludedPrice"].ToInt32OrDefault(System.Globalization.NumberStyles.Currency, -1),
         Price = keyedRow["Price"].ToInt32OrDefault(System.Globalization.NumberStyles.Currency, -1),
         Maker = keyedRow["Maker"]
     };
 }
Beispiel #26
0
        protected override void OnLoad(EventArgs e)
        {
            var view = new PlotView
            {
                Size                 = Size,
                Dock                 = DockStyle.Fill,
                PanCursor            = Cursors.Hand,
                ZoomHorizontalCursor = Cursors.SizeWE,
                ZoomRectangleCursor  = Cursors.SizeNWSE,
                ZoomVerticalCursor   = Cursors.SizeNS
            };

            Controls.Add(view);

            var model = new PlotModel {
                Title = "Struna"
            };

            void AddSerie(string title, DataPoint[] p, OxyColor?color = null)
            {
                var serie = new LineSeries {
                    Title = title
                };

                if (color.HasValue)
                {
                    serie.Color = color.Value;
                }
                serie.Points.AddRange(p);
                model.Series.Add(serie);
            }

            AddSerie("", new DataPoint[] { new DataPoint(x[0], 0), new DataPoint(x[x.Count - 1], 0) }, OxyColors.Black);
            AddSerie("f", x.Zip(y, (x, y) => new DataPoint(x, func(x))).ToArray());
            AddSerie("Metoda siti", x.Zip(y, (x, y) => new DataPoint(x, -y)).ToArray());
            AddSerie("Analyticke reseni", x.Select(x => new DataPoint(x, doubleIntegrateFunc(x))).ToArray());

            view.Model = model;
        }
Beispiel #27
0
        private void Append(IList <LogEvent> logEvents)
        {
            lock (_logEventsLock)
            {
                var needSort = logEvents.Zip(logEvents.Skip(1), (a, b) => a.TimeStamp < b.TimeStamp).Contains(false);
                if (needSort)
                {
                    logEvents = logEvents.OrderBy(logEvent => logEvent.TimeStamp).ToList();
                }

                _logEvents.Add(logEvents);
            }
        }
Beispiel #28
0
        private static void AssertCollectionsAreEqual <T>(IList <T> expected, IList <T> actual)
        {
            // The collection equality assertion in XUnit Assert.Equal doesn't print a great
            // error message if the list is large. It truncates the list and prints ellipses.
            //
            // This method asserts the equality of each item one by one, providing better error
            // messages.

            Assert.All(
                expected.Zip(actual),
                ((T expected, T actual)pair) => Assert.Equal(pair.expected, pair.actual));
            Assert.Equal(expected.Count, actual.Count);
        }
Beispiel #29
0
        public IEnumerator <InternalAmount> GetEnumerator()
        {
            var ziped = list1.Zip(list2, (e1, e2) => new { e1, e2 }).Zip(list3, (e1e2, e3) => new InternalAmount {
                A = e1e2.e1,
                B = e1e2.e2,
                C = e3,
            });

            foreach (InternalAmount e in ziped)
            {
                yield return(e);
            }
        }
Beispiel #30
0
 /// <summary>
 /// Получить элементы подписей из базы по их идентификационным номерам
 /// </summary>
 private IResultAppCollection <IStampSignature> GetStampSignaturesByIds(IList <IStampSignature> stampSignatures) =>
 new ResultAppCollection <IStampSignature>(stampSignatures).
 ResultValueOk(_ => stampSignatures.Select(signatureStamp => new SignatureFileRequest(signatureStamp.SignatureLibrary.PersonId,
                                                                                      signatureStamp.IsVertical))).
 ResultValueOkBind(personIds => SignaturesSearching.GetSignaturesByIds(personIds)).
 ResultValueContinue(signaturesFile => signaturesFile.Count == stampSignatures.Count,
                     okFunc: signaturesFile => signaturesFile,
                     badFunc: signaturesFile => new ErrorApplication(ErrorApplicationType.SignatureNotFound,
                                                                     "Количество подписей в файле не совпадает с загруженным из базы данных")).
 ResultValueOk(signaturesFile =>
               stampSignatures.Zip(signaturesFile,
                                   (signatureStamp, signatureFile) => signatureStamp.InsertSignature(signatureFile))).
 ToResultCollection();
Beispiel #31
0
        public static List <ConceptApplication> FromDatabaseObjects(IList <DatabaseObject> databaseObjects)
        {
            var conceptApplications = databaseObjects.Select(o => new ConceptApplication(o)).ToList();

            var pairs = databaseObjects.Zip(conceptApplications, (databaseObject, conceptApplication) => new { databaseObject, conceptApplication });
            var applicationByObject = pairs.ToDictionary(pair => pair.databaseObject, pair => pair.conceptApplication);

            foreach (var pair in pairs)
            {
                pair.conceptApplication.DependsOn = pair.databaseObject.DependsOn.Select(dbObject => applicationByObject[dbObject]).ToArray();
            }

            return(conceptApplications);
        }
Beispiel #32
0
        public override bool Equals(object o)
        {
            var other = o as GameState;

            return(other != null &&
                   TurnPhase == other.TurnPhase &&
                   SunSpaces == other.SunSpaces &&
                   SunCounter == other.SunCounter &&
                   Board.Equals(other.Board) &&
                   Deck.Equals(other.Deck) &&
                   CurrentPlayer == other.CurrentPlayer &&
                   Hands.Count == other.Hands.Count &&
                   Hands.Zip(other.Hands, (a, b) => a.Equals(b)).All(b => b));
        }
        void AssertEquers(IList<string> firstList, IList<string> secondList)
        {
            Assert.AreEqual(firstList.Count(), secondList.Count());

            firstList = firstList.OrderBy(item => item).ToList();
            secondList = secondList.OrderBy(item => item).ToList();

            Assert
                .IsTrue(firstList
                    .Zip(secondList
                        , (first, second) =>
                            first == second)
                    .All(item => item));
        }
        public static ModelShip FromCsvRecord(IList <string> header, IList <string> row)
        {
            var keyedRow = header.Zip(row, (h, r) => new { h, r }).ToDictionary(a => a.h, a => a.r);

            return(new ModelShip()
            {
                No = keyedRow["No"].ToInt32(),
                ClassOfShip = keyedRow["ClassOfShip"],
                Name = keyedRow["Name"],
                TaxIncludedPrice = keyedRow["TaxIncludedPrice"].ToInt32OrDefault(System.Globalization.NumberStyles.Currency, -1),
                Price = keyedRow["Price"].ToInt32OrDefault(System.Globalization.NumberStyles.Currency, -1),
                Maker = keyedRow["Maker"]
            });
        }
        public void Activate()
        {
            var fac = new EditorFontAndColors();

            foreach (var p in Presets.Zip(PresetThemes, (x, y) => new Tuple <LineTextPreview, IndentTheme>(x, y)))
            {
                p.Item1.Font               = new Font(fac.FontFamily, 8.0f, fac.FontBold ? FontStyle.Bold : FontStyle.Regular);
                p.Item1.ForeColor          = fac.ForeColor;
                p.Item1.BackColor          = fac.BackColor;
                p.Item1.HighlightBackColor = fac.HighlightBackColor;
                p.Item1.HighlightForeColor = fac.HighlightForeColor;
                p.Item1.VisibleWhitespace  = true;
                p.Item1.Theme              = p.Item2;
            }
        }
Beispiel #36
0
        protected virtual void ShowMashup(IList <object> values)
        {
            drawnValues = values;
            foreach (var mashupValue in values.Zip(EnumerableMashup(this, Mashups.Select(xs => (DialogTypeVisualizer)xs.Visualizer)), (value, visualizer) => new { value, visualizer }))
            {
                mashupValue.visualizer.Show(mashupValue.value);
            }

            visualizerCanvas.MakeCurrent();
            if (visualizerImage != null)
            {
                imageTexture.Update(visualizerImage);
            }
            visualizerCanvas.Canvas.Invalidate();
        }
Beispiel #37
0
        public static void UpdateAll <T>(
            this IDbConnection connection,
            IList <T> oldObjects,
            IList <T> newObjects,
            IDbTransaction transaction = null)
        {
            if (oldObjects.Count != newObjects.Count)
            {
                throw new ArgumentException(string.Format(
                                                "Mismatch between length of old object list ({0}) and length of new object list."));
            }

            var target = oldObjects.Zip(newObjects, Tuple.Create);

            UpdateAll(connection, target, transaction);
        }
    public IList<Task<IObjectState>> SaveAllAsync(IList<IObjectState> states,
        IList<IDictionary<string, IParseFieldOperation>> operationsList,
        string sessionToken,
        CancellationToken cancellationToken) {
      var requests = states.Zip(operationsList, (item, ops) => new Dictionary<string, object> {
        { "method", (item.ObjectId == null ? "POST" : "PUT") },
        { "path",  (item.ObjectId == null ?
            string.Format("/1/classes/{0}", Uri.EscapeDataString(item.ClassName)) :
            string.Format("/1/classes/{0}/{1}", Uri.EscapeDataString(item.ClassName),
                Uri.EscapeDataString(item.ObjectId))) },
        { "body", ParseObject.ToJSONObjectForSaving(ops) }
      }).Cast<object>().ToList();

      var batchTasks = ExecuteBatchRequests(requests, sessionToken, cancellationToken);
      var stateTasks = new List<Task<IObjectState>>();
      foreach (var task in batchTasks) {
        stateTasks.Add(task.OnSuccess(t => {
          return ParseObjectCoder.Instance.Decode(t.Result, ParseDecoder.Instance);
        }));
      }

      return stateTasks;
    }
 public static bool Checkit(IList<double> first, IList<double> second)
 {
     return (first.Count == second.Count) && !first.Zip(second, (f, s) => (f - s)).Any(d => Math.Abs(d) > 1e-6);
 }
Beispiel #40
0
        public Tuple<double, double> DoDeltaCalibration(int numFactors, IList<PointError> zBedProbePoints, bool normalise)
        {
            if (numFactors != 3 && numFactors != 4 && numFactors != 6 && numFactors != 7)
            {
                throw new Exception("Error: " + numFactors + " factors requested but only 3, 4, 6 and 7 supported");
            }
            if (numFactors > zBedProbePoints.Count)
            {
                throw new Exception("Error: need at least as many points as factors you want to calibrate");
            }

            // Transform the probing points to motor endpoints and store them in a matrix, so that we can do multiple iterations using the same data
            var probeMotorPositions = new PointError[zBedProbePoints.Count];
            var corrections = new double[zBedProbePoints.Count];
            var initialSumOfSquares = 0.0;
            for (var i = 0; i < zBedProbePoints.Count; ++i)
            {
                corrections[i] = 0.0;
                var machinePos = new double[3]
                {
                    zBedProbePoints[i].X,
                    zBedProbePoints[i].Y,
                    0
                };

                probeMotorPositions[i] = new PointError(Transform(machinePos, 0), Transform(machinePos, 1), Transform(machinePos, 2));

                initialSumOfSquares += FSquare(zBedProbePoints[i].X) + FSquare(zBedProbePoints[i].Y) + FSquare(zBedProbePoints[i].ZError);
            }

            // remove any erroneous data points..  maybe not the best idea??
            var zip = zBedProbePoints
                .Zip(probeMotorPositions, (point, pos) => new { point, pos })
                .Where(_ => !_.pos.X.Equals(double.NaN) && !_.pos.Y.Equals(double.NaN) && !_.pos.ZError.Equals(double.NaN))
                .ToList();
            zBedProbePoints = (from z in zip select z.point).ToList();
            probeMotorPositions = (from z in zip select z.pos).ToArray();

            // Do 1 or more Newton-Raphson iterations
            var iteration = 0;
            double expectedRmsError;
            for (;;)
            {
                // Build a Nx7 matrix of derivatives with respect to xa, xb, yc, za, zb, zc, diagonal.
                var derivativeMatrix = new double[zBedProbePoints.Count, numFactors];
                for (var i = 0; i < zBedProbePoints.Count; ++i)
                {
                    for (var j = 0; j < numFactors; ++j)
                    {
                        derivativeMatrix[i, j] =
                            ComputeDerivative(j, probeMotorPositions[i].X, probeMotorPositions[i].Y, probeMotorPositions[i].ZError);
                    }
                }

                // Now build the normal equations for least squares fitting
                var normalMatrix = new double[numFactors, numFactors + 1];
                double temp;
                for (var i = 0; i < numFactors; ++i)
                {
                    for (var j = 0; j < numFactors; ++j)
                    {
                        temp = derivativeMatrix[0,i] * derivativeMatrix[0,j];
                        for (var k = 1; k < zBedProbePoints.Count; ++k)
                        {
                            temp += derivativeMatrix[k,i] * derivativeMatrix[k,j];
                        }
                        normalMatrix[i,j] = temp;
                    }
                    temp = derivativeMatrix[0,i] * -(zBedProbePoints[0].ZError + corrections[0]);
                    for (var k = 1; k < zBedProbePoints.Count; ++k)
                    {
                        temp += derivativeMatrix[k,i] * -(zBedProbePoints[k].ZError + corrections[k]);
                    }
                    normalMatrix[i, numFactors] = temp;
                }

                double[] solution = GaussJordan(ref normalMatrix, numFactors);
                if (solution.Any(_ => _.Equals(double.NaN)))
                    throw new Exception("Unable to calculate corrections. Please make sure the bed probe points are all distinct.");

                //if (debug)
                //{
                //    DebugPrint(PrintVector("Solution", solution));

                //    // Calculate and display the residuals
                //    var residuals = [];
                //    for (var i = 0; i < numPoints; ++i)
                //    {
                //        var r = zBedProbePoints[i];
                //        for (var j = 0; j < numFactors; ++j)
                //        {
                //            r += solution[j] * derivativeMatrix.data[i][j];
                //        }
                //        residuals.push(r);
                //    }
                //    DebugPrint(PrintVector("Residuals", residuals));
                //}

                Adjust(numFactors, solution, normalise);

                // Calculate the expected probe heights using the new parameters
                {
                    var expectedResiduals = new double[zBedProbePoints.Count];
                    var sumOfSquares = 0.0;
                    for (var i = 0; i < zBedProbePoints.Count; ++i)
                    {
                        probeMotorPositions[i] = new PointError(probeMotorPositions[i].X + solution[0], probeMotorPositions[i].Y + solution[1], probeMotorPositions[i].ZError + solution[2]);
                        var newZ = InverseTransform(probeMotorPositions[i].X, probeMotorPositions[i].Y, probeMotorPositions[i].ZError);
                        corrections[i] = newZ;
                        expectedResiduals[i] = zBedProbePoints[i].ZError + newZ;
                        sumOfSquares += FSquare(expectedResiduals[i]);
                    }

                    expectedRmsError = Math.Sqrt(sumOfSquares / zBedProbePoints.Count);
                }

                // Decide whether to do another iteration Two is slightly better than one, but three doesn't improve things.
                // Alternatively, we could stop when the expected RMS error is only slightly worse than the RMS of the residuals.
                ++iteration;
                if (iteration == 2) { break; }
            }

            return Tuple.Create(Math.Sqrt(initialSumOfSquares / zBedProbePoints.Count), expectedRmsError);
        }
Beispiel #41
0
        private static void PitchShift2(float pitchShift, int numSampsToProcess, int sampleOverlap, int sampleRate, IList<float> data)
        {
            var fftBuffer = data.Zip(
                Enumerable.Repeat(0f, data.Count),
                (real, imaginary) => new Complex(real, imaginary)).ToArray();

            ShortTimeFourierTransform(fftBuffer, FftDirection.Forward);

            var bins = CalculateBins(SampleRate, fftBuffer);

            var dcOffset = bins[0].Magnitude / fftBuffer.Length;

            var shiftedBins = PitchShiftBins(pitchShift, bins);

            var newBuffer = SynthesizeFft(SampleRate, shiftedBins);

            ShortTimeFourierTransform(newBuffer, FftDirection.Inverse);

            var factor = (newBuffer.Length / 2f);

            for (var i = 0; i < fftBuffer.Length; i++)
            {
                data[i] = newBuffer[i].Real / factor - dcOffset;
            }
        }
 private double distance(IList<double> sample1, IList<double> sample2)
 {
     // Simple euclidian distance
     return Math.Sqrt(sample1.Zip(sample2, (s1, s2) => Math.Pow(s1 - s2, 2.0)).Sum());
 }
 private void AssertKeyCollectionsEquality(IList<Key> expected, IList<Key> actual)
 {
     Assert.NotNull(actual);
     Assert.Equal(expected.Count, actual.Count);
     Assert.True(expected.Zip(actual, (k1, k2) => k1.Equals(k2)).All(r => r));
 }
        /// <summary>
        /// Computes the distance between two points in the sample space
        /// </summary>
        private double distance(IList<double> sample1, IList<double> sample2)
        {
            // Euclidian distance
            return Math.Sqrt(sample1.Zip(sample2, (s1, s2) => Math.Pow(s1 - s2, 2.0)).Sum());

            // Manhattan distance
            //return sample1.Zip(sample2, (s1, s2) => Math.Abs(s1 - s2)).Sum();
        }
Beispiel #45
0
 private void AssertTokenStreamEquals(IList<Token> eTokens, IList<Token> tokens)
 {
     Assert.AreEqual(eTokens.Count, tokens.Count);
     foreach (var tokenPair in eTokens.Zip(tokens, (token, token1) => new {expected = token, actual = token1}))
     {
         Assert.AreEqual(tokenPair.expected.Kind, tokenPair.actual.Kind);
         Assert.AreEqual(tokenPair.expected.Value, tokenPair.actual.Value);
     }
 }
Beispiel #46
0
        private static void WriteIcoToStream(Stream stream, IList<Bitmap> bitmaps)
        {
            if (bitmaps.Any(bmp => bmp.Width> 256 || bmp.Height> 256))
            {
            throw new ArgumentException(
                "ICO files cannot contain images with dimensions greater than 256x256 pixels");
            }
            bitmaps = bitmaps.Where(bmp => bmp.Width> 0 && bmp.Height> 0).ToList();

            if (bitmaps.Count> ushort.MaxValue)
            {
            throw new ArgumentException(
                "ICO files can only contain up to " + short.MaxValue + " images.");
            }

            IList<byte[]> pngImages = new List<byte[]>(bitmaps.Count);
            foreach (var bmp in bitmaps)
            {
            using (var pngStream = new MemoryStream())
            {
                bmp.Save(pngStream, ImageFormat.Png);
                pngImages.Add(pngStream.ToArray());
            }
            }

            var numImages = (ushort) bitmaps.Count;
            WriteIcoMainHeader(stream, numImages);

            uint headerSize = 6;
            uint imageHeaderSize = 16;
            uint offset = headerSize + numImages * imageHeaderSize;
            foreach (var images in bitmaps.Zip(pngImages, Tuple.Create))
            {
            var bmp = images.Item1;
            var png = images.Item2;
            var imageSize = (uint) png.Length;
            // The direct cast to a byte here is safe. We validate the image size above,
            // so all images have a width/height in the range [1, 256]. Casting [1, 255]
            // to a byte returns the same number, and casting 256 returns 0, which represents
            // an image of size 256 bytes in the ICO format.
            WriteIcoImageHeader(stream, (byte) bmp.Width, (byte) bmp.Height, imageSize, offset);
            offset += imageSize;
            }

            foreach (var png in pngImages)
            {
            stream.Write(png, 0, png.Length);
            }
        }