public void ArraysShouldBeRoundtrippable()
        {
            new TestScheduler().With(sched =>
            {
                string path;
                var input = new[] {new UserObject {Bio = "A totally cool cat!", Name = "octocat", Blog = "http://www.github.com"}, new UserObject {Bio = "zzz", Name = "sleepy", Blog = "http://example.com"}};
                UserObject[] result;

                using (Utility.WithEmptyDirectory(out path))
                {
                    using (var fixture = CreateBlobCache(path))
                    {
                        fixture.InsertObject("key", input);
                    }
                    sched.Start();
                    using (var fixture = CreateBlobCache(path))
                    {
                        var action = fixture.GetObjectAsync<UserObject[]>("key");
                        sched.Start();
                        result = action.First();
                    }
                }

                Assert.Equal(input.First().Blog, result.First().Blog);
                Assert.Equal(input.First().Bio, result.First().Bio);
                Assert.Equal(input.First().Name, result.First().Name);
                Assert.Equal(input.Last().Blog, result.Last().Blog);
                Assert.Equal(input.Last().Bio, result.Last().Bio);
                Assert.Equal(input.Last().Name, result.Last().Name);
            });
        }
Esempio n. 2
0
        static CubeHash()
        {
            var hashes = new[] {28, 32, 48, 64};
            var rounds = new[] {1, 2, 4, 8, 16};
            var blocksizes = new[] {1, 2, 4, 8, 16, 32, 64, 128};
            var inits = new uint[rounds.Last() + 1,hashes.Last() + 1,blocksizes.Last() + 1][];
            var zeroes = new byte[blocksizes.Last()];

            foreach(int round in rounds)
            {
                foreach(int hashsize in hashes)
                {
                    foreach(int blocksize in blocksizes)
                    {
                        CubeHash ch = new CubeHashCustom(HashLib.HashSize.HashSize256, round, blocksize);

                        ch.m_state[0] = (uint)hashsize;
                        ch.m_state[1] = (uint)blocksize;
                        ch.m_state[2] = (uint)round;

                        for(int i = 0; i < 10; i++)
                            ch.TransformBlock(zeroes, 0);

                        inits[round, hashsize, blocksize] = new uint[32];
                        Array.Copy(ch.m_state, inits[round, hashsize, blocksize], 32);
                    }
                }
            }

            m_inits = inits;
        }
        public void ArraysShouldBeRoundtrippableUsingObjectFactory()
        {
            new TestScheduler().With(sched =>
            {
                string path;
                var input = new[] {new UserModel(new UserObject()) {Age = 123, Name = "Old"}, new UserModel(new UserObject()) {Age = 123, Name = "Old"}};
                UserModel[] result;

                using (Utility.WithEmptyDirectory(out path))
                {
                    using (var fixture = new TPersistentBlobCache(path))
                    {
                        fixture.InsertObject("key", input);
                    }
                    sched.Start();
                    using (var fixture = new TPersistentBlobCache(path))
                    {
                        var action = fixture.GetObjectAsync<UserModel[]>("key");
                        sched.Start();
                        result = action.First();
                    }
                }

                Assert.Equal(input.First().Age, result.First().Age);
                Assert.Equal(input.First().Name, result.First().Name);
                Assert.Equal(input.Last().Age, result.Last().Age);
                Assert.Equal(input.Last().Name, result.Last().Name);
            });
        }
Esempio n. 4
0
    public static void Main () {
        var ints = new[] { 1, 2, 3, 4 };

        Console.WriteLine(ints.Last());

        Console.WriteLine(ints.Last((i) => i < 3));

        // Test the non-IList path
        Console.WriteLine(ints.Skip(1).Last());

        Console.WriteLine(ints.Skip(1).Last((i) => i < 3));
    }
		public static void PathEquals(this Uri u, string pathAndQueryString)
		{
			var paths = (pathAndQueryString ?? "").Split(new[] { '?' }, 2);

			string path = paths.First(), query = string.Empty;
			if (paths.Length > 1)
				query = paths.Last();

			var expectedUri = new UriBuilder("http", "localhost", u.Port, path, "?" + query).Uri;

			u.AbsolutePath.Should().Be(expectedUri.AbsolutePath);
			u = new UriBuilder(u.Scheme, u.Host, u.Port, u.AbsolutePath, u.Query.Replace("pretty=true&", "").Replace("pretty=true", "")).Uri;

			var queries = new[] { u.Query, expectedUri.Query };
			if (queries.All(string.IsNullOrWhiteSpace)) return;
			if (queries.Any(string.IsNullOrWhiteSpace))
			{
				queries.Last().Should().Be(queries.First());
				return;
			}

			var clientKeyValues = u.Query.Substring(1).Split('&')
				.Select(v => v.Split('='))
				.Where(k => !string.IsNullOrWhiteSpace(k[0]))
				.ToDictionary(k => k[0], v => v.Last());
			var expectedKeyValues = expectedUri.Query.Substring(1).Split('&')
				.Select(v => v.Split('='))
				.Where(k => !string.IsNullOrWhiteSpace(k[0]))
				.ToDictionary(k => k[0], v => v.Last());

			clientKeyValues.Count.Should().Be(expectedKeyValues.Count);
			clientKeyValues.Should().ContainKeys(expectedKeyValues.Keys.ToArray());
			clientKeyValues.Should().Equal(expectedKeyValues);
		}
        public void Should_route_to_pared_down_process()
        {
            var messageABC = new SequentialProcess
            {
                StepAInfo = "Foo",
                StepBInfo = "Bar",
                StepCInfo = "Baz",
            };

            var destinations = new[]
            {
                "NServiceBus.MessageRouting.RoutingSlips.Samples.StepA",
                "NServiceBus.MessageRouting.RoutingSlips.Samples.StepC",
                "NServiceBus.MessageRouting.RoutingSlips.Samples.ResultHost",
            };

            Console.WriteLine("Sending message...");

            var last = destinations.Last();

            var events = _fixture.SendAndWait(
                bus => bus.Route(messageABC, Guid.NewGuid(), destinations),
                c => c.Endpoint != last,
                TimeSpan.FromSeconds(60)).ToArray();

            events.Count().ShouldEqual(3);
        }
Esempio n. 7
0
        static int CalculateRibbon(Package package)
        {
            IEnumerable<int> smallest = new[] { package.Length, package.Width, package.Height }.OrderBy(x => x).Take(2);

            int ribbon = (smallest.First() * 2) + (smallest.Last() * 2) + (package.Length * package.Width * package.Height);

            return ribbon;
        }
Esempio n. 8
0
 public void DataChunk_WithTwoItems_SetsLastItem()
 {
     //Arrange
     var input = new[] { "Johnson", "Controls" };
     //Act
     var actual = new DataChunk<string>(input, isEnd: true);
     //Assert
     Assert.AreEqual(input.Last(), actual.LastElement, "Failed to set last item of enumeration.");
 }
Esempio n. 9
0
 public void OrderBy_DoesNotSort_WhenExpressionsIsNull()
 {
     var data = new[]
     {
         new User { Name = "user2" },
         new User { Name = "user3" },
         new User { Name = "user1" },
     };
     var orderedQueryable = data.AsQueryable().OrderBy(null);
     orderedQueryable.Count().ShouldEqual(3);
     orderedQueryable.First().ShouldEqual(data.First());
     orderedQueryable.Skip(1).First().ShouldEqual(data.Skip(1).First());
     orderedQueryable.Last().ShouldEqual(data.Last());
 }
Esempio n. 10
0
 public void OrderBy_SortsSimpleQueryable_Ascending()
 {
     var data = new[]
     {
         new User { Name = "user2" },
         new User { Name = "user3" },
         new User { Name = "user1" },
     };
     var orderBy = new Dictionary<Expression<Func<User, object>>, OrderByDirection>
     {
         { x => x.Name, OrderByDirection.Ascending },
     };
     var orderedQueryable = data.AsQueryable().OrderBy(orderBy);
     orderedQueryable.Count().ShouldEqual(3);
     orderedQueryable.First().ShouldEqual(data.Last());
     orderedQueryable.Skip(1).First().ShouldEqual(data.First());
     orderedQueryable.Last().ShouldEqual(data.Skip(1).First());
 }
		public void GetSameMappingFromTwoDifferentIndices()
		{
			var indices = new[]
			{
				ElasticsearchConfiguration.NewUniqueIndexName(),
				ElasticsearchConfiguration.NewUniqueIndexName()
			};

			var x = this.Client.CreateIndex(indices.First(), s => s
				.AddMapping<ElasticsearchProject>(m => m.MapFromAttributes())
			);
			Assert.IsTrue(x.Acknowledged, x.ConnectionStatus.ToString());

			x = this.Client.CreateIndex(indices.Last(), s => s
				.AddMapping<ElasticsearchProject>(m => m.MapFromAttributes())
			);
			Assert.IsTrue(x.Acknowledged, x.ConnectionStatus.ToString());

			var response = this.Client.GetMapping<ElasticsearchProject>(i => i
				.Index(string.Join(",", indices))
				.Type("elasticsearchprojects")
			);
			response.Should().NotBeNull();
			response.Mappings.Should().NotBeEmpty()
				.And.HaveCount(2);
			foreach (var indexMapping in response.Mappings)
			{
				var indexName = indexMapping.Key;
				indices.Should().Contain(indexName);
				var mappings = indexMapping.Value;
				mappings.Should().NotBeEmpty().And.HaveCount(1);
				foreach (var mapping in mappings)
				{
					mapping.TypeName.Should().Be("elasticsearchprojects");
					TestElasticsearchProjectMapping(mapping.Mapping);
				}
			}


		}
Esempio n. 12
0
        public void LastWorks()
        {
            var sut = new[] {1, 2, 3};
            Assert.AreEqual(3, sut.Last());
            var sut2 = new int[0];
            Assert.AreEqual(0, sut2.Last());
            try {
                Assert.AreEqual(0, sut2.Last(true));
                throw new Exception("This line should not be reached.");
            }
            catch (InvalidOperationException) {}

            var sut3 = new[] {"1", "2", "3"};
            Assert.AreEqual("3", sut3.Last());
            var sut4 = new string[0];
            Assert.Null(sut4.Last());
            try {
                Assert.Null(sut4.Last(true));
                throw new Exception("This line should not be reached.");
            }
            catch (InvalidOperationException) {}
        }
        public void CourseViewHasAllStudents()
        {
            var courseId = Guid.NewGuid();

            var courses = new[]
            {
                new CourseModel { Id = Guid.NewGuid(), Name = "first name" },
                new CourseModel { Id = courseId, Name = "second name" }
            };

            mockCourseRepository.Setup(r => r.FindAll()).Returns(courses);

            var students = new[]
            {
                new StudentModel { Id = Guid.NewGuid(), FirstName = "first first name" },
                new StudentModel { Id = Guid.NewGuid(), FirstName = "second first name" }
            };

            mockStudentRepository.Setup(r => r.FindAll()).Returns(students);

            var result = controller.Course(courseId) as ViewResult;
            var model = result.Model as CoursesTakenModel;
            Assert.That(model.ToAssign.Count(), Is.EqualTo(2));

            var names = model.ToAssign.Select(a => a.Name);
            Assert.That(names, Contains.Item("first first name"));
            Assert.That(names, Contains.Item("second first name"));

            var ids = model.ToAssign.Select(a => a.Id);
            Assert.That(ids, Contains.Item(students.First().Id));
            Assert.That(ids, Contains.Item(students.Last().Id));
        }
        public void SubtypeHasFurtherSubtype()
        {
            encounterTypeAndAmount.Clear();
            encounterTypeAndAmount["creature[challenge rating]"] = "creature amount";

            requiresSubtype.Add("creature");
            requiresSubtype.Add("other creature");

            var subSubtypes = new[] { "wrong subtype", "subtype" };
            mockCollectionSelector.Setup(s => s.SelectFrom(TableNameConstants.CreatureGroups, "other creature"))
                .Returns(subSubtypes);
            mockCollectionSelector.Setup(s => s.SelectFrom(TableNameConstants.CreatureGroups, "creature"))
                .Returns(new[] { "wrong creature", "other creature" });

            mockCollectionSelector.SetupSequence(s => s.SelectRandomFrom(subSubtypes)).Returns(subSubtypes.First()).Returns(subSubtypes.Last());

            var tableName = string.Format(TableNameConstants.CREATURESubtypeChallengeRatings, "creature");
            mockCollectionSelector.Setup(s => s.SelectFrom(tableName, "other creature")).Returns(new[] { "other challenge rating" });

            tableName = string.Format(TableNameConstants.CREATURESubtypeChallengeRatings, "other creature");
            mockCollectionSelector.Setup(s => s.SelectFrom(tableName, "subtype")).Returns(new[] { "challenge rating" });
            mockRollSelector.Setup(s => s.SelectFrom(level, "challenge rating")).Returns("roll");
            mockDice.Setup(d => d.Roll("roll")).Returns(600);
            mockCollectionSelector.Setup(s => s.SelectFrom(tableName, "wrong subtype")).Returns(new[] { "wrong challenge rating" });
            mockCollectionSelector.Setup(s => s.SelectFrom(tableName, "wrong creature")).Returns(new[] { "wrong challenge rating" });
            mockRollSelector.Setup(s => s.SelectFrom(level, "wrong challenge rating")).Returns("wrong roll");
            mockDice.Setup(d => d.Roll("wrong roll")).Returns(1337);

            mockRollSelector.Setup(s => s.SelectFrom("creature amount", 9876)).Returns("creature effective roll");
            mockDice.Setup(d => d.Roll("creature effective roll")).Returns(7654);

            var encounter = encounterGenerator.Generate(environment, level, temperature, timeOfDay);
            Assert.That(encounter, Is.Not.Null);

            var creature = encounter.Creatures.Single();
            Assert.That(creature.Name, Is.EqualTo("creature"));
            Assert.That(creature.Description, Is.EqualTo("other creature (subtype)"));
            Assert.That(creature.Quantity, Is.EqualTo(7654));
            Assert.That(encounter.Characters, Is.Empty);
        }
        public void Dequeue_ShouldFetchJobs_FromMultipleQueues()
        {
            string arrangeSql = string.Format(CultureInfo.InvariantCulture, @"
                EXECUTE BLOCK (invocationData BLOB SUB_TYPE 1 SEGMENT SIZE 80 CHARACTER SET UNICODE_FSS = @invocationData,
                    arguments BLOB SUB_TYPE 1 SEGMENT SIZE 80 CHARACTER SET UNICODE_FSS = @arguments,
                    queue VARCHAR(20) CHARACTER SET UNICODE_FSS = @queue)
                AS
                DECLARE new_id int;
                BEGIN
                    INSERT INTO ""{0}.JOB"" (invocationdata, arguments, createdat) 
                    VALUES (:invocationData, :arguments, DATEADD(minute, -{1:N5}*60, current_timestamp))
                    RETURNING id INTO :new_id;
                    
                    INSERT INTO ""{0}.JOBQUEUE"" (jobid, queue) 
                    VALUES (:new_id, :queue);
                    
                    SUSPEND;
                END", _options.Prefix, _options.UtcOffset);  

            var queueNames = new[] { "default", "critical" };

            UseConnection(connection =>
            {
                connection.Execute(
                    arrangeSql,
                    new[]
                    {
                        new { queue = queueNames.First(), invocationData = "", arguments = "" },
                        new { queue = queueNames.Last(), invocationData = "", arguments = "" }
                    });

                var queue = CreateJobQueue(connection);

                var queueFirst = (FirebirdFetchedJob)queue.Dequeue(
                    queueNames,
                    CreateTimingOutCancellationToken());

                Assert.NotNull(queueFirst.JobId);
                Assert.Contains(queueFirst.Queue, queueNames);

                var queueLast = (FirebirdFetchedJob)queue.Dequeue(
                    queueNames,
                    CreateTimingOutCancellationToken());

                Assert.NotNull(queueLast.JobId);
                Assert.Contains(queueLast.Queue, queueNames);
            });
        }
        public virtual void Ensure_Correct_Timestamps_On_Revisions_Multiple_Units_Of_Work()
        {
            var e = new[]
                {
                    HiveModelCreationHelper.MockTypedEntity(), 
                    HiveModelCreationHelper.MockTypedEntity()
                };

            using (var writer = ProviderSetup.UnitFactory.Create())
            {
                e.ForEach(x => writer.EntityRepository.Revisions.AddOrUpdate(new Revision<TypedEntity>(x)));
                writer.Complete();
            }
            PostWriteCallback.Invoke();
            Thread.Sleep(TimeSpan.FromSeconds(0.7));

            using (var writer = ProviderSetup.UnitFactory.Create())
            {
                //create revisions with same status twice
                e.ForEach(x => writer.EntityRepository.Revisions.AddOrUpdate(new Revision<TypedEntity>(x)));
                writer.Complete();
            }
            PostWriteCallback.Invoke();
            Thread.Sleep(TimeSpan.FromSeconds(0.7));

            using (var writer = ProviderSetup.UnitFactory.Create())
            {
                //new revision with new draft status
                e.ForEach(x => writer.EntityRepository.Revisions.AddOrUpdate(new Revision<TypedEntity>(x) { MetaData = new RevisionData(FixedStatusTypes.Draft) }));
                writer.Complete();
            }
            PostWriteCallback.Invoke();
            Thread.Sleep(TimeSpan.FromSeconds(0.7));

            using (var writer = ProviderSetup.UnitFactory.Create())
            {
                //dont' create a saved rev for the last one
                e.Where(x => x != e.Last()).ForEach(x => writer.EntityRepository.Revisions.AddOrUpdate(new Revision<TypedEntity>(x) { MetaData = new RevisionData(FixedStatusTypes.Saved) }));
                writer.Complete();
            }
            PostWriteCallback.Invoke();

            using (var reader = ReadonlyProviderSetup.ReadonlyUnitFactory.CreateReadonly())
            {
                var result = reader.EntityRepository.Revisions.GetAll<TypedEntity>().ToArray();
                Assert.AreEqual(7, result.Count());
                //ensure entity status changed dates are correct
                Assert.AreEqual(3, result.Where(x => x.Item.Id == e.ElementAt(0).Id).Select(x => x.Item.UtcStatusChanged).Distinct().Count());
                Assert.AreEqual(2, result.Where(x => x.Item.Id == e.ElementAt(1).Id).Select(x => x.Item.UtcStatusChanged).Distinct().Count());

                //ensure rev created dates are correct
                Assert.AreEqual(4, result.Where(x => x.Item.Id == e.ElementAt(0).Id).Select(x => x.MetaData.UtcCreated).Distinct().Count());
                Assert.AreEqual(3, result.Where(x => x.Item.Id == e.ElementAt(1).Id).Select(x => x.MetaData.UtcCreated).Distinct().Count());

                //ensure entity modifieid dates are correct
                Assert.AreEqual(4, result.Where(x => x.Item.Id == e.ElementAt(0).Id).Select(x => x.Item.UtcModified).Distinct().Count());
                Assert.AreEqual(3, result.Where(x => x.Item.Id == e.ElementAt(1).Id).Select(x => x.Item.UtcModified).Distinct().Count());

                //ensure entity created dates are correct
                Assert.AreEqual(1, result.Where(x => x.Item.Id == e.ElementAt(0).Id).Select(x => x.Item.UtcCreated).Distinct().Count());
                Assert.AreEqual(1, result.Where(x => x.Item.Id == e.ElementAt(1).Id).Select(x => x.Item.UtcCreated).Distinct().Count());
            }

        }
Esempio n. 17
0
        static void Main(string[] args)
        {
            List<int> list1 = new List<int>() { 1, 2, 3, 4, 5, 6 };
            List<int> list2 = new List<int>() { 6, 4, 2, 7, 9, 0 };

            // select many with list2.
            var query = list1.SelectMany(o => list2);

            foreach (var q in query)
                Console.Write("{0} ", q);

            // LINQ statement of SelectMany
            var query1 = from item1 in list1
                         from item2 in list2
                         select new { a = item1, b = item2 };

            foreach (var q in query1)
                Console.WriteLine("{0} ", q);

            // select many with list2
            var query2 = list1.SelectMany(o => list2, (a, b) => new { a, b });

            foreach (var q in query2)
                Console.WriteLine("{0} ", q);

            // join is equivalent to LINQ statement.
            //var query = from item1 in list1
            //            join item2 in list2 on item1 equals item2
            //            select item2;

            var query3 = list1.Join(
                list2,
                item1 => item1,
                item2 => item2,
                (item1, item2) => item2);

            foreach (var q in query3)
                Console.WriteLine("{0} ", q);

            // LINQ statement with group join
            var query4 = from item1 in list1
                         join item2 in list2 on item1 equals item2 into g
                         from item in g
                         select new { v = item1, c = item };

            foreach (var q in query4)
                Console.WriteLine("{0} count: {1} ", q.v, q.c);

            // LINQ method call equivalent to LINQ statement.            
            var query5 = list1.GroupJoin(
                list2,
                item1 => item1,
                item2 => item2,
                (item1, item2) => new { v = item1, c = item2.Count() });

            foreach (var q in query5)
                Console.WriteLine("{0} count: {1} ", q.v, q.c);

            //List<int> sequences = new List<int>() { 1, 2, 4, 3, 2, 4, 6, 4, 2, 4, 5, 6, 5, 2, 2, 6, 3, 5, 7, 5 };

            //var group = sequences.GroupBy(o => o);

            //foreach (var g in group)
            //    Console.WriteLine("{0} count: {1}", g.Key, g.Count());

            //var group2 = sequences.GroupBy(
            //    o => (o % 2 == 0) ? "Odd Number" : "Even Numbder",
            //    o2 => (o2 % 2 == 0) ? "Odd" : "Even");

            //foreach (var g in group2)
            //    Console.WriteLine(g.ToString());

            // ToLookup() demo
            var nameValuesGroup = new[]
            {
                new { name = "Allen", value = 65, group = "A" },
                new { name = "Abbey", value = 120, group = "A" },
                new { name = "Slong", value = 330, group = "B" },
                new { name = "George", value = 213, group = "C" },
                new { name = "Meller", value = 329, group = "C" },
                new { name = "Mary", value = 192, group = "B" },
                new { name = "Sue", value = 200, group = "C" }
            };
            var lookupValues = nameValuesGroup.ToLookup(c => c.group);
            foreach (var g in lookupValues)
            {
                Console.WriteLine("=== Group : {0} ===", g.Key);
                foreach (var item in g)
                    Console.WriteLine("name: {0}, value: {1}", item.name, item.value);
            }

            // order list.
            var nameValues = new[]
            {
                new { name = "Allen", value = 65 },
                new { name = "Abbey", value = 120 },
                new { name = "Slong", value = 330 },
                new { name = "George", value = 213 },
                new { name = "Meller", value = 329 },
                new { name = "Mary", value = 192 },
                new { name = "Sue", value = 200 }
            };

            // single sort
            var sortedNames = nameValues.OrderBy(c => c.name);
            var sortedValues = nameValues.OrderBy(c => c.value);
            Console.WriteLine("== OrderBy() demo: sortedNames ==");
            foreach (var q in sortedNames)
                Console.WriteLine("name: {0} value: {1} ", q.name, q.value);
            Console.WriteLine("== OrderBy() demo: sortedValues ==");
            foreach (var q in sortedValues)
                Console.WriteLine("name: {0} value: {1} ", q.name, q.value);

            // multiple sort conditions.
            var sortedByNameValues = nameValues.OrderBy(c => c.name).ThenBy(c =>
            c.value);
            var sortedByValueNames = nameValues.OrderBy(c => c.value).ThenBy(c => c.name);
            Console.WriteLine("== OrderBy() + ThenBy() demo: sortedByNameValues ==");
            foreach (var q in sortedByNameValues)
                Console.WriteLine("name: {0} value: {1} ", q.name, q.value);
            Console.WriteLine("== OrderBy() + ThenBy() demo: sortedByValueNames ==");
            foreach (var q in sortedByValueNames)
                Console.WriteLine("name: {0} value: {1} ", q.name, q.value);

            // Union/Intersect/Except
            int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };
            int[] numbersB = { 1, 3, 5, 7, 8 };

            var unionResults = numbersA.Union(numbersB);
            var intersectResults = numbersA.Intersect(numbersB);
            var exceptResults = numbersA.Except(numbersB);

            Console.WriteLine("== Union ==");

            foreach (var q in unionResults)
                Console.Write(q + " ");

            Console.WriteLine();
            Console.WriteLine("== Intersect ==");

            foreach (var q in intersectResults)
                Console.Write(q + " ");

            Console.WriteLine();
            Console.WriteLine("== Except ==");

            foreach (var q in exceptResults)
                Console.Write(q + " ");

            Console.WriteLine();

            // distinct
            int[] numberSeries = { 2, 2, 3, 5, 5 };

            var distinctValues = numberSeries.Distinct();

            Console.WriteLine("Distinct values from numberSeries");

            foreach (var q in distinctValues)
                Console.Write(q + " ");

            Console.WriteLine();

            var firstLastItems = new[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };

            // First()/Last()
            string firstContainsO = firstLastItems.First(s => s.Contains('o'));
            string lastContainsO = firstLastItems.Last(s => s.Contains('o'));

            Console.WriteLine("First string starting with 'o': {0}", firstContainsO);
            Console.WriteLine("Last string starting with 'o': {0}", lastContainsO);
            
            // ElementAt()
            string itemAtThree = firstLastItems.ElementAt(2);
            string itemAtSix = firstLastItems.ElementAt(5);

            Console.WriteLine("3rd string in list : {0}", itemAtThree);
            Console.WriteLine("6th string in list : {0}", itemAtSix);

            // 存款
            double myBalance = 100.0;
            // 提款的額度
            int[] withdrawItems = { 20, 10, 40, 50, 10, 70, 30 };
            double balance = withdrawItems.Aggregate(myBalance,
            (originbalance, nextWithdrawal) =>
            {
                Console.WriteLine("originbalance: {0}, nextWithdrawal: {1}",
                originbalance, nextWithdrawal);
                Console.WriteLine("Withdrawal status: {0}", (nextWithdrawal <=
                originbalance) ? "OK" : "FAILED");
                // 若存款餘額不夠時,不會扣除,否則扣除提款額度。
                return ((nextWithdrawal <= originbalance) ? (originbalance -
                nextWithdrawal) : originbalance);
            });
            // 顯示最終的存款數
            Console.WriteLine("Ending balance: {0}", balance);

            var balanceStatus = withdrawItems.Aggregate(myBalance,
                (originbalance, nextWithdrawal) =>
                {
                    return ((nextWithdrawal <= originbalance) ? (originbalance -
                    nextWithdrawal) : originbalance);
                },
                (finalbalance) =>
                {
                    return (finalbalance >= 1000) ? "Normal" : "Lower";
                });

            Console.WriteLine("Balance status: {0}", balanceStatus);


            Console.ReadLine();
        }
Esempio n. 18
0
 public void LastReturnsLastElementInSequenceThatMatchesThePredicate()
 {
     var source = new[] { 1, 2, 3 };
     Assert.That(source.Last(i => i == 2), Is.EqualTo(2));
 }
Esempio n. 19
0
 public void InvalidOperationExceptionIsThrownWhenNoElementsMatchThePredicate()
 {
     var source = new[] { 1, 2, 3 };
     source.Last(i => i == 4);
 }
Esempio n. 20
0
 public void LastReturnsLastElementInSequenceWhenNoPredicateIsProvided()
 {
     var source = new[] { 1, 2, 3 };
     Assert.That(source.Last(), Is.EqualTo(3));
 }
Esempio n. 21
0
 void GenerateExtensibilityDeclarations(CodeTypeDeclaration entity, Table table)
 {
     var partialMethods = new[] { CreatePartialMethod("OnCreated") }
         .Concat(table.Type.Columns.Select(c => new[] { CreateChangedMethodDecl(c), CreateChangingMethodDecl(c) })
             .SelectMany(md => md)).ToArray();
     partialMethods.First().StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Extensibility Method Declarations"));
     partialMethods.Last().EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, null));
     entity.Members.AddRange(partialMethods);
 }
		public void GetDifferentMappingsFromMultipleIndices()
		{
			var indices = new[]
			{
				ElasticsearchConfiguration.NewUniqueIndexName(),
				ElasticsearchConfiguration.NewUniqueIndexName()
			};

			var x = this.Client.CreateIndex(indices.First(), s => s
				.AddMapping<ElasticsearchProject>(m => m.MapFromAttributes())
				.AddMapping<Person>(m => m.MapFromAttributes())
			);
			Assert.IsTrue(x.Acknowledged, x.ConnectionStatus.ToString());

			x = this.Client.CreateIndex(indices.Last(), s => s
				.AddMapping<ElasticsearchProject>(m => m.MapFromAttributes())
				.AddMapping<MockData.Domain.CustomGeoLocation>(m => m.MapFromAttributes())
			);
			Assert.IsTrue(x.Acknowledged, x.ConnectionStatus.ToString());

			var response = this.Client.GetMapping(new GetMappingRequest(string.Join(",", indices), "*"));
			response.Should().NotBeNull();
			response.Mappings.Should().NotBeEmpty()
				.And.HaveCount(2);
			foreach (var indexMapping in response.Mappings)
			{
				var indexName = indexMapping.Key;
				indices.Should().Contain(indexName);
				var mappings = indexMapping.Value;
				mappings.Should().NotBeEmpty().And.HaveCount(2);
				mappings.Should().Contain(m => m.TypeName == "elasticsearchprojects")
					.And.Contain(m=>m.TypeName == (indexName == indices.First() ? "person" : "customgeolocation"));
				foreach (var mapping in mappings)
				{
					switch (mapping.TypeName)
					{
						case "elasticsearchprojects":
							TestElasticsearchProjectMapping(mapping.Mapping);
							break;
						case "person":
							TestPersonMapping(mapping.Mapping);
							break;
						case "customgeolocation":
							break;
						default:
							Assert.Fail("Unexpected mapping found {0}", mapping.TypeName);
							break;
					}
				}
			}


		}
        int GeneratePrime(int index)
        {
            // Simulate the hard work 
            Thread.Sleep(2000);

            var firstNumbers = new[] { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, };
            if (index < firstNumbers.Length)
            {
                return firstNumbers[index];
            }

            // THIS IS JUST FOR DEMONSTRATION, I DONT REALLY HAVE MAGICAL GENERATOR
            return firstNumbers.Last();
        }
Esempio n. 24
0
        public void FillsForwardFromPreMarket()
        {
            var dataResolution = Time.OneMinute;
            var reference = new DateTime(2015, 6, 25, 9, 28, 0);
            var data = new []
            {
                new TradeBar
                {
                    Time = reference,
                    Value = 0,
                    Period = dataResolution
                },
                new TradeBar
                {
                    Time = reference.AddMinutes(4),
                    Value = 1,
                    Period = dataResolution
                }
            }.ToList();
            var enumerator = data.GetEnumerator();

            var exchange = new EquityExchange();
            var isExtendedMarketHours = false;
            var fillForwardEnumerator = new FillForwardEnumerator(enumerator, exchange, TimeSpan.FromMinutes(1), isExtendedMarketHours, data.Last().EndTime, dataResolution);

            // 9:29
            Assert.IsTrue(fillForwardEnumerator.MoveNext());
            Assert.AreEqual(reference.AddMinutes(1), fillForwardEnumerator.Current.EndTime);
            Assert.AreEqual(0, fillForwardEnumerator.Current.Value);
            Assert.IsFalse(fillForwardEnumerator.Current.IsFillForward);
            Assert.AreEqual(dataResolution, fillForwardEnumerator.Current.EndTime - fillForwardEnumerator.Current.Time);

            // 9:31 (ff)
            Assert.IsTrue(fillForwardEnumerator.MoveNext());
            Assert.AreEqual(reference.AddMinutes(3), fillForwardEnumerator.Current.EndTime);
            Assert.AreEqual(0, fillForwardEnumerator.Current.Value);
            Assert.IsTrue(fillForwardEnumerator.Current.IsFillForward);
            Assert.AreEqual(dataResolution, fillForwardEnumerator.Current.EndTime - fillForwardEnumerator.Current.Time);

            // 9:32 (ff)
            Assert.IsTrue(fillForwardEnumerator.MoveNext());
            Assert.AreEqual(reference.AddMinutes(4), fillForwardEnumerator.Current.EndTime);
            Assert.AreEqual(0, fillForwardEnumerator.Current.Value);
            Assert.IsTrue(fillForwardEnumerator.Current.IsFillForward);
            Assert.AreEqual(dataResolution, fillForwardEnumerator.Current.EndTime - fillForwardEnumerator.Current.Time);

            // 9:33
            Assert.IsTrue(fillForwardEnumerator.MoveNext());
            Assert.AreEqual(reference.AddMinutes(5), fillForwardEnumerator.Current.EndTime);
            Assert.AreEqual(1, fillForwardEnumerator.Current.Value);
            Assert.IsFalse(fillForwardEnumerator.Current.IsFillForward);
            Assert.AreEqual(dataResolution, fillForwardEnumerator.Current.EndTime - fillForwardEnumerator.Current.Time);

            Assert.IsFalse(fillForwardEnumerator.MoveNext());
        }
Esempio n. 25
0
 private static void ComposeExpressionForSegments(System.Data.Services.SegmentInfo[] segments, IDataService service)
 {
     bool flag = Deserializer.IsCrossReferencedSegment(segments[0], service);
     int num = -1;
     System.Data.Services.SegmentInfo lastSegment = segments.Last<System.Data.Services.SegmentInfo>();
     if ((lastSegment.Operation != null) && (lastSegment.Operation.Kind == OperationKind.Action))
     {
         for (int j = segments.Length - 2; j > -1; j--)
         {
             if (!segments[j].IsTypeIdentifierSegment)
             {
                 num = j;
                 break;
             }
         }
     }
     System.Data.Services.SegmentInfo segment = null;
     System.Data.Services.SegmentInfo previous = null;
     for (int i = 0; i < segments.Length; i++)
     {
         bool isLastSegment = i == (segments.Length - 1);
         bool checkRights = !isLastSegment && (i != num);
         bool flag4 = i != num;
         previous = segment;
         segment = segments[i];
         if (!flag && (previous != null))
         {
             segment.RequestExpression = previous.RequestExpression;
         }
         if ((!flag && (segment.TargetKind != RequestTargetKind.Link)) && (segment.Identifier != "$count"))
         {
             if (segment.IsTypeIdentifierSegment)
             {
                 ComposeExpressionForTypeNameSegment(segment, previous);
             }
             else if (segment.TargetSource == RequestTargetSource.EntitySet)
             {
                 ComposeExpressionForEntitySet(segment, service, isLastSegment, checkRights);
             }
             else if (segment.TargetSource == RequestTargetSource.ServiceOperation)
             {
                 if (DataServiceActionProviderWrapper.IsServiceActionSegment(segment))
                 {
                     ComposeExpressionForServiceAction(segment, previous, service);
                 }
                 else
                 {
                     ComposeExpressionForServiceOperation(segment, service, flag4, lastSegment);
                 }
             }
             else if ((segment.TargetSource == RequestTargetSource.Property) && (segment.Identifier != "$value"))
             {
                 if ((segment.ProjectedProperty != null) && !segment.ProjectedProperty.IsOfKind(ResourcePropertyKind.Stream))
                 {
                     ComposeExpressionForProperty(segment, previous, service, isLastSegment, checkRights);
                 }
                 else if (segment.TargetKind == RequestTargetKind.OpenProperty)
                 {
                     segment.RequestExpression = SelectOpenProperty(previous.RequestExpression, segment.Identifier);
                 }
             }
         }
     }
 }
Esempio n. 26
0
        public async Task Linq_Unwrap()
        {
            var toBot = MakeTestMessage();

            var words = new[] { "hello", "world" };

            using (var container = Build(Options.Reflection))
            {
                foreach (var word in words)
                {
                    using (var scope = DialogModule.BeginLifetimeScope(container, toBot))
                    {
                        DialogModule_MakeRoot.Register(scope, MakeUnwrapQuery);

                        var task = scope.Resolve<IPostToBot>();
                        toBot.Text = word;
                        await task.PostAsync(toBot, CancellationToken.None);
                    }
                }

                var expected = words.Last();
                AssertQueryText(expected, container);
            }
        }
Esempio n. 27
0
 public void Last()
 {
     var ints = new[] { 1, 2, 3, 4 };
     var last = ints.Last();
     AssertEquals(last, 4);
 }
Esempio n. 28
0
        public void TestRandomSubsetIsUnbiased()
        {
            const int count = 20;
            var sequence = Enumerable.Range(1, count);

            var rsdTrials = new[] { 1000, 10000, 100000, 500000, 10000000 };
            var rsdResults = new[] { 0.0, 0.0, 0.0, 0.0, 0.0 };

            var trialIndex = 0;
            foreach (var trialSize in rsdTrials)
            {
                var biasAccumulator = Enumerable.Repeat(0.0, count).ToArray();

                for (var i = 0; i < trialSize; i++)
                {
                    var index = 0;
                    var result = sequence.RandomSubset(count);
                    foreach (var itemA in result)
                        biasAccumulator[index++] += itemA;
                }

                rsdResults[trialIndex++] = RelativeStandardDeviation(biasAccumulator);
            }

            // ensure that wth increasing trial size the a RSD% continually decreases
            for (var j = 0; j < rsdResults.Length - 1; j++)
                Assert.Less(rsdResults[j + 1], rsdResults[j]);

            // ensure that the RSD% for the 5M trial size is < 1.0    (this is somewhat arbitrary)
            Assert.Less(rsdResults.Last(), 1.0);

            // for sanity, we output the RSD% values as a cross-check, the expected result should be
            // that the RSD% rapidly decreases and eventually drops below 1.0
            Console.WriteLine("RSD% = {0:0.00000}, {1:0.00000}, {2:0.00000}, {3:0.00000}, {4:0.00000}",
                              rsdResults[0], rsdResults[1], rsdResults[2], rsdResults[3], rsdResults[4]);
        }
Esempio n. 29
0
        public HasManyAndBelongsTo(DynamicRepository repository, DynamicRepository reference)
        {
            Repository = repository;

            this.reference = reference;

            var sorted = new[] { repository.TableName, reference.TableName }.OrderBy(s => s);

            throughTable = sorted.First() + sorted.Last();

            MethodName = repository.TableName;
        }
Esempio n. 30
0
        static void Main(string[] args)
        {
            var data = Enumerable.Range(1, 50);

            var method = // IEnumerable<string>
                 data.Where(x => x % 2 == 0)
                 .Select(x => x.ToString());

            var query = // IEnumerable<string>
                from d in data
                where d % 2 == 0
                select d.ToString();

            Debugger.Break();

            var projection =
                from d in data
                select new
                {
                    Even = (d % 2 == 0),
                    Odd = !(d % 2 == 0),
                    Value = d,
                };

            var letters = new[] { "A", "C", "B", "E", "Q" };

            Debugger.Break();

            var sortAsc =
                from d in data
                orderby d ascending
                select d;

            var sortDesc =
                data.OrderByDescending(x => x);

            Debugger.Break();

            // candy

            var values = new[] { "A", "B", "A", "C", "A", "D" };

            var distinct = values.Distinct();
            var first = values.First();
            var firstOr = values.FirstOrDefault();
            var last = values.Last();
            var page = values.Skip(2).Take(2);

            Debugger.Break();

            // aggregates

            var numbers = Enumerable.Range(1, 50);
            var any = numbers.Any(x => x % 2 == 0);
            var count = numbers.Count(x => x % 2 == 0);
            var sum = numbers.Sum();
            var max = numbers.Max();
            var min = numbers.Min();
            var avg = numbers.Average();

            Debugger.Break();

            var dictionary = new Dictionary<string, string>()
            {
                 {"1", "B"}, {"2", "A"}, {"3", "B"}, {"4", "A"},
            };

            var group = // IEnumerable<string, IEnumerable<string>>
                from d1 in dictionary
                group d1 by d1.Value into g
                select new
                {
                    Key = g.Key,
                    Members = g,
                };

            Debugger.Break();

            var dictionary1 = new Dictionary<string, string>()
            {
                 {"1", "B"}, {"2", "A"}, {"3", "B"}, {"4", "A"},
            };

            var dictionary2 = new Dictionary<string, string>()
            {
                 {"5", "B"}, {"6", "A"}, {"7", "B"}, {"8", "A"},
            };

            var join =
                from d1 in dictionary1
                join d2 in dictionary2 on d1.Value equals d2.Value
                select new
                {
                    Key1 = d1.Key,
                    Key2 = d2.Key,
                    Value = d1.Value
                };

            Debugger.Break();
        }