コード例 #1
0
        public void FilterManager_FilterOnTag_Whitespace()
        {
            List <IPackage> packages = new List <IPackage>()
            {
                new IPackageMock("0")
                {
                    Tags = " Dummy1 Dummy2 "
                },
                new IPackageMock("1")
                {
                    Tags = ""
                },
                new IPackageMock("2")
                {
                    Tags = null
                },
                new IPackageMock("3")
                {
                    Tags = " Dummy2 Dummy3 "
                }
            };

            List <IPackage> expected = new List <IPackage>()
            {
                packages[0]
            };

            // we remove any whitespace around the search tag -- this enforces 'exact match' semantics
            List <IPackage> filtered = FilterManager.FilterOnTag(packages.AsQueryable(), " Dummy1 ").ToList();

            Assert.Equal(expected, filtered);
        }
コード例 #2
0
        private async void Edit_Click(object sender, RoutedEventArgs e)
        {
            if (FilterListBox.SelectedItem == null)
            {
                return;                                     // No selection.
            }
            try
            {
                Filter filter = FilterManager.Load(FilterListBox.SelectedItem as string);

                var window = new ItemFilterEditWindow(filter)
                {
                    Owner = this
                };
                if (window.ShowDialog() == true)
                {
                    try
                    {
                        FilterManager.Save(filter);
                        FilterManager.Enable(filter);
                    } catch (Exception ex)
                    {
                        await this.ShowErrorAsync("An error occurred while attempting to save item filter.", ex.Message);
                    }
                }
            }
            catch (Exception ex)
            {
                await this.ShowErrorAsync("An error occurred while attempting to load item filter.", ex.Message);
            }
        }
コード例 #3
0
        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            var b = new Bitmap(@"c:\share\1425539750793.png");

            using (MemoryStream memory = new MemoryStream())
            {
                //var bitmap = FilterManager.CopyAsGrayscale(b);
                //var bitmap = FilterManager.CopyWithTransparency(b);
                //var bitmap = FilterManager.CopyAsSepiaTone(b);
                //var bitmap = FilterManager.Cartoon(b);
                //var bitmap = FilterManager.FuzzyEdgeBlurFilter(b);
                //var bitmap = FilterManager.MedianFilter(b, 5);
                //var bitmap = FilterManager.AdjustBrightness(b, 50);
                var bitmap = FilterManager.GaussianBlur(b);

                bitmap.Save(memory, ImageFormat.Png);
                memory.Position = 0;
                BitmapImage bitmapImage = new BitmapImage();
                bitmapImage.BeginInit();
                bitmapImage.StreamSource = memory;
                bitmapImage.CacheOption  = BitmapCacheOption.OnLoad;
                bitmapImage.EndInit();
                xImage.Source = bitmapImage;
            }
        }
コード例 #4
0
ファイル: frmDynamicHelp.cs プロジェクト: daxnet/guluwin
 public frmDynamicHelp(frmMain _parent)
     : base(_parent)
 {
     InitializeComponent();
     guluManager__ = new GuluManager();
     filterManager__ = new FilterManager();
 }
コード例 #5
0
        private void FillRepository()
        {
            var filter = FilterManager.ReverseFilter(DiscoverRepository.CurrentRepository.Files);

            fileFilter.SetFilter(filter);
            fileFilter_OnSearch(new FileFilterParameters(filter));
        }
コード例 #6
0
        public async void Get_Test()
        {
            IDirectory iDirectory = Substitute.For <IDirectory>();

            iDirectory.GetFilesAsync("*.*", SearchOption.AllDirectories).Returns(new List <string>
            {
                @"f\bla\ra\t.dat",
                @"books\csharp\csharp.pdf",
                @"proj\tools\utils.cpp"
            });

            int    expected1 = 3;
            string expected2 = @"tad.t\ar\alb\f";
            string expected3 = @"fdp.prahsc\prahsc\skoob";
            string expected4 = @"ppc.slitu\sloot\jorp";

            IFileFilter filter = new FilterManager("reversed2");

            string[] actual = await filter.GetFilteredFiles(iDirectory);

            Assert.Equal(expected1, actual.Length);
            Assert.Equal(expected2, actual[0]);
            Assert.Equal(expected3, actual[1]);
            Assert.Equal(expected4, actual[2]);
        }
コード例 #7
0
ファイル: VoicesManager.cs プロジェクト: pema4/MultimodSynth
        /// <summary>
        /// Генерация новых выходных данных.
        /// </summary>
        /// <returns>Выходной сигнал.</returns>
        public float Process()
        {
            // Вызовы этих методов обновляют значение параметров, которые подвержены сглаживанию.
            OscAManager.Process();
            OscBManager.Process();
            FilterManager.Process();
            OscAVolumeEnvelopeManager.Process();
            OscBVolumeEnvelopeManager.Process();
            FilterCutoffEnvelopeManager.Process();

            float sum = 0;

            for (int i = 0; i < activeVoices.Count;)
            {
                var voice = activeVoices[i];
                sum += voice.Process();
                if (!voice.IsActive)
                {
                    // StopVoice помечает голос как свободный
                    // и удаляет его из массива activeVoices.
                    // При этом инкрементировать значение i не нужно, потому что
                    // все элементы activeVoices сдвигаются влево
                    StopVoice(voice);
                }
                else
                {
                    i += 1;
                }
            }
            return(sum);
        }
コード例 #8
0
ファイル: BanManager.cs プロジェクト: neecdefender/SyncPlugin
 public BanManager(string save_path, FilterManager manager)
 {
     Info          = LoadBanInfo(save_path);
     FilterManager = manager;
     ClientFilter  = new BanClientFilter(this);
     ServerFliter  = new BanServerFilter(this);
 }
コード例 #9
0
        public PacketskHandler()
        {
            this.m_DirectionFilterManager = new FilterManager<Direction>();

            this.m_IpStorage = new IpStorage();

            IPEndPoint[] ipep = Listener.EndPoints;

            m_Listeners = new Listener[ipep.Length];

            bool success = false;

            do
            {
                for (int i = 0; i < ipep.Length; i++)
                {
                    Listener l = new Listener(ipep[i],this);
                    if (!success && l != null)
                        success = true;
                    m_Listeners[i] = l;
                }
                if (!success)
                {
                    Console.WriteLine("Retrying...");
                    Thread.Sleep(10000);
                }
            } while (!success);

            m_Peek = new byte[4];
        }
コード例 #10
0
ファイル: ViewRepository.cs プロジェクト: Zero-Xiong/frapid
        public long CountFiltered(string filterName)
        {
            if (string.IsNullOrWhiteSpace(this.Database))
            {
                return(0);
            }

            if (!this.SkipValidation)
            {
                if (!this.Validated)
                {
                    this.Validate(AccessTypeEnum.Read, this.LoginId, this.Database, false);
                }
                if (!this.HasAccess)
                {
                    Log.Information(
                        $"Access to count entity \"{this.FullyQualifiedObjectName}\" was denied to the user with Login ID {this.LoginId}. Filter: {filterName}.");
                    throw new UnauthorizedException("Access is denied.");
                }
            }

            var filters = this.GetFilters(this.Database, filterName);
            var sql     = Sql.Builder.Append($"SELECT COUNT(*) FROM {this.FullyQualifiedObjectName} WHERE 1 = 1");

            FilterManager.AddFilters(ref sql, filters);

            return(Factory.Scalar <long>(this.Database, sql));
        }
コード例 #11
0
        //end profast code

        /// <summary>
        /// Builds the filter expression and raises the FilterExpressionBuilding event
        /// </summary>
        /// <param name="sender">The event source.</param>
        /// <param name="e">The <see cref="System.ComponentModel.CancelEventArgs"/> instance containing the event data.</param>
        /// <remarks>
        /// Override <b>OnFilterExpressionBuilding</b> to provide a filter expression construction
        /// logic and to set the values of the <see cref="DgvBaseColumnFilter.FilterExpression"/> and <see cref="DgvBaseColumnFilter.FilterCaption"/> properties.
        /// The <see cref="DgvFilterManager"/> will use these properties in constructing the whole filter expression and to change the header text of the filtered column.
        /// Otherwise, you can create an event handler and set the <i>Cancel</i> property of event argument to true, to skip standard filter expression building logic.
        /// </remarks>
        protected override void OnFilterExpressionBuilding(object sender, CancelEventArgs e)
        {
            base.OnFilterExpressionBuilding(sender, e);
            if (e.Cancel)
            {
                FilterManager.RebuildFilter();
                return;
            }

            string ResultFilterExpression = "";
            string ResultFilterCaption    = OriginalDataGridViewColumnHeaderText;

            // Managing the NULL and NOT NULL cases which are type-independent
            if (comboBoxOperator.Text == "= Ø")
            {
                ResultFilterExpression = GetNullCondition(this.DataGridViewColumn.DataPropertyName);
            }
            if (comboBoxOperator.Text == "<> Ø")
            {
                ResultFilterExpression = GetNotNullCondition(this.DataGridViewColumn.DataPropertyName);
            }

            if (ResultFilterExpression != "")
            {
                FilterExpression = ResultFilterExpression;
                FilterCaption    = ResultFilterCaption + "\n " + comboBoxOperator.Text;
                FilterManager.RebuildFilter();
                return;
            }

            //Fix 7/14 by ProFast: catch case where user inputs a value in the text area instead of making a combobox selection
            //object FilterValue = comboBoxValue.SelectedValue;
            object FilterValue = comboBoxValue.Text;
            //EndFix 7/14
            string FormattedValue = "";

            if (ColumnDataType == typeof(string))
            {
                // Managing the string-column case
                string EscapedFilterValue = StringEscape(FilterValue.ToString());
                ResultFilterExpression = this.DataGridViewColumn.DataPropertyName + " " + comboBoxOperator.Text + "'" + EscapedFilterValue + "'";
                ResultFilterCaption   += "\n" + comboBoxOperator.Text + " " + comboBoxValue.Text;
            }
            else
            {
                // Managing the other cases
                FormattedValue = FormatValue(FilterValue, this.ColumnDataType);
                if (FormattedValue != "")
                {
                    ResultFilterExpression = this.DataGridViewColumn.DataPropertyName + " " + comboBoxOperator.Text + FormattedValue;
                    ResultFilterCaption   += "\n" + comboBoxOperator.Text + " " + comboBoxValue.Text;
                }
            }
            if (ResultFilterExpression != "")
            {
                FilterExpression = ResultFilterExpression;
                FilterCaption    = ResultFilterCaption;
                FilterManager.RebuildFilter();
            }
        }
コード例 #12
0
        public async Task <IEnumerable <dynamic> > GetWhereAsync(long pageNumber, List <Filter> filters)
        {
            if (string.IsNullOrWhiteSpace(this.Database))
            {
                return(null);
            }

            if (!this.SkipValidation)
            {
                if (!this.Validated)
                {
                    await this.ValidateAsync(AccessTypeEnum.Read, this.LoginId, this.Database, false).ConfigureAwait(false);
                }
                if (!this.HasAccess)
                {
                    Log.Information("Access to Page #{Page} of the filtered entity \"Filter\" was denied to the user with Login ID {LoginId}. Filters: {Filters}.", pageNumber, this.LoginId, filters);
                    throw new UnauthorizedException("Access is denied.");
                }
            }

            long offset = (pageNumber - 1) * 50;
            var  sql    = new Sql("SELECT * FROM config.filters WHERE 1 = 1");

            FilterManager.AddFilters(ref sql, new Filter(), filters);

            sql.OrderBy("filter_id");

            if (pageNumber > 0)
            {
                sql.Append(FrapidDbServer.AddOffset(this.Database, "@0"), offset);
                sql.Append(FrapidDbServer.AddLimit(this.Database, "@0"), 50);
            }

            return(await Factory.GetAsync <dynamic>(this.Database, sql).ConfigureAwait(false));
        }
コード例 #13
0
        public async Task <IEnumerable <dynamic> > GetWhereAsync(long pageNumber, List <Filter> filters)
        {
            if (string.IsNullOrWhiteSpace(this.Database))
            {
                return(null);
            }

            if (!this.SkipValidation)
            {
                if (!this.Validated)
                {
                    await this.ValidateAsync(AccessTypeEnum.Read, this.LoginId, this.Database, false).ConfigureAwait(false);
                }
                if (!this.HasAccess)
                {
                    Log.Information($"Access to Page #{pageNumber} of the filtered entity \"{this.FullyQualifiedObjectName}\" was denied to the user with Login ID {this.LoginId}. Filters: {filters}.");
                    throw new UnauthorizedException(Resources.AccessIsDenied);
                }
            }

            long offset = (pageNumber - 1) * Config.GetPageSize(this.Database);
            var  sql    = new Sql($"SELECT * FROM {this.FullyQualifiedObjectName} WHERE 1 = 1");

            FilterManager.AddFilters(ref sql, filters);

            sql.OrderBy("1");

            if (pageNumber > 0)
            {
                sql.Append(FrapidDbServer.AddOffset(this.Database, "@0"), offset);
                sql.Append(FrapidDbServer.AddLimit(this.Database, "@0"), Config.GetPageSize(this.Database));
            }

            return(await Factory.GetAsync <dynamic>(this.Database, sql).ConfigureAwait(false));
        }
コード例 #14
0
        public async Task <long> CountFilteredAsync(string filterName)
        {
            if (string.IsNullOrWhiteSpace(this.Database))
            {
                return(0);
            }

            if (!this.SkipValidation)
            {
                if (!this.Validated)
                {
                    await this.ValidateAsync(AccessTypeEnum.Read, this.LoginId, this.Database, false).ConfigureAwait(false);
                }
                if (!this.HasAccess)
                {
                    Log.Information($"Access to count entity \"{this.FullyQualifiedObjectName}\" was denied to the user with Login ID {this.LoginId}. Filter: {filterName}.");
                    throw new UnauthorizedException(Resources.AccessIsDenied);
                }
            }

            var filters = await this.GetFiltersAsync(this.Database, filterName).ConfigureAwait(false);

            var sql = new Sql($"SELECT COUNT(*) FROM {this.FullyQualifiedObjectName} WHERE 1 = 1");

            FilterManager.AddFilters(ref sql, filters.ToList());

            return(await Factory.ScalarAsync <long>(this.Database, sql).ConfigureAwait(false));
        }
コード例 #15
0
        /// <summary>
        /// Builds the filter expression and raises the FilterExpressionBuilding event
        /// </summary>
        /// <param name="sender">The event source.</param>
        /// <param name="e">The <see cref="System.ComponentModel.CancelEventArgs"/> instance containing the event data.</param>
        /// <remarks>
        /// Override <b>OnFilterExpressionBuilding</b> to provide a filter expression construction
        /// logic and to set the values of the <see cref="DgvBaseColumnFilter.FilterExpression"/> and <see cref="DgvBaseColumnFilter.FilterCaption"/> properties.
        /// The <see cref="DgvFilterManager"/> will use these properties in constructing the whole filter expression and to change the header text of the filtered column.
        /// Otherwise, you can create an event handler and set the <i>Cancel</i> property of event argument to true, to skip standard filter expression building logic.
        /// </remarks>
        protected override void OnFilterExpressionBuilding(object sender, CancelEventArgs e)
        {
            base.OnFilterExpressionBuilding(sender, e);
            if (e.Cancel)
            {
                FilterManager.RebuildFilter();
                return;
            }

            DateTime MinDate, MaxDate;

            if (comboBoxMonth.SelectedIndex == 0)
            {
                MinDate       = new DateTime(mYearMin + comboBoxYear.SelectedIndex, 1, 1, 0, 0, 0);
                MaxDate       = MinDate.AddYears(1);
                FilterCaption = OriginalDataGridViewColumnHeaderText + "\n = " + comboBoxYear.Text;
            }
            else
            {
                MinDate       = new DateTime(mYearMin + comboBoxYear.SelectedIndex, comboBoxMonth.SelectedIndex, 1, 0, 0, 0);
                MaxDate       = MinDate.AddMonths(1);
                FilterCaption = OriginalDataGridViewColumnHeaderText + "\n = " + comboBoxMonth.Text + " " + comboBoxYear.Text;
            }

            FilterExpression = DataGridViewColumn.DataPropertyName + " >= " + FormatValue(MinDate, ColumnDataType) + " AND " + DataGridViewColumn.DataPropertyName + " < " + FormatValue(MaxDate, ColumnDataType);
            FilterManager.RebuildFilter();
            return;
        }
コード例 #16
0
        public IResponseFilter GetResourceResponseFilter(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response)
        {
            if (saveAllRespnseForDebug)
            {//save all file to
                var filter = FilterManager.CreateFilter(request.Identifier.ToString());
                return(filter);
            }

            //   Console.WriteLine(" GetResourceResponseFilter ");
            //var url = new Uri(request.Url);
            //if (url.AbsoluteUri.Contains(PageUrlCharacteristic.QRCODE))
            //{
            //    var filter = FilterManager.CreateFilter(request.Identifier.ToString());

            //    return filter;
            //}

            //if (request.Url.EndsWith(PageUrlCharacteristic.MEMBERINFO_END) && response.StatusCode == 200)
            //{ //用户信息.
            //    var filter = FilterManager.CreateFilter(request.Identifier.ToString());
            //    return filter;
            //}

            return(null);
        }
コード例 #17
0
        public async Task <long> CountWhereAsync(List <Filter> filters)
        {
            if (string.IsNullOrWhiteSpace(this.Database))
            {
                return(0);
            }

            if (!this.SkipValidation)
            {
                if (!this.Validated)
                {
                    await this.ValidateAsync(AccessTypeEnum.Read, this.LoginId, this.Database, false).ConfigureAwait(false);
                }
                if (!this.HasAccess)
                {
                    Log.Information(
                        $"Access to count entity \"{this.FullyQualifiedObjectName}\" was denied to the user with Login ID {this.LoginId}. Filters: {filters}.");
                    throw new UnauthorizedException("Access is denied.");
                }
            }

            var sql = Sql.Builder.Append($"SELECT COUNT(*) FROM {this.FullyQualifiedObjectName} WHERE deleted = @0", false);

            FilterManager.AddFilters(ref sql, filters);

            return(await Factory.ScalarAsync <long>(this.Database, sql).ConfigureAwait(false));
        }
コード例 #18
0
ファイル: frmDynamicHelp.cs プロジェクト: daxnet/guluwin
 public frmDynamicHelp(frmMain _parent)
     : base(_parent)
 {
     InitializeComponent();
     guluManager__   = new GuluManager();
     filterManager__ = new FilterManager();
 }
コード例 #19
0
        public IFilterManager BuildFilterManager()
        {
            var cfg = Get();
            var fm  = new FilterManager(cfg.Filters);

            return(fm);
        }
コード例 #20
0
        Inline CreateUrlLink(TwitterUrl URL)
        {
            MenuItem item = new MenuItem
            {
                Header     = Localization.Resources.MuteDomain,
                Foreground = new SolidColorBrush(Colors.Black)
            };

            item.Click += (sender, e) =>
            {
                Uri uri;
                if (Uri.TryCreate(URL.ExpandedValue, UriKind.Absolute, out uri))
                {
                    var filter = FilterManager.SetupMute(FilterType.Text, uri.Host);
                    Dependency.Resolve <IMessageService>().ShowMessage(String.Format(Localization.Resources.MutedUntil, filter.IsValidUntil.ToString("f")), "");
                }
                else
                {
                    Dependency.Resolve <IMessageService>().ShowError(Localization.Resources.NotValidURL);
                }
            };

            string value = string.IsNullOrWhiteSpace(URL.ExpandedValue) ? URL.Value : URL.ExpandedValue;

            return(CreateBaseLink(TweetTextConverter.TrimUrl(value), Localization.Resources.CopyLink, value, item));
        }
コード例 #21
0
ファイル: CatalogBase.cs プロジェクト: GLDPA/Car-Dealership
        // private Dictionary<string, Filter<TDomainClass>> _filters;

        /// <summary>
        /// Sets up the catalog as a paired collection and source
        /// </summary>
        /// <param name="collection">
        /// In-memory collection of domain objects
        /// </param>
        /// <param name="source"></param>
        /// Source for loading/saving domain objects
        /// <param name="loadWhenCreated"></param>
        public CatalogBase(CollectionBase <TDomainClass> collection,
                           SourceBase <TDomainClass> source,
                           bool loadWhenCreated = false)
        {
            // Sanity checks, so we don't need null checks elsewhere
            if (collection == null)
            {
                throw new ArgumentNullException(nameof(collection));
            }
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }

            _source        = source;
            _collection    = collection;
            _filterManager = new FilterManager <TDomainClass>();

            Modified = true;

            if (loadWhenCreated)
            {
                Load();
            }
        }
コード例 #22
0
        public void With_filters()
        {
            var settings = new RepositorySettings {
                PluginId = PluginType.Debug, Name = "debug"
            };
            var expression = new List <FilterExpressionSettings>()
            {
                new FilterExpressionSettings()
                {
                    Operation = FilterType.Time, Operand = Rand.IntegerAsString, Operator = Rand.ComparisionOperator
                },
                new FilterExpressionSettings()
                {
                    Operation = FilterType.Category, Operand = Rand.Text, Operator = Rand.EnsembleOperator
                },
                new FilterExpressionSettings()
                {
                    Operation = FilterType.Level, Operand = Rand.Text, Operator = Rand.EnsembleOperator
                },
            };

            IPluginManager pm = new PluginManager(new DebugLoader(), _logger);
            IFilterManager fm = new FilterManager();

            var p = pm.Build(settings);
            var f = fm.Build(expression, "and");

            var day  = p.GetDays().ElementAt(0);
            var logs = f.Filter(p.GetLogs(day));

            Assert.NotNull(logs);
        }
コード例 #23
0
        public void Execute()
        {
            var apple = new Product("Apple", Color.Green, Size.Small);
            var tree  = new Product("Tree", Color.Green, Size.Large);
            var house = new Product("House", Color.Blue, Size.Large);

            Product[] products = { apple, tree, house };

            var filtrMngr = new FilterManager <Product>();

            Console.WriteLine("Green products (new):");
            foreach (var p in filtrMngr.Filter(products, new ColorSpecification(Color.Green)))
            {
                Console.WriteLine($" - {p.Name} is green");
            }

            Console.WriteLine("Large products");
            foreach (var p in filtrMngr.Filter(products, new SizeSpecification(Size.Large)))
            {
                Console.WriteLine($" - {p.Name} is large");
            }

            Console.WriteLine("Large blue items");
            foreach (var p in filtrMngr.Filter(products,
                                               new AndSpecification <Product>(
                                                   new ColorSpecification(Color.Blue),
                                                   new SizeSpecification(Size.Large))))
            {
                Console.WriteLine($" - {p.Name} is big and blue");
            }
        }
コード例 #24
0
        public void FilterManager_FilterOnTag_MixedCase()
        {
            List <IPackage> packages = new List <IPackage>()
            {
                new IPackageMock("0")
                {
                    Tags = " Dummy1 Dummy2 "
                },
                new IPackageMock("1")
                {
                    Tags = ""
                },
                new IPackageMock("2")
                {
                    Tags = null
                },
                new IPackageMock("3")
                {
                    Tags = " Dummy2 Dummy3 "
                }
            };

            List <IPackage> expected = new List <IPackage>()
            {
                packages[0]
            };

            // we remove any whitespace around the search tag
            List <IPackage> filtered = FilterManager.FilterOnTag(packages.AsQueryable(), " DumMY1 ").ToList();

            Assert.Equal(expected, filtered);
        }
コード例 #25
0
        private async void Delete_Click(object sender, RoutedEventArgs e)
        {
            string name = FilterListBox.SelectedItem as string;

            if (name == null)
            {
                return;               // No selection.
            }
            if (await this.ShowQuestionAsync("Are you sure you want to delete this item filter?") == MessageBoxResult.No)
            {
                return;
            }

            try
            {
                FilterManager.Delete(name);

                FilterNames.Remove(name);
            }
            catch (Exception ex)
            {
                // Check whether deletion of filter definition failed, or only game filter file.
                if (!FilterManager.Exists(name))
                {
                    FilterNames.Remove(name);
                }

                await this.ShowErrorAsync("An error occurred while attempting to delete item filter.", ex.Message);
            }
        }
コード例 #26
0
        public void FilterManager_FilterOnTag_NonEmpty()
        {
            List <IPackage> packages = new List <IPackage>()
            {
                new IPackageMock("0")
                {
                    Tags = " Dummy1 Dummy2 "
                },
                new IPackageMock("1")
                {
                    Tags = ""
                },
                new IPackageMock("2")
                {
                    Tags = null
                },
                new IPackageMock("3")
                {
                    Tags = " Dummy2 Dummy3"
                }
            };

            List <IPackage> expected = new List <IPackage>()
            {
                packages[0]
            };

            List <IPackage> filtered = FilterManager.FilterOnTag(packages.AsQueryable(), "Dummy1").ToList();

            Assert.Equal(expected, filtered);
        }
コード例 #27
0
        public PacketskHandler()
        {
            this.m_DirectionFilterManager = new FilterManager <Direction>();

            this.m_IpStorage = new IpStorage();

            IPEndPoint[] ipep = Listener.EndPoints;

            m_Listeners = new Listener[ipep.Length];

            bool success = false;

            do
            {
                for (int i = 0; i < ipep.Length; i++)
                {
                    Listener l = new Listener(ipep[i], this);
                    if (!success && l != null)
                    {
                        success = true;
                    }
                    m_Listeners[i] = l;
                }
                if (!success)
                {
                    Console.WriteLine("Retrying...");
                    Thread.Sleep(10000);
                }
            } while (!success);

            m_Peek = new byte[4];
        }
コード例 #28
0
        public async Task <IEnumerable <DisplayField> > GetLookupFieldsAsync(List <Filter> filters)
        {
            if (string.IsNullOrWhiteSpace(this.Database))
            {
                return(new List <DisplayField>());
            }

            if (!this.SkipValidation)
            {
                if (!this.Validated)
                {
                    await this.ValidateAsync(AccessTypeEnum.Read, this.LoginId, this.Database, false).ConfigureAwait(false);
                }
                if (!this.HasAccess)
                {
                    Log.Information($"Access to get display field for entity \"{this.FullyQualifiedObjectName}\" was denied to the user with Login ID {this.LoginId}", this.LoginId);
                    throw new UnauthorizedException(Resources.AccessIsDenied);
                }
            }

            var sql = new Sql($"SELECT {this.LookupField} AS \"key\", {this.NameColumn} as \"value\" FROM {this.FullyQualifiedObjectName} WHERE 1=1");

            FilterManager.AddFilters(ref sql, filters);
            sql.OrderBy("1");

            return(await Factory.GetAsync <DisplayField>(this.Database, sql).ConfigureAwait(false));
        }
コード例 #29
0
        /// <summary>
        /// Filter the specified phaseInput.
        /// </summary>
        /// <returns>The filter.</returns>
        /// <param name="phaseInput">Phase input.</param>
        public IEnumerable <PhaseData <SensorReading> > Filter(PhaseInput <SensorReading> phaseInput)
        {
            var results = new List <PhaseData <SensorReading> >();

            foreach (var input in phaseInput.Input)
            {
                // input = name plus collection of data records
                foreach (var record in input.Data)
                {
                    // each data record is a single sensor reading
                    foreach (var param in phaseInput.Parameters)
                    {
                        // check to see if desired field exists for this reading
                        // if not, proceed to next parameter
                        var filterField = record.GetType().GetProperty(param.Field);
                        if (filterField == null)
                        {
                            continue;
                        }

                        // if it does exist, check to see if value satisfies clause
                        // collection for this parameter ...
                        var filterValue = filterField.GetValue(record, null).ToString();
                        var isMatch     = param.MatchesClause(filterValue);

                        // if we fail to match, start over with next record
                        // (ends parameter for-each)
                        if (!isMatch)
                        {
                            break;
                        }

                        // if valid match AND user chose to split output,
                        // update result names to produce output split
                        string resultName = (param.UseOutputSplit()
                                             ? FilterManager.GetFilterFilename(input.Name, filterValue)
                                             : input.Name);
                        if (!results.Select(x => x.Name).Contains(resultName))
                        {
                            var newResult = new PhaseData <SensorReading>
                            {
                                Name = resultName,
                                Data = new List <SensorReading> {
                                    record
                                }
                            };
                            results.Add(newResult);
                        }
                        else
                        {
                            var existingResult = results.Where(x => x.Name.Equals(resultName)).FirstOrDefault();
                            existingResult.Data.Add(record);
                        }
                    }
                }
            }

            return(results);
        }
コード例 #30
0
        public void Process_CommandIsPendingWithNoFilters_ReturnTrue()
        {
            var command = new TestCommand(CommandState.Pending);

            FilterManager filterManager = new FilterManager();
            var result = filterManager.Process(command);
            Assert.IsTrue(result);
        }
コード例 #31
0
        public void Process_CommandIsNotPending_ReturnFalse()
        {
            var command = new TestCommand(CommandState.New);

            FilterManager filterManager = new FilterManager();
            var result = filterManager.Process(command);
            Assert.IsFalse(result);
        }
コード例 #32
0
        private void AddNewItem_Click(object sender, EventArgs e)
        {
            m_filterManager          = new FilterManager();
            m_filterManager.MyParent = this;
            m_filterManager.ShowDialog();

            FillCustomizedFilters();
        }
コード例 #33
0
        //==========================================

        xDataOutput filtersBlock()
        {
            xDataOutput o = new xDataOutput(1024);

            FilterManager.getInstance().saveFilterSets(o);

            return(o);
        }
コード例 #34
0
 /// <summary>
 /// Create a new filter dialog.
 /// </summary>
 /// <param name="parent">The container for this dialog. This probably doesn't need to be the RunHistoryScreen,
 /// but it seems reasonable to be. Should contain a child named "Content"</param>
 /// <param name="saveManager">The main game's save manager.</param>
 /// <param name="filterManager">The filter manager. Should be empty when this constructor is called.</param>
 public RunFilterDialog(RunHistoryScreen parent, SaveManager saveManager, FilterManager filterManager)
 {
     this.saveManager   = saveManager;
     this.filterManager = filterManager;
     // (a little fail-safe to avoid duplicate filters in the filter manager if the constructor is called again)
     filterManager.Clear();
     Reinit(parent);
 }
コード例 #35
0
        public void AddFilter_WithEmptyFilter_ItemIsAdded()
        {
            bool wasAdded = false;
            var filter = new EmptyFilter();

            FilterManager filterManager = new FilterManager();
            filterManager.ItemsAdded.Subscribe(Observer.Create<IFilter>(_ => wasAdded = true));

            filterManager.AddFilter(filter);

            Assert.IsTrue(wasAdded);
        }
コード例 #36
0
        public void AddFilter_WithEmptyFilter_AddedItemIsTheSame()
        {
            bool areSame = false;
            var filter = new EmptyFilter();

            FilterManager filterManager = new FilterManager();
            filterManager.ItemsAdded.Subscribe(Observer.Create<IFilter>(f => areSame = filter == f));

            filterManager.AddFilter(filter);

            Assert.IsTrue(areSame);
        }
コード例 #37
0
        public void ItemsChanged_WithEmptyFilter_ChangedItemsIsCalledForAddAndRemove()
        {
            int timesCalled = 0;
            var filter = new EmptyFilter();

            FilterManager filterManager = new FilterManager();
            filterManager.ItemsChanged.Subscribe(Observer.Create<IFilter>(_ => ++timesCalled));

            filterManager.AddFilter(filter);
            filterManager.RemoveFilter(filter);

            Assert.AreEqual(2, timesCalled);
        }
コード例 #38
0
        /// <summary>
        /// Creates the actual description.
        /// </summary>
        /// <param name="targetType">Type of the target.</param>
        /// <returns></returns>
        protected virtual IViewModelDescription CreateCore(Type targetType) 
        {
            var customFactory = targetType
                .GetAttributes<IViewModelDescriptionFactory>(true)
                .FirstOrDefault();

            if (customFactory != null)
                return customFactory.Create(targetType);

            var description = new DefaultViewModelDescription(conventionManager, targetType);
            var filters = new FilterManager(targetType, description.TargetType, serviceLocator);
            var actions = actionLocator.Locate(new ActionLocationContext(serviceLocator, targetType, filters));

            description.Filters = filters;
            actions.Apply(description.AddAction);

            return description;
        }
コード例 #39
0
    //***********<RIVER...>*************
    public RiverGenerator(TerrainGenerator terrain)
    {
        this.terrain = terrain;
        filtermanager = terrain.filterManager;
        terrain.riverGenerator = this;

        vertices = terrain.vertices;
        terrainSize = terrain.terrainSize;
        heightMap = terrain.heightMap;

        frp = new FunctionRiverPlanner(this);
        frd = new FunctionRiverDigger(this);
        fmc = new FunctionMathCalculator(this);
        ftm = new FunctionTerrainManager(this);
        fd = new FunctionDebugger(this);

        currentRiver = new RiverInfo(terrain);

        AssignFunctions();
    }
コード例 #40
0
        public void Process_CommandIsPendingWitWithOnePassingFilter_CommandNotFiltered()
        {
            var command = new TestCommand(CommandState.Pending);

            FilterManager filterManager = new FilterManager();
            var filter = new GenericFilter(c => true);
            filterManager.AddFilter(filter);
            var result = filterManager.Process(command);
            Assert.IsTrue(result);
        }
コード例 #41
0
        public void PublishOrderedCommands_OneCommandInCommands_ThisCommandIsExecuted()
        {
            var resetEvent = new ManualResetEventSlim(false);

            var filterManager = new FilterManager();
            var processor = new CommandProcessor(null, filterManager);
            var command = new TestCommand(CommandState.New);
            command.RegisterForStateChange(Observer.Create<CommandState>(b =>
            {
                if (b == CommandState.Executing)
                {
                    resetEvent.Set();
                }
            }));
            processor.PublishOrderedCommands(new[] {command});

            resetEvent.Wait();

            Assert.AreEqual(CommandState.Executing, command.CurrentState);
        }
コード例 #42
0
ファイル: SceneManager.cs プロジェクト: ja003/Fractal-Nature
    void Start()
    {
        // Initialise main Class object
        terrain = new TerrainGenerator();

        // Calling the constructor (Unity's C# does not allow conventional constructors)
        terrain.initialise(patchSize, patchMatrixSize);

        // Updating end-point of main mesh
        endPoint = new Vector3(terrain.terrainSize - 1, 0, terrain.terrainSize - 1);

        // Generate fractal Diamond-Square turbulence
        terrain.applyDiamondSquare(diSqStrength);

        // Initialise procedural texture variables
        terrain.applyProceduralTex(true, sandColor, sandLimit, sandStrength, sandCoverage, true, grassColor, grassStrength, true, snowColor, snowLimit, snowStrength, snowCoverage, true, rockColor, slopeLimit, slopeStrength, noiseTexValue);

        // Build mesh
        terrain.build();

        // erosionManager has to be created when
        erosionManager = new ErosionManager(terrain);
        erosionManager.initHydraulicMaps();
        filterManager = new FilterManager(terrain);
        //riverGenerator has to be after filterManager!
        riverGenerator = new RiverGenerator(terrain);

        //doesn't work well with on-fly generation
        riverGenerator.ftm.PerserveMountains(5, 30, 20);
    }
コード例 #43
0
        //   [TestMethod]
        ///TODO: Fix this test!
        public void PublishOrderedCommands_TwoCommandsAreSendInOrder_CommandsAreExecutedInOrder()
        {
            var resetEvent = new ManualResetEventSlim(false);
            var commandsCompleted = new bool[2];

            var filterManager = new FilterManager();
            var processor = new CommandProcessor(null, filterManager);
            var command = new TestCommand(CommandState.New, shouldCompleteAfterExecute:false) { Order = 13};

            command.RegisterForStateChange(Observer.Create<CommandState>(b =>
            {
                if (b == CommandState.Successed)
                {
                    commandsCompleted[0] = true;
                }
            }));

            var command2 = new TestCommand(CommandState.New, shouldCompleteAfterExecute: true) { Order = 2 };

            command2.RegisterForStateChange(Observer.Create<CommandState>(b =>
            {
                if (b == CommandState.Successed)
                {
                    commandsCompleted[1] = true;
                    resetEvent.Set();
                }
            }));
            processor.PublishOrderedCommands(new[] { command, command2 });

            resetEvent.Wait();

            Assert.IsTrue(commandsCompleted.All(f => f));
        }
コード例 #44
0
ファイル: VixenSystem.cs プロジェクト: komby/vixen
        public static void LoadSystemConfig()
        {
            Execution.initInstrumentation();
            DataFlow = new DataFlowManager();
            Elements = new ElementManager();
            Nodes = new NodeManager();
            OutputControllers = new OutputControllerManager(
                new ControllerLinkingManagement<OutputController>(),
                new OutputDeviceCollection<OutputController>(),
                new OutputDeviceExecution<OutputController>());
            SmartOutputControllers = new SmartOutputControllerManager(
                new ControllerLinkingManagement<SmartOutputController>(),
                new OutputDeviceCollection<SmartOutputController>(),
                new OutputDeviceExecution<SmartOutputController>());
            Previews = new PreviewManager(
                new OutputDeviceCollection<OutputPreview>(),
                new OutputDeviceExecution<OutputPreview>());
            Contexts = new ContextManager();
            Filters = new FilterManager(DataFlow);
            ControllerLinking = new ControllerLinker();
            ControllerManagement = new ControllerFacade();
            ControllerManagement.AddParticipant(OutputControllers);
            ControllerManagement.AddParticipant(SmartOutputControllers);
            OutputDeviceManagement = new OutputDeviceFacade();
            OutputDeviceManagement.AddParticipant(OutputControllers);
            OutputDeviceManagement.AddParticipant(SmartOutputControllers);
            OutputDeviceManagement.AddParticipant(Previews);

            // Load system data in order of dependency.
            // The system data generally resides in the data branch, but it
            // may not be in the case of an alternate context.
            string systemDataPath = _GetSystemDataPath();
            // Load module data before system config.
            // System config creates objects that use modules that have data in the store.
            ModuleStore = _LoadModuleStore(systemDataPath) ?? new ModuleStore();
            SystemConfig = _LoadSystemConfig(systemDataPath) ?? new SystemConfig();

            Elements.AddElements(SystemConfig.Elements);
            Nodes.AddNodes(SystemConfig.Nodes);
            OutputControllers.AddRange(SystemConfig.OutputControllers.Cast<OutputController>());
            SmartOutputControllers.AddRange(SystemConfig.SmartOutputControllers.Cast<SmartOutputController>());
            Previews.AddRange(SystemConfig.Previews.Cast<OutputPreview>());
            ControllerLinking.AddRange(SystemConfig.ControllerLinking);
            Filters.AddRange(SystemConfig.Filters);

            DataFlow.Initialize(SystemConfig.DataFlow);
        }
コード例 #45
0
        public void Process_NonPassingFilterAddedDuringCommandProcessing_CommandIsFiltered()
        {
            var command = new TestCommand(CommandState.Pending);

            FilterManager filterManager = new FilterManager();
            ManualResetEventSlim evt = new ManualResetEventSlim(false);
            var filter = new GenericFilter(c =>
                {
                    evt.Wait();
                    return true;
                });

            filterManager.AddFilter(filter);

            Task<bool> result = Task.Factory.StartNew(() => filterManager.Process(command));

            filterManager.AddFilter(new GenericFilter(c => false));
            evt.Set();

            Assert.IsFalse(result.Result);
        }