public void TestMethod1() { var dateTimeFuncs = new Func<Double, TimeSpan>[] { TimeSpan.FromSeconds, TimeSpan.FromMinutes, TimeSpan.FromHours, TimeSpan.FromDays, x => TimeSpan.FromDays(30 * x), x => TimeSpan.FromDays(365 * x), }; var allCultures = CultureInfo.GetCultures(CultureTypes.AllCultures); var supportedCultures = new List<CultureInfo>(); foreach (var culture in allCultures) { try { var dateTimeFormatStrings = DateTimeExtensions.GetFormatString(culture); supportedCultures.Add(culture); } catch (NotSupportedException) {} } var distinctSupportedLanguageCultures = supportedCultures.GroupBy(x => x.ThreeLetterISOLanguageName).Select(x => x.First()).ToList(); foreach (var culture in distinctSupportedLanguageCultures) { foreach (var dateTimeFunc in dateTimeFuncs) { for (var i = 0; i != 3; i++) { var dateTime = DateTime.Now.Subtract(dateTimeFunc(i)); var timeAgo = dateTime.TimeAgo(culture); Debug.WriteLine(timeAgo); } } } }
public void GetReport_Returns_5_Elements_For_5_Input() { string skill1 = "C#"; string skill2 = "JavaScript"; string skill3 = "C"; DateTime date1 = new DateTime(year: 2016, month: 2, day: 8); IQueryable<CandidateInformation> _CandidateInfoColl = new List<CandidateInformation>() { new CandidateInformation() { SkillSet = skill1, SavedOn = date1 }, new CandidateInformation() { SkillSet = skill1, SavedOn = date1 }, new CandidateInformation() { SkillSet = skill2, SavedOn = date1 }, new CandidateInformation() { SkillSet = skill3, SavedOn = date1 }, new CandidateInformation() { SkillSet = skill3, SavedOn = date1 }, }.AsQueryable(); DateTime reportDate = date1; IRepository<CandidateInformation> mockCandidateInfoRepository = MockRepository.GenerateMock<IRepository<CandidateInformation>>(); mockCandidateInfoRepository.Stub(x => x.Find(Arg<Expression<Func<CandidateInformation, bool>>>.Is.Anything)).Return(_CandidateInfoColl); IReportGenerator reportGenerator = new ReportGenerator(reportDate, mockCandidateInfoRepository); IEnumerable<string> actualOutput = reportGenerator.GetReport(); IEnumerable<string> expectedOutput = _CandidateInfoColl.GroupBy(x => x.SkillSet) .OrderBy(x => x.Key) .Select(x => string.Format("{0},{1}", x.Key, x.Count())); mockCandidateInfoRepository.AssertWasCalled(x => x.Find(Arg<Expression<Func<CandidateInformation, bool>>>.Is.Anything)); Assert.AreEqual(expectedOutput.Count() + 1, actualOutput.Count()); //Added 1 to compensate for the header row. foreach (string expectedString in expectedOutput) { Assert.IsTrue(actualOutput.Contains(expectedString)); } }
public void EnsureDeckHasRightNumberOfSuites() { var testDeck = new PrivateObject(typeof(Deck)); var cardsInTestDeck = new List<Card>((Stack<Card>)testDeck.GetFieldOrProperty("_cards")); var result = cardsInTestDeck.GroupBy(card => card.Suit); Assert.IsFalse(result.Count() < 4, "Suits Error", "The deck contains less than four suits."); Assert.IsFalse(result.Count() > 4, "Suits Error", "The deck contains more than four suits."); }
public void EnsureDeckHasRightNumberOfValues() { var testDeck = new PrivateObject(typeof(Deck)); var cardsInTestDeck = new List<Card>((Stack<Card>)testDeck.GetFieldOrProperty("_cards")); var result = cardsInTestDeck.GroupBy(card => card.Value); Assert.IsFalse(result.Count() < 13, "Value Error", "The deck contains less than thirteen values."); Assert.IsFalse(result.Count() > 13, "Value Error", "The deck contains more than thirteen values."); }
public void IntEqualityComparerTest() { var source = new List<int> { 1, 5, 5, 2,7,12,15,18,20,24,25,10,5,1,8,11,30 }; var comparer = new IntEqualityComparer(5); source.Sort(); var res = source.GroupBy(g => g, comparer); Assert.AreEqual(5, res.Count()); }
public void GameHandlerReturnsRandomColors() { GameHandler gameHandler = new GameHandler(); List<List<GameColors>> colors = new List<List<GameColors>>(); //1000 is a large enough number to reduce the the chance of getting the same color in the first position //beyond probable infinity (1/8)^1000 for (int i = 0; i < 1000; i++) { colors.Add(gameHandler.GetInitialColors()); } Assert.IsTrue(colors.GroupBy(f => f.First()).Count() > 1, "Colors returned by GameHandler does not appear to be random."); }
public void DLINQPerformsDistributedGroupBy() { bool isFailed = false; BluepathListener listener1; BluepathListener listener2; ConnectionManager connectionManager; Log.TraceMessage(Log.Activity.Custom,string.Format("GroupBy test lift off!")); PrepareDLINQEnviroment(out listener1, out listener2, out connectionManager); try { var inputCollection = new List<string>(); for (int i = 0; i < 100; i++) { inputCollection.Add(string.Format("{0}{1}", (i % 2 == 0 ? "a" : "b"), i)); } var locallyGrouped = inputCollection.GroupBy(s => s[0]); var localDict = locallyGrouped.ToDictionary(g => g.Key, g => g); var storage = new RedisStorage(Host); var groupedCollection = inputCollection.AsDistributed(storage, connectionManager) .GroupBy(s => s[0]); Log.TraceMessage(Log.Activity.Custom,"GroupBy Begin actual processing"); var processedCollection = groupedCollection.ToDictionary(g => g.Key, g => g); Log.TraceMessage(Log.Activity.Custom,"GroupBy processing finished, begin asserts"); processedCollection.Keys.Count.ShouldBe(2); processedCollection['a'].Count().ShouldBe(localDict['a'].Count()); processedCollection['b'].Count().ShouldBe(localDict['b'].Count()); Log.TraceMessage(Log.Activity.Custom,"GroupBy test passed"); } catch (Exception ex) { Log.ExceptionMessage(ex, Log.Activity.Info); isFailed = true; } finally { listener1.Stop(); listener2.Stop(); Log.TraceMessage(Log.Activity.Custom, string.Format("GroupBy test finished, isFailed: {0}", isFailed)); if(isFailed) { Assert.Fail(); } } }
public void TestFindDuplicates_DetectDuplicates() { Random random = new Random(); // build a list of random values var list = new List<int>(100); Sublist.Generate(100, i => random.Next(100)).AddTo(list.ToSublist()); // duplicates must appear next to each other list.ToSublist().Sort().InPlace(); var result = list.ToSublist().FindDuplicates(); if (!result.Exists) { Assert.AreEqual(list.Count, list.GroupBy(i => i).Count(), "Duplicates were not detected."); } else { var actual = list.ToSublist(result.Index, 2); int[] expected = new int[2] { list[result.Index], list[result.Index] }; Assert.IsTrue(expected.ToSublist().IsEqualTo(actual), "No duplicates were not found."); } }
public void ObservableThreadsWithThrottleOnCompute() { Console.WriteLine("Starting Thread " + Thread.CurrentThread.ManagedThreadId); BehaviorSubject<int> s1 = new BehaviorSubject<int>(2); BehaviorSubject<int> s2 = new BehaviorSubject<int>(3); BehaviorSubject<int> sum = new BehaviorSubject<int>(5); List<int> computeThreads = new List<int>(); List<int> receiveThreads = new List<int>(); IScheduler computeScheduler = new EventLoopScheduler(); IObservable<int> sumObservable = s1.Throttle(TimeSpan.FromMilliseconds(100), computeScheduler).ObserveOn(computeScheduler).CombineLatest(s2.Throttle(TimeSpan.FromMilliseconds(100), computeScheduler).ObserveOn(computeScheduler), (first, second) => { Console.WriteLine("Computing value " + first + " + " + second + " = " + (first + second) + " on Thread " + Thread.CurrentThread.ManagedThreadId + "."); computeThreads.Add(Thread.CurrentThread.ManagedThreadId); return first + second; }); sumObservable.Subscribe(sum.OnNext); sum.ObserveOn(new EventLoopScheduler()).Subscribe(v => { Console.WriteLine("Received value " + v + " on Thread " + Thread.CurrentThread.ManagedThreadId + "."); receiveThreads.Add(Thread.CurrentThread.ManagedThreadId); }); Thread.Sleep(150); s2.OnNext(1); Thread.Sleep(50); s1.OnNext(4); Thread.Sleep(150); s2.OnNext(4); Thread.Sleep(250); s1.OnNext(1); Thread.Sleep(150); foreach (KeyValuePair<int, int> p in computeThreads.GroupBy(v => v).Select(g => new KeyValuePair<int, int>(g.Key, g.Count()))) { Console.WriteLine(p.Value + " computes on Thread " + p.Key); } foreach (KeyValuePair<int, int> p in receiveThreads.GroupBy(v => v).Select(g => new KeyValuePair<int, int>(g.Key, g.Count()))) { Console.WriteLine(p.Value + " receives on Thread " + p.Key); } }
public void TestJoinLists() { // Create a new list of apps var apps = new List<EmailApplication>() { new EmailApplication() {Id = 1, CustomerId = 1, IPAccessRestrictions = "123.43.56.2"}, new EmailApplication() {Id = 2, CustomerId = 1, IPAccessRestrictions = "123.43.56.36"}, new EmailApplication() {Id = 3, CustomerId = 1}, new EmailApplication() {Id = 4, CustomerId = 2}, new EmailApplication() {Id = 5, CustomerId = 3, IPAccessRestrictions = "123.43.45.1"} }; var customers = new List<Customer>(); foreach (var customer in m_repository.GetSortedCustomers()) { // customer.Applications = apps.Where(a => a.CustomerId == customer.Id).ToList(); customers.Add(customer); } // Join customers to applications (with filter to those with IP restrictions) var joinQuery = customers.Join(apps, c => c.Id, a => a.CustomerId, (c, a) => new { Name = c.LastName + ", " + c.FirstName, IpRestrictions = a.IPAccessRestrictions }).Where(w => !String.IsNullOrEmpty(w.IpRestrictions)); foreach (var item in joinQuery) { Debug.WriteLine(item.Name.ToString() + " : " + item.IpRestrictions); } // Try to get customers with IP access restrictions var manyQuery = customers .Select(c => c.Applications .Where(a => !String.IsNullOrEmpty(a.IPAccessRestrictions))); foreach (var item in manyQuery) { Debug.WriteLine(item.ToString()); } // The above query is an enumerable of an enumerable, which ain't great // Using SelectMany will flatten a parent/child relationship and allow projection on either var customersWithIpRestrictions = customers .SelectMany(c => c.Applications .Where(a => !String.IsNullOrEmpty(a.IPAccessRestrictions)), // project to customer (c, a) => c) .Distinct(); foreach (var item in customersWithIpRestrictions) { Debug.WriteLine(item.LastName + ", " + item.FirstName); } Debug.WriteLine(customers.Sum(c => 1)); var groupBy = apps.GroupBy(a => a.CustomerId, a => a.Id, (key, id) => new { ClientId = key, NumApps = id.Sum(a => 1), MeanApps = id.Sum() / id.Sum(a => 1), Avg = id.Average() }); foreach (var item in groupBy) { Debug.WriteLine(item.ClientId + " has this many apps: " + item.NumApps + " with mean: " + item.Avg); } var modeJoin = apps.Join(customers, a => a.CustomerId, c => c.Id, (a, c) => new { ClientName = c.LastName + ", " + c.FirstName, ApplicationId = a.Id }); var modeQuery = modeJoin.GroupBy(e => e.ClientName) .OrderByDescending(group => group.Count()) .Select(group => group.Key); Debug.WriteLine("ClientId with most apps: " + modeQuery.FirstOrDefault()); Assert.IsNotNull(joinQuery); }
public void ScaleRetrievalTest() { var manager = new QueueMessageManagerSql(); manager.Db.ExecuteNonQuery("delete from queuemessageitems"); var sw = new Stopwatch(); sw.Start(); for (int i = 0; i < 30000; i++) { string imageId = "10"; // Create a message object // item contains many properties for pushing // values back and forth as well as a few message fields var item = manager.CreateItem(); item.QueueName = "Queue1"; item.TextInput = DataUtils.GenerateUniqueId(15); // Set the message status and timestamps as submitted manager.SubmitRequest(item,autoSave: true); } Console.WriteLine("Insert time: " + sw.ElapsedMilliseconds); IdList = new List<string>(); IdErrors = new List<string>(); for (int i = 0; i < 20; i++) { var thread = new Thread(ProcessGetNextItem); thread.Start(); } for (int i = 0; i < 10000; i++) { if (CancelProcessing) break; string imageId = "10"; // Create a message object // item contains many properties for pushing // values back and forth as well as a few message fields var item = manager.CreateItem(); item.QueueName = "Queue1"; item.TextInput = DataUtils.GenerateUniqueId(15); // Set the message status and timestamps as submitted manager.SubmitRequest(item, autoSave: true); Thread.Sleep(2); } Console.WriteLine("Waiting for 5 seconds"); Thread.Sleep(5000); CancelProcessing = true; Thread.Sleep(100); Console.WriteLine("Done"); Console.WriteLine("Items processed: " + IdList.Count); var grouped = IdList.GroupBy(s => s); Console.WriteLine("Unique Count: " + grouped.Count()); foreach (var error in IdErrors) Console.WriteLine(" " + error); }
public void ScaleControllerRetrievalTest() { var manager = new QueueMessageManagerMongoDb(CONNECTION_STRING); manager.Collection.RemoveAll(); CancelProcessing = false; var sw = new Stopwatch(); sw.Start(); for (int i = 0; i < 30000; i++) { string imageId = "10"; // Create a message object // item contains many properties for pushing // values back and forth as well as a few message fields var item = manager.CreateItem(); item.QueueName = "Queue1"; item.TextInput = DataUtils.GenerateUniqueId(15); // Set the message status and timestamps as submitted manager.SubmitRequest(item, autoSave: true); } Console.WriteLine("Done adding: " + sw.ElapsedMilliseconds + "ms"); Console.WriteLine("Items inserted."); IdList = new List<string>(); IdErrors = new List<string>(); for (int i = 0; i < 10; i++) { var thread = new Thread(ProcessGetNextItem); thread.Start(); } //Task.Run(() => //{ // for (int i = 0; i < 100; i++) // { // manager = new QueueMessageManagerSql(); // string imageId = "10"; // // Create a message object // // item contains many properties for pushing // // values back and forth as well as a few message fields // var item = manager.CreateItem(); // item.QueueName = "Queue1"; // item.TextInput = DataUtils.GenerateUniqueId(15); // // Set the message status and timestamps as submitted // manager.SubmitRequest(item, autoSave: true); // } // Thread.Sleep(60); //}); for (int i = 0; i < 500; i++) { if (CancelProcessing) break; string imageId = "10"; // Create a message object // item contains many properties for pushing // values back and forth as well as a few message fields var item = manager.CreateItem(); item.QueueName = "Queue1"; item.TextInput = DataUtils.GenerateUniqueId(15); // Set the message status and timestamps as submitted manager.SubmitRequest(item, autoSave: true); Thread.Yield(); } Console.WriteLine("Waiting for 5 seconds"); Thread.Sleep(5000); CancelProcessing = true; Thread.Sleep(150); Console.WriteLine("Done"); Console.WriteLine("Items processed: " + IdList.Count); IdList.Add("12345"); IdList.Add("321321"); IdList.Add("12345"); var grouped = IdList.GroupBy(s => s); Console.WriteLine("Unique Count: " + grouped.Count()); foreach (var error in IdErrors) Console.WriteLine(" " + error); }
public void GroupBy_abnormal() { // arrange List<Javascript> list = new List<Javascript>() { new Javascript("Angular", 1), new Javascript("React", 1), new Javascript("Backbone", 5) }; Func<Javascript, Javascript> func = null; // act and assert try { list.GroupBy(func); Assert.Fail(); } catch (Exception e) { Assert.IsTrue(e is ArgumentNullException); } }
public void TestLiveListGroupBy2() { var data = new List<A>() .ToLiveList(); data.TraceAll("data").ToDebug(); using (Publish.Transaction(true)) { Enumerable.Range(0, 7) .ForEach(i => { var aa = new A(); aa.I.Init(i % 5, 0); data.PublishInner.Add(aa); }); } var a = data .GroupBy(i => i.I) .ToIndependent(); a.TraceAll("a").ToDebug(); }
public void AsyncObservableThreadsWithBetterThrottleOnComputeAndIsCalculating() { Console.WriteLine("Starting Thread " + Thread.CurrentThread.ManagedThreadId); BehaviorSubject<int> s1 = new BehaviorSubject<int>(2); BehaviorSubject<int> s2 = new BehaviorSubject<int>(3); BehaviorSubject<int> sum = new BehaviorSubject<int>(5); List<int> computeThreads = new List<int>(); List<int> receiveThreads = new List<int>(); IScheduler throttleScheduler = new EventLoopScheduler(); Func<IScheduler> getComputeScheduler = () => new EventLoopScheduler(); IScheduler receiveScheduler = new EventLoopScheduler(); IObservable<Tuple<int, int>> sumObservable = s1.CombineLatest(s2, Tuple.Create).Throttle(TimeSpan.FromMilliseconds(100), throttleScheduler); IDisposable sumObservableSubscription = null; using (sumObservable.Subscribe(v => { if (sumObservableSubscription != null) { Console.WriteLine("Canceling previous."); sumObservableSubscription.Dispose(); } sumObservableSubscription = Observable.Create<int>((o, token) => Task.Factory.StartNew(() => { Thread.Sleep(200); if (!token.IsCancellationRequested) { Console.WriteLine("Computing value " + v.Item1 + " + " + v.Item2 + " = " + (v.Item1 + v.Item2) + " on Thread " + Thread.CurrentThread.ManagedThreadId + "."); computeThreads.Add(Thread.CurrentThread.ManagedThreadId); o.OnNext(v.Item1 + v.Item2); } o.OnCompleted(); return Disposable.Empty; })).ObserveOn(receiveScheduler).Subscribe(v2 => { Console.WriteLine("Received value " + v2 + " on Thread " + Thread.CurrentThread.ManagedThreadId + "."); receiveThreads.Add(Thread.CurrentThread.ManagedThreadId); }); })) { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); Thread.Sleep(150); s2.OnNext(1); Thread.Sleep(50); s1.OnNext(4); Thread.Sleep(250); s2.OnNext(4); Thread.Sleep(150); s1.OnNext(1); Thread.Sleep(350); stopwatch.Stop(); Console.WriteLine("Total Time: " + stopwatch.ElapsedMilliseconds + " ms"); foreach (KeyValuePair<int, int> p in computeThreads.GroupBy(v => v).Select(g => new KeyValuePair<int, int>(g.Key, g.Count()))) { Console.WriteLine(p.Value + " computes on Thread " + p.Key); } foreach (KeyValuePair<int, int> p in receiveThreads.GroupBy(v => v).Select(g => new KeyValuePair<int, int>(g.Key, g.Count()))) { Console.WriteLine(p.Value + " receives on Thread " + p.Key); } } }
public void ValidateDensePairAnsiWriteDensePairAnsi() { List<KeyValuePair<string, UOPair<char>>> keyValListObj = new List<KeyValuePair<string, UOPair<char>>>(); var enumObj = keyValListObj.GroupBy(x => x.Key); DensePairAnsi dpaObj = DensePairAnsi.GetInstance(enumObj); ParallelOptions paObj = new ParallelOptions(); dpaObj.WriteDensePairAnsi(Constants.FastQTempTxtFileName, paObj); DensePairAnsi newDpaObj = DensePairAnsi.GetInstance(Constants.FastQTempTxtFileName, paObj); Assert.IsNotNull(newDpaObj); ApplicationLog.WriteLine( "DensePairAnsi BVT : Validation of WriteDensePairAnsi() method successful"); }
public void TestListMaxByKey() { var l = new List<int> {0, 1, 1, 2, 3, 4, 5}.ToLiveList(); var groups = l.GroupBy(x => x.ToLiveConst()); ILiveValue<KeyValuePair<int, ILiveCollection<int>>> maxGroup = groups.MaxByKey(); maxGroup.SelectStatic(kv => kv.Key).Trace("key").ToDebug(); maxGroup.Select(kv => kv.Value).TraceAll("members").ToDebug(); l.PublishInner.Add(-1); l.PublishInner.Add(6); l.PublishInner.Remove(5); l.PublishInner.Add(6); l.PublishInner.Remove(6); l.PublishInner.Remove(6); l.PublishInner.Add(-1); l.PublishInner.Remove(-1); l.PublishInner.Remove(-1); }
public void GenerateWithOneLetterOrNumber10TimesExpectedDifferentNumberAndLettersEachTime() { //Initialize var results = new List<string>(); //Get 10 random letters for (var i = 0; i < 10; i++) { results.Add(_dev2Random.GetRandom(enRandomType.LetterAndNumbers, 1, -1, -1)); } //Count duplicates var countDuplicates = results.GroupBy(group => group) .Select(item => new { Value = item.Key, Count = item.Count() }); //Assert no item is duplicated more than twice foreach (var elem in countDuplicates) { Assert.IsTrue(elem.Count <= 5, elem.Count + " duplicate letters and numbers where generated by Dev2Random class (out of 10)"); } }
private int countPermutations(List<int> values) { var groups = values.GroupBy(i => i); int nominator = factorial(values.Count); int denominator = 1; foreach (var group in groups) { denominator *= factorial(group.Count()); } return nominator / denominator; }
public void CompressTest() { //var str = "Amaze UI 含近 20 个 CSS 组件、10 个 JS 组件,更有 17 款包含近 60 个主题的 Web 组件,可快速构建界面出色、体验优秀的跨屏页面,大幅提升开发效率"; //str = CompressHelper.Compress(str); //Console.WriteLine(str); //str = CompressHelper.Decompress(str); //Console.WriteLine(str); //Console.WriteLine(RandomHelper.RandomHanzi(4)); //Console.WriteLine(RandomHelper.RandomHanzi(4, 3)); //Console.WriteLine(CombHelper.NewComb()); var list = new List<string>(); for (int i = 0; i < 100 * 1000; i++) { list.Add(CombHelper.Guid16); } var result = list.GroupBy(t => t).Select(t => new { key = t.Key, c = t.Count() }).OrderByDescending(t => t.c); foreach (var item in result.Take(50)) { Console.WriteLine(item.ToJson()); } }
public void GroupBy() { List<Javascript> list = new List<Javascript>() { new Javascript("Angular", 1), new Javascript("React", 1), new Javascript("Backbone", 5) }; // act var actual = list.GroupBy(x => x.Age).ToList(); // assert Assert.AreEqual(true, actual[0].Any(x => x.Name == "Angular")); Assert.AreEqual(true, actual[0].Any(x => x.Name == "React")); Assert.AreEqual(false, actual[0].Any(x => x.Name == "Backbone")); Assert.AreEqual(false, actual[1].Any(x => x.Name == "Angular")); Assert.AreEqual(false, actual[1].Any(x => x.Name == "React")); Assert.AreEqual(true, actual[1].Any(x => x.Name == "Backbone")); }
public void After500IterationsNoDuplicateDecks() { var deck = this.deckBuilder.Build(); var shuffleResults = new List<string>(); for (var i = 0; i < 500; i++) { deck = this.dealer.Shuffle(deck); shuffleResults.Add(Utils.DeckCardsToString(deck)); } var duplicatesGroup = shuffleResults.GroupBy(x => x).Where(x => x.Count() > 1).Select(x => x.Key); Assert.AreEqual(0, duplicatesGroup.Count()); }
public void RxOnlyAsyncObservableThreadsWithBetterThrottleOnComputeAndIsCalculating() { Console.WriteLine("Starting Thread " + Thread.CurrentThread.ManagedThreadId); BehaviorSubject<int> s1 = new BehaviorSubject<int>(2); BehaviorSubject<int> s2 = new BehaviorSubject<int>(3); List<int> computeThreads = new List<int>(); List<int> receiveThreads = new List<int>(); IScheduler throttleScheduler = new EventLoopScheduler(); IScheduler computeScheduler = NewThreadScheduler.Default; IScheduler receiveScheduler = new EventLoopScheduler(); IObservable<Tuple<int, int>> sumObservable = s1.CombineLatest(s2, Tuple.Create).Throttle(TimeSpan.FromMilliseconds(100), throttleScheduler); Func<CalculatedPropertyHelper, int, int, Task<int>> calculate = async (helper, v1, v2) => { Thread.Sleep(200); helper.CheckCancellationToken(); Console.WriteLine("Computing value " + v1 + " + " + v2 + " = " + (v1 + v2) + " on Thread " + Thread.CurrentThread.ManagedThreadId + "."); computeThreads.Add(Thread.CurrentThread.ManagedThreadId); return await Task.FromResult(v1 + v2); }; BehaviorSubject<int> sum = new BehaviorSubject<int>(0); IDisposable scheduledTask = computeScheduler.ScheduleAsync(async (scheduler, token) => { await scheduler.Yield(); sum.OnNext(await calculate(new CalculatedPropertyHelper(scheduler, token), s1.Value, s2.Value)); }); using (sumObservable.Subscribe(v => { if (scheduledTask != null) { Console.WriteLine("Canceling previous."); scheduledTask.Dispose(); } scheduledTask = computeScheduler.ScheduleAsync(async (scheduler, token) => { await scheduler.Yield(); sum.OnNext(await calculate(new CalculatedPropertyHelper(scheduler, token), v.Item1, v.Item2)); }); })) { using (sum.ObserveOn(receiveScheduler).Subscribe(v2 => { Console.WriteLine("Received value " + v2 + " on Thread " + Thread.CurrentThread.ManagedThreadId + "."); receiveThreads.Add(Thread.CurrentThread.ManagedThreadId); })) { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); Thread.Sleep(150); s2.OnNext(1); Thread.Sleep(50); s1.OnNext(4); Thread.Sleep(250); s2.OnNext(4); Thread.Sleep(150); s1.OnNext(1); Thread.Sleep(350); stopwatch.Stop(); Console.WriteLine("Total Time: " + stopwatch.ElapsedMilliseconds + " ms"); foreach (KeyValuePair<int, int> p in computeThreads.GroupBy(v => v).Select(g => new KeyValuePair<int, int>(g.Key, g.Count()))) { Console.WriteLine(p.Value + " computes on Thread " + p.Key); } foreach (KeyValuePair<int, int> p in receiveThreads.GroupBy(v => v).Select(g => new KeyValuePair<int, int>(g.Key, g.Count()))) { Console.WriteLine(p.Value + " receives on Thread " + p.Key); } } } }
public void ThreadSwitching() { Console.WriteLine("Starting Thread " + Thread.CurrentThread.ManagedThreadId); BehaviorSubject<int> s1 = new BehaviorSubject<int>(2); BehaviorSubject<int> s2 = new BehaviorSubject<int>(3); BehaviorSubject<int> sum = new BehaviorSubject<int>(5); List<int> computeThreads = new List<int>(); List<int> receiveThreads = new List<int>(); IScheduler switchScheduler = new EventLoopScheduler(); IScheduler computeScheduler = new EventLoopScheduler(); IObservable<int> sumObservable = s1.Select(v => new Tuple<int, int>(v, s2.Value)).Merge(s2.Select(v => new Tuple<int, int>(s1.Value, v))).Throttle(TimeSpan.FromMilliseconds(100), switchScheduler).Select(v => { Console.WriteLine("Not yet switching computing value " + v.Item1 + " + " + v.Item2 + " = " + (v.Item1 + v.Item2) + " from Thread " + Thread.CurrentThread.ManagedThreadId + "."); return v; }).Select(v => { Console.WriteLine("Switching computing value " + v.Item1 + " + " + v.Item2 + " = " + (v.Item1 + v.Item2) + " from Thread " + Thread.CurrentThread.ManagedThreadId + "."); return v; }).ObserveOn(computeScheduler).Select(v => { Console.WriteLine("Already switched computing value " + v.Item1 + " + " + v.Item2 + " = " + (v.Item1 + v.Item2) + " to Thread " + Thread.CurrentThread.ManagedThreadId + "."); return v; }).Select(v => { Console.WriteLine("Computing value " + v.Item1 + " + " + v.Item2 + " = " + (v.Item1 + v.Item2) + " on Thread " + Thread.CurrentThread.ManagedThreadId + "."); computeThreads.Add(Thread.CurrentThread.ManagedThreadId); return v.Item1 + v.Item2; }); sumObservable.Subscribe(sum.OnNext); sum.ObserveOn(new EventLoopScheduler()).Subscribe(v => { Console.WriteLine("Received value " + v + " on Thread " + Thread.CurrentThread.ManagedThreadId + "."); receiveThreads.Add(Thread.CurrentThread.ManagedThreadId); }); Thread.Sleep(150); s2.OnNext(1); Thread.Sleep(50); s1.OnNext(4); Thread.Sleep(150); s2.OnNext(4); Thread.Sleep(250); s1.OnNext(1); Thread.Sleep(150); foreach (KeyValuePair<int, int> p in computeThreads.GroupBy(v => v).Select(g => new KeyValuePair<int, int>(g.Key, g.Count()))) { Console.WriteLine(p.Value + " computes on Thread " + p.Key); } foreach (KeyValuePair<int, int> p in receiveThreads.GroupBy(v => v).Select(g => new KeyValuePair<int, int>(g.Key, g.Count()))) { Console.WriteLine(p.Value + " receives on Thread " + p.Key); } }
//verify that all buffers referencing the same array are contiguous i.e no overlap private static void AssertIsContiguous(List<IBuffer> bufferList) { var orderedGroups = bufferList.GroupBy(o => o.GetSegments()[0].Array); foreach (var grp in orderedGroups) { var orderedList = grp.OrderBy(o => o.GetSegments()[0].Offset).ToList(); Assert.AreEqual(orderedList[0].GetSegments()[0].Offset, 0); for (int i = 1; i < orderedList.Count; i++) { Assert.IsTrue( orderedList[i].GetSegments()[0].Offset == orderedList[i - 1].GetSegments()[0].Offset + orderedList[i - 1].GetSegments()[0].Count ); } } }
public void ValidateDensePairAnsiGetInstanceIEnum() { List<KeyValuePair<string, UOPair<char>>> keyValListObj = new List<KeyValuePair<string, UOPair<char>>>(); var enumObj = keyValListObj.GroupBy(x => x.Key); DensePairAnsi dpaObj = DensePairAnsi.GetInstance(enumObj); Assert.IsNotNull(dpaObj); ApplicationLog.WriteLine( "DensePairAnsi BVT : Validation of GetInstance(enum, char) method successful"); }