Example #1
0
        public List<int> CalculateSum(string ItemName, int BatchAmount)
        {
            //拿出資料集合
            List<Product> Products = _ProductDao.GetAll();

            //決定要加總那一個項目
            List<int> Items = new List<int>();
            switch (ItemName)
            {
                case "Id":
                    Items = Products.Select(p => p.Id).ToList();
                    break;
                case "Cost":
                    Items = Products.Select(p => p.Cost).ToList();
                    break;
                case "Revenue":
                    Items = Products.Select(p => p.Revenue).ToList();
                    break;
                case "SellPrice":
                    Items = Products.Select(p => p.SellPrice).ToList();
                    break;
              }
        
            //計算集合
            List<int> Result = new List<int>();
            for (int i = 0; i < Items.Count / BatchAmount + (Items.Count % BatchAmount == 0 ? 0 : 1); i++)
            {
                Result.Add(Items.Skip(i * BatchAmount).Take(BatchAmount).Sum());
            }

            return Result;
        }
Example #2
0
        public void EtwFileSourceTest()
        {
            var observable = EtwObservable.FromFiles(FileName);
            var source = new TimeSource<EtwNativeEvent>(observable, e => e.TimeStamp);

             var parsed = from p in source
                        where p.Id == 2
                        select p.TimeStamp;

            var buf = parsed.Take(13).Buffer(TimeSpan.FromSeconds(1), source.Scheduler);

            var list = new List<IList<DateTimeOffset>>();
            ManualResetEvent completed = new ManualResetEvent(false);

            buf.Subscribe(
                t => list.Add(t),
                ()=>completed.Set());

            source.Connect();
            completed.WaitOne();

            Assert.AreEqual(2, list.Count());
            Assert.AreEqual(7, list.First().Count);
            Assert.AreEqual(6, list.Skip(1).First().Count);
        }
        public async Task TestMaxItemCount()
        {
            var nextItem = 0;
            var pool = new PipelinedPool<int>(() => TaskPort.FromResult(++nextItem), null, new PipelinedPoolOptions
            {
                MaxRequestsPerItem = 10,
                TargetItemCount = 2,
            });

            var items = new List<IPooledItem<int>>();
            for (int i = 0; i < 20; ++i)
            {
                var task = pool.Borrow();
                Assert.AreEqual(true, task.IsCompleted);
                var item = await task;
                items.Add(item);
            }
            Assert.AreEqual(20, items.Count);
            Assert.AreEqual(10, items.Count(v => v.Item == 1));
            Assert.AreEqual(10, items.Count(v => v.Item == 2));

            var waiter = pool.Borrow();
            Assert.AreEqual(false, waiter.IsCompleted);

            items.First().Dispose();
            Assert.AreEqual(true, waiter.IsCompleted);
            foreach (var item in items.Skip(1))
            {
                item.Dispose();
            }
            waiter.Result.Dispose();
        }
Example #4
0
        public void ShortSpam()
        {
            InitializeDatastore.Run();

              var testList = new List<Tuple<string, bool>> {
            new Tuple<string, bool> ("a somewhat short message1", false),
            new Tuple<string, bool> ("Waterboyy I'm not, leblanc is just annoying to play against", false),
            new Tuple<string, bool> ("i see you're a master theory crafter", false),
            new Tuple<string, bool> ("a somewhat short message2", false),
            new Tuple<string, bool> ("a somewhat short message3", true),
              };

              var total = new List<Message>();
              foreach (var tuple in testList) {
            total.Add(new PublicMessage(tuple.Item1));
            var op = total.First();
            var context = total.Skip(1).ToList();
            var testCase = new Banner(op, null, context).SelfSpam();
            if (tuple.Item2) {
              Assert.IsNotNull(testCase);
            } else {
              Assert.IsNull(testCase);
            }
              }
        }
        public void CanReadTest()
        {
            ConcatenatedStream cStream = new ConcatenatedStream(streamSampleOne, streamSampleTwo, streamSampleThree);

            int totalLength = sampleStreamSize * 2;

            List<byte> output = new List<byte>();

            while (cStream.CanRead)
            {
                output.Add((byte)cStream.ReadByte());
            }

            Assert.IsTrue(
                output.Take(sampleStreamSize).SequenceEqual(streamSampleOne.ToArray()),
                "First array does not match");

            Assert.IsTrue(
                output.Skip(sampleStreamSize).Take(sampleStreamSize).SequenceEqual(streamSampleTwo.ToArray()),
                "Second array does not match");

            Assert.IsTrue(
                output.Skip(sampleStreamSize * 2).Take(sampleStreamSize).SequenceEqual(streamSampleThree.ToArray()),
                "Third array does not match");
        }
 public void VerifyTerminalVelocityReached()
 {
     List<double> velocities = new List<double> { 0 };
     const int MAX_ITER = 10000;
     while (velocities.Count < MAX_ITER)
         velocities.Add(VelocitySimulation.CalculateNewVelocity(velocities.Last()));
     Assert.IsTrue(Math.Abs(velocities.Skip(MAX_ITER - 100).Take(100).Average() - velocities.Last()) < 0.001);
 }
        private List<string> GetMethodCode(List<string> codeLines, string functionName)
        {
            const int lineNumbersToRead = 20;

            // find line number where the method starts, check if, the method name does not occur in comment line
            int findNeighbourLineNumber = codeLines.FindIndex(line => line.Contains(functionName) && !line.Contains("//"));

            // just take the 20 following lines of the beginning line of the method
            // TODO: could make it more accurate and find end of method
            return codeLines.Skip(findNeighbourLineNumber - 1).Take(lineNumbersToRead).ToList();
        }
Example #8
0
        public void TestXmlSerializer_IEnumerable()
        {
            IEnumerable<int> list = new List<int>() { 1, 2, 3, 4 };

            var xml = XmlSerializer.Serialize(list);

            var roundTrip = (XmlSerializer.Deserialize(xml) as IEnumerable).Cast<int>();

            Assert.IsNotNull(roundTrip);
            Assert.AreEqual<int>(list.Count(), roundTrip.Count());
            int count = list.Count();
            for (int i = 0; i < count; i++)
            {
                Assert.AreEqual<int>(list.Skip(i).First(), roundTrip.Skip(i).First());
            }
        }
        public void ShouldListAllArtists()
        {
            // Arrange
            List<string> artists = new List<string>
            {
                "1", "2", "3", "4"
            };

            Dictionary<string, IEnumerable<string>> genreArtistMap = new Dictionary<string, IEnumerable<string>>
            {
                { "Pop", artists.Take(2) },
                { "Rock", artists.Skip(2).Take(2) }
            };

            IArtistsRepository repos = MockArtistsRepository.CreateMockRepository(genreArtistMap);

            ArtistsController controller = new ArtistsController(repos);

            // Act
            ViewResult result = controller.AllArtists(1);

            // Assert
            Assert.AreEqual("", result.ViewName);
        }
Example #10
0
        public void TestSendMessageIteration()
        {
            var array = new List<int>{1,2,3,4,5,6,7,8,9};
            var max = 2;
            var iterations = array.Count / max;

            for (int i = 0; i < iterations + 1; i++)
            {
                array.Skip(i * max).Take(max).ToList<int>().ForEach(it =>{
                    Console.WriteLine(it);
                });
            }
        }
Example #11
0
        public void TestSaveAndGet_IEnumerable()
        {
            IEnumerable<int> testList = new List<int>() { 1, 2, 3, 4 };

            testFile.SaveItem(key, testList);

            var roundtrip = testFile.GetItem<IEnumerable>(key).Cast<int>();

            Assert.IsNotNull(testList);
            Assert.IsNotNull(roundtrip);

            Assert.AreEqual<int>(testList.Count(), roundtrip.Count());

            int count = testList.Count();
            for (int i = 0; i < count; i++)
            {
                Assert.AreEqual<int>(testList.Skip(i).First(), roundtrip.Skip(i).First());
            }
        }
Example #12
0
        internal async Task TestAllReduceInternal()
        {
            var data = Enumerable.Range(1, 1000).Select(_ => Generator.GenerateShared(10)).ToList();

            var stringSerializerCompiler = (VowpalWabbitSingleExampleSerializerCompiler<CbAdfShared>)
                VowpalWabbitSerializerFactory.CreateSerializer<CbAdfShared>(new VowpalWabbitSettings { EnableStringExampleGeneration = true });
            var stringSerializerAdfCompiler = (VowpalWabbitSingleExampleSerializerCompiler<CbAdfAction>)
                VowpalWabbitSerializerFactory.CreateSerializer<CbAdfAction>(new VowpalWabbitSettings { EnableStringExampleGeneration = true });

            var stringData = new List<List<string>>();

            VowpalWabbitPerformanceStatistics statsExpected;
            using (var spanningTree = new SpanningTreeClr())
            {
                spanningTree.Start();

                using (var vw1 = new VowpalWabbit(new VowpalWabbitSettings(@"--total 2 --node 1 --unique_id 0 --span_server localhost --cb_adf --rank_all --interact xy") { EnableStringExampleGeneration = true }))
                using (var vw2 = new VowpalWabbit(new VowpalWabbitSettings(@"--total 2 --node 0 --unique_id 0 --span_server localhost --cb_adf --rank_all --interact xy") { EnableStringExampleGeneration = true } ))
                {
                    var stringSerializer = stringSerializerCompiler.Func(vw1);
                    var stringSerializerAdf = stringSerializerAdfCompiler.Func(vw1);

                    // serialize
                    foreach (var d in data)
                    {
                        var block = new List<string>();

                        using (var context = new VowpalWabbitMarshalContext(vw1))
                        {
                            stringSerializer(context, d.Item1, SharedLabel.Instance);
                            block.Add(context.ToString());
                        }

                        block.AddRange(d.Item2.Select((a, i) =>
                            {
                                using (var context = new VowpalWabbitMarshalContext(vw1))
                                {
                                    stringSerializerAdf(context, a, i == d.Item3.Action ? d.Item3 : null);
                                    return context.ToString();
                                }
                            }));

                        stringData.Add(block);
                    }

                    await Task.WhenAll(
                        Task.Factory.StartNew(() => Ingest(vw1, stringData.Take(500))),
                        Task.Factory.StartNew(() => Ingest(vw2, stringData.Skip(500))));

                    vw1.SaveModel("expected.1.model");
                    vw2.SaveModel("expected.2.model");

                    statsExpected = vw1.PerformanceStatistics;
                }
            }

            // skip header
            var expected1Model = File.ReadAllBytes("expected.1.model").Skip(0x15).ToList();
            var expected2Model = File.ReadAllBytes("expected.2.model").Skip(0x15).ToList();

            var settings = new VowpalWabbitSettings("--cb_adf --rank_all --interact xy")
            {
                ParallelOptions = new ParallelOptions
                {
                    MaxDegreeOfParallelism = 2
                },
                ExampleCountPerRun = 2000,
                ExampleDistribution = VowpalWabbitExampleDistribution.RoundRobin
            };

            using (var vw = new VowpalWabbitThreadedLearning(settings))
            {
                await Task.WhenAll(
                    Task.Factory.StartNew(() => Ingest(vw, stringData.Take(500))),
                    Task.Factory.StartNew(() => Ingest(vw, stringData.Skip(500))));

                // important to enqueue the request before Complete() is called
                var statsTask = vw.PerformanceStatistics;
                var modelSave = vw.SaveModel("actual.model");

                await vw.Complete();

                var statsActual = await statsTask;
                VWTestHelper.AssertEqual(statsExpected, statsActual);

                await modelSave;

                // skip header
                var actualModel = File.ReadAllBytes("actual.model").Skip(0x15).ToList();

                CollectionAssert.AreEqual(expected1Model, actualModel);
                CollectionAssert.AreEqual(expected2Model, actualModel);
            }

            using (var vw = new VowpalWabbitThreadedLearning(settings))
            {
                var vwManaged = vw.Create<CbAdfShared, CbAdfAction>();

                await Task.WhenAll(
                    Task.Factory.StartNew(() => Ingest(vwManaged, data.Take(500))),
                    Task.Factory.StartNew(() => Ingest(vwManaged, data.Skip(500))));

                // important to enqueue the request before Complete() is called
                var statsTask = vw.PerformanceStatistics;
                var modelSave = vw.SaveModel("actual.managed.model");

                await vw.Complete();

                var statsActual = await statsTask;
                VWTestHelper.AssertEqual(statsExpected, statsActual);

                await modelSave;

                // skip header
                var actualModel = File.ReadAllBytes("actual.managed.model").Skip(0x15).ToList();

                CollectionAssert.AreEqual(expected1Model, actualModel);
                CollectionAssert.AreEqual(expected2Model, actualModel);
            }
        }
Example #13
0
        public void TestRemove()
        {
            List<int> list = new List<int> { 1, 2, 3 };
            Window<int> window = new Window<int>(list, 1);
            ReadOnlyWindow<int> readOnlyWindow = new ReadOnlyWindow<int>(list, 1);

            int[] l = list.Skip(1).ToArray();
            CollectionAssert.AreEqual(l, window);
            CollectionAssert.AreEqual(l, readOnlyWindow);

            Assert.AreEqual(2, window.Count);
            Assert.AreEqual(3, window.Length);
            Assert.AreEqual(1, window.Offset);
            Assert.AreEqual(2, readOnlyWindow.Count);
            Assert.AreEqual(3, readOnlyWindow.Length);
            Assert.AreEqual(1, readOnlyWindow.Offset);

            // Remove through window
            window.Remove(2);
            l = list.Skip(1).ToArray();
            CollectionAssert.AreEqual(l, window);
            CollectionAssert.AreEqual(l, readOnlyWindow);

            Assert.AreEqual(1, window.Count);
            Assert.AreEqual(2, window.Length);
            Assert.AreEqual(1, window.Offset);
            Assert.AreEqual(1, readOnlyWindow.Count);
            Assert.AreEqual(2, readOnlyWindow.Length);
            Assert.AreEqual(1, readOnlyWindow.Offset);

            // Remove from underlying list (note that the offset doesn't change, the window is effectively moved).
            list.Remove(1);
            l = list.Skip(1).ToArray();
            CollectionAssert.AreEqual(l, window);
            CollectionAssert.AreEqual(l, readOnlyWindow);

            Assert.AreEqual(0, window.Count);
            Assert.AreEqual(1, window.Length);
            Assert.AreEqual(1, window.Offset);
            Assert.AreEqual(0, readOnlyWindow.Count);
            Assert.AreEqual(1, readOnlyWindow.Length);
            Assert.AreEqual(1, readOnlyWindow.Offset);

            // Remove all items!
            list.Clear();

            Assert.AreEqual(0, window.Count);
            Assert.AreEqual(0, window.Length);
            Assert.AreEqual(1, window.Offset); // Note the offset is beyond the end of the underlying data
            Assert.AreEqual(0, readOnlyWindow.Count);
            Assert.AreEqual(0, readOnlyWindow.Length);
            Assert.AreEqual(1, readOnlyWindow.Offset); // Note the offset is beyond the end of the underlying data
        }
Example #14
0
        public void TestListSkipComplex()
        {
            var l = new List<int> { -1, -2, -3, -4, -5 }.ToLiveList();
            var t = l.Skip(3.ToLiveConst()).ToIndependent();

            t.Check1(
                () => Enumerable.Range(0, 5).ForEach(i => l.PublishInner.Insert(i, 100 + i)),
                state =>
                {
                    var s = state.Skip(1).First();
                    Assert.IsTrue(s.Status == StateStatus.Connected);
                    Assert.IsTrue(s.Delta.HasChange());
                    Assert.IsTrue(s.Inner.SequenceEqual(new[] { 103, 104, -1, -2, -3, -4, -5 }));
                    Assert.IsTrue(s.Delta.IndexDeltas.SequenceEqual(new[]
                    {
                        new IndexNode<int>
                        {
                            Index = 0,
                            DenseIndex = 0,
                            Data = new ListIndexDelta<int>
                            {
                                InsertItems = new[] { 103, 104, -1, -2, -3 },
                            },
                        },
                    }, new IndexNodeComparer<int>()));
                });

            l = new List<int> { -1, -2, -3, -4, -5 }.ToLiveList();
            t = l.Skip(3.ToLiveConst()).ToIndependent();

            t.Check1(
                () =>
                {
                    l.PublishInner.Insert(1, 100);
                    l.PublishInner.Insert(3, 200);
                    l.PublishInner.Insert(5, 300);
                    l.PublishInner.Insert(7, 400);
                },
                state =>
                {
                    var s = state.Skip(1).First();
                    Assert.IsTrue(s.Status == StateStatus.Connected);
                    Assert.IsTrue(s.Delta.HasChange());
                    Assert.IsTrue(s.Inner.SequenceEqual(new[] { 200, -3, 300, -4, 400, -5 }));
                    Assert.IsTrue(s.Delta.IndexDeltas.SequenceEqual(new[]
                    {
                        new IndexNode<int>
                        {
                            Index = 0,
                            DenseIndex = 0,
                            Data = new ListIndexDelta<int>
                            {
                                InsertItems = new[] { 200, -3, 300 },
                            },
                        },
                        new IndexNode<int>
                        {
                            Index = 4,
                            DenseIndex = 1,
                            Data = new ListIndexDelta<int>
                            {
                                InsertItems = new[] { 400 },
                            },
                        },
                    }, new IndexNodeComparer<int>()));
                });

            l = new List<int> { -1, -2, -3, -4, -5 }.ToLiveList();
            t = l.Skip(3.ToLiveConst()).ToIndependent();

            t.Check1(
                () =>
                {
                    l.PublishInner.Insert(1, 100);
                    l.PublishInner.Insert(3, 200);
                    l.PublishInner.RemoveAt(4);
                    l.PublishInner.Insert(5, 300);
                    l.PublishInner.Insert(7, 400);
                },
                state =>
                {
                    var s = state.Skip(1).First();
                    Assert.IsTrue(s.Status == StateStatus.Connected);
                    Assert.IsTrue(s.Delta.HasChange());
                    Assert.IsTrue(s.Inner.SequenceEqual(new[] { 200, -4, 300, -5, 400 }));
                    Assert.IsTrue(s.Delta.IndexDeltas.SequenceEqual(new[]
                    {
                        new IndexNode<int>
                        {
                            Index = 0,
                            DenseIndex = 0,
                            Data = new ListIndexDelta<int>
                            {
                                InsertItems = new[] { 200 },
                            },
                        },
                        new IndexNode<int>
                        {
                            Index = 2,
                            DenseIndex = 1,
                            Data = new ListIndexDelta<int>
                            {
                                InsertItems = new[] { 300 },
                            },
                        },
                        new IndexNode<int>
                        {
                            Index = 4,
                            DenseIndex = 2,
                            Data = new ListIndexDelta<int>
                            {
                                InsertItems = new[] { 400 },
                            },
                        },
                    }, new IndexNodeComparer<int>()));
                });
        }
		public void GetPaginationTest()
		{
			for (int i = 0; i < 20; i++)
			{
				List<int> items = new List<int>();
				for (int j = 0; j < i; j++)
				{
					items.Add(j);
				}

				for (int resultsPerPage = 1; resultsPerPage < 21; resultsPerPage++)
				{
					var pageNumber = 0;
					var page = items.GetPagination(resultsPerPage, ref pageNumber);
					Assert.IsTrue(page.Count <= resultsPerPage);
					Assert.IsTrue(page.IsEqualOrdered(items.Take(resultsPerPage).ToList()));

					pageNumber = 99; // last page
					page = items.GetPagination(resultsPerPage, ref pageNumber);
					Assert.AreNotEqual(pageNumber, 99, i + " / " + resultsPerPage);
					Assert.IsTrue(page.Count <= resultsPerPage);
					if (items.Count > 0)
					{
						Assert.IsTrue(page.Count > 0, i + " / " + resultsPerPage);
						Assert.IsTrue(page.IsEqualOrdered(items.Skip(items.Count - page.Count).Take(page.Count).ToList()));
					}
				}
			}
		}
Example #16
0
        public void Skip()
        {
            // arrange
            List<int> list = new List<int>() { 1, 2, 3 };

            // act
            List<int> actual = list.Skip(2).ToList();
            List<int> actualOver = list.Skip(3).ToList();

            // assert
            Assert.AreEqual(3, actual[0]);
            Assert.AreEqual(0, actualOver.Count());
        }
        private Mock<IBlogPostRepository> CreateMockedBlogPostRepository(int numberOfPosts)
        {
            var blogPosts = new List<BlogPost>();

            for (int i = 0; i < numberOfPosts; i++)
            {
                var post = new BlogPost(i.ToString(), i.ToString(), i.ToString(), new ImageReference(1, "/noimage.jpg"), DateTime.Now, new BlogUser());
                blogPosts.Add(post);
            }

            var mockedBlogPostRepository = new Mock<IBlogPostRepository>();

            mockedBlogPostRepository.SetupGet(r => r.Count).Returns(numberOfPosts);
            mockedBlogPostRepository.Setup(r => r.GetPosts(It.IsAny<int>(), It.IsAny<int>(), It.IsAny<IEnumerable<string>>()))
                .Returns<int, int, IEnumerable<string>>((skip, take, tags) => blogPosts.Skip(skip).Take(take));

            return mockedBlogPostRepository;
        }
Example #18
0
        public void TestLinqExpr()
        {
            var A = new Dictionary<string, List<string>>
            {
                {"dbo.Table00", new List<string> {"column10", "column11", "column12", "column00"}}
            };
            var B = new Dictionary<string, List<string>>
            {
                {"dbo.Table10", new List<string> {"column10", "column11", "column02"}}
            };

            System.Diagnostics.Debug.WriteLine("Union");

            var union = A.SelectMany(x => x.Value).Union(B.SelectMany(y => y.Value));
            foreach (var r in union)
                System.Diagnostics.Debug.WriteLine(r);

            System.Diagnostics.Debug.WriteLine("");

            System.Diagnostics.Debug.WriteLine("Intesect");
            var intersect = A.SelectMany(x => x.Value).Intersect(B.SelectMany(y => y.Value));
            foreach(var r in intersect)
                System.Diagnostics.Debug.WriteLine(r);

            System.Diagnostics.Debug.WriteLine("");

            System.Diagnostics.Debug.WriteLine("Set Difference");
            var setDiff = A.SelectMany(x => x.Value).Except(B.SelectMany(y => y.Value));
            foreach(var r in setDiff)
                System.Diagnostics.Debug.WriteLine(r);

            System.Diagnostics.Debug.WriteLine("");

            System.Diagnostics.Debug.WriteLine("Symetric Difference");
            var symetricDiff =
                A.SelectMany(x => x.Value)
                    .Except(B.SelectMany(y => y.Value))
                    .Union(B.SelectMany(y => y.Value).Except(A.SelectMany(x => x.Value)));

            foreach(var r in symetricDiff)
                System.Diagnostics.Debug.WriteLine(r);

            System.Diagnostics.Debug.WriteLine("");

            var Alist = new List<string> {"column10", "column11", "column12", "column00"};
            var BList = new List<string> {"column10", "column11", "column02"};

            var simpleListSetDiff = Alist.Select(x => x).Except(BList.Select(y => y)).ToList();

            System.Diagnostics.Debug.WriteLine("Set Difference (on simple lists)");
            foreach(var li in simpleListSetDiff)
                System.Diagnostics.Debug.WriteLine(li);

            //powershell'esque array splice
            var myList = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,17 };
            var lastIndex = myList.Count - 1;

            var left = myList.Take(16).ToList();
            var right = myList.Skip(16).Take(myList.Count).ToList();
            foreach(var dk in right)
                System.Diagnostics.Debug.WriteLine(dk);
        }
        public void Search_Multiple_Results_Verify_Result()
        {
            var nonEmptyQuery = "tfs";
            var expectedResults = new List<SearchResultItem>()
                                      {
                                          new SearchResultItem("101", "102", "description 113"),
                                          new SearchResultItem("201", "202", "description 213"),
                                          new SearchResultItem("301", "302", "description 313"),
                                          new SearchResultItem("401", "402", "description 413"),
                                      };
            var output = new List<LocalViewwwJob>()
                             {
                                    new LocalViewwwJob
                                    {
                                        RecordId = 101,
                                        Creator = 102,
                                        Created = DateTime.Now,
                                        Session = 103,
                                        StartTime = DateTime.Now,
                                        Duration = 104,
                                        Customer = 105,
                                        Project = 106,
                                        ProjectId = "107-108",
                                        ProjectDescription = "project 109",
                                        JobType = 110,
                                        RateGroup = 111,
                                        RateName = 112,
                                        Description = "description 113",
                                        Enabled = false,
                                        ForceJobsEnabled = false
                                    },
                                    new LocalViewwwJob
                                    {
                                        RecordId = 201,
                                        Creator = 202,
                                        Created = DateTime.Now,
                                        Session = 203,
                                        StartTime = DateTime.Now,
                                        Duration = 204,
                                        Customer = 205,
                                        Project = 206,
                                        ProjectId = "207-208",
                                        ProjectDescription = "project 209",
                                        JobType = 210,
                                        RateGroup = 211,
                                        RateName = 212,
                                        Description = "description 213",
                                        Enabled = false,
                                        ForceJobsEnabled = false
                                    },
                                    new LocalViewwwJob
                                    {
                                        RecordId = 301,
                                        Creator = 302,
                                        Created = DateTime.Now,
                                        Session = 303,
                                        StartTime = DateTime.Now,
                                        Duration = 304,
                                        Customer = 305,
                                        Project = 306,
                                        ProjectId = "307-308",
                                        ProjectDescription = "project 309",
                                        JobType = 310,
                                        RateGroup = 311,
                                        RateName = 312,
                                        Description = "description 313",
                                        Enabled = false,
                                        ForceJobsEnabled = false
                                    },
                                    new LocalViewwwJob
                                    {
                                        RecordId = 401,
                                        Creator = 402,
                                        Created = DateTime.Now,
                                        Session = 403,
                                        StartTime = DateTime.Now,
                                        Duration = 404,
                                        Customer = 405,
                                        Project = 406,
                                        ProjectId = "407-408",
                                        ProjectDescription = "project 409",
                                        JobType = 410,
                                        RateGroup = 411,
                                        RateName = 412,
                                        Description = "description 413",
                                        Enabled = false,
                                        ForceJobsEnabled = false
                                    },
                             };

            _mockDataAccessLayer1.Setup(x => x.Fetch(nonEmptyQuery)).Returns(output.Take(2).Select(job => job as IConvertableTo<SearchResultItem>).ToList());
            _mockDataAccessLayer2.Setup(x => x.Fetch(nonEmptyQuery)).Returns(output.Skip(2).Select(job => job as IConvertableTo<SearchResultItem>).ToList());

            List<SearchResultItem> results = _searchService.Search(nonEmptyQuery);

            Assert.IsNotNull(results);
            Assert.AreEqual(4, results.Count);
            foreach (SearchResultItem expectedInResult in expectedResults)
            {
                Assert.IsTrue(results.Any(r => r.EmployeeKey == expectedInResult.EmployeeKey && r.EntryKey == expectedInResult.EntryKey && r.ProjectKey == expectedInResult.ProjectKey));
            }
        }
Example #20
0
        public void TestSkipAndTakeWorksLikePs1()
        {
            var myList = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
            var lastIndex = myList.Count - 1;
            var myI = 7;

            var left = myList.Take(myI).ToList();
            var printMySkipTakeList = string.Join(",", left);
            System.Diagnostics.Debug.WriteLine(printMySkipTakeList);

            var right = myList.Skip(myI+1).Take(lastIndex).ToList();
            left.AddRange(right);

            printMySkipTakeList = string.Join(",", left);
            System.Diagnostics.Debug.WriteLine(printMySkipTakeList);
        }
        private List<PersonDto> GetPersonList(int count, int skip = 0)
        {
            var people = new List<PersonDto>() {
                        new PersonDto() { DateOfBirth = new DateTime(1980, 1, 1), Id = "1", Name = "Terrence" },
                        new PersonDto() { DateOfBirth = new DateTime(1981, 1, 1), Id = "2", Name = "Boris" },
                        new PersonDto() { DateOfBirth = new DateTime(1982, 1, 1), Id = "3", Name = "Bob" },
                        new PersonDto() { DateOfBirth = new DateTime(1983, 1, 1), Id = "4", Name = "Jane" },
                        new PersonDto() { DateOfBirth = new DateTime(1984, 1, 1), Id = "5", Name = "Rachel" },
                        new PersonDto() { DateOfBirth = new DateTime(1985, 1, 1), Id = "6", Name = "Sarah" },
                        new PersonDto() { DateOfBirth = new DateTime(1986, 1, 1), Id = "7", Name = "Brad" },
                        new PersonDto() { DateOfBirth = new DateTime(1987, 1, 1), Id = "8", Name = "Phillip" },
                        new PersonDto() { DateOfBirth = new DateTime(1988, 1, 1), Id = "9", Name = "Cory" },
                        new PersonDto() { DateOfBirth = new DateTime(1989, 1, 1), Id = "10", Name = "Burt" },
                        new PersonDto() { DateOfBirth = new DateTime(1990, 1, 1), Id = "11", Name = "Gladis" },
                        new PersonDto() { DateOfBirth = new DateTime(1991, 1, 1), Id = "12", Name = "Ethel" },

                        new PersonDto() { DateOfBirth = new DateTime(1992, 1, 1), Id = "13", Name = "Terry" },
                        new PersonDto() { DateOfBirth = new DateTime(1993, 1, 1), Id = "14", Name = "Bernie" },
                        new PersonDto() { DateOfBirth = new DateTime(1994, 1, 1), Id = "15", Name = "Will" },
                        new PersonDto() { DateOfBirth = new DateTime(1995, 1, 1), Id = "16", Name = "Jim" },
                        new PersonDto() { DateOfBirth = new DateTime(1996, 1, 1), Id = "17", Name = "Eva" },
                        new PersonDto() { DateOfBirth = new DateTime(1997, 1, 1), Id = "18", Name = "Susan" },
                        new PersonDto() { DateOfBirth = new DateTime(1998, 1, 1), Id = "19", Name = "Justin" },
                        new PersonDto() { DateOfBirth = new DateTime(1999, 1, 1), Id = "20", Name = "Gerry" },
                        new PersonDto() { DateOfBirth = new DateTime(2000, 1, 1), Id = "21", Name = "Fitz" },
                        new PersonDto() { DateOfBirth = new DateTime(2001, 1, 1), Id = "22", Name = "Ellie" },
                        new PersonDto() { DateOfBirth = new DateTime(2002, 1, 1), Id = "23", Name = "Gordon" },
                        new PersonDto() { DateOfBirth = new DateTime(2003, 1, 1), Id = "24", Name = "Gail" },
                        new PersonDto() { DateOfBirth = new DateTime(2004, 1, 1), Id = "25", Name = "Gary" },
                        new PersonDto() { DateOfBirth = new DateTime(2005, 1, 1), Id = "26", Name = "Gabby" }
                    };

            return people.Skip(skip).Take(count).ToList();
        }
Example #22
0
        public void TestListSkip()
        {
            var l = new List<int> { 1, 2, 3, 4, 5 }.ToLiveList();
            var t = l.Skip(3.ToLiveConst()).ToIndependent();

            t.States().Take(1).Check(
                () => { },
                state =>
                {
                    var s = state.Single();
                    Assert.IsTrue(s.Status == StateStatus.Connecting);
                    Assert.IsTrue(s.Inner.SequenceEqual(new[] { 4, 5 }));
                    Assert.IsTrue(s.Delta == null);
                });

            t.States().Skip(1).Take(1).Check(
                () => l.PublishInner.Insert(0, 0),
                state =>
                {
                    var s = state.Single();
                    Assert.IsTrue(s.Status == StateStatus.Connected);
                    Assert.IsTrue(s.Inner.SequenceEqual(new[] { 3, 4, 5 }));
                    Assert.IsTrue(s.Delta.IndexDeltas.SequenceEqual(new[]
                    {
                        new IndexNode<int>
                        {
                            Index = 0,
                            DenseIndex = 0,
                            Data = new ListIndexDelta<int>
                            {
                                InsertItems = new[] { 3 },
                            },
                        },
                    }, new IndexNodeComparer<int>()));
                });

            t.States().Skip(1).Take(1).Check(
                () => l.PublishInner.RemoveAt(0),
                state =>
                {
                    var s = state.Single();
                    Assert.IsTrue(s.Status == StateStatus.Connected);
                    Assert.IsTrue(s.Inner.SequenceEqual(new[] { 4, 5 }));
                    Assert.IsTrue(s.Delta.IndexDeltas.SequenceEqual(new[]
                    {
                        new IndexNode<int>
                        {
                            Index = 0,
                            DenseIndex = 0,
                            Data = new ListIndexDelta<int>
                            {
                                DeleteItems = new[] { 3 },
                            },
                        },
                    }, new IndexNodeComparer<int>()));
                });

            t.States().Skip(1).Take(1).Check(
                () => l.PublishInner[1] = 99,
                state => Assert.AreEqual(0, state.Count()));

            t.States().Skip(1).Take(1).Check(
                () => l.PublishInner[3] = 88,
                state =>
                {
                    var s = state.Single();
                    Assert.IsTrue(s.Status == StateStatus.Connected);
                    Assert.IsTrue(s.Delta.HasChange());
                    Assert.IsTrue(s.Inner.SequenceEqual(new[] { 88, 5 }));
                    Assert.IsTrue(s.Delta.IndexDeltas.SequenceEqual(new[]
                    {
                        new IndexNode<int>
                        {
                            Index = 0,
                            DenseIndex = 0,
                            Data = new ListIndexDelta<int>
                            {
                                InsertItems = new[] { 88 },
                                DeleteItems = new[] { 4 },
                            },
                        },
                    }, new IndexNodeComparer<int>()));
                });

            t.Check1(
                () =>
                {
                    l.PublishInner.Insert(0, -1);
                    l.PublishInner.Insert(3, 77);
                },
                state =>
                {
                    var s = state.Skip(1).First();
                    Assert.IsTrue(s.Status == StateStatus.Connected);
                    Assert.IsTrue(s.Delta.HasChange());
                    Assert.IsTrue(s.Inner.SequenceEqual(new[] { 77, 3, 88, 5 }));
                    Assert.IsTrue(s.Delta.IndexDeltas.SequenceEqual(new[]
                    {
                        new IndexNode<int>
                        {
                            Index = 0,
                            DenseIndex = 0,
                            Data = new ListIndexDelta<int>
                            {
                                InsertItems = new[] { 77, 3 },
                            },
                        },
                    }, new IndexNodeComparer<int>()));
                });

            t.States().Skip(1).Take(1).Check(
                () => l.PublishInner[2] = -1,
                state => Assert.AreEqual(0, state.Count()));
        }
Example #23
0
        public void TestInsert()
        {
            List<int> list = new List<int> { 1, 2, 3 };
            Window<int> window = new Window<int>(list, 1);
            ReadOnlyWindow<int> readOnlyWindow = new ReadOnlyWindow<int>(list, 1);

            int[] l = list.Skip(1).ToArray();
            CollectionAssert.AreEqual(l, window);
            CollectionAssert.AreEqual(l, readOnlyWindow);

            Assert.AreEqual(2, window.Count);
            Assert.AreEqual(3, window.Length);
            Assert.AreEqual(1, window.Offset);
            Assert.AreEqual(2, readOnlyWindow.Count);
            Assert.AreEqual(3, readOnlyWindow.Length);
            Assert.AreEqual(1, readOnlyWindow.Offset);

            // Insert through window
            window.Insert(1, 4);
            Assert.AreEqual(4, list[2]);
            Assert.AreEqual(window[1], list[2]);

            l = list.Skip(1).ToArray();
            CollectionAssert.AreEqual(l, window);
            CollectionAssert.AreEqual(l, readOnlyWindow);

            Assert.AreEqual(3, window.Count);
            Assert.AreEqual(4, window.Length);
            Assert.AreEqual(1, window.Offset);
            Assert.AreEqual(3, readOnlyWindow.Count);
            Assert.AreEqual(4, readOnlyWindow.Length);
            Assert.AreEqual(1, readOnlyWindow.Offset);

            // Insert through underlying data
            list.Insert(3, 5);
            Assert.AreEqual(5, list[3]);
            Assert.AreEqual(window[2], list[3]);

            l = list.Skip(1).ToArray();
            CollectionAssert.AreEqual(l, window);
            CollectionAssert.AreEqual(l, readOnlyWindow);

            Assert.AreEqual(4, window.Count);
            Assert.AreEqual(5, window.Length);
            Assert.AreEqual(1, window.Offset);
            Assert.AreEqual(4, readOnlyWindow.Count);
            Assert.AreEqual(5, readOnlyWindow.Length);
            Assert.AreEqual(1, readOnlyWindow.Offset);
        }
Example #24
0
        public void OcrParallelizationExperiment()
        {
            // Init Drive
            var relpath = Path.Combine(Dir.OcrDirectory, Dir.OcrParallelizationTesting);
            var drive = new Drive(relpath, Drive.Reason.Read);
            var regs = drive.Files("reg").ToList();
            var revs = drive.Files("rev").ToList();

            // Sort to ensure correct pairing
            regs.Sort();
            revs.Sort();

            // Concatenate and Recognize
            var images = regs.Concat(revs).Select(path => new Bitmap(path)).ToList();
            int revStart = regs.Count;
            var datas = new List<OcrData>(OCR.ParallelRecognize(images, images.Count(), Accuracy.Low, "eng", true));
            var regdata = datas.Take(revStart);
            var revdata = datas.Skip(revStart);

            var difference = regdata.Zip(revdata, (reg, rev) =>
                {
                    Console.WriteLine("-----------------------------------------------");
                    Console.WriteLine(OCR.StripNewLine(reg.Text + " vs " + rev.Text));
                    Console.WriteLine(reg.Cost + " vs " + rev.Cost);
                    Console.WriteLine("Diff: " + (reg.Cost - rev.Cost));
                    Console.WriteLine("scantime: " + reg.ScanTime + "ms and " + rev.ScanTime + "ms");
                    Console.WriteLine();
                    return reg.Cost - rev.Cost;
                }).ToList();

            difference.ForEach(diff => Assert.IsTrue(diff < 0));
        }