/// <summary> /// This is a method thar runs on the initialization of the class /// to load all objects using the service class /// </summary> /// <returns></returns> protected override async Task LoadAll() { try { if (AllObjects?.Count > 0) { AllObjects.Clear(); } if (FilteredCollection?.Count > 0) { FilteredCollection.Clear(); } await RunMethodAsync(() => { var allObjects = service.GetAll() ?? new List <T>(); AllObjects = FilteredCollection = new ObservableCollection <T>(allObjects); }, () => IsBusy); } catch (Exception e) { toaster.ShowErrorToast(Toaster.ErrorTitle, e.Message); } }
private void FilterItems() { IEnumerable source = ItemsSource; if (source == null) { FilteredItems.Clear(); return; } IEnumerator enumerator = source.GetEnumerator(); if (!enumerator.MoveNext()) { FilteredItems.Clear(); return; } FilterPredicate predicate = Predicate; FilteredCollection filtered = new FilteredCollection(); do { object item = enumerator.Current; if (predicate == null || predicate.Matches(item)) { filtered.Add(item); } }while (enumerator.MoveNext()); FilteredItems = filtered; }
public async Task Load() { var gList = await ExGalleryList.DownloadGalleryListAsync(0, $"https://exhentai.org/?f_search={ WebUtility.UrlEncode(Key)}&{SearchConfig.ToString()}"); var gList2 = new FilteredCollection <ExGallery, ExGalleryList>(gList, this.GalleryFilter); SearchGalleryList = gList2; // Add the search record to DB if user defined keywords if (!String.IsNullOrWhiteSpace(Key)) { try { using (var db = new AppDbContext()) { db.ExSearchRecords.Add(ExSearchRecord.Create(Key)); db.SaveChanges(); } } catch (Exception ex) { await new MessageDialog(ex.Message, "Fail to save search record").ShowAsync(); } } }
public void FilterCollection() { if (FilterValue == null || FilterValue.Equals(default(TInner))) { FilteredCollection.Clear(); return; } foreach (var item in UnfilteredCollection) { if (PassFilterDelegate(item, FilterValue)) { if (!FilteredCollection.Contains(item)) { FilteredCollection.Add(item); } } else { if (FilteredCollection.Contains(item)) { FilteredCollection.Remove(item); } } } }
private void UpdateBindedCollection() { if (ShowCategory == CategoryEnum.All) { if (Device.RuntimePlatform == Device.Android) { FilteredCollection.Clear(); } else { FilteredCollection = new ObservableCollection <JokeItem>(); } foreach (var item in JokeList) { FilteredCollection.Add(item); } } else { if (Device.RuntimePlatform == Device.Android) { FilteredCollection.Clear(); } else { FilteredCollection = new ObservableCollection <JokeItem>(); } foreach (var item in JokeList.Where(joke => joke.Category == ShowCategory)) { FilteredCollection.Add(item); } } }
/// <summary> /// Provides derived classes an opportunity to handle changes to the SourceCollection property. /// </summary> protected virtual void OnSourceCollectionChanged(IList oldSourceCollection, IList newSourceCollection) { //Debug.WriteLine("CollectionFilterControl: OnSourceCollectionChanged"); // watch the collection if it support INotifyCollectionChanged if (oldSourceCollection != null) { var cc = oldSourceCollection as INotifyCollectionChanged; if (cc != null) { cc.CollectionChanged -= cc_CollectionChanged; } } if (newSourceCollection != null) { var cc = newSourceCollection as INotifyCollectionChanged; if (cc != null) { cc.CollectionChanged += cc_CollectionChanged; } } FilteredCollection.Clear(); // Drop all the results RunFilter(); // Rerun the filter }
public static void UpdateCollection(string search) { ObservableCollection <Service> hold = new ObservableCollection <Service>(); hold = ServiceCollection; if (!string.IsNullOrEmpty(search)) { ServiceCollection.Clear(); IEnumerable <Service> serviceQuery = Services.Where(x => (x.Service_Name.ToLower()).Contains(search)); foreach (Service service in serviceQuery) { FilteredCollection.Add(service); } ServiceCollection = FilteredCollection; CollectionViewSource.GetDefaultView(ServiceCollection).Refresh(); } else { ServiceCollection = hold; FilteredCollection = ServiceCollection; CollectionViewSource.GetDefaultView(ServiceCollection).Refresh(); } //ServiceCollection = Services; /* * Pet petToUpdate = PetCollection.FirstOrDefault(x => x.Name == pet.Name); * petToUpdate.Stock = petToUpdate.Stock - purchasedAmount; * CollectionViewSource.GetDefaultView(PetCollection).Refresh();*/ }
public EncumbranceSubsystem(EntityManager em) { entities = em.Get(typeof(Creature)); containers = em.Get <ItemContainerComponent>(); equipments = em.Get <EquipmentComponent>(); containers.OnEntityAdd += containers_OnEntityAdd; }
private static async Task <Post> GetPostAtAsync(FilteredCollection <Post, Posts> posts, int postPointer) { while ((postPointer >= posts.Count) && (posts.HasMoreItems)) { await posts.LoadMoreItemsAsync(1); } return(posts[postPointer]); }
public void LoadFilterSet() { if (!IsExpanded) { return; } var EnumerableObjects = from object p in CompleteCollection select p; FilteredCollection.ClearAndAddRange(EnumerableObjects.Where(t => t.ToString().ContainsInvariant(FilterText)).Take(MaxResults)); }
/// <summary> /// Provides derived classes an opportunity to handle changes to the FieldName property. /// </summary> protected virtual void OnFieldNameChanged(StringList oldFieldName, StringList newFieldName) { var field = string.Empty; if (newFieldName != null && newFieldName.Count > 0) { field = newFieldName[0]; } FilteredCollection.ChangeSort(new SorterName()); }
public MapPanel(World world, AssetsManager assetsManager, PanelTemplate template) : base(template) { ViewOffset = new Point(0, 0); _assets = assetsManager; World = world; _entities = world.EntityManager.Get(typeof(GameObject), typeof(Sprite), typeof(VisibleComponent)); _player = world.Player; }
/// <summary> /// method for filterCommand /// </summary> public void FilterExecute() { FilteredCollection.Clear(); switch (SelectedFilterItem) { case "System.Windows.Controls.ComboBoxItem: Titel": foreach (ViewComic viewComic in _comicList) { if (viewComic.Title.Trim().Contains(FilterQuery.Trim())) { FilteredCollection.Add(new GridRow(viewComic)); } } break; case "System.Windows.Controls.ComboBoxItem: Reeks": foreach (ViewComic viewComic in _comicList) { if (viewComic.Series.Name.Trim().Contains(FilterQuery.Trim())) { FilteredCollection.Add(new GridRow(viewComic)); } } break; case "System.Windows.Controls.ComboBoxItem: Auteur": foreach (ViewComic viewComic in _comicList) { foreach (ViewAuthor author in viewComic.Authors) { if (author.Name.Trim().Contains(FilterQuery.Trim())) { FilteredCollection.Add(new GridRow(viewComic)); } } } break; case "System.Windows.Controls.ComboBoxItem: Uitgeverij": foreach (ViewComic viewComic in _comicList) { if (viewComic.Publisher.Name.Trim().Contains(FilterQuery.Trim())) { FilteredCollection.Add(new GridRow(viewComic)); } } break; default: break; } }
public void FilterVeggies() { filter.FilterVeggies(); if (FilteredCollection != null) { FilteredCollection.Clear(); } foreach (var item in filter.productCatalogFilters) { FilteredCollection.Add(item); } }
public ImagesViewModel(FilteredCollection <Post, Posts> posts) { _posts = posts; foreach (var post in _posts) { var image = new ImageViewModel(); image.Post = post; Images.Add(image); } _posts.CollectionChanged += _posts_CollectionChanged; }
public NotificationsTabViewModel(IChatState chatState) : base(chatState) { Container.RegisterType<object, NotificationsTabView>(NotificationsTabView); notificationManager = new FilteredCollection<NotificationModel, IViewableObject>( ChatModel.Notifications, MeetsFilter, true); notificationManager.Collection.CollectionChanged += (sender, args) => { OnPropertyChanged("HasNoNotifications"); OnPropertyChanged("NeedsAttention"); }; }
public NotificationsTabViewModel(IChatState chatState) : base(chatState) { Container.RegisterType <object, NotificationsTabView>(NotificationsTabView); notificationManager = new FilteredCollection <NotificationModel, IViewableObject>( ChatModel.Notifications, MeetsFilter, true); notificationManager.Collection.CollectionChanged += (sender, args) => { OnPropertyChanged("HasNoNotifications"); OnPropertyChanged("NeedsAttention"); }; }
protected override void DoFilter() { base.DoFilter(); if (!string.IsNullOrEmpty(CategoryFilter) || FilterByMarketCategory) { FilteredCollection = new ObservableCollection <DomainObjectViewModel <Item> >( FilteredCollection.Where(p => (string.IsNullOrEmpty(CategoryFilter) || (!string.IsNullOrEmpty(p.DomainObject.Category) && p.DomainObject.Category.ToLower().Contains(CategoryFilter.ToLower()))) && (!FilterByMarketCategory || p.DomainObject.MarketCategory == MarketCategoryFilter)) .OrderBy(p => p.DomainObject.Name)); } }
private void RepopulateFilteredCollection() { List <BoardGameDataItem> filtered = new List <BoardGameDataItem>(); foreach (BoardGameDataItem ci in Collection) { bool ShowMe = true; if (CurrentPlayerFilter != null) { ShowMe = CurrentPlayerFilter.Matches(ci); } if (ShowMe && CurrentPlayTimeFilter != null) { ShowMe = CurrentPlayTimeFilter.Matches(ci); } if (ShowMe && CurrentStatusFilter != null) { ShowMe = CurrentStatusFilter.Matches(ci); } if (ShowMe && CurrentExpansionFilter != null) { ShowMe = CurrentExpansionFilter.Matches(ci); } if (ShowMe && CurrentTextFilter != null) { ShowMe = CurrentTextFilter.Matches(ci); } if (ShowMe) { filtered.Add(ci); } } IOrderedEnumerable <BoardGameDataItem> sortedList = CurrentCollectionSorter.Sort(filtered); FilteredCollection.Clear(); foreach (BoardGameDataItem item in sortedList) { FilteredCollection.Add(item); } RaisePropertyChanged("NumberItemsDisplayed"); }
public NotificationsTabViewModel( IChatModel cm, IUnityContainer contain, IRegionManager regman, IEventAggregator eventagg, ICharacterManager manager) : base(contain, regman, eventagg, cm, manager) { Container.RegisterType<object, NotificationsTabView>(NotificationsTabView); notificationManager = new FilteredCollection<NotificationModel, IViewableObject>( ChatModel.Notifications, MeetsFilter, true); notificationManager.Collection.CollectionChanged += (sender, args) => { OnPropertyChanged("HasNoNotifications"); OnPropertyChanged("NeedsAttention"); }; }
public static async Task SetTileAsync(FilteredCollection <Post, Posts> posts) { List <string> faces = new List <string>(); int postPointer = 0; // Remove all old face file first try { var imageFolder = await ApplicationData.Current.LocalFolder.CreateFolderAsync(TILE_FOLDER_NAME, CreationCollisionOption.ReplaceExisting); } catch (Exception ex) { } // Download up to 20 faces while (faces.Count < 20 && ((posts.Count - 1 > postPointer) || (posts.HasMoreItems))) { if ((posts.Count - 1 < postPointer) && (posts.HasMoreItems)) { // Need to download more posts data await posts.LoadMoreItemsAsync(1); } else { // No need to download more posts data, read next post directly Post post = await GetPostAtAsync(posts, postPointer); var previewBuffer = await(new Windows.Web.Http.HttpClient()).GetBufferAsync(new Uri(post.PreviewUrl)); var rects = (await DetechFromBufferAsync(previewBuffer, 5, 55)).Faces; await SaveFacesForTileAsync(rects, previewBuffer, post.Id); foreach (var rect in rects) { faces.Add($"{post.Id}-{rects.IndexOf(rect)}.jpg"); } postPointer++; } } // Update the rile notification if (true) { UpdateTile(faces); } }
public IEnumerable <IEmergingPattern> Mine(InstanceModel model, IEnumerable <Instance> instances, Feature classFeature) { EmergingPatternCreator EpCreator = new EmergingPatternCreator(); EmergingPatternComparer epComparer = new EmergingPatternComparer(new ItemComparer()); IEmergingPatternSimplifier simplifier = new EmergingPatternSimplifier(new ItemComparer()); FilteredCollection <IEmergingPattern> minimal = new FilteredCollection <IEmergingPattern>(epComparer.Compare, FilterRelation); if (MinePatternsWhileBuildingTree) { DecisionTreeBuilder.OnSplitEvaluation = delegate(IDecisionTreeNode node, ISplitIterator iterator, List <SelectorContext> currentContext) { IChildSelector currentSelector = null; for (int i = 0; i < iterator.CurrentDistribution.Length; i++) { double[] distribution = iterator.CurrentDistribution[i]; if (EPTester.Test(distribution, model, classFeature)) { if (currentSelector == null) { currentSelector = iterator.CreateCurrentChildSelector(); } EmergingPattern ep = EpCreator.ExtractPattern(currentContext, model, classFeature, currentSelector, i); ep.Counts = (double[])distribution.Clone(); minimal.Add(simplifier.Simplify(ep)); } } }; DoMine(model, instances, classFeature, EpCreator, null); } else { DoMine(model, instances, classFeature, EpCreator, p => { if (EPTester.Test(p.Counts, model, classFeature)) { minimal.Add(simplifier.Simplify(p)); } } ); } return(minimal.GetItems()); }
public async Task SearchAsync(string keyword) { // Validate the keyword // Dont search if there is more than 6 tags if (keyword.Split(' ').Where(o => !String.IsNullOrWhiteSpace(o)).Count() > 6) { var resourceLoader = ResourceLoader.GetForCurrentView(); await new MessageDialog(resourceLoader.GetString("/BooruHomePage/MessageDialogTooManyTags/Content"), resourceLoader.GetString("/BooruHomePage/MessageDialogTooManyTags/Title")).ShowAsync(); return; } // Dont search if there is any rating metatag if (keyword.Split(' ').FirstOrDefault(o => o.Contains("rating:")) != default(String)) { // Unlock the rating filter if (!YandeSettings.Current.IsRatingFilterUnlocked) { YandeSettings.Current.IsRatingFilterUnlocked = true; } var resourceLoader = ResourceLoader.GetForCurrentView(); await new MessageDialog(resourceLoader.GetString("/BooruHomePage/MessageDialogRatingTag/Content"), resourceLoader.GetString("/BooruHomePage/MessageDialogRatingTag/Title")).ShowAsync(); return; } // Updated the search results Posts posts; try { posts = await Posts.DownloadPostsAsync(1, $"{YandeClient.HOST}/post.xml?tags={WebUtility.UrlEncode(keyword)}"); } catch (Exception ex) { posts = new Posts(); } SearchPosts = new FilteredCollection <Post, Posts>(posts, SearchPostFilter); }
public static async Task RunAsync() { var yandeSettings = YandeSettings.Current; var key = yandeSettings.TileUpdateTaskSearchKey; var filter = yandeSettings.TilePostFilter; try { var cost = BackgroundWorkCost.CurrentBackgroundWorkCost; var posts = await Posts.DownloadPostsAsync(1, $"{YandeClient.HOST}/post.xml?tags={ WebUtility.UrlEncode(key) }"); var filteredPosts = new FilteredCollection <Post, Posts>(posts, filter); await AnimePersonalization.SetTileAsync(filteredPosts); } catch (Exception ex) { ToastService.ToastDebug("Cannot Update Tile", ex.StackTrace); ToastService.ToastDebug("Cannot Update Tile", ex.Message); } }
public DescriptiveResponse <FilteredCollection <TRead> > FilterCollection(Filtration filter) { try { // Add userId in case of entity of type managed entity if (typeof(TRead).IsSubclassOf(typeof(ManagedEntity <TId, TUId>))) { if (filter == null) { filter = new Filtration(); } if (filter.SearchCriteria == null) { filter.SearchCriteria = new List <FilterSearchCriteria>(); } filter.SearchCriteria.Add(new FilterSearchCriteria { Field = "CreatedBy", Operator = LogicalOperator.Equal, SearchKey = UserUtility <TUId> .CurrentUser.UserId.ToString() }); } // Find all items that match filteration FilteredCollection <TRead> filteredCollection = _readRepository.Find(filter); // Return success response return(DescriptiveResponse <FilteredCollection <TRead> > .Success(filteredCollection)); } catch (Exception ex) { // Log error Logger.Log(ex); // return unexpected error return(DescriptiveResponse <FilteredCollection <TRead> > .Error(ErrorStatus.UNEXPECTED_ERROR)); } }
private async void RunFilter() { _delay?.Cancel(); _delay = new CancellationTokenSource(); try { await Task.Delay(500, _delay.Token); } catch (TaskCanceledException) { // request was canceled, return; return; } var currentText = _searchBox?.Text ?? string.Empty; var sourceCollection = SourceCollection.Cast <FileContainer>().ToList(); if (string.IsNullOrWhiteSpace(currentText)) { // When nothing is being filtered, we dont need to filter any thing. FilteredCollection.Clear(); FilteredCollection.AddRange(sourceCollection, true); } else { // Remove any items in the filtered collection that are no longer available in the primary collection var oldItems = (from x in FilteredCollection where !sourceCollection.Contains(x) select x).ToList(); oldItems.ForEach(x => FilteredCollection.Remove(x)); // look at existing filtered items and remove those that do not match the filter oldItems = (from x in FilteredCollection where !DoesContainString(x, currentText) select x).ToList(); oldItems.ForEach(x => FilteredCollection.Remove(x)); // Look at the source colleciton and find out what needs to be in the filtered collection var newItems = (from x in sourceCollection where DoesContainString(x, currentText) && !FilteredCollection.Contains(x) select x).ToList(); FilteredCollection.AddRange(newItems, true); } }
public static async Task RunAsync() { var yandeSettings = YandeSettings.Current; var appSettings = AppSettings.Current; var key = yandeSettings.WallpaperUpdateTaskSearchKey; var shuffle = yandeSettings.WallpaperUpdateTaskShuffleCount; var filter = yandeSettings.WallpaperPostFilter; var old = yandeSettings.WallpaperUpdateTaskCurrentImageFileUri; yandeSettings.WallpaperUpdateTaskCurrentImageID = ""; try { // Search for posts var posts = await Posts.DownloadPostsAsync(1, $"https://yande.re/post.xml?tags={ WebUtility.UrlEncode(key) }"); var filteredPosts = new FilteredCollection <Post, Posts>(posts, filter); // Unset the previous wallpaper, so that the image file is no longer in use yandeSettings.WallpaperUpdateTaskCurrentImageID = ""; // Set wallpaper var result = await AnimePersonalization.SetBackgroundImageAsync(filteredPosts, shuffle, yandeSettings.WallpaperUpdateTaskCropMethod, appSettings.ScreenSize, false, yandeSettings.WallpaperUpdateTaskQuality); // Notice the app that the wallpapaer was changed yandeSettings.WallpaperUpdateTaskCurrentImageID = result; // Motice user about the change // TODO: need opt out settings //BigImageToast(result, yandeSettings.WallpaperUpdateTaskCurrentImageFileUri, yandeSettings.AvatarUri); } catch (Exception ex) { yandeSettings.WallpaperUpdateTaskCurrentImageID = old; ToastService.ToastDebug("Cannot Update Wallpaper", ex.StackTrace); ToastService.ToastDebug("Cannot Update Wallpaper", ex.Message); } }
protected override void Dispose(bool isManaged) { if (isManaged) { checkTick.Dispose(); cooldownTimer.Dispose(); noteCooldownTimer.Dispose(); noteCooldownUpdateTick.Dispose(); checkTick = null; cooldownTimer = null; noteCooldownTimer = null; noteCooldownUpdateTick = null; StatusChanged = null; Events.GetEvent <NewUpdateEvent>().Unsubscribe(OnNewUpdateEvent); messageManager.Dispose(); messageManager = null; } base.Dispose(isManaged); }
public Level(Size size, World world, string fill, IEnumerable <Terrain> terrainDefinitions) : base(size) { Uid = new UniqueId(); Map = new string[Size.Width, Size.Height]; TerrainDefinitions = new Dictionary <string, Terrain>(); foreach (var terrain in terrainDefinitions) { TerrainDefinitions.Add(terrain.Definition, terrain); } this.World = world; _entities = world.EntityManager.Get <GameObject>(); _blockers = world.EntityManager.Get(typeof(GameObject), typeof(Scenery)); Cells = new Cell[size.Width, size.Height]; for (int x = 0; x < Map.GetLength(0); x++) { for (int y = 0; y < Map.GetLength(1); y++) { Map[x, y] = fill; Cells[x, y].Walkable = true; Cells[x, y].Transparent = true; } } foreach (var entity in _entities) { InitializeBlocker(entity); } _blockers.OnEntityAdd += InitializeBlocker; _blockers.OnEntityRemove += OnRemoveBlocker; }
public PmChannelViewModel(string name, IChatState chatState, IManageNotes notes, IGetProfiles profile) : base(chatState) { try { model = Container.Resolve<PmChannelModel>(name); Model = model; noteService = notes; notes.GetNotesAsync(name); profileService = profile; profile.GetProfileDataAsync(name); Model.PropertyChanged += OnModelPropertyChanged; Container.RegisterType<object, PmChannelView>( StringExtensions.EscapeSpaces(Model.Id), new InjectionConstructor(this)); Events.GetEvent<NewUpdateEvent>() .Subscribe(OnNewUpdateEvent, ThreadOption.PublisherThread, true, UpdateIsOurCharacter); cooldownTimer.Elapsed += (s, e) => { isInCoolDown = false; cooldownTimer.Enabled = false; OnPropertyChanged("CanPost"); }; noteCooldownTimer.Elapsed += (s, e) => { isInNoteCoolDown = false; noteCooldownTimer.Enabled = false; noteCooldownUpdateTick.Enabled = false; OnPropertyChanged("CanPost"); OnPropertyChanged("CanShowNoteTimeLeft"); }; if (AllKinks == null) AllKinks = new ListCollectionView(new ProfileKink[0]); noteCooldownUpdateTick.Elapsed += (s, e) => OnPropertyChanged("NoteTimeLeft"); checkTick.Elapsed += (s, e) => { if (!IsTyping) checkTick.Enabled = false; if (!string.IsNullOrEmpty(Message) && typingLengthCache == Message.Length) { IsTyping = false; SendTypingNotification(TypingStatus.Paused); checkTick.Enabled = false; } if (IsTyping) typingLengthCache = Message?.Length ?? 0; }; Model.Settings = SettingsService.GetChannelSettings( ChatModel.CurrentCharacter.Name, Model.Title, Model.Id, Model.Type); ChannelSettings.Updated += (s, e) => { OnPropertyChanged("ChannelSettings"); if (!ChannelSettings.IsChangingSettings) { SettingsService.UpdateSettingsFile( ChannelSettings, ChatModel.CurrentCharacter.Name, Model.Title, Model.Id); } }; messageManager = new FilteredCollection<IMessage, IViewableObject>( Model.Messages, message => true); ChatModel.PropertyChanged += (sender, args) => { if (args.PropertyName == "CurrentCharacterData") UpdateProfileProperties(); }; isCharacterStatusExpanded = false; if (!string.IsNullOrWhiteSpace(ChannelSettings.LastMessage)) return; Message = ChannelSettings.LastMessage; ChannelSettings.LastMessage = null; LoggingSection = "pm channel vm"; } catch (Exception ex) { ex.Source = "PM Channel ViewModel, init"; Exceptions.HandleException(ex); } }
protected override void Dispose(bool isManaged) { if (isManaged) { checkTick.Dispose(); cooldownTimer.Dispose(); checkTick = null; cooldownTimer = null; StatusChanged = null; Events.GetEvent<NewUpdateEvent>().Unsubscribe(OnNewUpdateEvent); messageManager.Dispose(); messageManager = null; } base.Dispose(isManaged); }
/// <summary> /// This method controls the compression of the image. Starting at the /// upper left of the image, it compresses 8x8 blocks of data until the /// entire image has been compressed. /// </summary> /// <param name="out"></param> private void WriteCompressedData() { // This initial setting of MinBlockWidth and MinBlockHeight is done to // ensure they start with values larger than will actually be the case. int MinBlockWidth = this.imageWidth % 8 != 0 ? (int)(Math.Floor(this.imageWidth / 8.0) + 1) * 8 : this.imageWidth; int MinBlockHeight = this.imageHeight % 8 != 0 ? (int)(Math.Floor(this.imageHeight / 8.0) + 1) * 8 : this.imageHeight; int comp, shuffledIndex; for (comp = 0; comp < JpegInfo.NumberOfComponents; comp++) { MinBlockWidth = Math.Min(MinBlockWidth, this.JpegObj.BlockWidth[comp]); MinBlockHeight = Math.Min(MinBlockHeight, this.JpegObj.BlockHeight[comp]); } int[] lastDCvalue = new int[JpegInfo.NumberOfComponents]; int[] emptyArray = new int[64]; int[] coeff = GetCoeff(MinBlockWidth, MinBlockHeight); int coeffCount = coeff.Length; int i, j, r, c; int _changed = 0; int _embedded = 0; int _examined = 0; int _expected = 0; int _one = 0; int _large = 0; int _thrown = 0; int _zero = 0; logger.Info("got " + coeffCount + " DCT AC/DC coefficients"); for (i = 0; i < coeffCount; i++) { if (i % 64 == 0) { continue; } else if (coeff[i] == 1 || coeff[i] == -1) { _one++; } else if (coeff[i] == 0) { _zero++; } } _large = coeffCount - _zero - _one - coeffCount / 64; _expected = _large + (int)(0.49 * _one); // logger.Info("one=" + _one); logger.Info("large=" + _large); // logger.Info("expected capacity: " + _expected + " bits"); logger.Info("expected capacity with"); for (i = 1; i < 8; i++) { int usable, changed, n; n = (1 << i) - 1; usable = _expected * i / n - _expected * i / n % n; changed = coeffCount - _zero - coeffCount / 64; changed = changed * i / n - changed * i / n % n; changed = n * changed / (n + 1) / i; // changed = _large - _large % (n + 1); changed = (changed + _one + _one / 2 - _one / (n + 1)) / (n + 1); usable /= 8; if (usable == 0) { break; } if (i == 1) { logger.Info("default"); } else { logger.Info("(1, " + n + ", " + i + ")"); } logger.Info(" code: " + usable + " bytes (efficiency: " + usable * 8 / changed + "." + usable * 80 / changed % 10 + " bits per change)"); } // westfeld if (this.embeddedData != null) { // Now we embed the secret data in the permutated sequence. logger.Info("Permutation starts"); F5Random random = new F5Random(Encoding.ASCII.GetBytes(this.password)); Permutation permutation = new Permutation(coeffCount, random); int nextBitToEmbed = 0; int byteToEmbed = Convert.ToInt32(this.embeddedData.Length); int availableBitsToEmbed = 0; // We start with the length information. Well, // the length information it is more than one // byte, so this first "byte" is 32 bits long. /*try { * byteToEmbed = this.embeddedData.available(); * } catch (final Exception e) { * e.printStackTrace(); * }*/ logger.Info("Embedding of " + (byteToEmbed * 8 + 32) + " bits (" + byteToEmbed + "+4 bytes) "); // We use the most significant byte for the 1 of n // code, and reserve one extra bit for future use. if (byteToEmbed > 0x007fffff) { byteToEmbed = 0x007fffff; } // We calculate n now for (i = 1; i < 8; i++) { int usable; this.n = (1 << i) - 1; usable = _expected * i / this.n - _expected * i / this.n % this.n; usable /= 8; if (usable == 0) { break; } if (usable < byteToEmbed + 4) { break; } } int k = i - 1; this.n = (1 << k) - 1; switch (this.n) { case 0: logger.Info("using default code, file will not fit"); this.n++; break; case 1: logger.Info("using default code"); break; default: logger.Info("using (1, " + this.n + ", " + k + ") code"); break; } byteToEmbed |= k << 24; // store k in the status word // Since shuffling cannot hide the distribution, the // distribution of all bits to embed is unified by // adding a pseudo random bit-string. We continue the random // we used for Permutation, initially seeked with password. byteToEmbed ^= random.GetNextByte(); byteToEmbed ^= random.GetNextByte() << 8; byteToEmbed ^= random.GetNextByte() << 16; byteToEmbed ^= random.GetNextByte() << 24; nextBitToEmbed = byteToEmbed & 1; byteToEmbed >>= 1; availableBitsToEmbed = 31; _embedded++; for (i = 0; i < permutation.Length; i++) { int shuffled_index = permutation.GetShuffled(i); if (shuffled_index % 64 == 0 || coeff[shuffled_index] == 0) { continue; } var cc = coeff[shuffled_index]; _examined += 1; if (cc > 0 && (cc & 1) != nextBitToEmbed) { coeff[shuffled_index]--; _changed++; } else if (cc < 0 && (cc & 1) == nextBitToEmbed) { coeff[shuffled_index]++; _changed++; } if (coeff[shuffled_index] != 0) { if (availableBitsToEmbed == 0) { if (n > 1 || embeddedData.Available == 1) { break; } byteToEmbed = embeddedData.Read(); byteToEmbed ^= random.GetNextByte(); availableBitsToEmbed = 8; } nextBitToEmbed = byteToEmbed & 1; byteToEmbed >>= 1; availableBitsToEmbed--; _embedded++; } else { _thrown++; } } if (n > 1) { bool isLastByte = false; FilteredCollection filtered_index = permutation.Filter(coeff, i + 1); while (!isLastByte) { int kBitsToEmbed = 0; for (i = 0; i < k; i++) { if (availableBitsToEmbed == 0) { if (embeddedData.Available == 0) { isLastByte = true; break; } byteToEmbed = embeddedData.Read(); byteToEmbed ^= random.GetNextByte(); availableBitsToEmbed = 8; } nextBitToEmbed = byteToEmbed & 1; byteToEmbed >>= 1; availableBitsToEmbed--; kBitsToEmbed |= nextBitToEmbed << i; _embedded++; } List <int> codeWord = filtered_index.Offer(this.n); int extractedBit; while (true) { int vhash = 0; int count = codeWord.Count; for (i = 0; i < count; i++) { int index = codeWord[i]; extractedBit = coeff[index] > 0 ? coeff[index] & 1 : (1 - (coeff[index] & 1)); if (extractedBit == 1) { vhash ^= i + 1; } } i = vhash ^ kBitsToEmbed; if (i == 0) { break; } i--; if (coeff[codeWord[i]] < 0) { coeff[codeWord[i]]++; } else { coeff[codeWord[i]]--; } _changed++; if (coeff[codeWord[i]] == 0) { _thrown++; codeWord.RemoveAt(i); codeWord.Add(filtered_index.Offer()); } } } } } logger.Info("Starting Huffman Encoding."); shuffledIndex = 0; for (r = 0; r < MinBlockHeight; r++) { for (c = 0; c < MinBlockWidth; c++) { for (comp = 0; comp < JpegInfo.NumberOfComponents; comp++) { for (i = 0; i < JpegObj.VsampFactor[comp]; i++) { for (j = 0; j < JpegObj.HsampFactor[comp]; j++) { Array.Copy(coeff, shuffledIndex, emptyArray, 0, 64); this.huffman.HuffmanBlockEncoder(this.output, emptyArray, lastDCvalue[comp], this.JpegObj.DCtableNumber[comp], this.JpegObj.ACtableNumber[comp]); lastDCvalue[comp] = emptyArray[0]; shuffledIndex += 64; } } } } } this.huffman.FlushBuffer(this.output); }
/// <summary> /// Map FilteredCollection of DTOEntity to FilteredCollection of DBEntity /// </summary> /// <param name="entityCollection"></param> /// <returns></returns> internal virtual FilteredCollection <DBEntity> ToDBObject(FilteredCollection <DTOEntity> entityCollection) { return(Mapper.Map <FilteredCollection <DTOEntity>, FilteredCollection <DBEntity> >(entityCollection)); }
public PmChannelViewModel(string name, IChatState chatState, IManageNotes notes, IGetProfiles profile) : base(chatState) { try { model = Container.Resolve <PmChannelModel>(name); Model = model; noteService = notes; notes.GetNotesAsync(name); profileService = profile; profile.GetProfileDataAsync(name); Model.PropertyChanged += OnModelPropertyChanged; Container.RegisterType <object, PmChannelView>( StringExtensions.EscapeSpaces(Model.Id), new InjectionConstructor(this)); Events.GetEvent <NewUpdateEvent>() .Subscribe(OnNewUpdateEvent, ThreadOption.PublisherThread, true, UpdateIsOurCharacter); cooldownTimer.Elapsed += (s, e) => { isInCoolDown = false; cooldownTimer.Enabled = false; OnPropertyChanged("CanPost"); }; noteCooldownTimer.Elapsed += (s, e) => { isInNoteCoolDown = false; noteCooldownTimer.Enabled = false; noteCooldownUpdateTick.Enabled = false; OnPropertyChanged("CanPost"); OnPropertyChanged("CanShowNoteTimeLeft"); }; if (AllKinks == null) { AllKinks = new ListCollectionView(new ProfileKink[0]); } noteCooldownUpdateTick.Elapsed += (s, e) => OnPropertyChanged("NoteTimeLeft"); checkTick.Elapsed += (s, e) => { if (!IsTyping) { checkTick.Enabled = false; } if (!string.IsNullOrEmpty(Message) && typingLengthCache == Message.Length) { IsTyping = false; SendTypingNotification(TypingStatus.Paused); checkTick.Enabled = false; } if (IsTyping) { typingLengthCache = Message?.Length ?? 0; } }; Model.Settings = SettingsService.GetChannelSettings( ChatModel.CurrentCharacter.Name, Model.Title, Model.Id, Model.Type); ChannelSettings.Updated += (s, e) => { OnPropertyChanged("ChannelSettings"); if (!ChannelSettings.IsChangingSettings) { SettingsService.UpdateSettingsFile( ChannelSettings, ChatModel.CurrentCharacter.Name, Model.Title, Model.Id); } }; messageManager = new FilteredCollection <IMessage, IViewableObject>( Model.Messages, message => true); ChatModel.PropertyChanged += (sender, args) => { if (args.PropertyName == "CurrentCharacterData") { UpdateProfileProperties(); } }; isCharacterStatusExpanded = false; if (!string.IsNullOrWhiteSpace(ChannelSettings.LastMessage)) { return; } Message = ChannelSettings.LastMessage; ChannelSettings.LastMessage = null; LoggingSection = "pm channel vm"; } catch (Exception ex) { ex.Source = "PM Channel ViewModel, init"; Exceptions.HandleException(ex); } }
public PmChannelViewModel( string name, IUnityContainer contain, IRegionManager regman, IEventAggregator events, IChatModel cm, ICharacterManager manager) : base(contain, regman, events, cm, manager) { try { var temp = Container.Resolve<PmChannelModel>(name); Model = temp; Model.PropertyChanged += OnModelPropertyChanged; Container.RegisterType<object, PmChannelView>( HelperConverter.EscapeSpaces(Model.Id), new InjectionConstructor(this)); Events.GetEvent<NewUpdateEvent>() .Subscribe(OnNewUpdateEvent, ThreadOption.PublisherThread, true, UpdateIsOurCharacter); cooldownTimer.Elapsed += (s, e) => { isInCoolDown = false; cooldownTimer.Enabled = false; OnPropertyChanged("CanPost"); }; checkTick.Elapsed += (s, e) => { if (!IsTyping) checkTick.Enabled = false; if (!string.IsNullOrEmpty(Message) && typingLengthCache == Message.Length) { IsTyping = false; SendTypingNotification(TypingStatus.Paused); checkTick.Enabled = false; } if (IsTyping) typingLengthCache = Message != null ? Message.Length : 0; }; Model.Settings = SettingsService.GetChannelSettings( cm.CurrentCharacter.Name, Model.Title, Model.Id, Model.Type); ChannelSettings.Updated += (s, e) => { OnPropertyChanged("ChannelSettings"); if (!ChannelSettings.IsChangingSettings) { SettingsService.UpdateSettingsFile( ChannelSettings, cm.CurrentCharacter.Name, Model.Title, Model.Id); } }; messageManager = new FilteredCollection<IMessage, IViewableObject>( Model.Messages, message => true); } catch (Exception ex) { ex.Source = "Utility Channel ViewModel, init"; Exceptions.HandleException(ex); } }