private Task Wizard(bool FSharpVersion) { cancelWizard = new CancellationTokenSource(); // run the study plan wizard in the background on a separate thread (so that the UI remains responsive) return(Task.Run(() => { if (plan.Items.Count() > 0 && StudyPlannerModel.isLegalPlan(plan.Items)) { IEnumerable <StudyPlan> wizard; if (FSharpVersion) { wizard = FSharpSchedulingWizard.TryToImproveSchedule(plan.Items); } else { wizard = CSharpSchedulingWizard.TryToImproveSchedule(plan.Items); } foreach (var betterPlan in wizard) { Debug.Assert(StudyPlannerModel.isLegalPlan(plan.Items)); uiFactory.StartNew(() => { // present each progressively improved study plan as they are discovered plan.Clear(); plan.AddRange(betterPlan); }, cancelWizard.Token); } } }, cancelWizard.Token)); }
public async Task GetPage(string query, int pageNumber) { if (string.IsNullOrEmpty(query)) { RemainingPages.OnNext(0); _moviesInternalList.Clear(); _searchActive = false; return; } if (query == _query && pageNumber == _pageNumber) { return; } // Cancel search if (_searchActive) { _cts.Cancel(); _cts = new CancellationTokenSource(); } try { _searchActive = true; var result = await _dataService.GetItemsAsync(query, pageNumber, _cts.Token); if (_query != query) { _moviesInternalList.Clear(); } _query = query; _pageNumber = pageNumber; if (result.Response) { _moviesInternalList.Edit(list => list.AddRange(result.Movies)); RemainingPages.OnNext(result.RemainingPages); } else { RemainingPages.OnNext(0); } } catch (OperationCanceledException) { Debug.WriteLine("Cancelled previous search"); _searchActive = false; await GetPage(query, pageNumber); } catch (Exception e) { RemainingPages.OnNext(0); Debug.WriteLine("Something unexpected happened while fetching data"); } finally { _searchActive = false; } }
public SearchViewModel() { SearchService = new DatabaseService(); // SearchResults = new ReactiveList<string>(); SearchResults = new SourceList <string>(); ResultsListBindable = new ObservableCollectionExtended <string>(); this.SearchResults.Connect().Bind(this.ResultsListBindable).Subscribe(); SearchQuery = "audio"; //User update var canClick = this.WhenAnyValue(x => x.SearchQuery, query => !string.IsNullOrWhiteSpace(query)); ClickCommand = ReactiveCommand.CreateFromObservable(this.ActionAsync, canClick);// Set the command source and its conditions //Auto update this.WhenAnyValue(x => x.SearchQuery) .Do(x => { if (string.IsNullOrEmpty(x)) { //clean list when text from searchbar is deleted SearchResults.Clear(); IsSearching = false; } }) .Where(x => !string.IsNullOrEmpty(x)) .Throttle(TimeSpan.FromMilliseconds(800), RxApp.MainThreadScheduler) .Subscribe(async searchTerm => { SearchResults.Clear(); if (!string.IsNullOrEmpty(searchTerm)) { IsSearching = true; Debug.WriteLine($"Searching for: {searchTerm}"); var results = await SearchService.FetchArtists(searchTerm); if (results?.Item1 == SearchQuery) { //there is no method in sqlite pcl to fetch strings so I have to loop here List <string> resultsString = new List <string>(); for (int i = 0; i < results.Item2.Count; i++) { resultsString.Add(results.Item2[i].Name); } SearchResults.AddRange(resultsString); IsSearching = false; } } IsSearching = false; }); }
public async Task OpenFile(string inputPath) { try { Status = "loading photos..."; _applicationStatusManager.ChangeCurrentAppStatus(Enums.Status.Working, ""); using (var pb = new Models.ProgressBar()) { var count = 0; var id = 0; var photoLoader = new PhotoLoader(); var files = GetFilesFromDir(inputPath, false); var enumerable = files as string[] ?? files.ToArray(); _photos.Clear(); foreach (var path in enumerable) { try { await using (var stream = File.OpenRead(path)) { if (Path.GetExtension(path).ToLower() != ".jpg" && Path.GetExtension(path).ToLower() != ".jpeg" && Path.GetExtension(path).ToLower() != ".png") { count++; continue; } var annotation = new Annotation { Filename = Path.GetFileName(path), Folder = Path.GetDirectoryName(path) }; var photo = await photoLoader.Load(path, stream, PhotoLoadType.Miniature); _photos.Add(new PhotoViewModel(id, photo, annotation)); id++; count++; InputProgress = (double)count / enumerable.Count() * 100; InputTextProgress = $"{Convert.ToInt32(InputProgress)} %"; _applicationStatusManager.ChangeCurrentAppStatus(Enums.Status.Working, $"Working | {(int)((double) count / enumerable.Count() * 100)} %, [{count} of {enumerable.Count()}]"); pb.Report((double)count / enumerable.Count(), $"Processed {count} of {enumerable.Count()}"); } } catch (Exception e) { Log.Warning(e, $"image from {path} is skipped!"); } } } _selectedIndex = 0; _applicationStatusManager.ChangeCurrentAppStatus(Enums.Status.Ready, ""); InputTextProgress = $"loads {_photos.Count} photos."; Log.Information($"Loads {_photos.Count} photos."); } catch (Exception ex) { Status = "error."; Log.Error(ex, "Unable to load photos."); } }
public void MergeManyShouldWork() { var a = new SourceList <int>(); var b = new SourceList <int>(); var c = new SourceList <int>(); var parent = new SourceList <SourceList <int> >(); parent.Add(a); parent.Add(b); parent.Add(c); var d = parent.Connect().MergeMany(e => e.Connect().RemoveIndex()).AsObservableList(); 0.Should().Be(d.Count); a.Add(1); 1.Should().Be(d.Count); a.Add(2); 2.Should().Be(d.Count); b.Add(3); 3.Should().Be(d.Count); b.Add(5); 4.Should().Be(d.Count); new[] { 1, 2, 3, 5 }.Should().BeEquivalentTo(d.Items); b.Clear(); // Fails below 2.Should().Be(d.Count); new[] { 1, 2 }.Should().BeEquivalentTo(d.Items); }
void PredicateTypeDropDownList_SelectedIndexChanged(object sender, EventArgs e) { DestinationCheckBoxList.Items.Clear(); SourceCheckBoxList.Items.Clear(); if (DestinationList != null) { DestinationList.Clear(); } if (SourceList != null) { SourceList.Clear(); } SourceListSizeDropDown.Items.Clear(); SourceListSizeDropDown.Visible = false; SourceListSizeLabel.Visible = false; //Set DataTextField for Source and Destination list box. if (_predicateDropDownList.SelectedItem.Text.Equals(_predicateTags)) { ObjectDataTextField = _predicateDataTextField; } else { ObjectDataTextField = _resourceObjectTypeDataTextField; } RefreshObjectTypeDropDown(); }
public void InitializeSession() { _acceleration.Clear(); _acceleration.Add(new Acceleration(0, 0, 0, 0)); _batteryLevel.Clear(); _batteryLevel.Add(new BatteryLevel(0, 0)); _bvp.Clear(); _bvp.Add(new Bvp(0, 0)); _gsr.Clear(); _gsr.Add(new Gsr(0, 0)); _hr.Clear(); _hr.Add(new Hr(0, 0, 0)); _ibi.Clear(); _ibi.Add(new Ibi(0, 0)); _tag.Clear(); _tag.Add(new Tag(0)); _temperature.Clear(); _temperature.Add(new Temperature(0, 0)); }
public HomeViewModel(ICacheService cacheService = null) { _cacheService = cacheService ?? Locator.Current.GetService <ICacheService>(); _repositoriesData = new SourceList <LocalRepository>(); ItemTreshold = -1; ConfigureAddCommand(); ConfigureLoadCommand(); var filter = this.WhenAnyValue(x => x.Search) .Throttle(TimeSpan.FromMilliseconds(500)) .Select(BuildFilter); _repositoriesData.Connect() .Filter(filter) .Sort(SortExpressionComparer <LocalRepository> .Descending(x => x.StarsCount)) .ObserveOn(RxApp.MainThreadScheduler) .Bind(out _repositories) .DisposeMany().Subscribe(); this.WhenAnyValue(x => x.Selected) .Where(x => x != null) .Do(x => _cacheService.SetCurrentRepository(x)) .Subscribe(); Observable.FromEventPattern( x => _cacheService.LanguageChanged += x, x => _cacheService.LanguageChanged -= x) .Do(x => _repositoriesData.Clear()) .Select(x => Unit.Default) .InvokeCommand(LoadCache); }
public void ScaleOut(int Regions) { var worldScale = SourceList[0].CopyToWorld(Regions); SourceList.Clear(); SourceList.Add(worldScale); }
public void InspectCollectionWithObservable() { var initialItems = Enumerable.Range(1, 10) .Select(i => new SimpleObjectWithObservable(i)) .ToArray(); //result should only be true when all items are set to true using (var sourceList = new SourceList <SimpleObjectWithObservable>()) using (var sut = new InspectCollectionWithObservable(sourceList)) { sourceList.AddRange(initialItems); sut.AllActive.Should().Be(false); //should remain false because initialItems[0].SetIsActive(true); sut.AllActive.Should().Be(false); //set all items to true foreach (var item in initialItems) { item.SetIsActive(true); } sut.AllActive.Should().Be(true); initialItems[0].SetIsActive(false); sut.AllActive.Should().Be(false); sourceList.Clear(); sut.AllActive.Should().Be(false); } }
public void Clear() { var people = _generator.Take(100).ToList(); _source.AddRange(people); _source.Clear(); Assert.AreEqual(0, _collection.Count, "Should be 100 items in the collection"); }
public void Clear() { var people = Generator.Take(100).ToList(); _source.AddRange(people); _source.Clear(); _collection.Count.Should().Be(0, "Should be 100 items in the collection"); }
void OnClearClicked(object sender, EventArgs e) { // verify that PropertyChanged interface works Data.PropertyChanged += (sn, ev) => { Console.WriteLine("Data changed"); }; List.Clear(); }
public DashboardViewModelCore(DustService dustService = null, ExcelGenerator excelGenerator = null, IScreen screen = null) { _excelGenerator = excelGenerator ?? Locator.Current.GetService <ExcelGenerator>(); _dustService = dustService ?? Locator.Current.GetService <DustService>(); HostScreen = screen ?? Locator.Current.GetService <IScreen>(); var canLoadDataCommand = this.WhenAnyValue(p => p.SelectedStation) .Select(p => p != null); LoadDataCommand = ReactiveCommand.CreateFromObservable <Station, Record[]>(station => { //Info = new DashboardInfo(); _values.Clear(); IObservable <Record[]> s = _dustService.GetAvailableParametersAsync(station) .Select(@params => @params.Select(p => p.Param).ToArray()) .Select(@params => _dustService.GetStationRecordsAsync(station.Code, @params)).Switch(); return(Observable.Start(() => s, RxApp.TaskpoolScheduler).Switch().TakeUntil(CancelCommand));; }, canLoadDataCommand); CancelCommand = ReactiveCommand.Create( () => { }, this.LoadDataCommand.IsExecuting); this.WhenActivated(cleanup => { var share = _values.Connect().Publish().RefCount(); share.ToCollection().Select(records => { return(Enum.GetValues(typeof(RecordType)).Cast <RecordType>() .Select(type => records.LastOrDefault(r => r.Type == type))); }).BindTo(this, vm => vm.LastRecords).DisposeWith(cleanup); share.Bind(StationData).Subscribe().DisposeWith(cleanup); LoadDataCommand.ThrownExceptions.Subscribe(ShowError).DisposeWith(cleanup); LoadDataCommand.Subscribe(records => { _values.Edit(e => e.AddRange(records)); }).DisposeWith(cleanup); var canSaveToExcelCommand = StationData.ObserveCollectionChanges().Select(_ => StationData.Count > 0); SaveToExcelCommand = ReactiveCommand.CreateFromTask <IEnumerable <Record> >(data => _excelGenerator.CreateExcel(SelectedStation.Code, data), canSaveToExcelCommand); SaveToExcelCommand.ThrownExceptions.Subscribe(ShowError); this.WhenAnyValue(p => p.SelectedStation).Where(p => p != null).Do(_ => CancelCommand.Execute().Subscribe()).InvokeCommand(LoadDataCommand).DisposeWith(cleanup);; }); }
private async Task OnReloadClicked(SourceList <Neuron> list) { try { list.Clear(); var neurons = await this.neuronQueryService.GetNeurons(this.avatarUrl); list.AddRange(neurons); this.StatusMessage = "Reload successful."; } catch (Exception ex) { this.StatusMessage = ex.Message; } }
public async Task UpdateAsync() { try { var historyBuilder = new TransactionHistoryBuilder(_wallet); var txRecordList = await Task.Run(historyBuilder.BuildHistorySummary); _transactionSourceList.Clear(); var trs = txRecordList.Select(transactionSummary => new HistoryItemViewModel(transactionSummary, _bitcoinStore)); _transactionSourceList.AddRange(trs.Reverse()); } catch (Exception ex) { Logger.LogError(ex); } }
public void InitializeSession() { _ocs.Clear(); _ocs.Add(new AnalysisData(0, 0)); _nnMean.Clear(); _nnMean.Add(new AnalysisData(0, 0)); _sdNn.Clear(); _sdNn.Add(new AnalysisData(0, 0)); _meanEda.Clear(); _meanEda.Add(new AnalysisData(0, 0)); _peakEda.Clear(); _peakEda.Add(new AnalysisData(0, 0)); }
public void UpdateLabels() { var labels = WalletHelpers.GetLabels(); var mostUsedLabels = labels.GroupBy(x => x) .Select(x => new { Label = x.Key, Count = x.Count() }) .OrderByDescending(x => x.Count) .ToList(); _sourceLabels.Clear(); _sourceLabels.AddRange( mostUsedLabels.Select(x => new SuggestionLabelViewModel(x.Label, x.Count))); }
private async Task GetMarketHistory() { IsBusy = true; SourceList.Clear(); MarketHistories.Clear(); try { SourceList.AddRange(await RestRepository.GetMarketHistory(CoinSymbol)); MarketHistories.AddRange(LoadMarketHistory(0)); } catch (Exception e) { Crashes.TrackError(e); await PageDialogService.DisplayAlertAsync("Error", e.Message, "OK"); } finally { IsBusy = false; } }
private void RefreshTaskList() { cachedService.Tasks .Connect() .Transform(task => new DesktopTask { Id = task.Id, Name = task.Name, GroupName = ParseGroupName(task.Name), Schedule = cachedService.Schedules.Items .FirstOrDefault(sched => sched.Id == task.ScheduleId)?.Name, Operations = string.Join("=>", cachedService.Operations .Items.Where(oper => oper.TaskId == task.Id) .Select(oper => new { oper.Number, oper.Name }) .OrderBy(pair => pair.Number) .Select(pair => pair.Name) .ToList()) }) .Bind(out var temp) .Subscribe(); cachedService.Tasks.Connect() .Subscribe(_ => { SelectedTask = null; selectedTaskInstances.Clear(); operInstances.Clear(); }); selectedTaskInstances.Connect() .Bind(out var tempti) .Subscribe(); SelectedTaskInstances = tempti; OperInstances = operInstances.SpawnCollection(); Tasks = temp; }
public void XamarinFormsGrouping() { var items = new[] { new Animal("Holly", "Cat", AnimalFamily.Mammal), new Animal("Rover", "Dog", AnimalFamily.Mammal), new Animal("Rex", "Dog", AnimalFamily.Mammal), new Animal("Whiskers", "Cat", AnimalFamily.Mammal), new Animal("Nemo", "Fish", AnimalFamily.Fish), new Animal("Moby Dick", "Whale", AnimalFamily.Mammal), new Animal("Fred", "Frog", AnimalFamily.Amphibian), new Animal("Isaac", "Next", AnimalFamily.Amphibian), new Animal("Sam", "Snake", AnimalFamily.Reptile), new Animal("Sharon", "Red Backed Shrike", AnimalFamily.Bird), }; var schedulerProvider = new TestSchedulerProvider(); using (var sourceList = new SourceList <Animal>()) using (var sut = new XamarinFormsGrouping(sourceList, schedulerProvider)) { //populate with initial data sourceList.AddRange(items); schedulerProvider.TestScheduler.Start(); sut.FamilyGroups.Count.Should().Be(5); sut.FamilyGroups.Single(group => group.Family == AnimalFamily.Mammal).Count.Should().Be(5); sut.FamilyGroups.Single(group => group.Family == AnimalFamily.Fish).Count.Should().Be(1); //apply a filter sut.Filter = a => a.Type == "Dog" || a.Type == "Fish"; schedulerProvider.TestScheduler.Start(); sut.FamilyGroups.Count.Should().Be(2); sut.FamilyGroups.Single(group => group.Family == AnimalFamily.Mammal).Count.Should().Be(2); sut.FamilyGroups.Single(group => group.Family == AnimalFamily.Fish).Count.Should().Be(1); //clear list and all groupings are gone sourceList.Clear(); schedulerProvider.TestScheduler.Start(); sut.FamilyGroups.Count.Should().Be(0); } }
public IDisposable Switch(bool useGroup) { SourceList.Clear(); return(Choose() .Subscribe(a => { SourceList.EditDiff(a); })); IObservable <IEnumerable <object> > Choose() { return(useGroup == false ? ungrouped .Connect() .ToCollection() : grouped .Connect() .ToCollection()); } }
public void LoadMarketData(DateTime start, DateTime end, Func <IDataSource> ds, IInstrument instrument) { if (ds == null || ds() == null) { MessageBox.Show("please select valid data source"); return; } var dl = ds().GetDataList(new List <IInstrument> { instrument }, start, end, MarketDataGrade.FiveMinutes); SourceList.Clear(); dl.ForEach(v => SourceList.Add(v)); var ml = MarketData.SummaryMarketDataList(dl, CurrentPeriod); MarketDataList.Clear(); ml.ForEach(v => MarketDataList.Add(v)); OnPropertyChanged("IsLoaded"); }
private Task LoadItemListAsync() { var random = new Random(); itemSourceList.Clear(); List <SourceItem> tmp = new List <SourceItem>(); for (int i = 0; i < 100; i++) { tmp.Add(new SourceItem { Name = $"Name {GetLastChars(i)}", SurName = $"Surname {GetLastChars(i)}", Birthdate = new DateTime(random.Next(1950, 2020), random.Next(1, 12), random.Next(1, 28)) }); } itemSourceList.AddRange(tmp); return(Task.CompletedTask); }
private async Task GetMarketDataOrders() { IsBusy = true; try { var marketOrders = await RestRepository.GetMarketOrdersData(Coin.Symbol); SourceList.Clear(); BuyOrders.Clear(); SourceList.AddRange(marketOrders.BuyOrders); BuyOrders.AddRange(LoadBuyOrders(0)); } catch (Exception e) { Crashes.TrackError(e); await PageDialogService.DisplayAlertAsync("Error", e.Message, "OK"); } finally { IsBusy = false; } }
void OnItemsSourceSetted() { SourceList.Clear(); if (_itemsSource == null) { return; } if (Element.IsGroupingEnabled) { var index = 0; foreach (var group in _itemsSource) { _headerIndexes[index] = true; var headerIndex = index; SourceList.Add(group); index++; var groupList = group as IEnumerable; foreach (var item in groupList) { SourceList.Add(item); index++; } } } else { foreach (var item in _itemsSource) { SourceList.Add(item); } } if (Element != null) { InitHeights(); } }
public IObservable <IChangeSet <T> > Run() { return(Observable.Create <IChangeSet <T> >(observer => { var locker = new object(); var destination = new SourceList <T>(); var populator = Observable.Switch(_sources .Do(_ => { lock (locker) destination.Clear(); })) .Synchronize(locker) .PopulateInto(destination); var publisher = destination.Connect().SubscribeSafe(observer); return new CompositeDisposable(destination, populator, publisher); })); }
private async Task GetRecordListAsync(long roomId) { try { IsLiveRecordBusy = true; RoomId = 0; ShortRoomId = 0; RecordCount = 0; _liveRecordSourceList.Clear(); var roomInitMessage = await _apiClient.GetRoomInitAsync(roomId); if (roomInitMessage?.data is not null && roomInitMessage.code == 0 && roomInitMessage.data.room_id > 0) { RoomId = roomInitMessage.data.room_id; ShortRoomId = roomInitMessage.data.short_id; RecordCount = long.MaxValue; var currentPage = 0; while (currentPage < Math.Ceiling((double)RecordCount / PageSize)) { var listMessage = await _apiClient.GetLiveRecordListAsync(roomInitMessage.data.room_id, ++currentPage, PageSize); if (listMessage?.data is not null && listMessage.data.count > 0) { RecordCount = listMessage.data.count; var list = listMessage.data?.list; if (list is not null) { _liveRecordSourceList.AddRange(list); } } else { _logger.LogWarning(@"[{0}]加载列表出错,可能该直播间无直播回放", roomId); RecordCount = 0; break; } }
private void ResetSearchControls() { //File search Patren, ex: *.md;build.gradel txtBoxFilePatren.Width = txtBoxGitUrl.Width - 2; lstBoxRepos.Width = txtBoxGitUrl.Width - 2; panelCtrl.Width = txtBoxGitUrl.Width - 2; txtBoxFilePatren.Text = ""; txtBoxFilePatren.PlaceHolderText = "File search Patren, ex: *.md;build.gradel"; IList SourceList; BindingSource bindingSource = (BindingSource)lstBoxRepos.DataSource; if (bindingSource != null) { SourceList = (IList)bindingSource.List; SourceList.Clear(); } SourceList = new List <string> { "-- Select Repository --" }; lstBoxRepos.DataSource = SourceList; }
public async Task UpdateAsync() { try { var historyBuilder = new TransactionHistoryBuilder(_wallet); var txRecordList = await Task.Run(historyBuilder.BuildHistorySummary); _transactionSourceList.Clear(); Money balance = Money.Zero; for (var i = 0; i < txRecordList.Count; i++) { var transactionSummary = txRecordList[i]; balance += transactionSummary.Amount; _transactionSourceList.Add(new HistoryItemViewModel(i, transactionSummary, _bitcoinStore, balance)); } } catch (Exception ex) { Logger.LogError(ex); } }
public void MergeManyShouldWork() { var a = new SourceList<int>(); var b = new SourceList<int>(); var c = new SourceList<int>(); var parent = new SourceList<SourceList<int>>(); parent.Add(a); parent.Add(b); parent.Add(c); var d = parent.Connect() .MergeMany(e => e.Connect().RemoveIndex()) .AsObservableList(); Assert.AreEqual(d.Count,0); a.Add(1); Assert.AreEqual(d.Count, 1); a.Add(2); Assert.AreEqual(d.Count, 2); b.Add(3); Assert.AreEqual(d.Count, 3); b.Add(5); Assert.AreEqual(d.Count, 4); CollectionAssert.AreEquivalent(d.Items, new[] { 1, 2, 3, 5 }); b.Clear(); // Fails below Assert.AreEqual(d.Count,2); CollectionAssert.AreEquivalent(d.Items, new[] { 1, 2}); }