Exemplo n.º 1
0
        private static IEnumerable<KeyValuePair<IndexedName, RealNode>> ReduceGroup(
			IEnumerable<KeyValuePair<IndexedName, RealNode>> aggr, IGrouping<XName, RealNode> items)
        {
            var addition = items.Select((elem, i) =>
                new KeyValuePair<IndexedName, RealNode>(new IndexedName(items.Key, i), elem));
            return aggr.Concat(addition);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Creates an instance of a <see cref="TemplateService"/>.
        /// </summary>
        /// <param name="configuration">The <see cref="TemplateServiceConfigurationElement"/> that represents the configuration.</param>
        /// <param name="defaultNamespaces">The enumerable of namespaces to add as default.</param>
        /// <returns>A new instance of <see cref="TemplateService"/>.</returns>
        public static TemplateService CreateTemplateService(TemplateServiceConfigurationElement configuration, IEnumerable<string> defaultNamespaces = null)
        {
            if (configuration == null)
                throw new ArgumentNullException("configuration");

            ILanguageProvider provider = null;
            MarkupParser parser = null;
            Type templateBaseType = null;

            if (!string.IsNullOrEmpty(configuration.LanguageProvider))
                provider = (ILanguageProvider)GetInstance(configuration.LanguageProvider);

            if (!string.IsNullOrEmpty(configuration.MarkupParser))
                parser = (MarkupParser)GetInstance(configuration.MarkupParser);

            if (!string.IsNullOrEmpty(configuration.TemplateBase))
                templateBaseType = GetType(configuration.TemplateBase);

            var namespaces = configuration.Namespaces
                .Cast<NamespaceConfigurationElement>()
                .Select(n => n.Namespace);

            if (defaultNamespaces != null)
            {
                namespaces = defaultNamespaces
                    .Concat(namespaces)
                    .Distinct();
            }

            var service = new TemplateService(provider, templateBaseType, parser);
            foreach (string ns in namespaces)
                service.Namespaces.Add(ns);

            return service;
        }
 protected MemberInfoProxyBase(System.Reflection.MemberInfo fieldInfo, IEnumerable<string> aliases)
 {
     _names = aliases
         .Concat(new[] { fieldInfo.Name })
         .Distinct()
         .ToList();
 }
 public ParameterValueReader(IEnumerable<IValueExpressionFactory> expressionFactories)
 {
     _expressionFactories = expressionFactories.Concat(
         new IValueExpressionFactory[]
         {
             new EnumExpressionFactory(),
             new BooleanExpressionFactory(),
             new ByteExpressionFactory(),
             new GuidExpressionFactory(),
             new DateTimeExpressionFactory(),
             new TimeSpanExpressionFactory(),
             new DateTimeOffsetExpressionFactory(),
             new DecimalExpressionFactory(),
             new DoubleExpressionFactory(),
             new SingleExpressionFactory(),
             new ByteArrayExpressionFactory(),
             new StreamExpressionFactory(),
             new LongExpressionFactory(),
             new IntExpressionFactory(),
             new ShortExpressionFactory(),
             new UnsignedIntExpressionFactory(),
             new UnsignedLongExpressionFactory(),
             new UnsignedShortExpressionFactory()
         })
         .ToList();
 }
Exemplo n.º 5
0
        public Post GetDomain(PostModel model, IEnumerable <TextComponent> texts, IEnumerable <ImageComponent> images,
                              IEnumerable <CommentModel> comments = default(IEnumerable <CommentModel>))
        {
            var commentMapper = new CommentSqlMapper();

            IEnumerable <PostElement> textElements  = texts?.Select(textModel => new TextElement(textModel.Text, textModel.OrderNum));
            IEnumerable <PostElement> imageElements = images?.Select(imageModel => new ImageElement(imageModel.ImagePath, imageModel.OrderNum));
            IEnumerable <PostElement> postElements;

            if (imageElements != null)
            {
                postElements = textElements?.Concat(imageElements).ToList();
            }
            else
            {
                postElements = textElements;
            }

            return(new Post(
                       model.Id,
                       model.Title,
                       postElements?.OrderBy(item => item.Number).ToList(),
                       model.DateCreation,
                       model.DateChange,
                       model.BlogModel.UserModel.Nickname,
                       comments?.Select(comment => commentMapper.GetDomain(comment)).ToList(),
                       model.PostTag.Select(tag => tag.Tag.Title).ToList()));
        }
Exemplo n.º 6
0
 public static void DoRepackForCmd(IEnumerable<string> args)
 {
     var repackOptions = new RepackOptions(args.Concat(new[] { "/log" }));
     var repack = new ILRepacking.ILRepack(repackOptions);
     repack.Repack();
     ReloadAndCheckReferences(repackOptions);
 }
Exemplo n.º 7
0
            protected override Expression VisitExpression(Expression exp)
            {
                // Store the opinion of previously traversed node (which is most likely our left sibling or
                // alternatively the right-most child of one of our parents' left-sibling)
                var prevCanBeExecutedLocally = _canBeExecutedLocally;
                var prevUnresolvedVars = _unresolvedVars;

                // Find out the opinion of the node itself (which will typically ask its children via base.Visit
                // and will add spice it up with its own logics)
                _canBeExecutedLocally = true;
                _unresolvedVars = new List<ParameterExpression>();
                exp = base.VisitExpression(exp);

                if (exp != null)
                {
                    if (!_simplificationMap.ContainsKey(exp))
                    {
                        _simplificationMap.Add(exp, _canBeExecutedLocally && _unresolvedVars.Count() == 0);
                    }
                }

                // Restore the opinion of previously traversed node (this is important so that parent will get a
                // joint opinion of all its children, not just the very right-most one's)
                _canBeExecutedLocally &= prevCanBeExecutedLocally;
                _unresolvedVars = _unresolvedVars.Concat(prevUnresolvedVars);

                return exp;
            }
Exemplo n.º 8
0
        public DependencyContext Build(CommonCompilerOptions compilerOptions,
            IEnumerable<LibraryExport> compilationExports,
            IEnumerable<LibraryExport> runtimeExports,
            bool portable,
            NuGetFramework target,
            string runtime)
        {
            if (compilationExports == null)
            {
                compilationExports = Enumerable.Empty<LibraryExport>();
            }

            var dependencyLookup = compilationExports
                .Concat(runtimeExports)
                .Select(export => export.Library.Identity)
                .Distinct()
                .Select(identity => new Dependency(identity.Name, identity.Version.ToString()))
                .ToDictionary(dependency => dependency.Name);

            var compilationOptions = compilerOptions != null
                ? GetCompilationOptions(compilerOptions)
                : CompilationOptions.Default;

            var runtimeSignature = GenerateRuntimeSignature(runtimeExports);

            return new DependencyContext(
                new TargetInfo(target.DotNetFrameworkName, runtime, runtimeSignature, portable),
                compilationOptions,
                GetLibraries(compilationExports, dependencyLookup, runtime: false).Cast<CompilationLibrary>(),
                GetLibraries(runtimeExports, dependencyLookup, runtime: true).Cast<RuntimeLibrary>(),
                new RuntimeFallbacks[] {});
        }
Exemplo n.º 9
0
        public static IEnumerable<SymbolExpression> GetLocalSymbols(this ContainerExpression container, IEnumerable<String> locals)
        {
            var list = new List<SymbolExpression>();
            var expressions = container.Expressions;

            if (expressions != null)
            {
                var op = container.Operator as FatArrowOperator;

                if (op != null)
                {
                    var left = expressions.FirstOrDefault();
                    var right = expressions.LastOrDefault();

                    if (left != null)
                    {
                        var symbols = new List<SymbolExpression>();
                        left.CollectSymbols(symbols);
                        list.AddRange(symbols);
                        var newLocals = locals.Concat(symbols.Select(m => m.SymbolName));
                        right.CollectLocalSymbols(list, newLocals);
                    }
                }
                else
                {
                    foreach (var expression in expressions)
                    {
                        expression.CollectLocalSymbols(list, locals);
                    }
                }
            }

            return list;
        }
Exemplo n.º 10
0
        /// <summary>
        /// Get information about specified staffing identifiers
        /// </summary>
        /// <returns>Result info</returns>
        public Model.StaffingExecutionResults StaffingGetRange(IEnumerable<long> identifiers)
        {
            UpdateSessionCulture();
            using (var logSession = Helpers.Log.Session($"{GetType()}.{System.Reflection.MethodBase.GetCurrentMethod().Name}()", VerboseLog, RaiseLog))
                try
                {
                    using (var rep = GetNewRepository(logSession))
                    {
                        SRVCCheckCredentials(logSession, rep, Repository.Model.RightType.Login);

                        var res = rep.Get<Repository.Model.Staffing>(e => identifiers.Contains(e.StaffingId), asNoTracking: true)
                            .ToArray()
                            .Select(i => AutoMapper.Mapper.Map<Model.Staffing>(i))
                            .ToArray();
                        return new StaffingExecutionResults(res);
                    }
                }
                catch (Exception ex)
                {
                    ex.Data.Add(nameof(identifiers), identifiers.Concat(i => i.ToString(), ","));
                    logSession.Enabled = true;
                    logSession.Add(ex);
                    return new StaffingExecutionResults(ex);
                }
        }
        /// <inheritdoc />
        protected sealed override async Task <IEnumerable <IDocument> > ExecuteContextAsync(IExecutionContext context)
        {
            if (_forceDocumentExecution || _config.RequiresDocument)
            {
                IEnumerable <IDocument> aggregateResults = null;
                TValue value = default;

                // Only need to evaluate the config delegate once
                if (!_config.RequiresDocument)
                {
                    value = await _config.GetValueAsync(null, context);
                }

                // Iterate the inputs
                foreach (IDocument input in context.Inputs)
                {
                    // If the config requires a document, evaluate it each time
                    if (_config.RequiresDocument)
                    {
                        value = await _config.GetValueAsync(input, context);
                    }

                    // Get the results for this input document
                    IEnumerable <IDocument> results = await ExecuteInputFunc(input, context, (i, c) => ExecuteConfigAsync(i, c, value));

                    if (results != null)
                    {
                        aggregateResults = aggregateResults?.Concat(results) ?? results;
                    }
                }
                return(aggregateResults);
            }

            return(await ExecuteConfigAsync(null, context, await _config.GetValueAsync(null, context)));
        }
Exemplo n.º 12
0
 public EdiPropertyDescriptor(PropertyInfo info, IEnumerable<EdiAttribute> attributes) {
     _Info = info;
     if (attributes == null) {
         attributes = info.GetCustomAttributes<EdiAttribute>()
                          .Concat(info.PropertyType.GetTypeInfo().GetCustomAttributes<EdiAttribute>());
         if (info.PropertyType.IsCollectionType()) {
             var itemType = default(Type);
             if (info.PropertyType.HasElementType) {
                 itemType = info.PropertyType.GetElementType();
             } else {
                 itemType = Info.PropertyType.GetGenericArguments().First();
             }
             attributes = attributes.Concat(itemType.GetTypeInfo().GetCustomAttributes<EdiAttribute>());
         }
     }
     _Attributes = attributes.ToList();
     _PathInfo = Attributes.OfType<EdiPathAttribute>().FirstOrDefault();
     _ConditionInfo = Attributes.OfType<EdiConditionAttribute>().FirstOrDefault();
     _ValueInfo = Attributes.OfType<EdiValueAttribute>().FirstOrDefault();
     _SegmentGroupInfo = Attributes.OfType<EdiSegmentGroupAttribute>().FirstOrDefault();
     if (_ValueInfo != null && _ValueInfo.Path != null && _PathInfo == null) {
         _PathInfo = new EdiPathAttribute(_ValueInfo.Path);
     }
     if (_SegmentGroupInfo != null && _SegmentGroupInfo.StartInternal.Segment != null && _PathInfo == null) {
         _PathInfo = new EdiPathAttribute(_SegmentGroupInfo.StartInternal.Segment);
     }
 }
        protected override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable<Attribute> attributes) {
            _adaptersLock.EnterReadLock();

            try {
                List<ModelValidator> results = new List<ModelValidator>();

                if (AddImplicitRequiredAttributeForValueTypes &&
                        metadata.IsRequired &&
                        !attributes.Any(a => a is RequiredAttribute)) {
                    attributes = attributes.Concat(new[] { new RequiredAttribute() });
                }

                foreach (ValidationAttribute attribute in attributes.OfType<ValidationAttribute>()) {
                    DataAnnotationsModelValidationFactory factory;
                    if (!AttributeFactories.TryGetValue(attribute.GetType(), out factory)) {
                        factory = DefaultAttributeFactory;
                    }
                    results.Add(factory(metadata, context, attribute));
                }

                return results;
            }
            finally {
                _adaptersLock.ExitReadLock();
            }
        }
Exemplo n.º 14
0
        /// <summary>
        /// Downloads the results of query defined by <paramref name="parameters"/>.
        /// </summary>
        public XDocument Download(IEnumerable<HttpQueryParameterBase> parameters)
        {
            parameters = parameters.ToArray();

            if (LogDownloading)
                LogRequest(parameters);

            parameters = new[] { new HttpQueryParameter("format", "xml") }.Concat(parameters);

            if (UseMaxlag)
                parameters = parameters.Concat(new[] { new HttpQueryParameter("maxlag", "5") });

            var client = new RestClient
            {
                BaseUrl = new Uri(m_wiki.ApiUrl.AbsoluteUri + "?rawcontinue"),
                CookieContainer = m_cookies,
                UserAgent = UserAgent
            };
            var request = new RestRequest(Method.POST);

            WriteParameters(parameters, request);

            var response = client.Execute(request);

            return XDocument.Parse(response.Content);
        }
Exemplo n.º 15
0
        public static IEnumerable <T> GetEntities <T>(TableQuery <T> query, string tableName) where T : ITableEntity, new()
        {
            if (query == null)
            {
                return(null);
            }

            var table = CreateOrGetTable(tableName);

            if (table == null)
            {
                return(null);
            }

            TableContinuationToken continuationToken = null;
            IEnumerable <T>        results           = null;

            do
            {
                var token  = continuationToken;
                var result = table.ExecuteQuerySegmented(query, token);
                results = results?.Concat(result.Results) ?? result;

                continuationToken = result.ContinuationToken;
            }while (continuationToken != null);

            return(results);
        }
Exemplo n.º 16
0
        public IDictionary<string, IList<FileDetails>> UploadMultipleList(IEnumerable<IFormFile> filelist1,
                                                                     IEnumerable<IFormFile> filelist2)
        {
            var fileDetailsDict = new Dictionary<string, IList<FileDetails>>
            {
                { "filelist1", new List<FileDetails>() },
                { "filelist2", new List<FileDetails>() }
            };
            var fileDetailsList = new List<FileDetails>();
            foreach (var file in filelist1.Concat(filelist2))
            {
                var parsedContentDisposition = ContentDispositionHeaderValue.Parse(file.ContentDisposition);
                using (var reader = new StreamReader(file.OpenReadStream()))
                {
                    var fileContent = reader.ReadToEnd();
                    var fileDetails = new FileDetails
                    {
                        Filename = parsedContentDisposition.FileName,
                        Content = fileContent
                    };
                    fileDetailsDict[parsedContentDisposition.Name].Add(fileDetails);
                }
            }

            return fileDetailsDict;
        }
Exemplo n.º 17
0
 IEnumerable<ICommandOutput> SetRemoteRepositories()
 {
     _remoteRepositories = new[] { HostEnvironment.CurrentDirectoryRepository, HostEnvironment.SystemRepository }
         .Concat(Remotes.FetchRepositories());
     if (HostEnvironment.ProjectRepository != null)
         _remoteRepositories = _remoteRepositories.Concat(new[] { HostEnvironment.ProjectRepository });
     yield break;
 }
Exemplo n.º 18
0
		private GenericAction(String name, IEnumerable<IObjectTreeNode> attributes, IEnumerable<IObjectTreeNode> elements)
		{
			_name = name;

			Children = attributes
				.Concat(elements)
				.ToList();
		}
Exemplo n.º 19
0
            public IEnumerable <CompilerReference> GetReferences(TypeContext context, IEnumerable <CompilerReference> includeAssemblies = null)
            {
                var newReference = new[] { CompilerReference.From(SystemRuntime), };

                var assemblies = includeAssemblies?.Concat(newReference) ?? newReference;

                return(Resolver.GetReferences(context, assemblies));
            }
Exemplo n.º 20
0
        public IEnumerable<string> ProduceSubKeys(IEnumerable<string> earlierKeys, string prefix, string delimiter)
        {
            // TODO: ProduceSubKeys method signature is pretty bad

            if (prefix == "" && delimiter == ":")
            {
                return earlierKeys.Concat(new[] { "Hardcoded" });
            }
            if (prefix == "Hardcoded:" && delimiter == ":")
            {
                return earlierKeys.Concat(new[] { "1", "2" });
            }
            if (prefix == "Hardcoded:1:" || prefix == "Hardcoded:2:")
            {
                return earlierKeys.Concat(new[] { "Caption" });
            }
            return earlierKeys;
        }
        //TODO: Add null showList parametr concatenation
        private void AddExtMethodsToMethodShowListOfSelectedType(ref IEnumerable <string> showList)
        {
            IEnumerable <string> extensionMethodsDeclarations = AssemblyTypesInfo.GetExtensionMethods(selectedType)?.Select(mi => mi.GetDeclaration()).ToList();

            if (extensionMethodsDeclarations != null)
            {
                showList = showList?.Concat(extensionMethodsDeclarations).ToList();
            }
        }
Exemplo n.º 22
0
 //review: is this even used, since we override GetSearchPaths()?
 public BloomFileLocator(CollectionSettings collectionSettings, XMatterPackFinder xMatterPackFinder, IEnumerable<string> factorySearchPaths, IEnumerable<string> userInstalledSearchPaths)
     : base(factorySearchPaths.Concat( userInstalledSearchPaths))
 {
     _bookSpecificSearchPaths = new List<string>();
     _collectionSettings = collectionSettings;
     _xMatterPackFinder = xMatterPackFinder;
     _factorySearchPaths = factorySearchPaths;
     _userInstalledSearchPaths = userInstalledSearchPaths;;
 }
Exemplo n.º 23
0
 private static IEnumerable<string> Combine(IEnumerable<string> @new, IEnumerable<string> old)
 {
     if (@new != null)
     {
         old = old ?? EmptyArray<string>.Value;
         return old.Concat(@new).Distinct().ToArray();
     }
     return old;
 }
 protected override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable<System.Attribute> attributes)
 {
     if(metadata.Model is Member)
     {
         var model = metadata.Model as Member;
         attributes = attributes.Concat(model.Attributes);
     }
     return base.GetValidators(metadata, context, attributes);
 }
        void AndGivenAPackageForANewerVersionOfTheApp()
        {
            _package = Packages.FromVersions(TestConstants.AppPackageId, new Version(1, 1)).Single();
            _appFiles = GetAppFileSubstitutes("app", "app.exe", "app.exe.config", "nuget.dll", @"content\logo.png").ToArray();
            _otherFiles = GetAppFileSubstitutes("", "README.md").ToArray();

            var packageFiles = _appFiles.Concat(_otherFiles);
            _package.GetFiles().Returns(packageFiles);
        }
Exemplo n.º 26
0
        /// <summary>
        /// Loads the plugins.
        /// </summary>
        public void LoadPlugins()
        {
            LoadedPluginTypes = new Collections.AsyncObservableCollection<Type>();

            foreach (System.Reflection.Assembly assembly in getAssemblies())
            {
                LoadedPluginTypes = LoadedPluginTypes.Concat(assembly.GetTypes().Where(x => x.IsSubclassOf(typeof(EasySocial.FrameWork.Plugins.BasePlugin))));
            }
        }
Exemplo n.º 27
0
        private static CSharpCompilation CreateCompilation(string source, IEnumerable<MetadataReference> references = null, CSharpCompilationOptions options = null)
        {
            options = options ?? TestOptions.ReleaseExe;

            IEnumerable<MetadataReference> asyncRefs = new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef };
            references = (references != null) ? references.Concat(asyncRefs) : asyncRefs;

            return CreateCompilationWithMscorlib45(source, options: options, references: references);
        }
Exemplo n.º 28
0
		/// <summary>
		/// Add specified search pathes to environment variable PATH
		/// </summary>
		/// <param name="searchPath">pathes to add</param>
		public static void AddEnvironmentPath(IEnumerable<string> searchPath) {
			searchPath = searchPath.Select(x => x.Trim()).ToArray();
			string pathVar = Environment.GetEnvironmentVariable("PATH") ?? string.Empty;
			var pathes = pathVar.Split(';').Select(x=>x.Trim());
			Environment.SetEnvironmentVariable("PATH", 
				String.Join(";", 
					searchPath.Concat(pathes.Where(x => !searchPath.Contains(x)))
				)
			);
		}
Exemplo n.º 29
0
 private async Task<JToken> CallApiMethod(string methodName, IEnumerable<KeyValuePair<string, string>> parameters)
 {
     var response = JObject.Parse(await WebHelper.PostRequest($"https://api.vk.com/method/{methodName}", 
         parameters.Concat(constantMethodParameters)));
     if(response["error"] != null)
     {
         throw new VkApiException(response["error"]);
     }
     return response["response"];
 }
        protected override IEnumerable<SelectedMemberInfo> OnSelectMembers(IEnumerable<SelectedMemberInfo> selectedMembers,
            string currentPath, ISubjectInfo context)
        {
            var matchingMembers =
                from member in context.RuntimeType.GetNonPrivateMembers()
                where pathToInclude.StartsWith(currentPath.Combine(member.Name))
                select member;

            return selectedMembers.Concat(matchingMembers).ToArray();
        }
Exemplo n.º 31
0
        public static IEnumerable<Tag> Affix(this IEnumerable<Tag> tags, IEnumerable<Tag> other)
        {
            // Union works with equality [http://www.healthintersections.com.au/?p=1941]
            // the other should overwrite the existing tags, so the union starts with other.

            IEnumerable<Tag> original = tags.Except(other);
            return other.Concat(original).FilterOnFhirSchemes();

            //return other.Union(tags).FilterOnFhirSchemes();
        }
Exemplo n.º 32
0
        private List <string> DependencyErrors()
        {
            IEnumerable <string> result = null;

            foreach (var dep in _dependencies)
            {
                var other = dep();
                result = result?.Concat(other) ?? other;
            }
            return(result?.ToList() ?? new List <string>());
        }
Exemplo n.º 33
0
        public static IEnumerable<SortingInfo> AddRequiredSort(IEnumerable<SortingInfo> sort, IEnumerable<string> requiredSelectors) {
            sort = sort ?? new SortingInfo[0];
            requiredSelectors = requiredSelectors.Except(sort.Select(i => i.Selector));

            var desc = sort.LastOrDefault()?.Desc;

            return sort.Concat(requiredSelectors.Select(i => new SortingInfo {
                Selector = i,
                Desc = desc != null && desc.Value
            }));
        }
Exemplo n.º 34
0
        private CSharpCompilation CreateCompilation(string source, IEnumerable<MetadataReference> references = null, CSharpCompilationOptions compOptions = null)
        {
            SynchronizationContext.SetSynchronizationContext(null);

            compOptions = compOptions ?? TestOptions.OptimizedExe;

            IEnumerable<MetadataReference> asyncRefs = new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef };
            references = (references != null) ? references.Concat(asyncRefs) : asyncRefs;

            return CreateCompilationWithMscorlib45(source, compOptions: compOptions, references: references);
        }
Exemplo n.º 35
0
        private void GenerateList(Site site, Page page, ref IEnumerable<Page> pageList)
        {
            var children = Kooboo.CMS.Sites.Services.ServiceFactory.PageManager.ChildPages(site, page.FullName, null);

            pageList = pageList.Concat(children);

            foreach (var s in children)
            {
                this.GenerateList(site, s, ref pageList);
            }
        }
Exemplo n.º 36
0
        public void Update(ShellSettings settings) {
            _shells = _shells
                .Where(s => s.Name != settings.Name)
                .ToArray();

            _shells = _shells
                .Concat(new[] { settings })
                .ToArray();

            Organize();
        }
Exemplo n.º 37
0
        private IEnumerable <T> Excavate <T>(Type type, Func <Type, IEnumerable <T> > excavator)
        {
            IEnumerable <T> excavated = null;

            while (type != null && type.BaseType != null)
            {
                IEnumerable <T> batch = excavator(type);
                excavated = (excavated?.Concat(batch) ?? batch);
                type      = type.BaseType;;
            }
            return(excavated);
        }
Exemplo n.º 38
0
 public static CSharpCompilation CreateCompilationWithMscorlibAndDocumentationComments(
     string text,
     IEnumerable <MetadataReference> references = null,
     CSharpCompilationOptions options           = null,
     string assemblyName = "Test")
 {
     return(CreateCompilation(
                new[] { Parse(text, options: TestOptions.RegularWithDocumentationComments) },
                references: references?.Concat(s_mscorlibRefArray) ?? s_mscorlibRefArray,
                options: (options ?? TestOptions.ReleaseDll).WithXmlReferenceResolver(XmlFileResolver.Default),
                assemblyName: assemblyName));
 }
Exemplo n.º 39
0
        public static IEnumerable <T> Excavate <T>(this Type type, Func <Type, IEnumerable <T> > excavator)
        {
            IEnumerable <T> excavated = null;

            while (type != null)
            {
                IEnumerable <T> batch = excavator(type);
                excavated = excavated?.Concat(batch) ?? batch;
                type      = type.BaseType;
            }
            return(excavated);
        }
        public static string GetValidationResultsText(IValidatableEntity validatableEntity, IEnumerable <IValidationResult> customResults = null)
        {
            var returnValue           = new StringBuilder();
            var validationResultIndex = 0;

            customResults?.Concat(GetValidationResults(validatableEntity, ObjectVisitationHelper.CreateInstance())).Each(vr =>
            {
                returnValue.AppendFormat(ValidationResultFormat, vr.Description, validationResultIndex + 1, Environment.NewLine);
                validationResultIndex++;
            });

            return(returnValue.ToString());
        }
Exemplo n.º 41
0
        /// <summary>
        /// Executes the module once for all input documents.
        /// </summary>
        /// <remarks>
        /// Override this method to execute the module once for all input documents. The default behavior
        /// calls <see cref="ExecuteInputAsync(IDocument, IExecutionContext)"/> for each input document
        /// and overriding this method will result in <see cref="ExecuteInputAsync(IDocument, IExecutionContext)"/>
        /// not being called.
        /// </remarks>
        /// <param name="context">The execution context.</param>
        /// <returns>The result documents.</returns>
        protected virtual async Task <IEnumerable <IDocument> > ExecuteContextAsync(IExecutionContext context)
        {
            IEnumerable <IDocument> aggregateResults = null;

            foreach (IDocument input in context.Inputs)
            {
                IEnumerable <IDocument> results = await ExecuteInputFunc(input, context, ExecuteInputAsync);

                if (results != null)
                {
                    aggregateResults = aggregateResults?.Concat(results) ?? results;
                }
            }
            return(aggregateResults);
        }
Exemplo n.º 42
0
        /// <summary>
        ///     Create a regex to find a resource in an assembly
        /// </summary>
        /// <param name="assembly">Assembly to look into</param>
        /// <param name="filePath">string with the filepath to find</param>
        /// <param name="ignoreCase">true, which is default, to ignore the case when comparing</param>
        /// <param name="alternativeExtensions">Besides the specified extension in the filePath, these are also allowed</param>
        /// <returns>Regex</returns>
        private Regex ResourceRegex(Assembly assembly, string filePath, bool ignoreCase = true, IEnumerable <string> alternativeExtensions = null)
        {
            // Resources don't have directory separators, they use ., fix this before creating a regex
            var resourcePath = filePath.Replace(Path.DirectorySeparatorChar, '.').Replace(Path.AltDirectorySeparatorChar, '.');
            // First get the extension to build the regex
            // TODO: this doesn't work 100% for double extensions like .png.gz etc but I will only fix this as soon as it's really needed
            var extensions = alternativeExtensions?.Concat(new[] { Path.GetExtension(filePath) }) ?? new[] { Path.GetExtension(filePath) };
            // Than get the filename without extension
            var filename = Path.GetFileNameWithoutExtension(resourcePath);
            // Assembly resources CAN have a prefix with the type namespace, use this instead of the default
            var prefix = $@"^({assembly.GetName().Name.Replace(".", @"\.")}\.)?";

            // build the regex
            return(FileTools.FilenameToRegex(filename, extensions, ignoreCase, prefix));
        }
Exemplo n.º 43
0
        public async Task SendNotificationsAsync(IReadOnlyCollection <INotification> notifications)
        {
            IEnumerable <WrappedFcmNotification> fcmNotifications = null;

            foreach (IFcmNotificationFormatter formatter in pushNotificationFormatters)
            {
                IEnumerable <WrappedFcmNotification> pushNotifications = await formatter.FormatPushNotification(notifications);

                fcmNotifications = fcmNotifications?.Concat(pushNotifications) ?? pushNotifications;
            }

            if (fcmNotifications != null)
            {
                fcmBrokerDispatcher.QueueNotifications(fcmNotifications);
            }
        }
Exemplo n.º 44
0
        public async Task SendNotificationsAsync(IEnumerable <INotification> notifications)
        {
            IEnumerable <WrappedApnsNotification> apnsNotifications = null;

            foreach (IApnsNotificationFormatter formatter in pushNotificationFormatters)
            {
                IEnumerable <WrappedApnsNotification> pushNotifications = await formatter.FormatPushNotification(notifications);

                apnsNotifications = apnsNotifications?.Concat(pushNotifications) ?? pushNotifications;
            }

            if (apnsNotifications != null)
            {
                apnsBrokerDispatcher.QueueNotifications(apnsNotifications);
            }
        }
Exemplo n.º 45
0
        /// <inheritdoc />
        protected sealed override async Task <IEnumerable <IDocument> > ExecuteContextAsync(IExecutionContext context)
        {
            if (ForceDocumentExecution || Configs.Any(x => x.Value.RequiresDocument))
            {
                // Only need to evaluate the context config delegates once
                ImmutableDictionary <string, object> .Builder configValuesBuilder = ImmutableDictionary.CreateBuilder <string, object>(StringComparer.OrdinalIgnoreCase);
                foreach (KeyValuePair <string, IConfig> config in Configs.Where(x => !x.Value.RequiresDocument))
                {
                    configValuesBuilder[config.Key] = await config.Value.GetValueAsync(null, context);
                }
                ImmutableDictionary <string, object> configValues = configValuesBuilder.ToImmutable();

                // Iterate the inputs
                IEnumerable <IDocument> aggregateResults = null;
                foreach (IDocument input in context.Inputs)
                {
                    // If the config requires a document, evaluate it each time
                    ImmutableDictionary <string, object> .Builder valuesBuilder = configValues.ToBuilder();
                    foreach (KeyValuePair <string, IConfig> config in Configs.Where(x => x.Value.RequiresDocument))
                    {
                        valuesBuilder[config.Key] = await config.Value.GetValueAsync(input, context);
                    }

                    // Get the results for this input document
                    IMetadata values = new ReadOnlyConvertingDictionary(valuesBuilder.ToImmutable());
                    IEnumerable <IDocument> results = await ExecuteInputFuncAsync(input, context, (i, c) => ExecuteConfigAsync(i, c, values));

                    if (results != null)
                    {
                        aggregateResults = aggregateResults?.Concat(results) ?? results;
                    }
                }
                return(aggregateResults);
            }
            else
            {
                // Only context configs
                ImmutableDictionary <string, object> .Builder valuesBuilder = ImmutableDictionary.CreateBuilder <string, object>();
                foreach (KeyValuePair <string, IConfig> config in Configs)
                {
                    valuesBuilder[config.Key] = await config.Value.GetValueAsync(null, context);
                }
                IMetadata values = new ReadOnlyConvertingDictionary(valuesBuilder.ToImmutable());
                return(await ExecuteConfigAsync(null, context, values));
            }
        }
Exemplo n.º 46
0
        /// <inheritdoc />
        protected sealed override async Task <IEnumerable <IDocument> > ExecuteContextAsync(IExecutionContext context)
        {
            if (_forceDocumentExecution || _config.RequiresDocument)
            {
                // Only need to evaluate a context config delegate once
                TValue contextValue = default;
                if (!_config.RequiresDocument)
                {
                    contextValue = await _config.GetValueAsync(null, context);
                }

                // Parallel
                if (Parallel && !context.SerialExecution)
                {
                    return(await context.Inputs.ParallelSelectManyAsync(
                               async input =>
                    {
                        TValue value = _config.RequiresDocument
                                ? await _config.GetValueAsync(input, context)
                                : contextValue;
                        return await ExecuteInputFuncAsync(input, context, (i, c) => ExecuteConfigAsync(i, c, value));
                    },
                               context.CancellationToken));
                }

                // Not parallel
                IEnumerable <IDocument> aggregateResults = null;
                foreach (IDocument input in context.Inputs)
                {
                    TValue value = _config.RequiresDocument
                        ? await _config.GetValueAsync(input, context)
                        : contextValue;

                    IEnumerable <IDocument> results = await ExecuteInputFuncAsync(input, context, (i, c) => ExecuteConfigAsync(i, c, value));

                    if (results != null)
                    {
                        aggregateResults = aggregateResults?.Concat(results) ?? results;
                    }
                }
                return(aggregateResults);
            }

            return(await ExecuteConfigAsync(null, context, await _config.GetValueAsync(null, context)));
        }
Exemplo n.º 47
0
        public static List <string> GetDirectoriesFromRootPath(string rootPath, BackgroundWorker worker = null)
        {
            if (!Directory.Exists(rootPath))
            {
                return(null);
            }

            IEnumerable <string> directories = GetDirectoriesFromPath(rootPath, worker) ?? new List <string>();

            foreach (var directory in directories.Where(dir => !Regex.Match(dir, "\\.git").Success))
            {
                var recursiveYield = GetDirectoriesFromRootPath(directory, worker);
                directories = recursiveYield != null
                    ? directories?.Concat(recursiveYield).ToList()
                    : null;
            }

            return(directories?.ToList());
        }
Exemplo n.º 48
0
        private static IEnumerable <JToken> GetFlattenedObjects(JToken token, IEnumerable <JProperty> otherProperties = null)
        {
            if (token is JObject obj)
            {
                var children = obj.Children <JProperty>().GroupBy(prop => prop.Value?.Type == JTokenType.Array).ToDictionary(gr => gr.Key);
                if (children.TryGetValue(false, out var directProps))
                {
                    otherProperties = otherProperties?.Concat(directProps) ?? directProps;
                }

                if (children.TryGetValue(true, out var ChildCollections))
                {
                    foreach (var childObj in ChildCollections.SelectMany(childColl => childColl.Values()).SelectMany(childColl => GetFlattenedObjects(childColl, otherProperties)))
                    {
                        yield return(childObj);
                    }
                }
                else
                {
                    var res = new JObject();
                    if (otherProperties != null)
                    {
                        foreach (var prop in otherProperties)
                        {
                            res.Add(prop);
                        }
                    }
                    yield return(res);
                }
            }
            else if (token is JArray arr)
            {
                foreach (var co in token.Children().SelectMany(c => GetFlattenedObjects(c, otherProperties)))
                {
                    yield return(co);
                }
            }
            else
            {
                throw new NotImplementedException(token.GetType().Name);
            }
        }
Exemplo n.º 49
0
        public NsaProvider(INsaReader[] nsaReaders, INsiReader[] nsiReaders)
        {
            _nsaReaders = nsaReaders;
            _nsiReaders = nsiReaders;

            IEnumerable <GenomeAssembly> assemblies = null;

            if (_nsaReaders != null)
            {
                DataSourceVersions = _nsaReaders.Select(x => x.Version);
                assemblies         = _nsaReaders.Select(x => x.Assembly);
            }

            if (_nsiReaders != null)
            {
                assemblies         = assemblies?.Concat(_nsiReaders.Select(x => x.Assembly)) ?? _nsiReaders.Select(x => x.Assembly);
                DataSourceVersions = DataSourceVersions?.Concat(_nsiReaders.Select(x => x.Version)) ?? _nsiReaders.Select(x => x.Version);
            }

            var distinctAssemblies = assemblies?.Where(x => GenomeAssemblyHelper.AutosomeAndAllosomeAssemblies.Contains(x)).Distinct().ToArray();

            if (distinctAssemblies == null || distinctAssemblies.Length > 1)
            {
                if (_nsaReaders != null)
                {
                    foreach (INsaReader nsaReader in _nsaReaders)
                    {
                        Console.WriteLine(nsaReader.Version + "\tAssembly:" + nsaReader.Assembly);
                    }
                }
                if (_nsiReaders != null)
                {
                    foreach (INsiReader nsiReader in _nsiReaders)
                    {
                        Console.WriteLine(nsiReader.Version + "\tAssembly:" + nsiReader.Assembly);
                    }
                }
                throw new UserErrorException("Multiple genome assemblies detected in Supplementary annotation directory");
            }

            Assembly = distinctAssemblies[0];
        }
Exemplo n.º 50
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            var categoryType = Autodesk.Revit.DB.CategoryType.Invalid;
            {
                var categoryValue = (int)categoryType;
                DA.GetData("Type", ref categoryValue);
                categoryType = (Autodesk.Revit.DB.CategoryType)categoryValue;
            }

            bool AllowsParameters = false;
            bool nofilterParams   = (!DA.GetData("AllowsParameters", ref AllowsParameters) && Params.Input[1].Sources.Count == 0);

            bool HasMaterialQuantities = false;
            bool nofilterMaterials     = (!DA.GetData("HasMaterialQuantities", ref HasMaterialQuantities) && Params.Input[2].Sources.Count == 0);

            var categories = Revit.ActiveDBDocument.Settings.Categories.Cast <Category>();

            if (categoryType != Autodesk.Revit.DB.CategoryType.Invalid)
            {
                categories = categories.Where((x) => x.CategoryType == categoryType);
            }

            if (!nofilterParams)
            {
                categories = categories.Where((x) => x.AllowsBoundParameters == AllowsParameters);
            }

            if (!nofilterMaterials)
            {
                categories = categories.Where((x) => x.HasMaterialQuantities == HasMaterialQuantities);
            }

            IEnumerable <Category> list = null;

            foreach (var group in categories.GroupBy((x) => x.CategoryType).OrderBy((x) => x.Key))
            {
                var orderedGroup = group.OrderBy((x) => x.Name);
                list = list?.Concat(orderedGroup) ?? orderedGroup;
            }

            DA.SetDataList("Categories", list);
        }
Exemplo n.º 51
0
        /// <summary>
        /// Get Test Case Members for a class.  If the class has 'test*' tests
        /// return those.  If there aren't any 'test*' tests return (if one at
        /// all) the runTest overridden method
        /// </summary>
        private static IEnumerable <KeyValuePair <string, LocationInfo> > GetTestCaseMembers(
            PythonAst ast,
            string sourceFile,
            Uri documentUri,
            ModuleAnalysis analysis,
            AnalysisValue classValue
            )
        {
            IEnumerable <KeyValuePair <string, LocationInfo> > tests = null, runTest = null;

            if (ast != null && !string.IsNullOrEmpty(sourceFile))
            {
                var walker = new TestMethodWalker(ast, sourceFile, documentUri, classValue.Locations);
                ast.Walk(walker);
                tests   = walker.Methods.Where(v => v.Key.StartsWithOrdinal("test"));
                runTest = walker.Methods.Where(v => v.Key.Equals("runTest"));
            }

            var methodFunctions = classValue.GetAllMembers(analysis.InterpreterContext)
                                  .Where(v => v.Value.Any(m => m.MemberType == PythonMemberType.Function || m.MemberType == PythonMemberType.Method))
                                  .Select(v => new KeyValuePair <string, LocationInfo>(v.Key, v.Value.SelectMany(av => av.Locations).FirstOrDefault(l => l != null)));

            var analysisTests = methodFunctions.Where(v => v.Key.StartsWithOrdinal("test"));
            var analysisRunTest = methodFunctions.Where(v => v.Key.Equals("runTest"));

            tests   = tests?.Concat(analysisTests) ?? analysisTests;
            runTest = runTest?.Concat(analysisRunTest) ?? analysisRunTest;

            if (tests.Any())
            {
                return(tests);
            }
            else
            {
                return(runTest);
            }
        }
Exemplo n.º 52
0
        /// <summary>
        /// Initializes the Covalence library
        /// </summary>
        internal void Initialize()
        {
            // Search for all provider types
            var baseType = typeof(ICovalenceProvider);
            IEnumerable <Type> candidateSet = null;

            foreach (var ass in AppDomain.CurrentDomain.GetAssemblies())
            {
                Type[] assTypes = null;
                try
                {
                    assTypes = ass.GetTypes();
                }
                catch (ReflectionTypeLoadException rtlEx)
                {
                    assTypes = rtlEx.Types;
                }
                catch (TypeLoadException tlEx)
                {
                    logger.Write(LogType.Warning, "Covalence: Type {0} could not be loaded from assembly '{1}': {2}", tlEx.TypeName, ass.FullName, tlEx);
                }
                if (assTypes != null)
                {
                    candidateSet = candidateSet?.Concat(assTypes) ?? assTypes;
                }
            }
            if (candidateSet == null)
            {
                logger.Write(LogType.Warning, "No Covalence providers found, Covalence will not be functional for this session.");
                return;
            }
            var candidates = new List <Type>(
                candidateSet.Where(t => t != null && t.IsClass && !t.IsAbstract && t.FindInterfaces((m, o) => m == baseType, null).Length == 1)
                );

            // Select a candidate
            Type selectedCandidate;

            if (candidates.Count == 0)
            {
                logger.Write(LogType.Warning, "No Covalence providers found, Covalence will not be functional for this session.");
                return;
            }
            if (candidates.Count > 1)
            {
                selectedCandidate = candidates[0];
                var sb = new StringBuilder();
                for (var i = 1; i < candidates.Count; i++)
                {
                    if (i > 1)
                    {
                        sb.Append(',');
                    }
                    sb.Append(candidates[i].FullName);
                }
                logger.Write(LogType.Warning, "Multiple Covalence providers found! Using {0}. (Also found {1})", selectedCandidate, sb);
            }
            else
            {
                selectedCandidate = candidates[0];
            }

            // Create it
            try
            {
                provider = (ICovalenceProvider)Activator.CreateInstance(selectedCandidate);
            }
            catch (Exception ex)
            {
                logger.Write(LogType.Warning, "Got exception when instantiating Covalence provider, Covalence will not be functional for this session.");
                logger.Write(LogType.Warning, "{0}", ex);
                return;
            }

            // Create mediators
            Server    = provider.CreateServer();
            Players   = provider.CreatePlayerManager();
            cmdSystem = provider.CreateCommandSystemProvider();

            // Initialize other things
            commands = new Dictionary <string, RegisteredCommand>();

            // Log
            logger.Write(LogType.Info, "Using Covalence provider for game '{0}'", provider.GameName);
        }
Exemplo n.º 53
0
 /// <summary>
 /// Appends the given objects to the original array source.
 /// </summary>
 /// <typeparam name="T">The specified type of the array</typeparam>
 /// <param name="source">The original array of values</param>
 /// <param name="toAdd">The values to append to the source.</param>
 /// <returns>The concatenated array of the specified type</returns>
 public static T[] Append <T>(this IEnumerable <T> source, params T[] toAdd) => source?.Concat(toAdd).ToArray();
Exemplo n.º 54
0
        private static IEnumerable <TResult> DoPagingQuery <TDb, TResult>(IReadOnlyList <TDb> dbs, Func <TDb, IQueryable <TResult> > query,
                                                                          int skip, int take, bool withCount, out int count) where TDb : ShardingDbContext
        {
            count = 0;
            if (take >= 10000 && withCount)
            {
                withCount = false;                             //查询大结果集时,不再计算总数
            }
            if (dbs.Count < 1)
            {
                return(new List <TResult>());
            }
            //单个分区时
            if (dbs.Count == 1)
            {
                var qr = query(dbs[0]);
                if (withCount)
                {
                    count = qr.Count();
                }
                return(skip == 0 ? qr.Take(take) : qr.Skip(skip).Take(take));
            }

            //跨分区查询
            var skipCount             = 0; //前面分区已经Skip数量
            var resCount              = 0;
            IEnumerable <TResult> res = null;

            foreach (var db in dbs)
            {
                var curQr = query(db);
                //统计总数
                var curAmount = 0; //当前分区总结果数
                if (withCount)
                {
                    curAmount = curQr.Count();
                    count    += curAmount;
                }
                if (resCount >= take)
                {
                    continue;                   //已查完结果,继续以统计总数
                }
                //当前结果集
                var curSkip = skip - skipCount;
                var curTake = take - resCount;
                var curRes  = (curSkip <= 0 ? curQr.Take(curTake) : curQr.Skip(curSkip).Take(curTake)).ToList();
                resCount += curRes.Count;
                res       = res?.Concat(curRes) ?? curRes;

                //是否查完结果
                if (resCount >= take)
                {
                    if (withCount)
                    {
                        continue;
                    }
                    break;
                }
                //计算skipCount
                if (curSkip <= 0)
                {
                    continue;
                }
                if (curRes.Count > 0)
                {
                    skipCount += curSkip;                   //有结果则肯定执行了skip
                }
                else //无结果则skip了当前分区结果数
                {
                    if (!withCount)
                    {
                        curAmount = curQr.Count();
                    }
                    skipCount += curAmount;
                }
            }

            return(res);
        }
Exemplo n.º 55
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            var categoryType = DB.CategoryType.Invalid;

            DA.GetData("Type", ref categoryType);

            bool AllowsParameters = false;
            bool nofilterParams   = (!DA.GetData("AllowsParameters", ref AllowsParameters) && Params.Input[1].Sources.Count == 0);

            bool HasMaterialQuantities = false;
            bool nofilterMaterials     = (!DA.GetData("HasMaterialQuantities", ref HasMaterialQuantities) && Params.Input[2].Sources.Count == 0);

            bool Cuttable         = false;
            bool nofilterCuttable = (!DA.GetData("Cuttable", ref Cuttable) && Params.Input[3].Sources.Count == 0);

            bool Hidden         = false;
            bool nofilterHidden = (!DA.GetData("Hidden", ref Hidden) && Params.Input[4].Sources.Count == 0);

            var categories = Revit.ActiveDBDocument.Settings.Categories.Cast <DB.Category>();

            if (categoryType != DB.CategoryType.Invalid)
            {
                categories = categories.Where((x) => x.CategoryType == categoryType);
            }

            if (!nofilterParams)
            {
                categories = categories.Where((x) => x.AllowsBoundParameters == AllowsParameters);
            }

            if (!nofilterMaterials)
            {
                categories = categories.Where((x) => x.HasMaterialQuantities == HasMaterialQuantities);
            }

            if (!nofilterCuttable)
            {
                categories = categories.Where((x) => x.IsCuttable == Cuttable);
            }

            if (!nofilterHidden)
            {
                categories = categories.Where((x) => x.IsHidden() == Hidden);
            }

            IEnumerable <DB.Category> list = null;

            foreach (var group in categories.GroupBy((x) => x.CategoryType).OrderBy((x) => x.Key))
            {
                var orderedGroup = group.OrderBy((x) => x.Name);
                list = list?.Concat(orderedGroup) ?? orderedGroup;
            }

            if (list is object)
            {
                DA.SetDataList("Categories", list);
            }
            else
            {
                DA.DisableGapLogic();
            }
        }
Exemplo n.º 56
0
 private static IEnumerable <ChannelProperty> AppendDataType(IEnumerable <ChannelProperty> source, ValueDataTypeProperty dataTypeProperty)
 {
     return(source?.Concat(new[] { dataTypeProperty }));
 }
Exemplo n.º 57
0
 public static IEnumerable <T> Append <T>(this IEnumerable <T> list, T item)
 {
     return(list?.Concat(new[] { item }) ?? new[] { item });
 }
Exemplo n.º 58
0
        protected override void TrySolveInstance(IGH_DataAccess DA, DB.Document doc)
        {
            var categoryType = DB.CategoryType.Invalid;

            DA.GetData("Type", ref categoryType);

            var  Parent           = default(DB.Category);
            var  _Parent_         = Params.IndexOfInputParam("Parent");
            bool nofilterParent   = (!DA.GetData(_Parent_, ref Parent) && Params.Input[_Parent_].DataType == GH_ParamData.@void);
            var  ParentCategoryId = Parent?.Id ?? DB.ElementId.InvalidElementId;

            var  Name         = default(string);
            var  _Name_       = Params.IndexOfInputParam("Name");
            bool nofilterName = (!DA.GetData(_Name_, ref Name) && Params.Input[_Name_].DataType == GH_ParamData.@void);

            bool AllowsSubcategories   = false;
            var  _AllowsSubcategories_ = Params.IndexOfInputParam("AllowsSubcategories");
            bool nofilterSubcategories = (!DA.GetData(_AllowsSubcategories_, ref AllowsSubcategories) && Params.Input[_AllowsSubcategories_].DataType == GH_ParamData.@void);

            bool AllowsParameters   = false;
            var  _AllowsParameters_ = Params.IndexOfInputParam("AllowsParameters");
            bool nofilterParams     = (!DA.GetData(_AllowsParameters_, ref AllowsParameters) && Params.Input[_AllowsParameters_].DataType == GH_ParamData.@void);

            bool HasMaterialQuantities   = false;
            var  _HasMaterialQuantities_ = Params.IndexOfInputParam("HasMaterialQuantities");
            bool nofilterMaterials       = (!DA.GetData(_HasMaterialQuantities_, ref HasMaterialQuantities) && Params.Input[_HasMaterialQuantities_].DataType == GH_ParamData.@void);

            bool Cuttable         = false;
            var  _Cuttable_       = Params.IndexOfInputParam("Cuttable");
            bool nofilterCuttable = (!DA.GetData(_Cuttable_, ref Cuttable) && Params.Input[_Cuttable_].DataType == GH_ParamData.@void);

            var categories = nofilterParent || !ParentCategoryId.IsValid() ?
                             BuiltInCategoryExtension.BuiltInCategories.Select(x => doc.GetCategory(x)).Where(x => x is object && x.Parent is null) :
                             DB.Category.GetCategory(doc, ParentCategoryId).SubCategories.Cast <DB.Category>();

            if (categoryType != DB.CategoryType.Invalid)
            {
                categories = categories.Where((x) => x.CategoryType == categoryType);
            }

            if (!nofilterSubcategories)
            {
                categories = categories.Where((x) => x.CanAddSubcategory == AllowsSubcategories);
            }

            if (!nofilterParams)
            {
                categories = categories.Where((x) => x.AllowsBoundParameters == AllowsParameters);
            }

            if (!nofilterMaterials)
            {
                categories = categories.Where((x) => x.HasMaterialQuantities == HasMaterialQuantities);
            }

            if (!nofilterCuttable)
            {
                categories = categories.Where((x) => x.IsCuttable == Cuttable);
            }

            if (!nofilterName)
            {
                categories = categories.Where((x) => x.Name.IsSymbolNameLike(Name));
            }

            IEnumerable <DB.Category> list = null;

            foreach (var group in categories.GroupBy((x) => x.CategoryType).OrderBy((x) => x.Key))
            {
                var orderedGroup = group.OrderBy((x) => x.Name);
                list = list?.Concat(orderedGroup) ?? orderedGroup;
            }

            if (list is object)
            {
                DA.SetDataList("Categories", list);
            }
            else
            {
                DA.DisableGapLogic();
            }
        }
Exemplo n.º 59
0
        public NsaProvider(INsaReader[] nsaReaders, INsiReader[] nsiReaders)
        {
            _nsaReaders = nsaReaders;
            _nsiReaders = nsiReaders;

            IEnumerable <GenomeAssembly> assemblies = null;

            if (_nsaReaders != null)
            {
                DataSourceVersions = _nsaReaders.Select(x => x.Version);
                assemblies         = _nsaReaders.Select(x => x.Assembly);
            }

            if (_nsiReaders != null)
            {
                assemblies         = assemblies?.Concat(_nsiReaders.Select(x => x.Assembly)) ?? _nsiReaders.Select(x => x.Assembly);
                DataSourceVersions = DataSourceVersions?.Concat(_nsiReaders.Select(x => x.Version)) ?? _nsiReaders.Select(x => x.Version);
            }

            var distinctAssemblies = assemblies?.Where(x => GenomeAssemblyHelper.AutosomeAndAllosomeAssemblies.Contains(x)).Distinct().ToArray();

            if (distinctAssemblies == null || distinctAssemblies.Length > 1)
            {
                if (_nsaReaders != null)
                {
                    foreach (INsaReader nsaReader in _nsaReaders)
                    {
                        Console.WriteLine(nsaReader.Version + "\tAssembly:" + nsaReader.Assembly);
                    }
                }
                if (_nsiReaders != null)
                {
                    foreach (INsiReader nsiReader in _nsiReaders)
                    {
                        Console.WriteLine(nsiReader.Version + "\tAssembly:" + nsiReader.Assembly);
                    }
                }
                throw new UserErrorException("Multiple genome assemblies detected in Supplementary annotation directory");
            }
            Assembly = distinctAssemblies[0];
            //check if there are any duplicate jsonKeys in any of the nsa files
            var jsonKeys = new HashSet <string>();

            if (_nsaReaders != null)
            {
                foreach (var reader in _nsaReaders)
                {
                    if (jsonKeys.Contains(reader.JsonKey))
                    {
                        throw new UserErrorException("Multiple nsa file found for the Json Key: " + reader.JsonKey);
                    }
                    jsonKeys.Add(reader.JsonKey);
                }
            }

            //check if there are any duplicate jsonKeys in any of the nsi files
            jsonKeys.Clear();
            if (_nsiReaders != null)
            {
                foreach (var reader in _nsiReaders)
                {
                    if (jsonKeys.Contains(reader.JsonKey))
                    {
                        throw new UserErrorException("Multiple nsi file found for the Json Key: " + reader.JsonKey);
                    }
                    jsonKeys.Add(reader.JsonKey);
                }
            }
        }
Exemplo n.º 60
0
        protected override void TrySolveInstance(IGH_DataAccess DA)
        {
            if (!Parameters.Document.GetDataOrDefault(this, DA, "Document", out var doc))
            {
                return;
            }

            var categoryType = DB.CategoryType.Invalid;

            DA.GetData("Type", ref categoryType);

            var  Parent           = default(DB.Category);
            var  _Parent_         = Params.IndexOfInputParam("Parent");
            bool nofilterParent   = (!DA.GetData(_Parent_, ref Parent) && Params.Input[_Parent_].DataType == GH_ParamData.@void);
            var  ParentCategoryId = Parent?.Id ?? DB.ElementId.InvalidElementId;

            var  Name         = default(string);
            var  _Name_       = Params.IndexOfInputParam("Name");
            bool nofilterName = (!DA.GetData(_Name_, ref Name) && Params.Input[_Name_].DataType == GH_ParamData.@void);

            bool AllowsSubcategories   = false;
            var  _AllowsSubcategories_ = Params.IndexOfInputParam("Allows Subcategories");
            bool nofilterSubcategories = (!DA.GetData(_AllowsSubcategories_, ref AllowsSubcategories) && Params.Input[_AllowsSubcategories_].DataType == GH_ParamData.@void);

            bool AllowsParameters   = false;
            var  _AllowsParameters_ = Params.IndexOfInputParam("Allows Parameters");
            bool nofilterParams     = (!DA.GetData(_AllowsParameters_, ref AllowsParameters) && Params.Input[_AllowsParameters_].DataType == GH_ParamData.@void);

            bool HasMaterialQuantities   = false;
            var  _HasMaterialQuantities_ = Params.IndexOfInputParam("Has Material Quantities");
            bool nofilterMaterials       = (!DA.GetData(_HasMaterialQuantities_, ref HasMaterialQuantities) && Params.Input[_HasMaterialQuantities_].DataType == GH_ParamData.@void);

            bool Cuttable         = false;
            var  _Cuttable_       = Params.IndexOfInputParam("Cuttable");
            bool nofilterCuttable = (!DA.GetData(_Cuttable_, ref Cuttable) && Params.Input[_Cuttable_].DataType == GH_ParamData.@void);

            var rootCategories = BuiltInCategoryExtension.BuiltInCategories.Select(x => doc.GetCategory(x)).Where(x => x is object && x.Parent is null);
            var subCategories  = rootCategories.SelectMany(x => x.SubCategories.Cast <DB.Category>());

            var nameIsSubcategoryFullName = Name is string && Name.Substring(1).Contains(':');
            var excludeSubcategories      = AllowsSubcategories || !nameIsSubcategoryFullName;

            // Default path iterate over categories looking for a match
            var categories = nofilterParent && !excludeSubcategories?
                             rootCategories.Concat(subCategories) : // All categories
                                 (
                                     Parent is null ?
                                     rootCategories :                          // Only root categories
                                     Parent.SubCategories.Cast <DB.Category>() // Only subcategories of Parent
                                 );

            // Fast path for exact match queries
            if (Operator.CompareMethodFromPattern(Name) == Operator.CompareMethod.Equals)
            {
                var components = Name.Split(':');
                if (components.Length == 1)
                {
                    if (doc.Settings.Categories.get_Item(components[0]) is DB.Category category)
                    {
                        nofilterName = true;
                        categories   = Enumerable.Repeat(category, 1);
                    }
                }
                else if (components.Length == 2)
                {
                    if (doc.Settings.Categories.get_Item(components[0]) is DB.Category category)
                    {
                        nofilterName = true;
                        if (category.SubCategories.get_Item(components[1]) is DB.Category subCategory)
                        {
                            categories = Enumerable.Repeat(subCategory, 1);
                        }
                        else
                        {
                            categories = Enumerable.Empty <DB.Category>();
                        }
                    }
                }
                else
                {
                    return;
                }
            }

            if (categoryType != DB.CategoryType.Invalid)
            {
                categories = categories.Where((x) => x.CategoryType == categoryType);
            }

            if (!nofilterSubcategories)
            {
                categories = categories.Where((x) => x.CanAddSubcategory == AllowsSubcategories);
            }

            if (!nofilterParams)
            {
                categories = categories.Where((x) => x.AllowsBoundParameters == AllowsParameters);
            }

            if (!nofilterMaterials)
            {
                categories = categories.Where((x) => x.HasMaterialQuantities == HasMaterialQuantities);
            }

            if (!nofilterCuttable)
            {
                categories = categories.Where((x) => x.IsCuttable == Cuttable);
            }

            if (!nofilterName)
            {
                if (nofilterParent)
                {
                    categories = categories.Where((x) => x.FullName().IsSymbolNameLike(Name));
                }
                else
                {
                    categories = categories.Where((x) => x.Name.IsSymbolNameLike(Name));
                }
            }

            IEnumerable <DB.Category> list = null;

            foreach (var group in categories.GroupBy((x) => x.CategoryType).OrderBy((x) => x.Key))
            {
                var orderedGroup = group.OrderBy((x) => x.Name);
                list = list?.Concat(orderedGroup) ?? orderedGroup;
            }

            DA.SetDataList("Categories", list);
        }