Exemplo n.º 1
0
        public void LinqOrderBy()
        {
            List<Movie> moreMovies = new List<Movie>();
            string sameTitle = "sameTitle";
            string sameMovieMaker = "sameMovieMaker";
            for (int i = 0; i < 10; i++)
            {
                Movie movie = Movie.GetRandomMovie();
                movie.Title = sameTitle;
                movie.MovieMaker = sameMovieMaker;
                moreMovies.Add(movie);
                _movieTable.Insert(movie).Execute();
            }

            var movieQuery = _movieTable.Where(m => m.Title == sameTitle && m.MovieMaker == sameMovieMaker);

            List<Movie> actualOrderedMovieList = movieQuery.Execute().ToList();
            List<Movie> expectedOrderedMovieList = moreMovies.OrderBy(m => m.Director).ToList();
            Assert.AreEqual(expectedOrderedMovieList.Count, actualOrderedMovieList.Count);
            for (int i = 0; i < expectedOrderedMovieList.Count; i++)
            {
                Assert.AreEqual(expectedOrderedMovieList[i].Director, actualOrderedMovieList[i].Director);
                Assert.AreEqual(expectedOrderedMovieList[i].MainActor, actualOrderedMovieList[i].MainActor);
                Assert.AreEqual(expectedOrderedMovieList[i].MovieMaker, actualOrderedMovieList[i].MovieMaker);
            }
        }
Exemplo n.º 2
0
		AstNode[] FindReferences(IEntity entity)
		{
			var result = new List<AstNode>();
			var searchScopes = findReferences.GetSearchScopes(entity);
			findReferences.FindReferencesInFile(searchScopes, parsedFile, compilationUnit, compilation,
			                                    (node, rr) => result.Add(node), CancellationToken.None);
			return result.OrderBy(n => n.StartLocation).ToArray();
		}
Exemplo n.º 3
0
		AstNode[] FindReferences(INamespace ns)
		{
			var result = new List<AstNode>();
			var searchScopes = findReferences.GetSearchScopes(ns);
			findReferences.FindReferencesInFile(searchScopes, unresolvedFile, syntaxTree, compilation,
			                                    (node, rr) => result.Add(node), CancellationToken.None);
			return result.OrderBy(n => n.StartLocation).ToArray();
		}
Exemplo n.º 4
0
        public void Generate_country_enum()
        {
            const string code = @"//This file was automatically generated by {0} on {1}
            //Don't modify this file directory, instead edit the code that generated this file

            using System.ComponentModel;
            using Portoa.Util;

            namespace Portoa.Globalization {{
            // ReSharper disable InconsistentNaming
            ///<summary>Auto-generated enumeration of every country supported by <see cref=""System.Globalization.CultureInfo""/></summary>
            public enum Country {{
            ///<summary>Country is unknown or not applicable</summary>
            [Description(""N/A"")]
            Unknown = int.MinValue,
            {2}
            }}
            // ReSharper restore InconsistentNaming

            public static class CountryExtensions {{
            /// <summary> Gets the human-readable display name for a <see cref=""Country""/> </summary>
            public static string GetDisplayName(this Country country) {{
            return country.GetAttributes<DescriptionAttribute>()[0].Description;
            }}
            }}
            }}";

            var cultures = CultureInfo.GetCultures(CultureTypes.SpecificCultures);
            var regions = new List<RegionInfo>();
            foreach (var region in cultures.Select(culture => new RegionInfo(culture.LCID)).Where(region => !regions.Contains(region))) {
                regions.Add(region);
            }

            var valuesCode = new StringBuilder(1000);
            var invalidCharRegex = new Regex(@"\W");
            foreach (var region in regions.OrderBy(region => region.EnglishName)) {
                valuesCode.Append(string.Format("\t\t///<summary>The country {0}</summary>{1}", region.EnglishName, Environment.NewLine));
                var name = region
                    .EnglishName
                    .Split(' ')
                    .Aggregate(string.Empty, (current, word) => current + (word[0].ToString().ToUpperInvariant() + word.Substring(1)));

                var validName = invalidCharRegex.Replace(name, "");

                valuesCode.Append(string.Format("\t\t[Description(\"{0}\")]{1}", region.EnglishName, Environment.NewLine));
                valuesCode.Append(string.Format("\t\t{0} = {1},{2}", validName, region.GeoId, Environment.NewLine));
            }

            const string path = @"c:\users\tmont\code\Portoa\Src\Portoa\Globalization\Country.cs";
            using (var stream = File.Open(path, FileMode.OpenOrCreate, FileAccess.Write)) {
                stream.SetLength(0);
                using (var writer = new StreamWriter(stream)) {
                    writer.Write(string.Format(code, GetType().FullName + ".Generate_country_enum()", DateTime.Now, valuesCode));
                }
            }
        }
Exemplo n.º 5
0
 public static void AreEqual(List<LoggedData> loggedDatas, List<TSK> tsks, Catalog catalog, string cardPath)
 {
     tsks = tsks.OrderBy(x => x.A).ToList();
     for (int i = 0; i < loggedDatas.Count; i++)
     {
         var loggedData = loggedDatas[i];
         var matchingTask = tsks[tsks.Count - loggedDatas.Count + i];
         AreEqual(loggedData, matchingTask, catalog, cardPath);
     }
 }
Exemplo n.º 6
0
        public void SubscriptionsWorkLikeExpectedWhenRabbitManagesThem()
        {
            // arrange
            DeleteQueue("test.rabbitsub.publisher");
            DeleteQueue("test.rabbitsub.sub1");
            DeleteQueue("test.rabbitsub.sub2");
            DeleteQueue("test.rabbitsub.sub3");

            var publisher = PullOneOutOfTheHat("test.rabbitsub.publisher");

            var receivedSub1 = new List<int>();
            var receivedSub2 = new List<int>();
            var receivedSub3 = new List<int>();

            var sub1 = PullOneOutOfTheHat("test.rabbitsub.sub1", receivedSub1.Add);
            var sub2 = PullOneOutOfTheHat("test.rabbitsub.sub2", receivedSub2.Add);
            var sub3 = PullOneOutOfTheHat("test.rabbitsub.sub3", receivedSub3.Add);

            // act
            publisher.Publish(new SomeEvent { Number = 1 });

            Thread.Sleep(200.Milliseconds());

            sub1.Subscribe<SomeEvent>();
            Thread.Sleep(200.Milliseconds());
            publisher.Publish(new SomeEvent { Number = 2 });

            sub2.Subscribe<SomeEvent>();
            Thread.Sleep(200.Milliseconds());
            publisher.Publish(new SomeEvent { Number = 3 });

            sub3.Subscribe<SomeEvent>();
            Thread.Sleep(200.Milliseconds());
            publisher.Publish(new SomeEvent { Number = 4 });

            Thread.Sleep(200.Milliseconds());

            sub3.Unsubscribe<SomeEvent>();
            Thread.Sleep(200.Milliseconds());
            publisher.Publish(new SomeEvent { Number = 5 });

            sub2.Unsubscribe<SomeEvent>();
            Thread.Sleep(200.Milliseconds());
            publisher.Publish(new SomeEvent { Number = 6 });

            sub1.Unsubscribe<SomeEvent>();
            Thread.Sleep(200.Milliseconds());
            publisher.Publish(new SomeEvent { Number = 7 });

            // assert
            receivedSub1.OrderBy(i => i).ToArray().ShouldBe(new[] { 2, 3, 4, 5, 6 });
            receivedSub2.OrderBy(i => i).ToArray().ShouldBe(new[] { 3, 4, 5 });
            receivedSub3.OrderBy(i => i).ToArray().ShouldBe(new[] { 4 });
        }
Exemplo n.º 7
0
        public void PrefixesShouldBeSortedCorrectly()
        {
            var usortedPrefixesList = new List<Prefix>
            {
                Prefix.Kb, Prefix.Mb, Prefix.Gb, Prefix.Gb, Prefix.Kb, Prefix.Tb, Prefix.Gb, Prefix.Mb,Prefix.Tb, Prefix.Gb, Prefix.Mb, Prefix.Kb
            };

            usortedPrefixesList.OrderBy(it => it).Should().BeInAscendingOrder();

            usortedPrefixesList.OrderByDescending(it => it).Should().BeInDescendingOrder();
        }
        public async Task GivenRegistryWithMultiplePipes_WhenResolvingFromAToD_ItShouldChainAllThePipes()
        {
            for (int counter = 0; counter < 15; counter++)
            {
                // pre-arrange
                var instanceClassA = new TestClassA();
                var instanceClassB = new TestClassB();
                var instanceClassC = new TestClassC();
                var instanceClassD = new TestClassD();

                // arrange
                var semanticBuilder = new SemanticBuilder();

                var enrollmentList = new List<Action>
                {
                    () => semanticBuilder.InstallPipe<TestClassA, TestClassB>((a, innerBroker) =>
                    {
                        Assert.AreSame(instanceClassA, a);
                        return instanceClassB;
                    }),
                    () => semanticBuilder.InstallPipe<TestClassB, TestClassC>((b, innerBroker) =>
                    {
                        Assert.AreSame(instanceClassB, b);
                        return instanceClassC;
                    }),
                    () => semanticBuilder.InstallPipe<TestClassC, TestClassD>((c, innerBroker) =>
                    {
                        Assert.AreSame(instanceClassC, c);
                        return instanceClassD;
                    }),
                };

                var enrollmentActions = enrollmentList.OrderBy(x=>Guid.NewGuid());
                foreach (var enrollmentAction in enrollmentActions)
                {
                    enrollmentAction();
                }

                ISemanticBroker broker = semanticBuilder.CreateBroker();

                // act
                var solvedExecution = await broker.On(instanceClassA).Output<TestClassD>();

                // assert
                Assert.AreEqual(instanceClassD, solvedExecution);
            }
        }
Exemplo n.º 9
0
        public void IgnoresQuotes()
        {
            var unorderedList = new List<string> {
                "ZZZ",
                "\"AAA",
                "ABC",
                "DDD",
                "\"CCC"
            };

            var orderedList = unorderedList.OrderBy(c => c, new PolicyHolderComparer());

            Assert.AreEqual("\"AAA", orderedList.ElementAt(0));
            Assert.AreEqual("ABC", orderedList.ElementAt(1));
            Assert.AreEqual("\"CCC", orderedList.ElementAt(2));
            Assert.AreEqual("ZZZ", orderedList.Last());
        }
Exemplo n.º 10
0
        public void MatchingCustomers_PostcodeSameAsSomeCustomers_MatchesCorrectCustomers()
        {
            List<ICustomerVM> famousCustomers = CreateFamousCustomerVMs();
            var customersToMatch = new List<ICustomerVM>();

            for (int i = 0; i < famousCustomers.Count; i++) {
                ICustomerVM customer = famousCustomers[i];
                if (i%2 != 0) continue;

                GiveAddressWithPostcode(customer, TestPostcode);
                customersToMatch.Add(customer);
            }
            sessionData.CustomersToReturn = famousCustomers;
            FindCustomerVM viewModel = CreateViewModel(TestPostcode);

            var expected = new List<ICustomerVM>(customersToMatch.OrderBy(cust => cust.FirstName));
            AssertAreEqual(expected, viewModel.MatchingCustomers.ToList());
        }
Exemplo n.º 11
0
        public void EnumerateFromKeys()
        {
            string path = Path.GetFullPath ("TestData\\EnumerateFromKeys");
            if (!Directory.Exists (path)) Directory.CreateDirectory (path);

            List<KeyValuePair<Key, Value>> items = new List<KeyValuePair<Key, Value>> ();

            int num_items = 10000;
            var mt = new MemTable ();
            for (int i = 0; i < num_items; i++) {
                var k0 = Key.Random (40);
                var v0 = Value.Random (200);
                mt.Add (k0, v0);

                items.Add (new KeyValuePair<Key, Value> (k0, v0));
            }

            mt.WriteToSortedBlockTable ("TestData\\EnumerateFromKeys", 10, 10);

            var cache = new RazorCache ();
            var sbt = new SortedBlockTable (cache, "TestData\\EnumerateFromKeys", 10, 10);

            try {
                var indexCache = new RazorCache ();

                var timer = new Stopwatch ();
                timer.Start ();
                Assert.AreEqual (10000, sbt.EnumerateFromKey (indexCache, new Key (new byte[] { 0 }, 0)).Count ());
                timer.Stop ();
                Console.WriteLine ("Counted from beginning at a throughput of {0} MB/s", (double)mt.Size / timer.Elapsed.TotalSeconds / (1024.0 * 1024.0));

                items = items.OrderBy ((a) => a.Key).ToList ();

                timer.Reset ();
                timer.Start ();
                Assert.AreEqual (5000, sbt.EnumerateFromKey (indexCache, items [5000].Key).Count ());
                timer.Stop ();
                Console.WriteLine ("Counted from halfway at a throughput of {0} MB/s", (double)mt.Size / 2 / timer.Elapsed.TotalSeconds / (1024.0 * 1024.0));

                Assert.AreEqual (0, sbt.EnumerateFromKey (indexCache, new Key (new byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }, 0xFF)).Count ());
            } finally {
                sbt.Close ();
            }
        }
        public void WorstCaseScenario_Should_ReturnAnswerInResonableTime()
        {
            // Arrange
            const int testSize = 1000;
            Solver solver = new Solver();
            Random rand = new Random();
            List<string> input = new List<string>(testSize);
            StringBuilder expected = new StringBuilder("0 ");
            for (int i = 0; i < testSize - 1; i++)
            {
                input.Add(String.Format("{0} {1}", i, i + 1));
                for (int j = i + 2; j < testSize - 2; j++)
                {
                    input.Add(String.Format("{0} {1}", i, j));
                }

                expected.Append(i + 1).Append(" ");
            }
            StringBuilder sb = new StringBuilder().AppendFormat("{0} {1}\n", testSize, input.Count);
            foreach (var experiment in input.OrderBy(d => rand.Next()))
            {
                sb.AppendLine(experiment);
            }
            string expectedResult = expected.ToString().TrimEnd() + "\r\n";

            // Act
            using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(sb.ToString())))
            using (var outMs = new MemoryStream())
            {
                Stopwatch sw = new Stopwatch();
                sw.Start();
                solver.Solve(ms, outMs);
                sw.Stop();
                Debug.WriteLine("Solved in {0}", sw.Elapsed);
                outMs.Position = 0;
                var result = new StreamReader(outMs).ReadToEnd();

                // Assert
                Assert.That(result, Is.EqualTo(expectedResult));
            }
        }
        public void CalculateSmallestNumber(string str, int n)
        {
            char[] mychar = str.ToCharArray();
            var smallest = mychar.FirstOrDefault();
            var list = new List<ComplexLetter>();

            var maxTrim = str.Length - n;

            while (list.Count < maxTrim)
            {
                StringBuilder stringBuilder = new StringBuilder(str);
                var traverseString = TraverseString(str, smallest);
                list.Add(traverseString);
                stringBuilder[traverseString.Position] = ' ';
                str = stringBuilder.ToString().Replace(" ", string.Empty);
                smallest = str.ToCharArray().FirstOrDefault();
            }

            Console.WriteLine();

            var orderedEnumerable = list.OrderBy(letter => letter.Position);
            orderedEnumerable.Each(letter => Console.WriteLine(letter.Letter + " " + letter.Position));
        }
Exemplo n.º 14
0
        public void PagingTest()
        {
            CreateTestData();
              var repository = Locator.GetInstance<IRepository<Product>>();

              var allItems = new List<Product>();

              var query = repository.CreateQuery<IPagedProductSearch>();
              query.Sort = PagedProductSearchSort.PriceAsc;
              query.ItemsPerPage = 2;
              query.PageNumber = 1;
              var actual = query.Execute();
              Assert.AreEqual(5, actual.TotalItems);
              Assert.AreEqual(2, actual.PageOfResults.Count());
              allItems.AddRange(actual.PageOfResults);

              query = repository.CreateQuery<IPagedProductSearch>();
              query.Sort = PagedProductSearchSort.PriceAsc;
              query.ItemsPerPage = 2;
              query.PageNumber = 2;
              actual = query.Execute();
              Assert.AreEqual(5, actual.TotalItems);
              Assert.AreEqual(2, actual.PageOfResults.Count());
              allItems.AddRange(actual.PageOfResults);

              query = repository.CreateQuery<IPagedProductSearch>();
              query.Sort = PagedProductSearchSort.PriceAsc;
              query.ItemsPerPage = 2;
              query.PageNumber = 3;
              actual = query.Execute();
              Assert.AreEqual(5, actual.TotalItems);
              Assert.AreEqual(1, actual.PageOfResults.Count());
              allItems.AddRange(actual.PageOfResults);

              Assert.True(allItems.SequenceEqual(
            allItems.OrderBy(p => p.UnitPrice)));
        }
Exemplo n.º 15
0
        public void withCategories(params string[] categories)
        {
            var actualCategories = new List<string>();

            var categoriesXml = _xml.Elements("categories");

            if (categoriesXml != null)
            {
                foreach(var category in categoriesXml.Elements("category").Select(c => c.Attribute("name").Value))
                {
                    actualCategories.Add(category);
                }
            }

            categories = categories.OrderBy(c => c).ToArray();
            actualCategories = actualCategories.OrderBy(c => c).ToList();

            Assert.That(categories, Is.EquivalentTo(actualCategories),
                String.Format("Expected {0} named {1} to have categories {2}, actually had {3}",
                    _typeName,
                    _name,
                    string.Join(",", categories),
                    string.Join(",", actualCategories)));
        }
Exemplo n.º 16
0
        public void CreateComparerFromDelegate()
        {
            var source = new List<int> { 1, 2, 3, 0, 4, 5, 6, 7 };
            var comparer = ComparerHelper.CreateComparer<int>(
                (x, y) =>
                {
                    if (x == 0)
                    {
                        return y == 0 ? 0 : -1;
                    }

                    if (y == 0)
                    {
                        return 1;
                    }

                    return y.CompareTo(x);
                });

            var sorted = source.OrderBy(x => x, comparer).ToList();

            var expected = new List<int> { 0, 7, 6, 5, 4, 3, 2, 1 };
            CollectionAssert.AreEqual(expected, sorted);
        }
Exemplo n.º 17
0
        public void GenerateSolverRun()
        {
            var l = new LibraryComponent();
            var lib1 = l.LoadLegacySokoSolve_SSX(l.GetPathData(@".\LegacySSX\Sasquatch.ssx"));
            var lib2 = l.LoadLegacySokoSolve_SSX(l.GetPathData(@".\LegacySSX\SasquatchIII.ssx"));
            var lib3 = l.LoadLegacySokoSolve_SSX(l.GetPathData(@".\LegacySSX\SasquatchIV.ssx"));
            var lib4 = l.LoadLegacySokoSolve_SSX(l.GetPathData(@".\LegacySSX\Thinking Rabbit Inc, Origonal.ssx"));

            var pool = new List<LibraryPuzzle>(lib1);
            pool.AddRange(lib2);
            pool.AddRange(lib3);
            pool.AddRange(lib4);

            var rep = new SokoDBRepository();

            int cc = 0;
            foreach (var puzzle in pool.OrderBy(x=>StaticAnalysis.CalculateRating(x)))
            {
                Console.WriteLine("Puzzle.{0}={1}", cc++, puzzle.Ident);
                var dto = new PuzzleDTO()
                {
                    Name = puzzle.Name,
                    CharMap = puzzle.ToString(),
                    Rating = (int)StaticAnalysis.CalculateRating(puzzle),
                    Hash = puzzle.GetHashCode(),
                    SourceIdent = puzzle.Ident.ToString(),
                    Created = DateTime.Now,
                    Modified = DateTime.Now
                };
                dto = rep.Confirm(dto);
                Assert.That(dto.PuzzleId, Is.Not.EqualTo(0));
            }

            Assert.That(lib1, Is.Not.Null);
            Assert.That(lib1.Count, Is.EqualTo(50));
        }
Exemplo n.º 18
0
        public void TestPersonOrdering()
        {
            Person taroSuzuki = new Person {
                FirstName = "Taro",
                LastName = "Suzuki"
            };
            Person jiroSuzuki = new Person {
                FirstName = "Jiro",
                LastName = "Suzuki"
            };
            Person taroSato = new Person {
                FirstName = "Taro",
                LastName = "Sato"
            };

            List<Person> personList = new List<Person> { taroSuzuki, jiroSuzuki, taroSato };

            Assert.That (SL.Enumerable.SequenceEqual (
                personList.OrderBy (person => person.LastName).ThenBy (person => person.FirstName),
                new []{taroSato, jiroSuzuki, taroSuzuki}));
        }
        public void TestCalibration()
        {
            string uimfFileLocation = Cheetah;

            LcImsPeptideSearchParameters parameters = new LcImsPeptideSearchParameters
            {
                ChargeStateMax = 5,
                NetTolerance = 0.5,
                IsotopicFitScoreThreshold = 0.15,
                MassToleranceInPpm = 30,
                NumPointForSmoothing = 9
            };

            List<PeptideTarget> targetList = MassTagImporter.ImportMassTags("elmer", "MT_Human_Sarcopenia_P789", 1e-10, true);
            Console.WriteLine("Using " + targetList.Count + " targets for calibration.");

            List<Tuple<double, double>> netAlignmentInput = new List<Tuple<double, double>>();
            List<Tuple<double, double>> massAlignmentInput = new List<Tuple<double, double>>();

            LcImsPeptideSearchWorkfow lcImsPeptideSearchWorkfow = new LcImsPeptideSearchWorkfow(uimfFileLocation, parameters);

            foreach (var imsTarget in targetList.OrderBy(x => x.NormalizedElutionTime))
            {
                ChargeStateCorrelationResult correlationResult = lcImsPeptideSearchWorkfow.RunInformedWorkflow(imsTarget);

                if (correlationResult == null || !correlationResult.CorrelatedResults.Any()) continue;

                LcImsTargetResult result = correlationResult.CorrelatedResults.OrderByDescending(x => x.Intensity).First();
                //LcImsTargetResult result = correlationResult.CorrelatedResults.OrderByDescending(X => X.Intensity * (1 - Math.Abs(X.NormalizedElutionTime - imsTarget.NormalizedElutionTime))).First();
                //LcImsTargetResult result = correlationResult.CorrelatedResults.OrderBy(X => X.NormalizedElutionTime).First();

                //if (netAlignmentInput.Count == 0 || Math.Abs(netAlignmentInput.Last().Item1 - imsTarget.NormalizedElutionTime) > 0.0001)
                //{
                //    netAlignmentInput.Add(new Tuple<double, double>(imsTarget.NormalizedElutionTime, result.NormalizedElutionTime));
                //    massAlignmentInput.Add(new Tuple<double, double>(imsTarget.NormalizedElutionTime, result.PpmError));
                //}

                netAlignmentInput.Add(new Tuple<double, double>(result.NormalizedElutionTime, imsTarget.NormalizedElutionTime));
                massAlignmentInput.Add(new Tuple<double, double>(result.IsotopicProfile.MonoPeakMZ, result.PpmError));
            }

            var netAlignmentInputGroup = netAlignmentInput.GroupBy(x => x.Item1).OrderBy(x => x.Key);
            var massAlignmentInputGroup = massAlignmentInput.GroupBy(x => x.Item1).OrderBy(x => x.Key);

            netAlignmentInput = netAlignmentInput.OrderBy(x => x.Item1).ToList();
            massAlignmentInput = massAlignmentInput.OrderBy(x => x.Item1).ToList();

            var groupedNetTuple = netAlignmentInputGroup.Select(x => x.OrderBy(y => Math.Abs(y.Item1 - y.Item2)).First()).ToArray();
            //var groupedNetTuple = netAlignmentInputGroup.Select(X => X.Average(Y => Y.Item2)).ToArray();
            var groupedMassTuple = massAlignmentInputGroup.Select(x => x.First()).ToArray();

            var loessInterpolatorForNetAlignment = new LoessInterpolator(0.1, 4);
            var loessInterpolatorForMassAlignment = new LoessInterpolator(0.2, 1);

            //double[] newNetValues = loessInterpolatorForNetAlignment.Smooth(netAlignmentInputGroup.Select(X => X.Key).ToArray(), netAlignmentInputGroup.Select(X => X.Average(Y => Y.Item2)).ToArray());
            double[] newNetValues = loessInterpolatorForNetAlignment.Smooth(groupedNetTuple.Select(x => x.Item1).ToArray(), groupedNetTuple.Select(x => x.Item2).ToArray());
            double[] newMassValues = loessInterpolatorForMassAlignment.Smooth(groupedMassTuple.Select(x => x.Item1).ToArray(), groupedMassTuple.Select(x => x.Item2).ToArray());

            using(StreamWriter writer = new StreamWriter("oldNetValues.csv"))
            {
                foreach (var netTuple in groupedNetTuple)
                {
                    writer.WriteLine(netTuple.Item1 + "," + netTuple.Item2);
                }
            }

            using (StreamWriter writer = new StreamWriter("oldMassValues.csv"))
            {
                foreach (var massTuple in groupedMassTuple)
                {
                    writer.WriteLine(massTuple.Item1 + "," + massTuple.Item2);
                }
            }

            using (StreamWriter writer = new StreamWriter("smoothedNetValues.csv"))
            {
                for (int i = 0; i < groupedNetTuple.Length; i++)
                {
                    writer.WriteLine(groupedNetTuple[i].Item1 + "," + newNetValues[i]);
                }
            }

            using (StreamWriter writer = new StreamWriter("smoothedMassValues.csv"))
            {
                for (int i = 0; i < groupedMassTuple.Length; i++)
                {
                    writer.WriteLine(groupedMassTuple[i].Item1 + "," + newMassValues[i]);
                }
            }
        }
Exemplo n.º 20
0
 public void GenInsertUids()
 {
     const int n = 5;
     int begin = 1000;
     List<int> list = new List<int>(n);
     int i;
     for (i = begin; i < begin + 8999; i++)
     {
         list.Add(i);
     }
     var random = list.OrderBy(a => Guid.NewGuid());
     var pairs = new List<string>();
     i = 1;
     foreach (int uid in random)
     {
         pairs.Add(string.Format("({0}, {1})", i, uid));
         i++;
     }
     var pairs_string = string.Join(",", pairs.ToArray());
     using (StreamWriter file = new StreamWriter(@"C:\insert_uids.sql"))
     {
         file.WriteLine("INSERT INTO public.unique_id(id, uid) VALUES " + pairs_string);
     }
 }
Exemplo n.º 21
0
        public void OrderBy_WeekDate_AreEqual()
        {
            var item0 = WeekDate.Parse("2000-W01-3");
            var item1 = WeekDate.Parse("2000-W11-2");
            var item2 = WeekDate.Parse("2000-W21-1");
            var item3 = WeekDate.Parse("2000-W31-7");

            var inp = new List<WeekDate>() { WeekDate.MinValue, item3, item2, item0, item1, WeekDate.MinValue };
            var exp = new List<WeekDate>() { WeekDate.MinValue, WeekDate.MinValue, item0, item1, item2, item3 };
            var act = inp.OrderBy(item => item).ToList();

            CollectionAssert.AreEqual(exp, act);
        }
Exemplo n.º 22
0
 public void Disposing_set_expires_all_items_before_dispose_returns_but_does_not_trigger_collection_changed()
 {
     var expired = false;
     var changed = false;
     var expiredEntries = new List<string>();
     var ttl = TimeSpan.FromSeconds(1);
     var set = new ExpiringDictionary<int, string>(TaskTimerFactory.Current);
     set.EntryExpired += (s, e) => { expiredEntries.Add(e.Entry.Key + ":" + e.Entry.Value); expired = true; };
     set.CollectionChanged += (s, e) => { changed = true; };
     set.Set(12, "foo", ttl);
     set.Set(21, "bar", ttl);
     Assert.IsFalse(expired, "expired was triggered");
     Assert.IsTrue(changed, "changed wasn't triggered");
     changed = false;
     set.Dispose();
     Assert.IsFalse(changed, "changed was triggered");
     Assert.IsTrue(expired, "expired wasn't triggered");
     Assert.AreEqual(new[] { "12:foo", "21:bar" }, expiredEntries.OrderBy(x => x).ToArray());
 }
Exemplo n.º 23
0
 public void AddUids()
 {
     const int n = 100;
     List<int> list = new List<int>(n);
     for (int i = 1000; i < 1000 + n; i++)
     {
         list.Add(i);
     }
     var random = list.OrderBy(a => Guid.NewGuid());
     using (ISession session = GetConfiguration().BuildSessionFactory().OpenSession())
         {
             foreach (int s in random)
             {
                 UniqueId uniqueId = new UniqueId(){Uid = s};
                 session.Save(uniqueId);
                 session.Flush();
             }
         }
 }
Exemplo n.º 24
0
        public Hand(string cardsText)
        {
            var cards = cardsText.Split(new [] { ' '}, StringSplitOptions.RemoveEmptyEntries);

            Cards = new List<Card>();
            foreach (var card in cards)
            {
                Cards.Add(new Card(card));
            }

            allSameSuit = Cards.Select(c => c.Suit).Distinct().Count() == 1;
            cardValueList = Cards.OrderBy(c => c.Value).Select(c => c.Value).ToList();

            if (IsRoyalFlush()) return;
            if (IsStraightFlush()) return;
            if (IsFourOfAKind()) return;
            if (IsFullHouse()) return;
            if (IsFlush()) return;
            if (IsStraight()) return;
            if (IsThreeOfAKind()) return;
            if (IsTwoPairs()) return;
            if (IsOnePair()) return;
            SetHighCard();
        }
        public void OrderBy_InternationalBankAccountNumber_AreEqual()
        {
            var item0 = InternationalBankAccountNumber.Parse("AE950210000000693123456");
            var item1 = InternationalBankAccountNumber.Parse("BH29BMAG1299123456BH00");
            var item2 = InternationalBankAccountNumber.Parse("CY17002001280000001200527600");
            var item3 = InternationalBankAccountNumber.Parse("DK5000400440116243");

            var inp = new List<InternationalBankAccountNumber>() { InternationalBankAccountNumber.Empty, item3, item2, item0, item1, InternationalBankAccountNumber.Empty };
            var exp = new List<InternationalBankAccountNumber>() { InternationalBankAccountNumber.Empty, InternationalBankAccountNumber.Empty, item0, item1, item2, item3 };
            var act = inp.OrderBy(item => item).ToList();

            CollectionAssert.AreEqual(exp, act);
        }
Exemplo n.º 26
0
        public void OrderBy_Month_AreEqual()
        {
            var item0 = Month.January;
            var item1 = Month.March;
            var item2 = Month.April;
            var item3 = Month.December;

            var inp = new List<Month>() { Month.Empty, item3, item2, item0, item1, Month.Empty };
            var exp = new List<Month>() { Month.Empty, Month.Empty, item0, item1, item2, item3 };
            var act = inp.OrderBy(item => item).ToList();

            CollectionAssert.AreEqual(exp, act);
        }
Exemplo n.º 27
0
        public void OrderBy_Year_AreEqual()
        {
            Year item0 = 1980;
            Year item1 = 1981;
            Year item2 = 1982;
            Year item3 = 1983;

            var inp = new List<Year>() { Year.Empty, item3, item2, item0, item1, Year.Empty };
            var exp = new List<Year>() { Year.Empty, Year.Empty, item0, item1, item2, item3 };
            var act = inp.OrderBy(item => item).ToList();

            CollectionAssert.AreEqual(exp, act);
        }
        public void save_and_load_local_strings_should_sort_on_key_for_easier_merges()
        {
            var strings = new List<LocalString>{
                new LocalString("c", "c-display"),
                new LocalString("d", "d-display"),
                new LocalString("a", "a-display"),
                new LocalString("b", "b-display"),
            };

            XmlDirectoryLocalizationStorage.Write("locale.xml", strings);

            XmlDirectoryLocalizationStorage.LoadFrom("locale.xml").ShouldHaveTheSameElementsAs(strings.OrderBy(x => x.value));
        }
Exemplo n.º 29
0
 public void Producer_consumer() {
     using(var pool = ConnectionPool.GetPool(TestConfig.Host, TestConfig.Port)) {
         var tube = Guid.NewGuid().ToString();
         var produced = new List<string>();
         var consumed = new List<string>();
         var n = 10000;
         var producerTimer = new Stopwatch();
         var producer = new Thread(() => {
             Console.WriteLine("producer started");
             using(var producerClient = new BeanstalkClient(pool)) {
                 producerClient.CurrentTube = tube;
                 Console.WriteLine("producing into tube '{0}'", producerClient.CurrentTube);
                 producerTimer.Start();
                 for(var i = 0; i < n; i++) {
                     var data = Guid.NewGuid().ToString();
                     produced.Add(data);
                     producerClient.PutString(data);
                     if(i % 2000 == 0) {
                         Console.WriteLine("enqueued {0} @ {1:0} items/sec", i, i / producerTimer.Elapsed.TotalSeconds);
                     }
                 }
                 producerTimer.Stop();
                 Console.WriteLine("done producing");
             }
         });
         producer.Start();
         Thread.Sleep(2000);
         var consumerTimer = new Stopwatch();
         Console.WriteLine("consumer started");
         using(var consumerClient = new BeanstalkClient(pool)) {
             consumerClient.WatchedTubes.Add(tube);
             consumerClient.WatchedTubes.Remove(BeanstalkClient.DEFAULT_TUBE);
             Console.WriteLine("consuming from tube '{0}'", tube);
             consumerTimer.Start();
             while(consumed.Count < n) {
                 var job = consumerClient.ReserveString(TimeSpan.Zero);
                 consumed.Add(job.Data);
                 consumerClient.Delete(job.JobId);
                 if(consumed.Count % 2000 == 0) {
                     Console.WriteLine("dequeued {0} @ {1:0} items/sec", consumed.Count, consumed.Count / consumerTimer.Elapsed.TotalSeconds);
                 }
             }
             consumerTimer.Stop();
             Console.WriteLine("done consuming");
         }
         producer.Join();
         Assert.AreEqual(n, produced.Count, "wrong number of produced items");
         Assert.AreEqual(n, consumed.Count, "wrong number of consumed items");
         Assert.AreEqual(produced.OrderBy(x => x).ToArray(), consumed.OrderBy(x => x).ToArray());
         Console.WriteLine("final enqueue: {0:0} items/sec", n / producerTimer.Elapsed.TotalSeconds);
         Console.WriteLine("final dequeue: {0:0} items/sec", n / consumerTimer.Elapsed.TotalSeconds);
     }
 }
Exemplo n.º 30
0
 public void Producer_consumer_load_test_runs_forever() {
     var pool = ConnectionPool.GetPool(TestConfig.Host, TestConfig.Port);
     var tube = "forever-" + Guid.NewGuid().ToString();
     Console.WriteLine("using tube: {0}", tube);
     var set = 0;
     while(true) {
         set++;
         var produced = new List<string>();
         var consumed = new List<string>();
         var n = 10000;
         var producerTimer = new Stopwatch();
         var producer = new Thread(() => {
             using(var producerClient = new BeanstalkClient(pool)) {
                 producerClient.CurrentTube = tube;
                 producerTimer.Start();
                 for(var i = 0; i < n; i++) {
                     var data = Guid.NewGuid().ToString();
                     produced.Add(data);
                     producerClient.PutString(data);
                 }
                 producerTimer.Stop();
             }
         });
         producer.Start();
         Thread.Sleep(1000);
         var consumerTimer = new Stopwatch();
         using(var consumerClient = new BeanstalkClient(pool)) {
             consumerClient.WatchedTubes.Add(tube);
             consumerClient.WatchedTubes.Remove(BeanstalkClient.DEFAULT_TUBE);
             consumerTimer.Start();
             while(consumed.Count < n) {
                 var job = consumerClient.ReserveString(TimeSpan.Zero);
                 consumed.Add(job.Data);
                 consumerClient.Delete(job.JobId);
             }
             consumerTimer.Stop();
         }
         producer.Join();
         Assert.AreEqual(n, produced.Count, "wrong number of produced items");
         Assert.AreEqual(n, consumed.Count, "wrong number of consumed items");
         Assert.AreEqual(produced.OrderBy(x => x).ToArray(), consumed.OrderBy(x => x).ToArray());
         Console.WriteLine("set {0} enqueue/dequeue: {1:0}/{2:0} items/sec",
             set,
             n / producerTimer.Elapsed.TotalSeconds,
             n / consumerTimer.Elapsed.TotalSeconds
         );
         using(var client = new BeanstalkClient(pool)) {
             foreach(var t in client.GetTubes()) {
                 var tubeStats = client.GetTubeStats(t);
                 Console.WriteLine("{0}:total:{1}/buried:{2}/delayed:{3}/ready:{4}/reserved:{5}/urgent:{6}/waiting:{7}",
                     tubeStats.Name,
                     tubeStats.TotalJobs,
                     tubeStats.CurrentBuriedJobs,
                     tubeStats.CurrentDelayedJobs,
                     tubeStats.CurrentReadyJobs,
                     tubeStats.CurrentReservedJobs,
                     tubeStats.CurrentUrgentJobs,
                     tubeStats.CurrentWaiting
                 );
             }
         }
     }
 }