Exemple #1
0
        public void BasicExamples()
        {
            var schtick = new Schtick();
            Exception taskEx = null;
            schtick.OnTaskException += (task, exception) => taskEx = exception;

            var allRecords = new List<RunRecord>();
            var all = schtick.AddTask("all", "sec(*)", (task, run) => { allRecords.Add(new RunRecord(DateTimeOffset.UtcNow, run)); });

            var evenRecords = new List<RunRecord>();
            var even = schtick.AddTask("even", "sec(*%2)", (task, run) => { evenRecords.Add(new RunRecord(DateTimeOffset.UtcNow, run)); });

            // give them a chance to run
            Thread.Sleep(4000);

            // look at the results
            all.StopSchedule();
            even.StopSchedule();

            Assert.IsNull(taskEx);

            Assert.GreaterOrEqual(allRecords.Count, 3);
            Assert.LessOrEqual(allRecords.Count, 5);
            Assert.GreaterOrEqual(evenRecords.Count, 1);
            Assert.LessOrEqual(evenRecords.Count, 3);

            // make sure all of the events are within 100 milliseconds of the intended time
            foreach (var r in allRecords.Concat(evenRecords))
            {
                Assert.LessOrEqual(r.MillisecondsDifference, 100);
            }
        }
 public void AddMany_CollectionIsNotEmptyItemsToAddIsNotEmpty_AddsItemsToAdd()
 {
     var originalCollectionContent = new List<object> { new object() };
     var collection = new List<object>(originalCollectionContent);
     var itemsToAdd = new[] { new object() };
     collection.AddMany(itemsToAdd);
     CollectionAssert.AreEqual(originalCollectionContent.Concat(itemsToAdd), collection);
 }
Exemple #3
0
        public void ConcatQueryReuse()
        {
            List<int> first = new List<int> { 1, 2 };
            List<int> second = new List<int> { 4, 5 };
            IEnumerable<int> enumerable = first.Concat(second);

            enumerable.AssertEqual(1, 2, 4, 5);

            first.Add(3);
            second.Add(6);
            enumerable.AssertEqual(1, 2, 3, 4, 5, 6);
        }
        public void recover_from_dropped_subscription_state_using_last_known_position()
        {
            const string stream = "read_all_events_forward_should_recover_from_dropped_subscription_state_using_last_known_position";
            using (var store = EventStoreConnection.Create())
            {
                store.Connect(Node.TcpEndPoint);
                var catched = new List<RecordedEvent>();
                Position lastKnonwPosition = null;
                var dropped = new AutoResetEvent(false);

                var create = store.CreateStreamAsync(stream, false, new byte[0]);
                Assert.DoesNotThrow(create.Wait);

                store.SubscribeAsync(stream,
                                     (@event, position) =>
                                     {
                                         catched.Add(@event);
                                         lastKnonwPosition = position;
                                     },
                                     () => dropped.Set());

                var testEvents = Enumerable.Range(1, 5).Select(x => new TestEvent(x.ToString())).ToArray();

                var write = store.AppendToStreamAsync(stream, ExpectedVersion.EmptyStream, testEvents);
                Assert.That(write.Wait(Timeout));

                store.UnsubscribeAsync(stream);
                Assert.That(dropped.WaitOne(Timeout));

                var write2 = store.AppendToStreamAsync(stream, testEvents.Length, testEvents);
                Assert.That(write2.Wait(Timeout));

                var missed = store.ReadAllEventsForwardAsync(lastKnonwPosition, int.MaxValue);
                Assert.That(missed.Wait(Timeout));

                var expected = testEvents.Concat(testEvents).ToArray();
                var actual = catched.Concat(missed.Result.Events.Skip(1)).ToArray();//skip 1 because readallforward is inclusive
                Assert.That(TestEventsComparer.Equal(expected, actual));
            }
        }
        public void should_flush_collection_with_multiple_writers()
        {
            var collection = new FlushableBlockingCollection<int>();

            var consumedItems = new List<int>();
            var consume = Task.Run(() =>
            {
                var index = 0;
                foreach (var item in collection.GetConsumingEnumerable())
                {
                    consumedItems.Add(item);

                    // simulate consumption lag
                    if (index % 10000 == 0)
                        Thread.Sleep(20);

                    ++index;
                }

                Console.WriteLine("Consumer done");
            });

            const int writerItemCount = 300000;

            var t1 = Task.Run(() =>
            {
                foreach (var item in Enumerable.Range(0, writerItemCount).Select(x => 3 * x))
                {
                    collection.Add(item);
                    if ((item - 0) % 1000 == 0)
                        Thread.Sleep(10);
                    else
                        Thread.Yield();
                }
                Console.WriteLine("T1 done");
            });
            var t2 = Task.Run(() =>
            {
                foreach (var item in Enumerable.Range(0, writerItemCount).Select(x => 3 * x + 1))
                {
                    collection.Add(item);
                    if ((item  - 1) % 1000 == 0)
                        Thread.Sleep(10);
                    else
                        Thread.Yield();
                }
                Console.WriteLine("T2 done");
            });
            var t3 = Task.Run(() =>
            {
                foreach (var item in Enumerable.Range(0, writerItemCount).Select(x => 3 * x + 2))
                {
                    collection.Add(item);
                    if ((item - 2) % 1000 == 0)
                        Thread.Sleep(10);
                    else
                        Thread.Yield();
                }
                Console.WriteLine("T3 done");
            });

            Thread.Sleep(50);

            Console.WriteLine("Flush #1");
            var flushedItems1 = collection.Flush(true);
            Console.WriteLine("{0} flushed items", flushedItems1.Count);

            Thread.Sleep(50);

            Console.WriteLine("Flush #2");
            var flushedItems2 = collection.Flush(true);
            Console.WriteLine("{0} flushed items", flushedItems2.Count);

            Task.WaitAll(t1, t2, t3);

            collection.CompleteAdding();
            consume.Wait();

            var exectedItems = Enumerable.Range(0, writerItemCount * 3).ToHashSet();
            var items = consumedItems.Concat(flushedItems1).Concat(flushedItems2).ToList();
            items.Count.ShouldEqual(exectedItems.Count);
            foreach (var item in items)
            {
                exectedItems.Contains(item).ShouldBeTrue();
            }
        }
        public void should_flush_collection_with_single_writer()
        {
            var collection = new FlushableBlockingCollection<int>();

            var consumedItems = new List<int>();
            var consume = Task.Run(() =>
            {
                foreach (var item in collection.GetConsumingEnumerable())
                {
                    consumedItems.Add(item);

                    // simulate very slow consumer
                    Thread.Sleep(10);
                }

                Console.WriteLine("Consumer done");
            });

            const int batchSize = 500000;

            foreach (var item in Enumerable.Range(0 * batchSize, batchSize))
            {
                collection.Add(item);
            }

            Thread.Sleep(100);
            Console.WriteLine("Flush #1");
            var flushedItems1 = collection.Flush(true);
            Console.WriteLine("{0} flushed items", flushedItems1.Count);

            foreach (var item in Enumerable.Range(1 * batchSize, batchSize))
            {
                collection.Add(item);
            }

            Thread.Sleep(100);
            Console.WriteLine("Flush #2");
            var flushedItems2 = collection.Flush(true);
            Console.WriteLine("{0} flushed items", flushedItems2.Count);

            foreach (var item in Enumerable.Range(2 * batchSize, batchSize))
            {
                collection.Add(item);
            }

            Thread.Sleep(100);
            Console.WriteLine("Flush #3");
            var flushedItems3 = collection.Flush(true);
            Console.WriteLine("{0} flushed items", flushedItems3.Count);

            collection.CompleteAdding();
            consume.Wait();

            var exectedItems = Enumerable.Range(0, 1500000).ToHashSet();
            var items = consumedItems.Concat(flushedItems1).Concat(flushedItems2).Concat(flushedItems3).ToList();
            items.Count.ShouldEqual(exectedItems.Count);
            foreach (var item in items)
            {
                exectedItems.Contains(item).ShouldBeTrue();
            }
        }
        public void ShouldTruncateResponseAtEpochBoundary()
        {
            var c = new Controller();

            var e = new Epoch(UNUSED_PROTOCOL);
            var dev1 = new UnitConvertingExternalDevice("dev2", "co", c, new Measurement(0, "V"));

            var sampleRate = new Measurement(1, "Hz");

            var samples = new List<IMeasurement> { new Measurement(1, "V"), new Measurement(2, "V"), new Measurement(3, "V") };

            var data = new OutputData(samples,
                                      sampleRate, true);

            e.Stimuli[dev1] = new RenderedStimulus((string) "ID1",
                                                   (IDictionary<string, object>) new Dictionary<string, object>(),
                                                   (IOutputData) data);
            e.Responses[dev1] = new Response();

            c.EnqueueEpoch(e);
            c.NextEpoch();
            c.PushInputData(dev1, new InputData(samples.Concat(samples).ToList(),
                sampleRate,
                DateTimeOffset.Now)
                .DataWithStreamConfiguration(streamFake, new Dictionary<string, object>())
                .DataWithExternalDeviceConfiguration(devFake, new Dictionary<string, object>()));

            Assert.That(((TimeSpan)e.Responses[dev1].Duration), Is.EqualTo((TimeSpan)e.Duration));
        }
        public void SetUp()
        {
            IPRangeRepositoryMock = new Mock<IRepository<IPRange>>();
            ProfileRepositoryMock = new Mock<IRepository<AwsProfile>>();
            ClientFactoryMock = new Mock<IAwsClientFactory>();
            Command = new RefreshIpRanges(ProfileRepositoryMock.Object, IPRangeRepositoryMock.Object, ClientFactoryMock.Object);

            _profileId = Guid.NewGuid();
            var profile = new AwsProfile
            {
                Id = _profileId
            };
            ProfileRepositoryMock.Setup(x => x.Find(_profileId)).Returns(profile);

            AwsClientMock = new Mock<IAwsClient>();
            NetworkServiceMock = new Mock<INetworkService>();

            AwsClientMock.Setup(x => x.NetworkService).Returns(NetworkServiceMock.Object);
            ClientFactoryMock.Setup(x => x.GetClient(profile)).Returns(AwsClientMock.Object);

            _ipsInRange = Enumerable.Range(8, 4)
                                    .Select(x => string.Format("255.255.255.{0}", x)).ToList();
            var allocatedIps = _ipsInRange.Concat(new List<string> { "192.168.1.1" });
            NetworkServiceMock.Setup(x => x.GetAllocatedIpAddresses()).Returns(allocatedIps);
        }
 private static void GetFourth(List<int> elements, List<List<int>> combinations, List<int> current, int ctr)
 {
     var n = elements.Count;
     var j = current[current.Count - 1];
     for (int k = j + 1; k < n; k++)
     {
         var c = current.Concat(new List<int> { k }).ToList();
         GetFifth(elements, combinations, c, ctr);
     }
 }
Exemple #10
0
        public IList<Point> GetRect(int[,] input)
        {
            //			var leftEdgeOnes = new List<Point>();
            //			var rightEdgeOnes = new List<Point>();
            //			var topEdgeOnes = new List<Point>();
            //			var bottomEdgeOnes = new List<Point>();
            //			var maxI = input.GetLength(0);
            //			var maxJ = input.GetLength(1);
            //			for (int i = 0; i < maxI; i++)
            //			{
            //				for (int j = 0; j < maxJ; j++)
            //				{
            //					if (input[i, j] == 1)
            //					{
            //						if (i == 0 || input[i - 1, j] == 0)
            //						{
            //							leftEdgeOnes.Add(new Point(i, j));
            //						}
            //						if (i == maxI - 1 || input[i + 1, j] == 0)
            //						{
            //							rightEdgeOnes.Add(new Point(i,j));
            //						}
            //						if (j == 0 || input[i,j - 1] == 0)
            //						{
            //							topEdgeOnes.Add(new Point(i,j));
            //						}
            //						if (j == maxJ -1 || input[i,j + 1] == 0)
            //						{
            //							bottomEdgeOnes.Add(new Point(i,j));
            //						}
            //					}
            //				}
            //			}
            //
            //			var allOnes = topEdgeOnes.Concat(bottomEdgeOnes).Concat(leftEdgeOnes).Concat(rightEdgeOnes).Distinct().ToList();

            var across = new List<List<Point>>{new List<Point>()};
            for (int i = 0; i < input.GetLength(0); i++)
            {
                for (int j = 0; j < input.GetLength(1); j++)
                {
                    if (input[i, j] == 1)
                    {
                        var list = across.Last();
                        list.Add(new Point(i, j));
                    }
                    else
                    {
                        across.Add(new List<Point>());
                    }
                }
                across.Add(new List<Point>());
            }

            var down = new List<List<Point>> { new List<Point>() };
            for (int j = 0; j < input.GetLength(1); j++)
            {
                for (int i = 0; i < input.GetLength(0); i++)
                {
                    if (input[i, j] == 1)
                    {
                        var list = down.Last();
                        list.Add(new Point(i, j));
                    }
                    else
                    {
                        down.Add(new List<Point>());
                    }
                }
                down.Add(new List<Point>());
            }

            var longest = down.Concat(across).OrderByDescending(x => x.Count).First();
            if (longest.Count == 1)
            {

                longest.Add(longest[0]);
            }
            if (longest.Count > 2)
            {
                longest = new List<Point> { longest.First(), longest.Last() };
            }
            return longest;
        }
Exemple #11
0
		public void Concat_Linq ()
		{
			// Concat all elements
			var groupOne = new List<int> (){ 1,2,3,4,5};
			var groupTwo = new List<int> (){4,5,6,7};
			
			var groupBoth = groupOne.Concat(groupTwo);
			var groupBothOrdered = from g in groupBoth
								   orderby g
								   select g;		
		
			Assert.AreEqual (9, groupBothOrdered.Count ());
			Assert.AreEqual (1, groupBothOrdered.First ());
			Assert.AreEqual (7, groupBothOrdered.Last ());
		}
Exemple #12
0
		public void Concat_LinqExt ()
		{
			// Concat all elements
			var groupOne = new List<int> (){ 1,2,3,4,5};
			var groupTwo = new List<int> (){4,5,6,7};
			var groupExcept = groupOne.Concat (groupTwo).OrderBy( x=> x);
		
			Assert.AreEqual (9, groupExcept.Count ());
			Assert.AreEqual (1, groupExcept.First ());
			Assert.AreEqual (7, groupExcept.Last ());
		}
        public void CacheLookup_MultipleUrisOneInCache_ReturnsVersion()
        {
            // Arrange

            var servers1 = new List<Uri>
            {
                Uri1
            };

            var servers2 = new List<Uri>
            {
                Uri2
            };

            var provider = new DefaultVersionProvider();

            provider.CacheStore(servers2, Version45);

            // Act

            var result = provider.CacheLookup(servers1.Concat(servers2));

            // Assert

            Assert.AreEqual(Version45, result);
        }
        public void recover_from_dropped_subscription_state_using_last_known_position()
        {
            Assert.Inconclusive("This tests has race condition in subscribe/first write sequence. And it is not clear what it tests...");

            const string stream = "read_all_events_forward_should_recover_from_dropped_subscription_state_using_last_known_position";
            using (var store = EventStoreConnection.Create())
            {
                store.Connect(_node.TcpEndPoint);
                store.CreateStream(stream, Guid.NewGuid(), false, new byte[0]);
                
                var catched = new List<RecordedEvent>();
                Position? lastKnownPosition = null;
                var dropped = new AutoResetEvent(false);

                var subscribed = new ManualResetEventSlim();
                bool wasSubscribed = false;
                using (var subscription = store.SubscribeToStream(stream,
                                                                  false,
                                                                  @event =>
                                                                  {
                                                                      catched.Add(@event.Event);
                                                                      lastKnownPosition = @event.OriginalPosition;
                                                                      wasSubscribed = true;
                                                                      subscribed.Set();
                                                                  },
                                                                  () =>
                                                                  {
                                                                      wasSubscribed = false;
                                                                      subscribed.Set();
                                                                      dropped.Set();
                                                                  }).Result)
                {
                    var testEvents = Enumerable.Range(1, 5).Select(x => TestEvent.NewTestEvent(x.ToString())).ToArray();
                    var write = store.AppendToStreamAsync(stream, ExpectedVersion.EmptyStream, testEvents);
                    Assert.That(write.Wait(Timeout));

                    Assert.IsTrue(subscribed.Wait(5000), "Subscription haven't happened in time.");
                    Assert.IsTrue(wasSubscribed, "Subscription failed.");
                    Assert.IsTrue(lastKnownPosition.HasValue, "Last know position should not be null.");

                    subscription.Unsubscribe();
                    Assert.That(dropped.WaitOne(Timeout), "Couldn't unsubscribe in time.");

                    var write2 = store.AppendToStreamAsync(stream, testEvents.Length, testEvents);
                    Assert.That(write2.Wait(Timeout));

                    var missed = store.ReadAllEventsForwardAsync(lastKnownPosition.Value, int.MaxValue, false);
                    Assert.That(missed.Wait(Timeout));

                    var expected = testEvents.Concat(testEvents).ToArray();
                    var actual = catched.Concat(missed.Result.Events.Skip(1).Select(x => x.Event)).ToArray();//skip 1 because readallforward is inclusive
                    Assert.That(EventDataComparer.Equal(expected, actual));
                }
            }
        }
        public void GenerateOpCodeClasses()
        {
            var globalKb = ILOpsKb.Content;

            // todo list for the generator
            // 1) introduce caching for property getters: 
            //    * NB! GENERATE IT rather than wrap around in e.g. ILOpBase
            // 2) same for prefix getters
            // 3) implement the "no." prefix 0xfe19 (CIL spec mentions it, but OpCodes do not)
            // 4) support "readonly." prefix for opcodes it's applicable to

            // first generate enumerations
            var enumTypes = new[] {typeof(OperatorType), typeof(PredicateType)};
            foreach (var t_enum in enumTypes)
            {
                // so far we need only enums
                t_enum.IsEnum.AssertTrue();

                Helpers.GenerateIntoClass(
                    @"..\..\..\Truesight\Parser\Api\Ops\" + t_enum.Name + ".cs",
                    "Truesight.Parser.Api.Ops",
                    "public enum " + t_enum.Name,
                    buffer => 
                    {
                        var values = Enum.GetValues(t_enum).Cast<Object>();
                        var s_values = values.Select(v => v.ToInvariantString().Indent().Indent());
                        buffer.Append(s_values.StringJoin("," + Environment.NewLine));
                    });
            }

            // second, set up redirections from enums to generated enums
            var typeRedirections = enumTypes.ToDictionary(
                t => t.GetCSharpRef(ToCSharpOptions.ForCodegen),
                t => "Truesight.Parser.Api.Ops." + t.Name);

            // third, generate the IILOpType enumeration
            Helpers.GenerateIntoClass(
                @"..\..\..\Truesight\Parser\Api\IILOpType.cs",
                "Truesight.Parser.Api",
                "public enum IILOpType",
                buffer => buffer.Append(globalKb.Select(fkb => "        " + fkb.Name.Capitalize()).StringJoin("," + Environment.NewLine)));

            // now generate opcode classes
            foreach (var fkb in globalKb)
            {
                var isIgnored = fkb.SubSpecs.Values.Any(kb => kb.Tags.Contains("Ignore"));
                (isIgnored && fkb.SubSpecs.Count > 1).AssertFalse();

                var isPrefix = fkb.SubSpecs.Values.Any(kb => kb.Tags.Contains("Prefix"));
                (isPrefix && fkb.SubSpecs.Count > 1).AssertFalse();

                var className = fkb.Name.Capitalize();
                fkb.OpCodes.AssertNotEmpty();
                var opCodesComment = "// " + 
                    fkb.OpCodes.Select(opcode => opcode.Name).StringJoin();
                var opcodesAttribute = String.Format("[{0}({1})]",
                    typeof(OpCodesAttribute).GetCSharpRef(ToCSharpOptions.ForCodegen),
                    fkb.OpCodes.Select(opcode => opcode.GetCSharpByteSequence()).StringJoin());
                var debuggerNonUserCodeAttribute = String.Format("[{0}]",
                    typeof(DebuggerNonUserCodeAttribute).GetCSharpRef(ToCSharpOptions.ForCodegen));
                var classDeclaration =
                    opCodesComment + Environment.NewLine + "    " +
                    opcodesAttribute + Environment.NewLine + "    " +
                    debuggerNonUserCodeAttribute + Environment.NewLine + "    " +
                    (isIgnored ? "internal" : "public") + " sealed class " + className + 
                    " : " + typeof(ILOp).GetCSharpRef(ToCSharpOptions.ForCodegen);

                Helpers.GenerateIntoClass(
                    @"..\..\..\Truesight\Parser\Api\Ops\" + className + ".cs",
                    "Truesight.Parser.Api.Ops",
                    classDeclaration,
                    buffer =>
                    {
                        var fields = fkb.SubSpecs.Values
                            .SelectMany(spec => spec.Fields.Values.Select(f => f.Name)).Distinct().Order()
                            .Select(fname => UniteSubSpecsForField(fkb, fname)).ToArray();
                        if (fkb.Name == "branch") fields = fields.Reverse().ToArray();
                        var props = fkb.SubSpecs.Values
                            .SelectMany(spec => spec.Props.Values.Select(p => p.Name)).Distinct().Order()
                            .Select(pname => UniteSubSpecsForProp(fkb, pname)).ToArray();
                        var prefixes = fkb.SubSpecs.Values
                            .SelectMany(spec => spec.Prefixes.Values.Select(p => p.Name)).Distinct().Order()
                            .Select(pname =>
                            {
                                var sample = fkb.SubSpecs.Values.First().Prefixes[pname];
                                fkb.SubSpecs.Values.AssertAll(kb =>
                                {
                                    var prefix = kb.Prefixes[pname];
                                    (prefix.Name == sample.Name).AssertTrue();
                                    (prefix.Type == sample.Type).AssertTrue();
                                    (prefix.PrefixName == sample.PrefixName).AssertTrue();
                                    (prefix.Getter == sample.Getter).AssertTrue();
                                    (prefix.Setter == sample.Setter).AssertTrue();
                                    // setters ain't supported since they weren't necessary
                                    prefix.Setter.AssertNullOrEmpty();
                                    return true;
                                });
                                return sample;
                            }).ToArray();

                        // 0. Generate OpCodeType
                        buffer.AppendFormat("public override {0} OpType {{ get {{ return {0}.{1}; }} }}".Indent().Indent(),
                            typeof(IILOpType).GetCSharpRef(ToCSharpOptions.ForCodegen), className).AppendLine().AppendLine();

                        // 1. Field declarations
                        foreach (var field in fields)
                        {
                            field.IsUnsafe.AssertFalse();
                            buffer.AppendLine(String.Format("private readonly {0} {1};",
                                field.Type.GetCSharpRef(ToCSharpOptions.ForCodegen), field.Name).Indent().Indent());
                        }
                        if (fields.Any()) buffer.AppendLine();

                        // 2. Constructor (parsing and field init)
                        var auxCtorHeadline = String.Format("internal {0}({1} source, {2} reader)",
                            className,
                            typeof(MethodBody).GetCSharpRef(ToCSharpOptions.ForCodegen),
                            typeof(BinaryReader).GetCSharpRef(ToCSharpOptions.ForCodegen));
                        buffer.AppendLine(auxCtorHeadline.Indent().Indent());
                        var emptyPrefixes = String.Format("{0}.ToReadOnly({1}.Empty<{2}>())",
                            typeof(EnumerableExtensions).GetCSharpRef(ToCSharpOptions.ForCodegen),
                            typeof(Enumerable).GetCSharpRef(ToCSharpOptions.ForCodegen),
                            typeof(ILOp).GetCSharpRef(ToCSharpOptions.ForCodegen));
                        buffer.AppendLine((": this(source, reader, " + emptyPrefixes + ")").Indent().Indent().Indent());
                        buffer.AppendLine("{".Indent().Indent());
                        buffer.AppendLine("}".Indent().Indent());
                        buffer.AppendLine();

                        var mainCtorHeadline = String.Format("{0}, {1} prefixes)",
                            auxCtorHeadline.Slice(0, -1),
                            typeof(ReadOnlyCollection<ILOp>).GetCSharpRef(ToCSharpOptions.ForCodegen));
                        buffer.AppendLine(mainCtorHeadline.Indent().Indent());
                        buffer.Append(": base(source, AssertSupportedOpCode(reader), ".Indent().Indent().Indent());
                        // note. be wary of offset magic here!
                        buffer.AppendFormat(
                            "({0})reader.BaseStream.Position - " +
                            "{1}.Sum({1}.Select(prefixes ?? {2}, prefix => prefix.Size))",
                            typeof(Int32).GetCSharpRef(ToCSharpOptions.ForCodegen),
                            typeof(Enumerable).GetCSharpRef(ToCSharpOptions.ForCodegen),
                            emptyPrefixes);
                        buffer.AppendLine(", prefixes ?? " + emptyPrefixes + ")");
                        buffer.AppendLine("{".Indent().Indent());
                        buffer.AppendLine("// this is necessary for further verification".Indent().Indent().Indent());
                        buffer.AppendLine("var origPos = reader.BaseStream.Position;".Indent().Indent().Indent());
                        buffer.AppendLine();
                        fields.ForEach(field =>
                        {
                            buffer.AppendLine(("// initializing " + field.Name).Indent().Indent().Indent());
                            buffer.AppendLine(field.Initializer.Indent().Indent().Indent());
                        });
                        buffer.AppendLine("// verify that we've read exactly the amount of bytes we should".Indent().Indent().Indent());
                        buffer.AppendLine("var bytesRead = reader.BaseStream.Position - origPos;".Indent().Indent().Indent());
                        // this validation is partially redundant for switch, tho I'm cba to invent something better now
                        buffer.AppendLine(String.Format("{0}.AssertTrue(bytesRead == SizeOfOperand);",
                            typeof(AssertionHelper).GetCSharpRef(ToCSharpOptions.ForCodegen)).Indent().Indent().Indent());
                        buffer.AppendLine();
                        buffer.AppendLine("// now when the initialization is completed verify that we've got only prefixes we support".Indent().Indent().Indent());
                        buffer.AppendLine(String.Format("{0}.AssertAll(Prefixes, prefix => ".Indent().Indent().Indent(),
                            typeof(AssertionHelper).GetCSharpRef(ToCSharpOptions.ForCodegen)));
                        buffer.AppendLine("{".Indent().Indent().Indent());
                        var cond_vars = new List<String>();
                        foreach (var prefix in prefixes)
                        {
                            var var_name = prefix.PrefixName + "_ok";
                            cond_vars.Add(var_name);
                            buffer.AppendLine(String.Format("var {0} = prefix is {1}{2};".Indent().Indent().Indent().Indent(),
                                var_name, prefix.PrefixName.Capitalize(),
                                prefix.Filter.IsNullOrEmpty() ? "" : " && " + prefix.Filter));
                        }
                        buffer.AppendLine(String.Format("return {0};".Indent().Indent().Indent().Indent(),
                            cond_vars.Concat("false").StringJoin(" || ")));
                        buffer.AppendLine("});".Indent().Indent().Indent());
                        buffer.AppendLine("}".Indent().Indent());
                        buffer.AppendLine();

                        // 3. OpCode inference
                        buffer.AppendLine(String.Format("private static {0} AssertSupportedOpCode({1} reader)",
                            typeof(OpCode).GetCSharpRef(ToCSharpOptions.ForCodegen),
                            typeof(BinaryReader).GetCSharpRef(ToCSharpOptions.ForCodegen)).Indent().Indent());
                        buffer.AppendLine("{".Indent().Indent());

                        buffer.AppendLine(String.Format(
                            "var opcode = {0}.ReadOpCode(reader);",
                            typeof(OpCodeReader).GetCSharpRef(ToCSharpOptions.ForCodegen)).Indent().Indent().Indent());
                        buffer.AppendLine(String.Format(
                            "{0}.AssertNotNull(opcode);",
                            typeof(AssertionHelper).GetCSharpRef(ToCSharpOptions.ForCodegen)).Indent().Indent().Indent());
                        buffer.AppendLine(opCodesComment.Indent().Indent().Indent());
                        buffer.AppendLine(String.Format(
                            "{0}.AssertTrue({1}.Contains(new {2}[]{{{3}}}, ({4})opcode.Value.Value));",
                            typeof(AssertionHelper).GetCSharpRef(ToCSharpOptions.ForCodegen),
                            typeof(Enumerable).GetCSharpRef(ToCSharpOptions.ForCodegen),
                            typeof(UInt16).GetCSharpRef(ToCSharpOptions.ForCodegen),
                            fkb.OpCodes.Select(opcode => opcode.GetCSharpByteSequence()).StringJoin(),
                            typeof(UInt16).GetCSharpRef(ToCSharpOptions.ForCodegen))
                            .Indent().Indent().Indent());

                        buffer.AppendLine();
                        buffer.AppendLine("return opcode.Value;".Indent().Indent().Indent());
                        buffer.AppendLine("}".Indent().Indent());
                        buffer.AppendLine();

                        // 4. SizeOfOperands override (special case for Switch)
                        if (fkb.OpCodes.SingleOrDefault2() == OpCodes.Switch)
                        {
                            buffer.AppendLine();
                            buffer.AppendLine(String.Format("public override {0} SizeOfOperand",
                                typeof(Int32).GetCSharpRef(ToCSharpOptions.ForCodegen)).Indent().Indent());
                            buffer.AppendLine("{".Indent().Indent());
                            buffer.AppendLine("get".Indent().Indent().Indent());
                            buffer.AppendLine("{".Indent().Indent().Indent());
                            buffer.AppendLine(String.Format("return sizeof({0}) + _targetOffsets.Count * sizeof({0});",
                                 typeof(Int32).GetCSharpRef(ToCSharpOptions.ForCodegen)).Indent().Indent().Indent().Indent());
                            buffer.AppendLine("}".Indent().Indent().Indent());
                            buffer.AppendLine("}".Indent().Indent());
                        }

                        // 5. Property declarations
                        if (props.IsNotEmpty()) buffer.AppendLine();
                        foreach (var prop in props)
                        {
                            buffer.AppendLine(String.Format("{0}public {1} {2}",
                                prop.IsUnsafe ? "unsafe " : "", 
                                prop.Type.GetCSharpRef(ToCSharpOptions.ForCodegen), 
                                prop.Name).Indent().Indent());

                            buffer.AppendLine("{".Indent().Indent());
                            buffer.AppendLine("get".Indent().Indent().Indent());
                            buffer.AppendLine("{".Indent().Indent().Indent());

                            var getter = prop.Getter.TrimEnd();
                            buffer.AppendLine(getter.Indent().Indent().Indent().Indent());
                            prop.Setter.AssertNullOrEmpty();

                            buffer.AppendLine("}".Indent().Indent().Indent());
                            buffer.AppendLine("}".Indent().Indent());
                            buffer.AppendLine();
                        }

                        // 6. Prefix declarations
                        if (props.IsEmpty() && prefixes.IsNotEmpty()) buffer.AppendLine();
                        foreach (var prefix in prefixes)
                        {
                            buffer.AppendLine(String.Format("{0}public {1} {2}",
                                prefix.IsUnsafe ? "unsafe " : "",
                                prefix.Type.GetCSharpRef(ToCSharpOptions.ForCodegen),
                                prefix.Name).Indent().Indent());

                            buffer.AppendLine("{".Indent().Indent());
                            buffer.AppendLine("get".Indent().Indent().Indent());
                            buffer.AppendLine("{".Indent().Indent().Indent());

                            prefix.Setter.AssertNullOrEmpty();
                            if (prefix.Getter == null)
                            {
                                var getter = String.Format(
                                    "return {0}.Any({0}.OfType<{1}>(Prefixes));",
                                    typeof(Enumerable).GetCSharpRef(ToCSharpOptions.ForCodegen),
                                    prefix.PrefixName.Capitalize());
                                buffer.AppendLine(getter.Indent().Indent().Indent().Indent());
                            }
                            else
                            {
                                var getter = String.Format(
                                    "return {0}.Single({0}.OfType<{1}>(Prefixes)).{2};",
                                    typeof(Enumerable).GetCSharpRef(ToCSharpOptions.ForCodegen),
                                    prefix.PrefixName.Capitalize(),
                                    prefix.Getter);
                                buffer.AppendLine(getter.Indent().Indent().Indent().Indent());
                            }

                            buffer.AppendLine("}".Indent().Indent().Indent());
                            buffer.AppendLine("}".Indent().Indent());
                            buffer.AppendLine();
                        }

                        // 7. Generate the stringify routine
                        if (props.IsEmpty()) buffer.AppendLine();
                        buffer.AppendLine(String.Format("public override {0} ToString()",
                            typeof(String).GetCSharpRef(ToCSharpOptions.ForCodegen)).Indent().Indent());
                        buffer.AppendLine("{".Indent().Indent());

                        // Part 1. Offset (for non-prefix only)
                        buffer.Append("var offset = ".Indent().Indent().Indent());
                        if (isPrefix) buffer.AppendLine("\"\"; // prefixes never get printed in standalone mode so nothing here");
                        if (!isPrefix) buffer.AppendLine("OffsetToString(Offset) + \":\";");

                        // Part 2. Prefixes (wrapped in brackets if any)
                        buffer.Append("var prefixSpec = ".Indent().Indent().Indent());
                        buffer.Append("Prefixes.Count == 0 ? \"\" : (\"[\" + ");
                        buffer.Append(String.Format("{0}.StringJoin(Prefixes)",
                            typeof(EnumerableExtensions).GetCSharpRef(ToCSharpOptions.ForCodegen)));
                        buffer.AppendLine(" + \"]\");");

                        // Part 3. Name (as simple as that lol)
                        var tos_name = fkb.Name == "operator" ? "OperatorTypeToString(OperatorType)" : ("\"" + fkb.Name + "\"");
                        buffer.AppendLine(("var name =  " + tos_name + ";").Indent().Indent().Indent());

                        var mods = new List<String>();
                        String operand = null;

                        // Time for some inference before we continue
                        // note. this stuff is hardcoded (see Visualizer.PrintOutILOpsWithProps for more info)
                        if (fkb.Name == "ldc")
                        {
                            mods.Add("Type == null || OpSpec.OpCode.Value == 0xd0 /*ldtoken*/ ? null : TypeToString(Type)");
                            operand = "ObjectToCSharpLiteral(Value)";
                        }
                        else if (fkb.Name == "cast")
                        {
                            mods.Add("ExpectsUn ? \"un\" : \"\"");
                            mods.Add("FailsOnOverflow ? \"ovf\" : \"\"");
                            mods.Add(String.Format("{0}.Format(\"{{0}}->{{1}}\", " + 
                                "ExpectsRefOrVal ? \"refval\" : (ExpectsRef ? \"ref\" : (ExpectsVal ? \"val\" : \"???\")), " +
                                "YieldsRefOrVal ? \"refval\" : (YieldsRef ? \"ref\" : (YieldsVal ? \"val\" : \"???\"))" + ")",
                                typeof(String).GetCSharpRef(ToCSharpOptions.ForCodegen)));
                            operand = "(Type != null ? TypeToString(Type) : null)";
                        }
                        else if (fkb.Name == "call")
                        {
                            mods.Add("IsVirtual ? \"virt\" : \"\"");
                            operand = "(Method != null ? MethodBaseToString(Method) : null)";
                        }
                        else if (fkb.Name == "operator")
                        {
                            mods.Add("ExpectsUn ? \"un\" : \"\"");
                            mods.Add("FailsOnOverflow ? \"ovf\" : \"\"");
                        }
                        else if (fkb.Name == "branch")
                        {
                            mods.Add("ExpectsUn ? \"un\" : \"\"");
                            mods.Add("PredicateTypeToString(PredicateType)");
                            operand = "OffsetToString(_absoluteTargetOffset)";
                        }
                        else if (fkb.Name == "new")
                        {
                            operand = "(Ctor != null ? ConstructorInfoToString(Ctor) : (Type != null ? TypeToString(Type) : null))";
                        }
                        else if (fkb.Name == "ldftn")
                        {
                            mods.Add("IsVirtual ? \"virt\" : \"\"");
                            operand = "(Method != null ? MethodBaseToString(Method) : null)";
                        }
                        else if (fkb.Name == "compare")
                        {
                            mods.Add("ExpectsUn ? \"un\" : \"\"");
                            mods.Add("PredicateTypeToString(PredicateType)");
                        }
                        else if (fkb.Name == "switch")
                        {
                            operand = "OffsetsToString(AbsoluteTargetOffsets)";
                        }
                        else if (fkb.Name == "calli")
                        {
                            operand = "Sig != null ? ByteArrayToString(Sig) : null";
                        }
                        else if (fkb.Name == "ldarg" || fkb.Name == "ldarga" || fkb.Name == "starg" ||
                            fkb.Name == "ldloc" || fkb.Name == "ldloca" || fkb.Name == "stloc")
                        {
                            props.AssertCount(2);
                            var index = props.Single(p => p.Name == "Index");
                            var other = props.Except(index).Single();

                            operand = String.Format("{2} != null ? "+
                                "{1}ToString({2}) : " + 
                                "{0}.ToString()",
                                index.Name,
                                other.Type.Name,
                                other.Name);
                        }
                        else if (props.Any(p => p.Name.Contains("Token")))
                        {
                            PropertySpec token, resolved;
                            if (props.Count() == 2)
                            {
                                token = props.Single(p => p.Name.Contains("Token"));
                                resolved = props.Except(token).SingleOrDefault2();
                            }
                            else
                            {
                                if (fkb.Name == "ldind" || fkb.Name == "stind")
                                {
                                    token = props.Single(p => p.Name == "TypeToken");
                                    resolved = props.Single(p => p.Name == "Type");
                                }
                                else if (fkb.Name == "ldfld" || fkb.Name == "stfld" || fkb.Name == "ldflda")
                                {
                                    token = props.Single(p => p.Name == "FieldToken");
                                    resolved = props.Single(p => p.Name == "Field");
                                }
                                else
                                {
                                    throw AssertionHelper.Fail();
                                }
                            }

                            operand = String.Format("{0}ToString({1})",
                                resolved.Type.Name,
                                resolved.Name);
                            if (!resolved.Type.IsValueType)
                            {
                                operand = String.Format("({1} != null ? {0} : null)",
                                    operand, resolved.Name);
                            }
                        }
                        else if (fkb.Name == "initblk" || fkb.Name == "cpblk")
                        {
                            // do nothing
                        }
                        else if (props.IsNotEmpty())
                        {
                            props.AssertCount(1);

                            operand = String.Format("{0}ToString({1})",
                                props.Single().Type.Name,
                                props.Single().Name);
                            if (!props.Single().Type.IsValueType)
                            {
                                operand = String.Format("({1} != null ? {0} : null)",
                                    operand, props.Single().Name);
                            }
                        }

                        // this hack is necessary for token-related ops
                        // not to crash when the module is left unspecified
                        if (props.Any(p => p.Name.Contains("Token")))
                        {
                            String tokenExpr; 
                            if (fkb.Name == "new")
                            {
                                var rawTokenExpr = "(_ctorToken ?? _typeToken).Value";
                                rawTokenExpr = String.Format("(\"0x\" + {0}.ToString(\"x8\"))", rawTokenExpr);

                                tokenExpr = "(OpSpec.OpCode.Value == 0x8d /*newarr*/ ? \"arr of \" : \"\") + ";
                                tokenExpr = "(" + tokenExpr + rawTokenExpr + ")";
                            }
                            else if (fkb.Name == "cast")
                            {
                                var token = props.Single(p => p.Name.Contains("Token"));
                                var rawTokenExpr = String.Format("(\"0x\" + {0}.ToString(\"x8\"))", token.Name);
                                tokenExpr = String.Format("(_typeToken == 0 ? {0} : {1})", operand, rawTokenExpr);
                            }
                            else if (fkb.Name == "call")
                            {
                                var calliExpr = "(Signature != null ? ByteArrayToString(Signature) : (\"0x\" + _signatureToken.ToString(\"x8\")))";
                                var callExpr = "(\"0x\" + _methodToken.ToString(\"x8\"))";
                                tokenExpr = String.Format("(OpSpec.OpCode.Value == 0x29 /*calli*/ ? {0} : {1})", calliExpr, callExpr);
                            }
                            else
                            {
                                var token = props.Single(p => p.Name.Contains("Token"));
                                tokenExpr = String.Format("(\"0x\" + {0}.ToString(\"x8\"))", token.Name);
                            }

                            operand = String.Format("({0} ?? ({1}))", operand, tokenExpr);
                        }

                        // Part 4. Mods (e.g. Un, Ovf and likes)
                        buffer.AppendLine(String.Format("var mods = new {0}();",
                            typeof(List<String>).GetCSharpRef(ToCSharpOptions.ForCodegen)).Indent().Indent().Indent());
                        mods.ForEach(mod => buffer.AppendLine(String.Format(
                            "mods.Add({0});", mod).Indent().Indent().Indent()));
                        buffer.AppendLine(String.Format("var modSpec = {0}.StringJoin({1}.Where(mods, mod => {2}.IsNeitherNullNorEmpty(mod)), \", \");",
                            typeof(EnumerableExtensions).GetCSharpRef(ToCSharpOptions.ForCodegen),
                            typeof(Enumerable).GetCSharpRef(ToCSharpOptions.ForCodegen),
                            typeof(EnumerableExtensions).GetCSharpRef(ToCSharpOptions.ForCodegen)).Indent().Indent().Indent());

                        // Part 5. Operand (something to be displayed near the opcode)
                        buffer.AppendLine(String.Format("var operand = {0};",
                            operand.IsNullOrEmpty() ? "\"\"" : operand).Indent().Indent().Indent());

                        // Now assemble the stringified view
                        buffer.AppendLine();
                        buffer.AppendLine("var parts = new []{offset, prefixSpec, name, modSpec, operand};".Indent().Indent().Indent());
                        buffer.AppendLine(String.Format(
                            "var result = {0}.StringJoin({1}.Where(parts, p => {2}.IsNeitherNullNorEmpty(p)), \" \");",
                            typeof(EnumerableExtensions).GetCSharpRef(ToCSharpOptions.ForCodegen),
                            typeof(Enumerable).GetCSharpRef(ToCSharpOptions.ForCodegen),
                            typeof(EnumerableExtensions).GetCSharpRef(ToCSharpOptions.ForCodegen)).Indent().Indent().Indent());
                        buffer.AppendLine();
                        buffer.AppendLine("return result;".Indent().Indent().Indent());

                        buffer.AppendLine("}".Indent().Indent());

                        // Fixup the last eoln in the class (added by the TextGeneratedIntoClass.template)
                        var eolnLen = Environment.NewLine.Length;
                        if (buffer.ToString(buffer.Length - eolnLen, eolnLen) == Environment.NewLine)
                            buffer.Remove(buffer.Length - eolnLen, eolnLen);

                        // Finally, don't forget to redirect from local enums to generated classes
                        typeRedirections.ForEach(redir => buffer.Replace(redir.Key, redir.Value));
                    });
            }
        }
        public void It_Should_Handle_Multiple_Transforms_With_Same_ReturnType_From_Different_StepSets()
        {
            var transformDefinitions1 = new List<TransformDefinition> { transformDefinition1 };
            var transformDefinitions2 = new List<TransformDefinition> { transformDefinition2 };

            var mockStepSet1 = new Mock<IStepSet>();
            mockStepSet1.Setup(ss => ss.StepDefinitions).Returns(new List<StepDefinition>());
            mockStepSet1.Setup(ss => ss.TransformDefinitions).Returns(new Dictionary<Type, IList<TransformDefinition>> { { typeof(int), transformDefinitions1 } });

            var mockStepSet2 = new Mock<IStepSet>();
            mockStepSet2.Setup(ss => ss.StepDefinitions).Returns(new List<StepDefinition>());
            mockStepSet2.Setup(ss => ss.TransformDefinitions).Returns(new Dictionary<Type, IList<TransformDefinition>> { { typeof(int), transformDefinitions2 } });

            stepMother.StepSets = new List<IStepSet> { mockStepSet1.Object, mockStepSet2.Object };
            var definitions = stepMother.TransformDefinitions.Values.SelectMany(x => x);

            definitions.Should().Have.SameSequenceAs(transformDefinitions1.Concat(transformDefinitions2));
        }
        public void ShouldTruncateResponseAtEpochBoundary()
        {
            Converters.Register("V", "V",
                (IMeasurement m) => m);

            var daq = new SimpleDAQController();
            var c = new NonValidatingController { DAQController = daq };
            var dev = new UnitConvertingExternalDevice("dev", UNUSED_DEVICE_MANUFACTURER, c, UNUSED_BACKGROUND);
            var outStream = new DAQOutputStream("out");
            var inStream = new DAQInputStream("in");
            dev.BindStream(outStream).BindStream(inStream);

            var sampleRate = new Measurement(1, "Hz");

            var samples = new List<IMeasurement> { new Measurement(1, "V"), new Measurement(2, "V"), new Measurement(3, "V") };

            var data = new OutputData(samples,
                                      sampleRate, true);

            var e = new Epoch(UNUSED_PROTOCOL);

            e.Stimuli[dev] = new RenderedStimulus((string) "ID1",
                                                   (IDictionary<string, object>) new Dictionary<string, object>(),
                                                   (IOutputData) data);
            e.Responses[dev] = new Response();

            bool pushed = false;
            daq.Started += (evt, args) =>
            {
                c.PullOutputData(dev, data.Duration);
                c.PushInputData(dev, new InputData(samples.Concat(samples).ToList(),
                                                   sampleRate,
                                                   DateTimeOffset.Now)
                                         .DataWithStreamConfiguration(streamFake, new Dictionary<string, object>())
                                         .DataWithExternalDeviceConfiguration(devFake, new Dictionary<string, object>()));
                pushed = true;

                c.RequestStop();
            };

            c.EnqueueEpoch(e);
            c.StartAsync(null);

            while (!pushed)
            {
                Thread.Sleep(1);
            }

            Assert.That(((TimeSpan)e.Responses[dev].Duration), Is.EqualTo((TimeSpan)e.Duration));
        }
        private static void GetThird(List<int> elements, List<List<int>> combinations, List<int> current, int ctr)
        {
            var n = elements.Count;
            var j = current[current.Count - 1];
            for (int k = j + 1; k < n; k++)
            {
                var c = current.Concat(new List<int> { k }).ToList();

                if (ctr == c.Count)
                {
                    var r = c.Select(i => elements[i]).ToList();
                    combinations.Add(r);
                }
                else
                {
                    GetFourth(elements, combinations, c, ctr);
                }
            }
        }
        public void TestGetDonationYearsForAuthenticatedUser()
        {
            var donations = new List<Donation>
            {
                new Donation
                {
                    donationDate = DateTime.Parse("1999-12-31 23:59:59"),
                },
                new Donation
                {
                    donationDate = DateTime.Parse("2000-01-01 00:00:01"),
                },
                new Donation
                {
                    donationDate = DateTime.Parse("1999-11-30 23:59:59"),
                },
                new Donation
                {
                    donationDate = DateTime.Parse("1998-10-30 23:59:59"),
                }
            };

            var softCreditDonations = new List<Donation>
            {
                new Donation
                {
                    donationDate = DateTime.Parse("1997-12-31 23:59:59"),
                },
                new Donation
                {
                    donationDate = DateTime.Parse("2001-01-01 00:00:01"),
                },
                new Donation
                {
                    donationDate = DateTime.Parse("1999-11-30 23:59:59"),
                },
                new Donation
                {
                    donationDate = DateTime.Parse("1997-11-30 23:59:59"),
                },
                new Donation
                {
                    donationDate = DateTime.Parse("1996-10-30 23:59:59"),
                }
            };

            var expectedYears = new List<string>
            {
                "2001",
                "2000",
                "1999",
                "1998",
                "1997",
                "1996"
            };

            _mpDonorService.Setup(mocked => mocked.GetDonationsForAuthenticatedUser("auth token", null, null)).Returns(donations.Concat(softCreditDonations).ToList());

            var response = _fixture.GetDonationYearsForAuthenticatedUser("auth token");
            _mpDonorService.VerifyAll();

            Assert.IsNotNull(response);
            Assert.IsNotNull(response.AvailableDonationYears);
            Assert.AreEqual(expectedYears.Count, response.AvailableDonationYears.Count);
        }