/// <summary>
 /// Initializes a new instance of the <see cref="CompositeContextProviderFactory"/> class.
 /// </summary>
 /// <param name="selectionFunction">
 /// The selection function.
 /// </param>
 /// <param name="factories">
 /// The factories to combine.
 /// </param>
 public CompositeContextProviderFactory(Func<IEnumerable<IContextProvider>, Type, IContextProvider> selectionFunction, params IContextProviderFactory[] factories)
 {
     selectionFunction.ThrowIfNull("selectionFunction");
     factories.ThrowIfNull("factories");
     this.selectionFunction = selectionFunction;
     this.factories = factories;
 }
        /// <summary>
        ///     Creates a new instance of the <see cref="ExpressionInstanceFactory" /> class.
        /// </summary>
        /// <exception cref="ArgumentNullException">factory can not be null.</exception>
        /// <param name="factory">The factory.</param>
        /// <param name="name">The name of the factory.</param>
        /// <param name="description">The description of the factory.</param>
        public ExpressionInstanceFactory( Func<IMemberInformation, Object> factory, String name = null, String description = null )
            : base(name, description)
        {
            factory.ThrowIfNull( nameof( factory ) );

            _factory = factory;
        }
Esempio n. 3
0
 public Task<IIndicesOperationResponse> PutWarmerAsync(string name, Func<PutWarmerDescriptor, PutWarmerDescriptor> selector)
 {
     selector.ThrowIfNull("selector");
     return this.DispatchAsync<PutWarmerDescriptor, PutWarmerQueryString, IndicesOperationResponse, IIndicesOperationResponse>(
         d => selector(d.Name(name).AllIndices()),
         (p, d) => this.RawDispatch.IndicesPutWarmerDispatchAsync(p, d)
     );
 }
		/// <inheritdoc />
		public IObservable<ISnapshotStatusResponse> SnapshotObservable(TimeSpan interval, Func<SnapshotDescriptor, SnapshotDescriptor> snapshotSelector = null)
		{
			snapshotSelector.ThrowIfNull("snapshotSelector");

			var snapshotDescriptor = snapshotSelector(new SnapshotDescriptor());
			var observable = new SnapshotObservable(this, snapshotDescriptor);
			return observable;
		}
Esempio n. 5
0
 /// <summary>
 /// Create an index with the specified index settings
 /// </summary>
 public IIndicesResponse CreateIndex(string index, Func<CreateIndexDescriptor, CreateIndexDescriptor> createIndexSelector)
 {
     index.ThrowIfEmpty("index");
     createIndexSelector.ThrowIfNull("createIndexSelector");
     var d = createIndexSelector(new CreateIndexDescriptor());
     var settings = d._IndexSettings;
     return this.CreateIndex(index, settings);
 }
        /// <summary>
        ///     Initializes a new instance of the <see cref="ExpressionMemberSelectionRule" /> class.
        /// </summary>
        /// <exception cref="ArgumentNullException">predicate can not be null.</exception>
        /// <param name="predicate">The predicate used to determine if a member matches the rule.</param>
        /// <param name="selectionMode">The selection mode to apply.</param>
        /// <param name="name">The name of the rule.</param>
        /// <param name="description">The description of the rule.</param>
        public ExpressionMemberSelectionRule( Func<IMemberInformation, Boolean> predicate, MemberSelectionMode selectionMode, String name = null, String description = null )
            : base(name, description)
        {
            predicate.ThrowIfNull( nameof( predicate ) );

            _predicate = predicate;
            _selectionMode = selectionMode;
        }
Esempio n. 7
0
 /// <inheritdoc />
 public IIndicesOperationResponse PutWarmer(string name, Func<PutWarmerDescriptor, PutWarmerDescriptor> selector)
 {
     selector.ThrowIfNull("selector");
     return this.Dispatch<PutWarmerDescriptor, PutWarmerRequestParameters, IndicesOperationResponse>(
         d => selector(d.Name(name).AllIndices()),
         (p, d) => this.RawDispatch.IndicesPutWarmerDispatch<IndicesOperationResponse>(p, d)
     );
 }
Esempio n. 8
0
        public ConcreteTypeConverter(Type baseType, Func<dynamic, Hit<dynamic>, Type> concreteTypeSelector, IEnumerable<string> partialFields)
        {
            concreteTypeSelector.ThrowIfNull("concreteTypeSelector");

            this._baseType = baseType;
            this._concreteTypeSelector = concreteTypeSelector;
            this._partialFields = partialFields;
        }
Esempio n. 9
0
		public UrlResolver(Func<IRouteCollection> routes, IHttpRuntime httpRuntime)
		{
			routes.ThrowIfNull("routes");
			httpRuntime.ThrowIfNull("httpRuntime");

			_routes = new Lazy<IRouteCollection>(routes);
			_httpRuntime = httpRuntime;
		}
		/// <inheritdoc />
		public IObservable<IRecoveryStatusResponse> RestoreObservable(TimeSpan interval, Func<RestoreDescriptor, RestoreDescriptor> restoreSelector = null)
		{
			restoreSelector.ThrowIfNull("restoreSelector");

			var restoreDescriptor = restoreSelector(new RestoreDescriptor());
			var observable = new RestoreObservable(this, restoreDescriptor);
			return observable;
		}
Esempio n. 11
0
		public ModelMapper(Func<Type, bool> parameterTypeMatchDelegate, IEnumerable<IModelPropertyMapper> propertyMappers)
		{
			parameterTypeMatchDelegate.ThrowIfNull("parameterTypeMatchDelegate");
			propertyMappers.ThrowIfNull("propertyMappers");

			_parameterTypeMatchDelegate = parameterTypeMatchDelegate;
			_modelPropertyMappers = propertyMappers.ToArray();
		}
        protected TexturedWindowRenderer(Func<TextureContent, WindowTexture> getWindowTextureDelegate)
        {
            getWindowTextureDelegate.ThrowIfNull("getWindowTextureDelegate");

            _getWindowTextureDelegate = getWindowTextureDelegate;
            BackgroundColor = Color.White;
            BorderColor = Color.White;
        }
Esempio n. 13
0
        /// <summary>
        ///     Returns a string which only contains the characters matching the given predicate.
        /// </summary>
        /// <exception cref="ArgumentNullException">The string can not be null.</exception>
        /// <exception cref="ArgumentNullException">The predicate can not be null.</exception>
        /// <param name="str">The input string.</param>
        /// <param name="predicate">The predicate.</param>
        /// <returns>Returns a string which only contains the characters matching the given predicate.</returns>
        public static String KeepWhere( this String str, Func<Char, Boolean> predicate )
        {
            str.ThrowIfNull( nameof( str ) );
            predicate.ThrowIfNull( nameof( predicate ) );

            return new String( str.ToCharArray()
                                  .Where( predicate )
                                  .ToArray() );
        }
		public SimilarityDescriptor CustomSimilarities(
			Func<FluentDictionary<string, SimilarityBase>, FluentDictionary<string, SimilarityBase>> similaritySelector)
		{
			similaritySelector.ThrowIfNull("similaritySelector");
			var similarities = new FluentDictionary<string, SimilarityBase>(this._SimilaritySettings.CustomSimilarities);
			var newSimilarities = similaritySelector(similarities);
			this._SimilaritySettings.CustomSimilarities = newSimilarities;
			return this;
		}
Esempio n. 15
0
 public Task<IIndicesOperationResponse> PutTemplateAsync(string name, Func<PutTemplateDescriptor, PutTemplateDescriptor> putTemplateSelector)
 {
     putTemplateSelector.ThrowIfNull("putTemplateSelector");
     var descriptor = putTemplateSelector(new PutTemplateDescriptor(this._connectionSettings).Name(name));
     return this.DispatchAsync<PutTemplateDescriptor, PutTemplateQueryString, IndicesOperationResponse, IIndicesOperationResponse>(
         descriptor,
         (p, d) => this.RawDispatch.IndicesPutTemplateDispatchAsync(p, d._TemplateMapping)
     );
 }
Esempio n. 16
0
        public void Map(Func<IContainer> container, Type type, MethodInfo method, Routing.Route route)
        {
            container.ThrowIfNull("container");
            type.ThrowIfNull("type");
            method.ThrowIfNull("method");
            route.ThrowIfNull("route");

            route.RespondWithNoContent();
        }
Esempio n. 17
0
		public JsonModelMapper(Func<Type, bool> parameterTypeMatchDelegate, JsonSerializerSettings serializerSettings, DataConversionErrorHandling errorHandling = DataConversionErrorHandling.UseDefaultValue)
		{
			parameterTypeMatchDelegate.ThrowIfNull("parameterTypeMatchDelegate");
			serializerSettings.ThrowIfNull("serializerSettings");

			_parameterTypeMatchDelegate = parameterTypeMatchDelegate;
			_serializerSettings = serializerSettings;
			_errorHandling = errorHandling;
		}
		/// <inheritdoc />
		public IIndicesOperationResponse PutTemplate(string name, Func<PutTemplateDescriptor, PutTemplateDescriptor> putTemplateSelector)
		{
			putTemplateSelector.ThrowIfNull("putTemplateSelector");
			var descriptor = putTemplateSelector(new PutTemplateDescriptor(_connectionSettings).Name(name));
			return this.Dispatch<IPutTemplateRequest, PutTemplateRequestParameters, IndicesOperationResponse>(
				descriptor,
				(p, d) => this.RawDispatch.IndicesPutTemplateDispatch<IndicesOperationResponse>(p, d.TemplateMapping)
			);
		}
 public Task<IMultiGetResponse> MultiGetAsync(Func<MultiGetDescriptor, MultiGetDescriptor> multiGetSelector)
 {
     multiGetSelector.ThrowIfNull("multiGetSelector");
     var descriptor = multiGetSelector(new MultiGetDescriptor(this._connectionSettings));
     return this.DispatchAsync<MultiGetDescriptor, MultiGetQueryString, MultiGetResponse, IMultiGetResponse>(
         descriptor,
         (p, d) => this.RawDispatch.MgetDispatchAsync(p, d),
         this.Serializer.DeserializeMultiGetResponse
     );
 }
Esempio n. 20
0
 /// <inheritdoc />
 public Task<IMultiGetResponse> MultiGetAsync(Func<MultiGetDescriptor, MultiGetDescriptor> multiGetSelector)
 {
     multiGetSelector.ThrowIfNull("multiGetSelector");
     var descriptor = multiGetSelector(new MultiGetDescriptor(_connectionSettings));
     var converter = CreateCovariantMultiGetConverter(descriptor);
     return this.DispatchAsync<MultiGetDescriptor, MultiGetRequestParameters, MultiGetResponse, IMultiGetResponse>(
         descriptor,
         (p, d) => this.RawDispatch.MgetDispatchAsync<MultiGetResponse>(p.DeserializationState(converter), d)
     );
 }
Esempio n. 21
0
        public AnalysisDescriptor CharFilters(
			Func<FluentDictionary<string, CharFilterBase>, FluentDictionary<string, CharFilterBase>> charFiltersSelecter)
        {
            charFiltersSelecter.ThrowIfNull("charFiltersSelecter");
            var charFilters = new FluentDictionary<string, CharFilterBase>(this._AnalysisSettings.CharFilters);
            var newCharFilters = charFiltersSelecter(charFilters);
            this._AnalysisSettings.CharFilters = newCharFilters;

            return this;
        }
 /// <inheritdoc />
 public Task<IMultiGetResponse> MultiGetAsync(Func<MultiGetDescriptor, MultiGetDescriptor> multiGetSelector)
 {
     multiGetSelector.ThrowIfNull("multiGetSelector");
     var descriptor = multiGetSelector(new MultiGetDescriptor(_connectionSettings));
     var converter = CreateCovariantMultiGetConverter(descriptor);
     return this.DispatchAsync<MultiGetDescriptor, MultiGetQueryString, MultiGetResponse, IMultiGetResponse>(
         descriptor,
         (p, d) => this.RawDispatch.MgetDispatchAsync<MultiGetResponse>(p, d, converter)
     );
 }
Esempio n. 23
0
        public AnalysisDescriptor Tokenizers(
			Func<FluentDictionary<string, TokenizerBase>, FluentDictionary<string, TokenizerBase>> tokenizerSelector)
        {
            tokenizerSelector.ThrowIfNull("tokenizerSelector");
            var tokenizers = new FluentDictionary<string, TokenizerBase>(this._AnalysisSettings.Tokenizers);
            var newTokenizers = tokenizerSelector(tokenizers);
            this._AnalysisSettings.Tokenizers = newTokenizers;

            return this;
        }
Esempio n. 24
0
		public ModelMapper(IContainer container, Func<Type, bool> parameterTypeMatchDelegate, IEnumerable<IModelPropertyMapper> propertyMappers)
		{
			container.ThrowIfNull("container");
			parameterTypeMatchDelegate.ThrowIfNull("parameterTypeMatchDelegate");
			propertyMappers.ThrowIfNull("propertyMappers");

			_container = container;
			_parameterTypeMatchDelegate = parameterTypeMatchDelegate;
			_modelPropertyMappers = propertyMappers.ToArray();
		}
Esempio n. 25
0
        public AnalysisDescriptor Analyzers(
			Func<FluentDictionary<string, AnalyzerBase>, FluentDictionary<string, AnalyzerBase>> analyzerSelector)
        {
            analyzerSelector.ThrowIfNull("analyzerSelector");
            var analyzers = new FluentDictionary<string, AnalyzerBase>(this._AnalysisSettings.Analyzers);
            var newAnalyzers = analyzerSelector(analyzers);
            this._AnalysisSettings.Analyzers = newAnalyzers;

            return this;
        }
Esempio n. 26
0
        public UrlResolver(Func<IRouteCollection> routes, IUrlResolverConfiguration configuration, IHttpRuntime httpRuntime)
        {
            routes.ThrowIfNull("routes");
            configuration.ThrowIfNull("configuration");
            httpRuntime.ThrowIfNull("httpRuntime");

            _routes = new Lazy<IRouteCollection>(routes);
            _configuration = configuration;
            _httpRuntime = httpRuntime;
        }
Esempio n. 27
0
        public Task MapAsync(Func<IContainer> container, Type type, MethodInfo method, Routing.Route route)
        {
            container.ThrowIfNull("container");
            type.ThrowIfNull("type");
            method.ThrowIfNull("method");
            route.ThrowIfNull("route");

            route.RespondWithNoContent();

            return Task.Factory.Empty();
        }
Esempio n. 28
0
        /// <summary>
        /// Gets warmers, query will be returned as json string
        /// </summary>
        public IWarmerResponse GetWarmer(Func<GetWarmerDescriptor, GetWarmerDescriptor> selector)
        {
            selector.ThrowIfNull("selector");
            var descriptor = selector(new GetWarmerDescriptor(_connectionSettings));
            descriptor.ThrowIfNull("descriptor");
            var path = this.PathResolver.GetWarmerPath(descriptor);

            ConnectionStatus status = this.Connection.GetSync(path);
            var r = this.Deserialize<WarmerResponse>(status);
            return r;
        }
		/// <inheritdoc />
		public IMultiGetResponse MultiGet(Func<MultiGetDescriptor, MultiGetDescriptor> multiGetSelector)
		{
			multiGetSelector.ThrowIfNull("multiGetSelector");
			var descriptor = multiGetSelector(new MultiGetDescriptor());
			var converter = CreateCovariantMultiGetConverter(descriptor);
			var customCreator = new MultiGetConverter((r, s) => this.DeserializeMultiGetResponse(r, s, converter));
			return this.Dispatch<MultiGetDescriptor, MultiGetRequestParameters, MultiGetResponse>(
				descriptor,
				(p, d) => this.RawDispatch.MgetDispatch<MultiGetResponse>(p.DeserializationState(customCreator), d)
			);
		}
Esempio n. 30
0
        public ReactiveCommand(
			Action<object> execute,
			Func<object, bool> canExecute,
			params INotifyPropertyChanged[] canExecuteNotifiers)
        {
            _execute = execute.ThrowIfNull();
            _canExecute = canExecute.ThrowIfNull();
            _canExecuteNotifiers = canExecuteNotifiers;

            _canExecuteNotifiers.ForEach(x => x.SubscribeWeakly(this, (c, s, e) => c.NotifyCanExecuteChanged()));
        }
        /// <summary>
        /// Registers a reliable stateful service with Service Fabric runtime.
        /// </summary>
        /// <param name="serviceTypeName">The service type name as provied in service manifest.</param>
        /// <param name="serviceFactory">A factory method to create stateful service objects.</param>
        /// <param name="timeout">The timeout for the register operation.</param>
        /// <para>The default timeout for this operation is taken from ServiceFactoryRegistrationTimeout in Hosting section of the cluster manifest. Default value for ServiceFactoryRegistrationTimeout is 120 seconds.</para>
        /// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
        /// <returns>
        /// A task that represents the asynchronous register operation.
        /// </returns>
        public async static Task RegisterServiceAsync(
            string serviceTypeName,
            Func <StatefulServiceContext, StatefulServiceBase> serviceFactory,
            TimeSpan timeout = default(TimeSpan),
            CancellationToken cancellationToken = default(CancellationToken))
        {
            serviceFactory.ThrowIfNull("serviceFactory");
            serviceTypeName.ThrowIfNullOrWhiteSpace("serviceTypeName");

            var runtimeContext = await RuntimeContext.GetOrCreateAsync(timeout, cancellationToken);

            await runtimeContext.Runtime.RegisterStatefulServiceFactoryAsync(
                serviceTypeName,
                new StatefulServiceReplicaFactory(runtimeContext, serviceFactory),
                timeout,
                cancellationToken);
        }
Esempio n. 32
0
        /// <inheritdoc />
        public IIndicesResponse Map <T>(Func <PutMappingDescriptor <T>, PutMappingDescriptor <T> > mappingSelector) where T : class
        {
            mappingSelector.ThrowIfNull("mappingSelector");
            var descriptor = mappingSelector(new PutMappingDescriptor <T>(_connectionSettings));

            return(this.Dispatch <PutMappingDescriptor <T>, PutMappingRequestParameters, IndicesResponse>(
                       descriptor,
                       (p, d) =>
            {
                var o = new Dictionary <string, RootObjectMapping>
                {
                    { p.Type, d._Mapping }
                };
                return this.RawDispatch.IndicesPutMappingDispatch <IndicesResponse>(p, o);
            }
                       ));
        }
        public MultiFieldMappingDescriptor <T> Fields(Func <CorePropertiesDescriptor <T>, CorePropertiesDescriptor <T> > fieldSelector)
        {
            fieldSelector.ThrowIfNull("fieldSelector");
            var properties = fieldSelector(new CorePropertiesDescriptor <T>());

            foreach (var p in properties.Properties)
            {
                var value = p.Value as IElasticCoreType;
                if (value == null)
                {
                    continue;
                }

                _Mapping.Fields[p.Key] = value;
            }
            return(this);
        }
Esempio n. 34
0
        public static double summation(this Array source, Func <double, int, double> action)
        {
            source.ThrowIfNull("source");
            action.ThrowIfNull("action");
            if (!(source.IsArrayOf(typeof(Double))))
            {
                throw new Exception("Needs to be double array");
            }
            double[] a   = (double[])source;
            double   sum = 0;

            for (int i = 0; i < a.Length; i++)
            {
                sum += action(a[i], i);
            }
            return(sum);
        }
Esempio n. 35
0
        /// <summary>
        ///    Aggregates the values of the specified enumerable using the given fold function.
        ///     If the enumerable is empty or all values are null, None is returned.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="enumerable"></param>
        /// <param name="fold"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException">
        ///     The enumerable argument or fold is null.
        /// </exception>
        public static Option <T> AggregateOptionalNullable <T>([NotNull] this IEnumerable <T?> enumerable, [NotNull] Func <T, T, T> fold)
            where T : struct
        {
            enumerable.ThrowIfNull(nameof(enumerable));
            fold.ThrowIfNull(nameof(fold));

            return(enumerable
                   .Aggregate(Option <T> .None, (accu, current) => {
                var currentOption = Option.From(current);

                return accu.Match(
                    None: () => currentOption,
                    Some: previousValue => currentOption.Match(
                        None: () => previousValue,
                        Some: currentValue => fold(previousValue, currentValue)));
            }));
        }
Esempio n. 36
0
        public NotifyChange(
            Func <T> getter,
            Action <T> setter = null,
            Func <T, bool> changeCondition         = null,
            INotifyPropertyChanged[] changeSources = null,
            Func <object, PropertyChangedEventArgs, bool> sourceNotifyCondition = null)
        {
            _getter                = getter.ThrowIfNull();
            _setter                = setter ?? NotifyChange.Defaults.SetterIsNotSupported;
            _changeCondition       = changeCondition ?? NotifyChange.Defaults.ChangeAlways;
            _sourceNotifyCondition = sourceNotifyCondition ?? NotifyChange.Defaults.SourceAlwaysNotifies;

            if (changeSources != null && changeSources.Length != 0)
            {
                SubscribeToChangeSourcesWeakly(changeSources);
            }
        }
        public static T CoalesceOrDefault <T>([CanBeNull] this T value, [NotNull] Func <T> defaultValueFactory, [NotNull][ItemCanBeNull] params T[] values)
            where T : class
        {
            defaultValueFactory.ThrowIfNull(nameof(defaultValueFactory));
            values.ThrowIfNull(nameof(values));

            if (value != null)
            {
                return(value);
            }

            var notNullValues = values
                                .Where(x => x != null)
                                .ToList();

            return(notNullValues.Any() ? notNullValues.First() : defaultValueFactory());
        }
Esempio n. 38
0
        public SearchDescriptor <T> TermSuggest(string name, Func <TermSuggestDescriptor <T>, TermSuggestDescriptor <T> > suggest)
        {
            name.ThrowIfNullOrEmpty("name");
            suggest.ThrowIfNull("suggest");
            if (this._Suggest == null)
            {
                this._Suggest = new Dictionary <string, SuggestDescriptorBucket <T> >();
            }
            TermSuggestDescriptor <T>   desc   = new TermSuggestDescriptor <T>();
            TermSuggestDescriptor <T>   item   = suggest(desc);
            SuggestDescriptorBucket <T> bucket = new SuggestDescriptorBucket <T> {
                _Text = item._Text, TermSuggest = item
            };

            this._Suggest.Add(name, bucket);
            return(this);
        }
Esempio n. 39
0
        /// <summary>
        /// The phrase suggester adds additional logic on top of the term suggester to select entire corrected phrases
        /// instead of individual tokens weighted based on ngram-langugage models.
        /// </summary>
        public SearchDescriptor <T> SuggestPhrase(string name, Func <PhraseSuggesterDescriptor <T>, PhraseSuggesterDescriptor <T> > suggest) => Assign(a =>
        {
            name.ThrowIfNullOrEmpty(nameof(name));
            suggest.ThrowIfNull(nameof(suggest));
            if (a.Suggest == null)
            {
                a.Suggest = new Dictionary <string, ISuggestBucket>();
            }

            var desc           = new PhraseSuggesterDescriptor <T>();
            var item           = suggest(desc);
            IPhraseSuggester i = item;
            var bucket         = new SuggestBucket {
                Text = i.Text, Phrase = item
            };
            a.Suggest.Add(name, bucket);
        });
Esempio n. 40
0
 /// <summary>
 /// Initializes a new instance of the XmlCollection class from the specified
 /// XML element.
 /// </summary>
 /// <param name="element">The XML element to initialize this instance
 /// from.</param>
 /// <param name="tag">The XML tag name of an entry.</param>
 /// <param name="conversion">A callback method which is invoked to convert
 /// an XML element into an instance of the specified type.</param>
 /// <exception cref="ArgumentNullException">The element parameter or the tag
 /// parameter or the conversion parameter is null.</exception>
 public XmlCollection(XmlElement element, string tag, Func <XmlElement, T> conversion)
 {
     element.ThrowIfNull("element");
     tag.ThrowIfNull("tag");
     conversion.ThrowIfNull("conversion");
     this.element    = element;
     this.tag        = tag;
     this.conversion = conversion;
     // Call GetItems method to verify each item in the collection can be
     // converted into an instance of the requested type.
     try {
         GetItems();
     } catch (Exception e) {
         throw new ArgumentException("The specified element contained invalid " +
                                     "data.", e);
     }
 }
Esempio n. 41
0
        public static HttpMessageHandler DecorateIf(this HttpMessageHandler @this, Func <DelegatingHandler> decoratorFactory
                                                    , Func <bool> condition)
        {
            @this.ThrowIfNull(typeof(HttpMessageHandler).Name.ToLower());
            decoratorFactory.ThrowIfNull(nameof(decoratorFactory));
            condition.ThrowIfNull(nameof(condition));

            Func <DelegatingHandler> decorate = () =>
            {
                var decorator = decoratorFactory();
                decorator.InnerHandler = @this;
                return(decorator);
            };

            return(condition()
                ? decorate()
                : @this);
        }
Esempio n. 42
0
        public async Task ParseAsync(IEnumerable <string> args, Func <ICommand, CancellationToken, Task> callback, Action <IEnumerable <Error> > errorCallback, CancellationToken token)
        {
            callback.ThrowIfNull(nameof(callback));
            errorCallback.ThrowIfNull(nameof(errorCallback));

            await CommandLine.Parser.Default
            .ParseArguments(args, _commandLookup.Keys.ToArray())
            .MapResult(async option =>
            {
                var command = MatchCommandWithOption((dynamic)option);
                await callback.Invoke(command, token);
            },
                       errors =>
            {
                errorCallback.Invoke(errors);
                return(Task.CompletedTask);
            });
        }
        public TemplateMappingDescriptor AddWarmer <T>(Func <CreateWarmerDescriptor, CreateWarmerDescriptor> warmerSelector)
            where T : class
        {
            warmerSelector.ThrowIfNull("warmerSelector");
            var warmerDescriptor = warmerSelector(new CreateWarmerDescriptor());

            warmerDescriptor.ThrowIfNull("warmerDescriptor");
            warmerDescriptor._WarmerName.ThrowIfNull("warmer has no name");

            var query = this._serializer.Serialize(warmerDescriptor._SearchDescriptor);

            var warmer = new WarmerMapping {
                Name = warmerDescriptor._WarmerName, Types = warmerDescriptor._Types, Source = query
            };

            this._TemplateMapping.Warmers[warmerDescriptor._WarmerName] = warmer;
            return(this);
        }
Esempio n. 44
0
        ///// <summary>
        ///// To avoid repetition of the suggest text, it is possible to define a global text.
        ///// </summary>
        //public SearchDescriptor<T> SuggestGlobalText(string globalSuggestText)
        //{
        //	if (Self.Suggest == null)
        //		Self.Suggest = new Dictionary<string, ISuggester>();
        //	Self.Suggest.Add("text", globalSuggestText);
        //	return this;
        //}

        /// <summary>
        /// The term suggester suggests terms based on edit distance. The provided suggest text is analyzed before terms are suggested.
        /// The suggested terms are provided per analyzed suggest text token. The term suggester doesn’t take the query into account that is part of request.
        /// </summary>
        public SearchDescriptor <T> SuggestTerm(string name, Func <TermSuggestDescriptor <T>, TermSuggestDescriptor <T> > suggest)
        {
            name.ThrowIfNullOrEmpty("name");
            suggest.ThrowIfNull("suggest");
            if (Self.Suggest == null)
            {
                Self.Suggest = new Dictionary <string, ISuggestBucket>();
            }
            var            desc   = new TermSuggestDescriptor <T>();
            var            item   = suggest(desc);
            ITermSuggester i      = item;
            var            bucket = new SuggestBucket {
                Text = i.Text, Term = item
            };

            Self.Suggest.Add(name, bucket);
            return(this);
        }
Esempio n. 45
0
        /// <summary>
        /// A facet query allows to return a count of the hits matching
        /// the facet query. The query itself can be expressed using the Query DSL.
        /// </summary>
        public SearchDescriptor <T> FacetQuery(string name, Func <QueryDescriptor <T>, QueryContainer> querySelector, bool?Global = null)
        {
            name.ThrowIfNullOrEmpty("name");
            querySelector.ThrowIfNull("query");
            if (Self.Facets == null)
            {
                Self.Facets = new Dictionary <PropertyPathMarker, IFacetContainer>();
            }

            var query = new QueryDescriptor <T>();
            var q     = querySelector(query);

            Self.Facets.Add(name, new FacetContainer {
                Query = q
            });

            return(this);
        }
Esempio n. 46
0
        public static TValue GetOrCreate <TKey, TValue>(
            this IDictionary <TKey, TValue> dictionary,
            [DisallowNull] TKey key,
            Func <TValue> newValueGetter)
            where TKey : notnull
        {
            dictionary.ThrowIfNull(nameof(dictionary));
            key.ThrowIfNullValue(nameof(key), assertOnPureValueTypes: false);
            newValueGetter.ThrowIfNull(nameof(newValueGetter));

            if (!dictionary.TryGetValue(key, out TValue value))
            {
                value           = newValueGetter();
                dictionary[key] = value;
            }

            return(value);
        }
Esempio n. 47
0
        /// <summary>
        /// Filters a data-producer based on a predicate on each value; the index
        /// in the sequence is used in the predicate
        /// </summary>
        /// <param name="source">The data-producer to be filtered</param>
        /// <param name="predicate">The condition to be satisfied</param>
        /// <returns>A filtered data-producer; only matching values will raise the DataProduced event</returns>
        public static IDataProducer <TSource> Where <TSource>(this IDataProducer <TSource> source, Func <TSource, int, bool> predicate)
        {
            source.ThrowIfNull("source");
            predicate.ThrowIfNull("predicate");

            DataProducer <TSource> ret = new DataProducer <TSource>();

            int index = 0;

            source.DataProduced += value => {
                if (predicate(value, index++))
                {
                    ret.Produce(value);
                }
            };
            source.EndOfData += () => { ret.End(); };
            return(ret);
        }
Esempio n. 48
0
        public static IList <T> ReplaceAll <T>(this IList <T> list, Predicate <T> itemSelector, Func <T, T> newItemGenerator)
        {
            list.ThrowIfNull("this");
            itemSelector.ThrowIfNull("itemSelector");
            newItemGenerator.ThrowIfNull("newItemGenerator");

            for (int index = 0; index < list.Count; index++)
            {
                var currentItem = list[index];
                if (!itemSelector(currentItem))
                {
                    continue;
                }

                list[index] = newItemGenerator(currentItem);
            }
            return(list);
        }
    /// <summary>
    /// Returns the number of elements in the specified sequence satisfy a condition,
    /// as a future value.
    /// </summary>
    /// <typeparam name="TSource">The type of the elements of source.</typeparam>
    /// <param name="source">A sequence that contains elements to be tested and counted.</param>
    /// <param name="predicate">A function to test each element for a condition.</param>
    /// <returns>A number that represents how many elements in the sequence satisfy
    /// the condition in the predicate function, as a future value.
    /// The actual count can only be retrieved after the source has indicated the end
    /// of its data.
    /// </returns>
    public static IFuture <int> Count <TSource>(this IDataProducer <TSource> source, Func <TSource, bool> predicate)
    {
        source.ThrowIfNull("source");
        predicate.ThrowIfNull("predicate");
        Future <int> ret   = new();
        int          count = 0;

        source.DataProduced += t =>
        {
            if (predicate(t))
            {
                count++;
            }
        };
        source.EndOfData += () => ret.Value = count;

        return(ret);
    }
Esempio n. 50
0
        /// <summary>
        /// A facet query allows to return a count of the hits matching
        /// the facet query. The query itself can be expressed using the Query DSL.
        /// </summary>
        public SearchDescriptor <T> FacetQuery(string name, Func <QueryDescriptor <T>, BaseQuery> querySelector, bool?Global = null)
        {
            name.ThrowIfNullOrEmpty("name");
            querySelector.ThrowIfNull("query");
            if (this._Facets == null)
            {
                this._Facets = new Dictionary <PropertyPathMarker, FacetDescriptorsBucket <T> >();
            }

            var query = new QueryDescriptor <T>();
            var q     = querySelector(query);

            this._Facets.Add(name, new FacetDescriptorsBucket <T> {
                Query = q
            });

            return(this);
        }
Esempio n. 51
0
        public static TResult Invoke <TServer, TResult>(Func <TResult> func, ref TServer server)
            where TServer : BaseAPI, new()
        {
            func.ThrowIfNull("func");

            if (server == null)
            {
                server = GetServer <TServer>();
                using (server.Connection)
                {
                    return(func());
                }
            }
            else
            {
                return(func());
            }
        }
Esempio n. 52
0
        /// <summary>
        /// The completion suggester is a so-called prefix suggester.
        /// It does not do spell correction like the term or phrase suggesters but allows basic auto-complete functionality.
        /// </summary>
        public SearchDescriptor <T> SuggestCompletion(string name, Func <CompletionSuggestDescriptor <T>, CompletionSuggestDescriptor <T> > suggest)
        {
            name.ThrowIfNullOrEmpty("name");
            suggest.ThrowIfNull("suggest");
            if (this._Suggest == null)
            {
                this._Suggest = new Dictionary <string, object>();
            }

            var desc   = new CompletionSuggestDescriptor <T>();
            var item   = suggest(desc);
            var bucket = new SuggestDescriptorBucket <T> {
                _Text = item._Text, CompletionSuggest = item
            };

            this._Suggest.Add(name, bucket);
            return(this);
        }
Esempio n. 53
0
        public PutTemplateDescriptor AddMapping <T>(Func <PutMappingDescriptor <T>, PutMappingDescriptor <T> > mappingSelector)
            where T : class
        {
            mappingSelector.ThrowIfNull("mappingSelector");
            var rootObjectMappingDescriptor = mappingSelector(new PutMappingDescriptor <T>(this._connectionSettings));

            rootObjectMappingDescriptor.ThrowIfNull("rootObjectMappingDescriptor");

            var inferrer = new ElasticInferrer(this._connectionSettings);
            var typeName = inferrer.TypeName(rootObjectMappingDescriptor._Type);

            if (typeName == null)
            {
                return(this);
            }
            this._TemplateMapping.Mappings[typeName] = rootObjectMappingDescriptor._Mapping;
            return(this);
        }
Esempio n. 54
0
        public static Tuple <IList <T>, IList <T> > Partition <T>(this IEnumerable <T> source, Func <T, bool> predicate, bool parallel = false)
        {
            source.ThrowIfNull("source");
            predicate.ThrowIfNull("predicate");

            if (parallel)
            {
                var trueList      = new List <T>();
                var falseList     = new List <T>();
                var partitionLock = new object();

                var items = source is IList <T>?(IList <T>)source : (IList <T>)source.ToList();
                Parallel.For(0, items.Count,
                             () => Tuple.Create(new List <T>(), new List <T>()),
                             (i, loop, tuple) =>
                {
                    if (predicate(items[i]))
                    {
                        tuple.Item1.Add(items[i]);
                    }
                    else
                    {
                        tuple.Item2.Add(items[i]);
                    }
                    return(tuple);
                },
                             tuple =>
                {
                    lock (partitionLock)
                    {
                        trueList.AddRange(tuple.Item1);
                        falseList.AddRange(tuple.Item2);
                    }
                });

                return(Tuple.Create((IList <T>)trueList, (IList <T>)falseList));
            }

            var stream = source.Memoize();

            return(stream != null
                ? Tuple.Create((IList <T>) stream.Where(predicate).ToList(), (IList <T>) stream.Where(s => !predicate(s)).ToList())
                : Tuple.Create((IList <T>) new T[0], (IList <T>) new T[0]));
        }
Esempio n. 55
0
        public static IEnumerable <T> Combinations <T>(int m, int n, Func <int[], T> select)
        {
            if (m < 0)
            {
                throw new ArgumentOutOfRangeException("m", m, "must be nonnegative");
            }
            if (n < 0)
            {
                throw new ArgumentOutOfRangeException("n", n, "must be nonnegative");
            }
            if (m > n)
            {
                throw new ArgumentOutOfRangeException("m", m, "must be smaller than n");
            }

            select.ThrowIfNull("select");

            return(CombinationsImpl(m, n, select));
        }
    /// <summary>
    /// Applies an accumulator function over the values yielded from
    /// a data-producer, performing a transformation on the final
    /// accululated value. The specified seed value
    /// is used as the initial accumulator value, and the specified function is used
    /// to select the result value
    /// </summary>
    /// <typeparam name="TSource">The type of data yielded by the data-source</typeparam>
    /// <typeparam name="TResult">The final result type (after the accumulator has been transformed)</typeparam>
    /// <typeparam name="TAccumulate">The type to be used for the accumulator</typeparam>
    /// <param name="func">Accumulator function to be applied to each term in the sequence</param>
    /// <param name="resultSelector">Transformation to apply to the final
    /// accumulated value to produce the result</param>
    /// <param name="seed">The initial value for the accumulator</param>
    /// <param name="source">The data-source for the values</param>
    public static IFuture <TResult> Aggregate <TSource, TAccumulate, TResult>
        (this IDataProducer <TSource> source,
        TAccumulate seed,
        Func <TAccumulate, TSource, TAccumulate> func,
        Func <TAccumulate, TResult> resultSelector)
    {
        source.ThrowIfNull("source");
        func.ThrowIfNull("func");
        resultSelector.ThrowIfNull("resultSelector");

        Future <TResult> result = new();

        TAccumulate current = seed;

        source.DataProduced += value => current = func(current, value);
        source.EndOfData    += () => result.Value = resultSelector(current);

        return(result);
    }
Esempio n. 57
0
        /// <summary>
        /// A filter facet (not to be confused with a facet filter) allows you to return a count of the h
        /// its matching the filter. The filter itself can be expressed using the Query DSL.
        /// Note, filter facet filters are faster than query facet when using native filters (non query wrapper ones).
        /// </summary>
        public SearchDescriptor <T> FacetFilter(string name, Func <FilterDescriptor <T>, BaseFilter> filterSelector)
        {
            name.ThrowIfNullOrEmpty("name");
            filterSelector.ThrowIfNull("filterSelector");

            if (this._Facets == null)
            {
                this._Facets = new Dictionary <PropertyPathMarker, FacetDescriptorsBucket <T> >();
            }

            var filter = new FilterDescriptor <T>();
            var f      = filterSelector(filter);

            this._Facets.Add(name, new FacetDescriptorsBucket <T> {
                Filter = f
            });

            return(this);
        }
Esempio n. 58
0
        /// <summary>
        /// A filter facet (not to be confused with a facet filter) allows you to return a count of the h
        /// its matching the filter. The filter itself can be expressed using the Query DSL.
        /// Note, filter facet filters are faster than query facet when using native filters (non query wrapper ones).
        /// </summary>
        public SearchDescriptor <T> FacetFilter(string name, Func <FilterDescriptor <T>, FilterContainer> filterSelector)
        {
            name.ThrowIfNullOrEmpty("name");
            filterSelector.ThrowIfNull("filterSelector");

            if (Self.Facets == null)
            {
                Self.Facets = new Dictionary <PropertyPathMarker, IFacetContainer>();
            }

            var filter = new FilterDescriptor <T>();
            var f      = filterSelector(filter);

            Self.Facets.Add(name, new FacetContainer {
                Filter = f
            });

            return(this);
        }
Esempio n. 59
0
 public DefaultAssemblyLoadContext(Func <INativeAssemblyUnloader> nativeAssemblyUnloaderFactory,
                                   Func <IPluginDependencyResolver> pluginDependencyResolverFactory,
                                   Func <IAssemblyLoadStrategy> assemblyLoadStrategyFactory,
                                   Func <string, IAssemblyDependencyResolver> assemblyDependencyResolverFactory,
                                   Func <IFileSystemUtilities> fileSystemUtilitiesFactory,
                                   Func <IRuntimeDefaultAssemblyContext> runtimeDefaultAssemblyLoadContextFactory,
                                   Func <IPluginDependencyContextProvider> pluginDependencyContextProviderFactory)
 {
     this.nativeAssemblyUnloader            = nativeAssemblyUnloaderFactory.ThrowIfNull(nameof(nativeAssemblyUnloaderFactory))();
     this.pluginDependencyResolverFactory   = pluginDependencyResolverFactory.ThrowIfNull(nameof(pluginDependencyResolverFactory));
     this.assemblyLoadStrategyFactory       = assemblyLoadStrategyFactory.ThrowIfNull(nameof(assemblyLoadStrategyFactory));
     this.assemblyDependencyResolverFactory = assemblyDependencyResolverFactory.ThrowIfNull(nameof(assemblyDependencyResolverFactory));
     this.fileSystemUtilities = fileSystemUtilitiesFactory.ThrowIfNull(nameof(fileSystemUtilitiesFactory))();
     this.runtimeDefaultAssemblyLoadContext = runtimeDefaultAssemblyLoadContextFactory.ThrowIfNull(nameof(runtimeDefaultAssemblyLoadContextFactory))();
     this.pluginDependencyContextProvider   = pluginDependencyContextProviderFactory.ThrowIfNull(nameof(pluginDependencyContextProviderFactory))();
     this.loadedNativeLibraries             = new ConcurrentDictionary <string, IntPtr>();
     this.loadedPlugins      = new ConcurrentBag <string>();
     this.assemblyReferences = new ConcurrentBag <WeakReference>();
 }
Esempio n. 60
0
        public virtual RescoreQueryDescriptor <T> Query(Func <QueryDescriptor <T>, BaseQuery> query)
        {
            query.ThrowIfNull("query");
            var q = new QueryDescriptor <T>().Strict(this._Strict);

            var bq = query(q);

            if (this._Strict && bq.IsConditionless)
            {
                throw new DslException("Query resulted in a conditionless query:\n{0}".F(JsonConvert.SerializeObject(bq, Formatting.Indented)));
            }

            else if (bq.IsConditionless)
            {
                return(this);
            }
            this._Query = bq;
            return(this);
        }