示例#1
1
 public void ShowDatabases(IList<string> databases)
 {
     var dict = databases.ToDictionary(i => i, i => i);
     _databaseComboBox.ValueMember = "Key";
     _databaseComboBox.DisplayMember = "Value";
     _databaseComboBox.DataSource = new BindingSource(dict, null);
 }
        public void UpdateMarkers(IList<MediaMarker> markers, bool forceRefresh)
        {
            var markersHash = markers.ToDictionary(i => i.Id, i => i);

            List<MediaMarker> newMarkers;
            List<MediaMarker> removedMarkers;

            if (forceRefresh)
            {
                newMarkers = markers.ToList();
                removedMarkers = _previousMarkers.Values.ToList();
            }
            else
            {
                newMarkers = markers.Where(i => !_previousMarkers.ContainsKey(i.Id)).ToList();
                removedMarkers = _previousMarkers.Values.Where(i => !markersHash.ContainsKey(i.Id)).ToList();
            }

            if (removedMarkers.Any() && MarkersRemoved != null)
            {
                MarkersRemoved(removedMarkers);
            }

            if (newMarkers.Any() && NewMarkers != null)
            {
                NewMarkers(newMarkers);
            }

            _previousMarkers = markersHash;
        }
        public TrendMarkerLabelProvider(int polarityId)
        {
            switch (polarityId)
            {
                case PolarityIds.RagLowIsGood:
                    Labels = new List<TrendMarkerLabel> {
                        CannotBeCalculated,
                        new TrendMarkerLabel{Id = TrendMarker.Increasing, Text = "Increasing and getting worse"},
                        new TrendMarkerLabel{Id = TrendMarker.Decreasing, Text = "Decreasing and getting better"},
                        NoChange
                    };
                    break;

                case PolarityIds.RagHighIsGood:
                    Labels = new List<TrendMarkerLabel> {
                        CannotBeCalculated,
                        new TrendMarkerLabel{Id = TrendMarker.Increasing, Text = "Increasing and getting better"},
                        new TrendMarkerLabel{Id = TrendMarker.Decreasing, Text = "Decreasing and getting worse"},
                        NoChange
                    };
                    break;

                default:
                    Labels = new List<TrendMarkerLabel> {
                        CannotBeCalculated,
                        new TrendMarkerLabel{Id = TrendMarker.Increasing, Text = "Increasing"},
                        new TrendMarkerLabel{Id = TrendMarker.Decreasing, Text = "Decreasing"},
                        NoChange
                    };
                    break;
            }

            _trendMarkerToLabel = Labels.ToDictionary(x => x.Id, x => x);
        }
示例#4
1
 public void ShowWriteOffOptions(IList<WriteOffOption> options)
 {
     var dict = options.ToDictionary(x => x.Id, x => x.Name);
     _optionComboBox.DisplayMember = "Value";
     _optionComboBox.ValueMember = "Key";
     _optionComboBox.DataSource = new BindingSource(dict, null);
     _optionComboBox.SelectedIndex = 0;
 }
 public EntityHierarchy GetEntityHierarchy(
     Entity entity,
     IList<PropertyDeleteOption> deleteOptions = null)
 {
     var deleteOptionsDict = deleteOptions == null ?
         null :
         deleteOptions.ToDictionary(x => x.HierarchyName);
     return GetEntityHierarchy(null, entity, deleteOptionsDict);
 }
 public OperatorManager(IList<IOperator> operators)
 {
     Operators = new ReadOnlyDictionary<char, IOperator>(operators.ToDictionary(o => o.OperatorCharacter, o => o));
     Priorities = operators.Select(o => o.Priority)
                           .Distinct()
                           .OrderBy(g => g)
                           .ToList()
                           .AsReadOnly();
 }
示例#7
1
    static void ParseInput()
    {
        n = int.Parse(Console.ReadLine());

        stationsInfo = Regex.Matches(
                ("0 --> " + Console.ReadLine()).Replace(" --> ", "►"),
                "([^►]+)►([^►]+)"
            ).Cast<Match>()
            .Select(match =>
                new KeyValuePair<string, int>(
                    match.Groups[2].Value,
                    int.Parse(match.Groups[1].Value)
                )
            ).ToArray();

        int id = 0;
        stationsByName = stationsInfo.ToDictionary(
            info => info.Key,
            info => id++
        );

        stationsByIndex = stationsByName.ToDictionary(
            kvp => kvp.Value,
            kvp => kvp.Key
        );

        var separator = new string[] { " | " };

        camerasInfo = Enumerable.Range(0, int.Parse(Console.ReadLine()))
            .Select(_ => Console.ReadLine())
            .Select(line => line.Split(separator, StringSplitOptions.None))
            .Select(match =>
                new Tuple<DateTime, int, int, int, char>(
                    DateTime.ParseExact(match[0], DateFormat, CultureInfo.InvariantCulture),
                    stationsByName[match[1]],
                    int.Parse(match[2]),
                    int.Parse(match[3]),
                    match[4][0]
                )
            ).ToArray();

        trainCapacity = int.Parse(Console.ReadLine());

#if DEBUG
        //Console.WriteLine("# INPUT");

        //Console.WriteLine(string.Join(Environment.NewLine, stationsInfo));
        //Console.WriteLine();

        //Console.WriteLine(string.Join(Environment.NewLine, camerasInfo));
        //Console.WriteLine();

        //Console.WriteLine(trainCapacity);
        //Console.WriteLine();
#endif
    }
 public EntityHierarchy GetEntityHierarchy(
     Entity entity,
     IList<PropertyDeleteOption> deleteOptions = null)
 {
     var deleteOptionsDict = deleteOptions == null ?
         null :
         deleteOptions.ToDictionary(x => x.HierarchyName);
     var index = 0;
     return GetEntityHierarchy(null, entity, deleteOptionsDict, string.Empty, ref index);
 }
示例#9
1
 public TreeClientApp(IList<String> sampleFiles)
 {
     timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(0.3) };
     timer.Tick += TimerStepForward;
     Program = String.Empty;
     ExecuteProgramCommand = new RelayCommand(ExecuteProgram);
     StepForwardCommand = new RelayCommand(StepForward, p => currentProgram != null);
     PlayCommand = new RelayCommand(Play, p => currentProgram != null);
     Samples = sampleFiles.ToDictionary(s => Path.GetFileName(s), s => new RelayCommand(o => LoadSample(s)));
 }
示例#10
1
        public ActionResult Behaviors(IList<BehaviorConfig> configs)
        {
            foreach (var config in configs)
            {
                BehaviorConfig.Update(CurrentInstance.Name, config);
            }

            var weights = configs.ToDictionary(c => c.BehaviorType, c => c.Weight);
            RecommendationEngineConfiguration.ChangeBehaviorWeights(CurrentInstance.Name, weights);

            return AjaxForm().ReloadPage();
        }
 public BadShooterViewModel(string name, double radius, IList<PlayerViewModel> players, ISoundEffect audioPlayer, IGunAimPhysics gunAimPhysics)
 {
     Name = name;
     Radius = radius;
     this.players = players;
     this.audioPlayer = audioPlayer;
     this.gunAimPhysics = gunAimPhysics;
     scores = players.ToDictionary(p => p.Key, p => 0);
     animationTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(10) };
     animationTimer.Tick += DispatcherTimerOnTick;
     gameTimer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(1) };
     gameTimer.Tick += CountDown;
 }
        public TeamSelection SelectStartingTeamForGameweek(IList<PredictedPlayerScore> predictedPlayerScores)
        {
            if(predictedPlayerScores.Count != 15)throw new Exception("Incorrect number of players to select starting team from");

            var selection = new TeamSelection
                                {
                                    Team = SelectTeam(predictedPlayerScores)
                                };
            selection.PredictedTotalTeamScore = CalculatePredictedTeamScore(
                predictedPlayerScores.ToDictionary(ps => ps.Player.Id, ps => ps.PredictedScore),
                selection.Team);

            return selection;
        }
        public CategoryAreaDataWriter(IAreasReader areasReader, IGroupDataReader groupDataReader, WorksheetInfo worksheet,
            ProfileDataWriter profileDataWriter, CategoryAreaType categoryAreaType)
            : base(areasReader, groupDataReader, worksheet, profileDataWriter)
        {
            _categoryAreaTypeId = categoryAreaType.CategoryTypeId;

            categories = areasReader.GetCategories(_categoryAreaTypeId);

                subnationalCategoryIdToCategoryAreaMap = categories
                    .ToDictionary<Category, int, IArea>(
                    category => category.Id,
                    category => CategoryArea.New(category)
                    );
        }
示例#14
0
        private async Task <string> CreateContainer(
            string imageName,
            IList <string> environmentVariables,
            IList <string> volumeBindings,
            IList <PortMapping> portMappings,
            IList <string> startCmd,
            HostConfig hostConfigOverrides,
            string workingDirectory)
        {
            HostConfig hostConfig = hostConfigOverrides ?? new HostConfig();

            hostConfig.NetworkMode  = SessionHostContainerConfiguration.DockerNetworkName;
            hostConfig.Binds        = volumeBindings;
            hostConfig.PortBindings = portMappings?.ToDictionary(p => $"{p.GamePort.Number}/{p.GamePort.Protocol}",
                                                                 p => (IList <PortBinding>)(new List <PortBinding>()
            {
                new PortBinding()
                {
                    HostPort = $"{p.NodePort}/{p.GamePort.Protocol}"
                }
            }));

            if (hostConfig.LogConfig == null)
            {
                hostConfig.LogConfig        = new LogConfig();
                hostConfig.LogConfig.Type   = "json-file";
                hostConfig.LogConfig.Config = new Dictionary <string, string>()
                {
                    { "max-size", "200m" }
                };
            }

            CreateContainerParameters containerParams = new CreateContainerParameters
            {
                Image        = imageName,
                Env          = environmentVariables,
                ExposedPorts = portMappings?.ToDictionary(p => $"{p.GamePort.Number}/{p.GamePort.Protocol}", p => new EmptyStruct()),
                HostConfig   = hostConfig,
                WorkingDir   = workingDirectory,
                Cmd          = startCmd
            };

            _logger.LogInformation($"Creating container. Image='{imageName}'");
            CreateContainerResponse response =
                await TaskUtil.TimedExecute(
                    async() => await _dockerClient.Containers.CreateContainerAsync(containerParams).ConfigureAwait(false),
                    _logger,
                    MetricConstants.ContainerStats,
                    MetricConstants.ContainerCreationTime);

            _logger.LogInformation($"Created a container with session host id: {response.ID}");

            return(response.ID);
        }
        public bool Update(Markdown updateThis)
        {
            var markdownDict = markdownList.ToDictionary(p => p.ProductName, p => p);

            markdownDict[updateThis.ProductName].Amount = updateThis.Amount;
            return(true);
        }
示例#16
0
        public async Task <GroupViewModel> GetGroupViewModel(Guid memoryBookUniverseId, Guid groupId)
        {
            IList <GroupReadModel> groups = await this.groupProvider.GetGroupsAsync(memoryBookUniverseId, groupId).ConfigureAwait(false);

            if (groups == null || groups.Count == 0)
            {
                return(null);
            }

            GroupReadModel groupReadModel = groups.First();
            GroupViewModel viewModel      = groupReadModel.ToViewModel();

            IList <DetailTypeReadModel> detailTypes = await this.detailTypeQueryManager.GetAllDetailTypes().ConfigureAwait(false);

            Dictionary <Guid, DetailTypeReadModel> detailTypesDictionary = detailTypes.ToDictionary(x => x.Id);

            Task <IList <DetailsByEntityModel> > groupDetails         = this.detailProvider.GetDetailsForGroups(memoryBookUniverseId, groupId);
            Task <IList <MemberViewModel> >      memberViewModelsTask = this.GetMemberViewModels(memoryBookUniverseId, groupReadModel.MemberIds, detailTypesDictionary);

            await Task.WhenAll(groupDetails, memberViewModelsTask).ConfigureAwait(false);

            viewModel.Details = groupDetails.Result?.FirstOrDefault()?.Details
                                .Select(x => x.ToViewModel(detailTypesDictionary)).ToList();

            viewModel.Members = memberViewModelsTask.Result;

            return(viewModel);
        }
示例#17
0
        protected internal BoltRequestMessageReader(BoltConnection connection, BoltResponseHandler externalErrorResponseHandler, IList <RequestMessageDecoder> decoders)
        {
            this._connection = connection;
            this._externalErrorResponseHandler = externalErrorResponseHandler;
//JAVA TO C# CONVERTER TODO TASK: Method reference arbitrary object instance method syntax is not converted by Java to C# Converter:
            this._decoders = decoders.ToDictionary(RequestMessageDecoder::signature, identity());
        }
        private void SendToSentry(LoggingEvent loggingEvent)
        {
            if (ravenClient == null)
            {
                ravenClient = new RavenClient(DSN)
                {
                    Logger = Logger
                };
            }

            var extra = SentryAppender.GetExtra();

            var tags = tagLayouts.ToDictionary(t => t.Name, t => (t.Layout.Format(loggingEvent) ?? "").ToString());

            var exception = loggingEvent.ExceptionObject ?? loggingEvent.MessageObject as Exception;
            var level     = SentryAppender.Translate(loggingEvent.Level);

            if (exception != null)
            {
                ravenClient.CaptureException(exception, null, level, tags: tags, extra: extra);
            }
            else
            {
                var message = loggingEvent.RenderedMessage;

                if (message != null)
                {
                    ravenClient.CaptureMessage(message, level, tags, extra);
                }
            }
        }
示例#19
0
        public void GetCollectionNakedObjectFromId()
        {
            IList <Claim>       claims = NakedObjectsFramework.GetService <ClaimRepository>().FindMyClaims(null, "");
            INakedObjectAdapter no     = NakedObjectsFramework.NakedObjectManager.CreateAdapter(claims, null, null);

            INakedObjectAdapter service = NakedObjectsFramework.ServicesManager.GetService("ClaimRepository");
            IActionSpec         action  = service.Spec.GetActions().Single(a => a.Id == "FindMyClaims");

            INakedObjectAdapter[] parms = new[] { null, "" }.Select(o => NakedObjectsFramework.NakedObjectManager.CreateAdapter(o, null, null)).ToArray();

            var cm    = CollectionMementoHelper.TestMemento(NakedObjectsFramework.LifecycleManager, NakedObjectsFramework.NakedObjectManager, NakedObjectsFramework.MetamodelManager, service, action, parms);

            no.SetATransientOid(cm);

            string id = NakedObjectsFramework.GetObjectId(no);

            INakedObjectAdapter no2 = NakedObjectsFramework.GetNakedObjectFromId(id);

            List <Claim> claims2 = no2.GetDomainObject <IEnumerable <Claim> >().ToList();

            Assert.AreEqual(claims.Count(), claims2.Count());

            int index = 0;
            Dictionary <Claim, Claim> dict = claims.ToDictionary(x => x, y => claims2.Skip(index++).First());

            dict.ForEach(kvp => Assert.AreSame(kvp.Key, kvp.Value));
        }
示例#20
0
        internal MessageDescriptor(DescriptorProto proto, FileDescriptor file, MessageDescriptor parent, int typeIndex, GeneratedCodeInfo generatedCodeInfo)
            : base(file, file.ComputeFullName(parent, proto.Name), typeIndex)
        {
            this.proto    = proto;
            parser        = generatedCodeInfo == null ? null : generatedCodeInfo.Parser;
            generatedType = generatedCodeInfo == null ? null : generatedCodeInfo.ClrType;

            containingType = parent;

            oneofs = DescriptorUtil.ConvertAndMakeReadOnly(
                proto.OneofDecl,
                (oneof, index) =>
                new OneofDescriptor(oneof, file, this, index, generatedCodeInfo == null ? null : generatedCodeInfo.OneofNames[index]));

            nestedTypes = DescriptorUtil.ConvertAndMakeReadOnly(
                proto.NestedType,
                (type, index) =>
                new MessageDescriptor(type, file, this, index, generatedCodeInfo == null ? null : generatedCodeInfo.NestedTypes[index]));

            enumTypes = DescriptorUtil.ConvertAndMakeReadOnly(
                proto.EnumType,
                (type, index) =>
                new EnumDescriptor(type, file, this, index, generatedCodeInfo == null ? null : generatedCodeInfo.NestedEnums[index]));

            fieldsInDeclarationOrder = DescriptorUtil.ConvertAndMakeReadOnly(
                proto.Field,
                (field, index) =>
                new FieldDescriptor(field, file, this, index, generatedCodeInfo == null ? null : generatedCodeInfo.PropertyNames[index]));
            fieldsInNumberOrder = new ReadOnlyCollection <FieldDescriptor>(fieldsInDeclarationOrder.OrderBy(field => field.FieldNumber).ToArray());
            // TODO: Use field => field.Proto.JsonName when we're confident it's appropriate. (And then use it in the formatter, too.)
            jsonFieldMap = new ReadOnlyDictionary <string, FieldDescriptor>(fieldsInNumberOrder.ToDictionary(field => JsonFormatter.ToCamelCase(field.Name)));
            file.DescriptorPool.AddSymbol(this);
            fields = new FieldCollection(this);
        }
        public bool Update(Product updateThis)
        {
            var productDict = priceList.ToDictionary(p => p.ProductName, p => p);

            productDict[updateThis.ProductName].Price = updateThis.Price;
            return(true);
        }
示例#22
0
        public void Calcular(IList <InfoPartido> partidos, int curulesDisponibles)
        {
            if (curulesDisponibles < 1)
            {
                throw new ArgumentException("No hay curules suficientes para realizar el cálculo");
            }

            int curulesAsignadas = curulesDisponibles;
            Dictionary <InfoPartido, decimal> dic = partidos.ToDictionary(k => k, v => v.VotosGanados * 1.0m);

            while (curulesAsignadas > 0)
            {
                // buscar el mayor
                List <KeyValuePair <InfoPartido, decimal> > m =
                    (from itm in dic orderby itm.Value descending select itm).ToList();

                // asignar curul
                InfoPartido partido = m[0].Key;
                partido.CurulesAsignadas = partido.CurulesAsignadas + 1;

                // decrementar indice y curules pendientes
                decimal cociente = partido.CurulesAsignadas == 1 ? 1.4m : ((2 * partido.CurulesAsignadas) + 1);
                dic[partido] = (partido.VotosGanados * 1m) / cociente;
                curulesAsignadas--;
            }
        }
示例#23
0
        protected virtual void InitializeProcessContext(ProcessInstance processInstance,
                                                        IList <ValuedDataObject> dataObjects)
        {
            var dataObjectsMap = dataObjects.ToDictionary(x => x.Id);

            IVariableType type = null;

            foreach (var dataObject in dataObjects)
            {
                var value = dataObject.Value;
                type = Variables.VariableType.Resolve(value);

                var variable = new Variable();
                variable.Name = dataObject.Id;
                variable.Type = type.Name;

                type.SetValue(variable, value);

                processInstance.Variables.Add(variable);
            }

            if (variables != null && variables.Count > 0)
            {
                var em = variables.GetEnumerator();
                while (em.MoveNext())
                {
                    processInstance.SetVariable(em.Current.Key, em.Current.Value);
                }
            }
        }
示例#24
0
        private async Task UpdateDocumentsAsync(IList <T> updatedObservations)
        {
            Dictionary <string, T> updatedObservationsByCompositeId = updatedObservations.ToDictionary(x => $"{x.DataProviderId}_{x.CatalogNumber}", x => x);
            var filterDef           = new FilterDefinitionBuilder <VersionedDocumentObservation <T> >();
            var filter              = filterDef.In(x => x.CompositeId, updatedObservations.Select(x => $"{x.DataProviderId}_{x.CatalogNumber}"));
            var foundObservations   = await(await Collection.FindAsync(filter)).ToListAsync();
            var changedObservations = new ConcurrentBag <VersionedDocumentObservation <T> >();

            Parallel.For(0, foundObservations.Count - 1, i =>
            {
                VersionedDocumentObservation <T> versionedObservation = foundObservations[i];
                var updatedObservation = updatedObservationsByCompositeId[versionedObservation.CompositeId];
                if (UpdateVersionedObservationObject(versionedObservation, updatedObservation))
                {
                    changedObservations.Add(versionedObservation);
                }
            });

            if (changedObservations.Count > 0)
            {
                // todo - create transaction?
                var deleteFilter = filterDef.In(x => x.CompositeId, changedObservations.Select(x => $"{x.DataProviderId}_{x.CatalogNumber}"));
                await Collection.DeleteManyAsync(deleteFilter);

                await Collection.InsertManyAsync(changedObservations);
            }
        }
        async Task EnsureAffectedRowsMigratedAsync(TableBatchOperation batch, TableRequestOptions requestOptions, OperationContext operationContext)
        {
            string partitionKey = ChainTableUtils.GetBatchPartitionKey(batch);

            var query = GenerateQueryForAffectedRows(batch);

            IList <MTableEntity> oldRows = await oldTable.ExecuteQueryAtomicAsync(query, requestOptions, operationContext);

            await monitor.AnnotateLastBackendCallAsync();

            IList <MTableEntity> newRows = await newTable.ExecuteQueryAtomicAsync(query, requestOptions, operationContext);

            await monitor.AnnotateLastBackendCallAsync();

            Dictionary <string, MTableEntity> oldDict = oldRows.ToDictionary(ent => ent.RowKey);
            Dictionary <string, MTableEntity> newDict = newRows.ToDictionary(ent => ent.RowKey);

            // Migrate any affected rows not already migrated.
            foreach (TableOperation op in batch)
            {
                string       targetedRowKey = op.GetEntity().RowKey;
                MTableEntity oldEntity;
                if (oldDict.TryGetValue(targetedRowKey, out oldEntity) && !newDict.ContainsKey(targetedRowKey))
                {
                    await TryCopyEntityToNewTableAsync(oldEntity, requestOptions, operationContext);
                }
            }
        }
示例#26
0
        /// <summary>实体列表的下拉列表。单选,自动匹配当前模型的选中项</summary>
        /// <param name="Html"></param>
        /// <param name="name"></param>
        /// <param name="list"></param>
        /// <param name="optionLabel"></param>
        /// <param name="autoPostback">自动回发</param>
        /// <returns></returns>
        public static IHtmlContent ForDropDownList(this IHtmlHelper Html, String name, IList <IEntity> list, String optionLabel = null, Boolean autoPostback = false)
        {
            var entity        = Html.ViewData.Model as IEntity;
            var selectedValue = entity == null ? WebHelper1.Params[name] : entity[name];

            var atts = new Dictionary <String, Object>();

            if (Setting.Current.BootstrapSelect)
            {
                atts.Add("class", "multiselect");
            }
            else
            {
                atts.Add("class", "form-control");
            }

            // 处理自动回发
            //if (autoPostback) atts.Add("onchange", "$(':submit').click();");
            if (autoPostback)
            {
                atts.Add("onchange", "$(this).parents('form').submit();");
            }

            var data = new SelectList(list.ToDictionary(), "Key", "Value", selectedValue);

            return(Html.DropDownList(name, data, optionLabel, atts));
        }
示例#27
0
        /// <summary>
        /// Constructs the scope for mapping the values of arguments to the parameters of the template.
        /// Throws errors if certain errors detected <see cref="TemplateErrors"/>.
        /// </summary>
        /// <param name="inputTemplateName">Template name to evaluate.</param>
        /// <param name="args">Arguments to map to the template parameters.</param>
        /// <param name="allTemplates">All templates.</param>
        /// <returns>
        /// An object.
        /// If the number of arguments is 0, returns the current scope.
        /// Otherwise, returns an CustomizedMemory that the mapping of the parameter name to the argument value added to the scope.
        /// </returns>
        public object ConstructScope(string inputTemplateName, List <object> args, IList <Template> allTemplates)
        {
            var templateMap  = allTemplates.ToDictionary(x => x.Name);
            var templateName = ParseTemplateName(inputTemplateName).pureTemplateName;

            if (!templateMap.ContainsKey(templateName))
            {
                throw new ArgumentException(TemplateErrors.TemplateNotExist(templateName));
            }

            var parameters   = templateMap[templateName].Parameters;
            var currentScope = CurrentTarget().Scope;

            if (args.Count == 0)
            {
                // no args to construct, inherit from current scope
                return(currentScope);
            }

            var newScope = parameters.Zip(args, (k, v) => new { k, v })
                           .ToDictionary(x => x.k, x => x.v);

            var memory = currentScope as CustomizedMemory;

            if (memory == null)
            {
                throw new InvalidOperationException(TemplateErrors.InvalidMemory);
            }

            // inherit current memory's global scope
            return(new CustomizedMemory(memory.GlobalMemory, new SimpleObjectMemory(newScope)));
        }
示例#28
0
        /// <inheritdoc/>
        public Dictionary <string, string> GetDrugsBrandNameByDIN(IList <string> drugIdentifiers)
        {
            // Contract.Requires(drugIdentifiers != null);
            this.logger.LogDebug("Getting drug brand names from DB");
            this.logger.LogTrace($"Identifiers: {JsonSerializer.Serialize(drugIdentifiers)}");
            List <string> uniqueDrugIdentifers = drugIdentifiers.Distinct().ToList();

            this.logger.LogDebug($"Total DrugIdentifiers: {drugIdentifiers.Count} | Unique identifiers:{uniqueDrugIdentifers.Count} ");

            // Retrieve the brand names using the Federal data
            IList <DrugProduct>         drugProducts = this.GetDrugProductsByDIN(uniqueDrugIdentifers);
            Dictionary <string, string> brandNames   = drugProducts.ToDictionary(pcd => pcd.DrugIdentificationNumber, pcd => pcd.BrandName);

            if (uniqueDrugIdentifers.Count > brandNames.Count)
            {
                // Get the DINs not found on the previous query
                IList <string> notFoundDins = uniqueDrugIdentifers.Where(din => !brandNames.Keys.Contains(din)).ToList();

                // Retrieve the brand names using the provincial data
                IList <PharmaCareDrug> pharmaCareDrugs = this.GetPharmaCareDrugsByDIN(notFoundDins);

                Dictionary <string, string> provicialBrandNames = pharmaCareDrugs.ToDictionary(dp => dp.DINPIN, dp => dp.BrandName);

                // Merge both data sets
                provicialBrandNames.ToList().ForEach(x => brandNames.Add(x.Key, x.Value));
            }

            this.logger.LogDebug("Finished getting drug brand names from DB");
            this.logger.LogTrace($"Names: {JsonSerializer.Serialize(brandNames)}");
            return(brandNames);
        }
示例#29
0
        // Note: this is not optimized, be wary of use with large collections
        public static void sync_with_never_duplicate <T, TSource, TKey>(IList <T> dest, IEnumerable <TSource> src, Func <TSource, T> create, Func <T, TKey> key_selector, Func <TSource, TKey> src_key_selector, IEqualityComparer <TKey> key_comparer)
        {
            var src_list = src as IList <TSource> ?? new List <TSource>(src);
            var src_map  = src_list.ToDictionary(src_key_selector);

            for (int i = 0; i < dest.Count; i++)
            {
                var k = key_selector(dest[i]);
                if (!src_map.ContainsKey(k))
                {
                    dest.RemoveAt(i);
                }
            }
            var dest_map = dest.ToDictionary(key_selector);

            for (int i = 0; i < src_list.Count; i++)
            {
                TKey key = src_key_selector(src_list[i]);
                if (dest_map.TryGetValue(key, out T dval))
                {
                    int curr_index = dest.IndexOf(dval);
                    if (curr_index != i)
                    {
                        dest.RemoveAt(curr_index);
                        dest.Insert(i, dval);
                    }
                }
                else
                {
                    dest.Insert(i, create(src_list[i]));
                }
            }
        }
示例#30
0
        private IEnumerable <ScoredDocument> GetDocs(IList <DocumentScore> scores, IxInfo ix)
        {
            var docAddressFileName = Path.Combine(_directory, ix.VersionId + ".da");

            IList <BlockInfo> docAdrs;

            using (var docAddressReader = new DocumentAddressReader(
                       new FileStream(docAddressFileName, FileMode.Open, FileAccess.Read, FileShare.Read, 4096 * 1, FileOptions.SequentialScan)))
            {
                var adrs = scores
                           .Select(s => new BlockInfo(s.DocumentId * _blockSize, _blockSize))
                           .OrderBy(b => b.Position)
                           .ToList();

                docAdrs = docAddressReader.Get(adrs).ToList();
            }

            var docFileName = Path.Combine(_directory, ix.VersionId + ".rdoc");

            using (var docReader = new DocumentReader(
                       new FileStream(docFileName, FileMode.Open, FileAccess.Read, FileShare.Read, 4096 * 4, FileOptions.SequentialScan),
                       (Compression)ix.Compression))
            {
                var dic = scores.ToDictionary(x => x.DocumentId, y => y.Score);

                foreach (var doc in docReader.Get(docAdrs))
                {
                    var score = dic[doc.Id];

                    yield return(new ScoredDocument {
                        Document = doc, Score = score
                    });
                }
            }
        }
示例#31
0
 public static object[,] ToRange <T>(IList <T> items)
 {
     if (items == null || items.Count == 0)
     {
         return(new object[, ] {
         });
     }
     object[,] output;
     if (items[0] is DictionaryEntry)
     {
         // If the internal array is of DictionaryEntry process
         var keyValuePairs = items.ToDictionary(k => ((DictionaryEntry)(object)k).Key,
                                                v => ((DictionaryEntry)(object)v).Value);
         output = new object[items.Count, 2];
         int idx = 0;
         foreach (var keyValuePair in keyValuePairs)
         {
             output[idx, 0]   = keyValuePair.Key;
             output[idx++, 1] = keyValuePair.Value;
         }
     }
     else
     {
         output = new object[items.Count, 1];
         for (int i = 0; i < items.Count(); i++)
         {
             output[i, 0] = items[i];
         }
     }
     return(output);
 }
示例#32
0
        private string PeptideToString(proteome.Peptide peptide, IList <phosphoRS.PTMSiteProbability> localizationProbabilities, PhosphoRSConfig config)
        {
            var probabilityMap = localizationProbabilities.ToDictionary(o => o.SequencePosition, o => o.Probability);

            string        format = String.Format("[{{0:f{0}}}]", 0);
            StringBuilder sb     = new StringBuilder();

            if (peptide.modifications().ContainsKey(proteome.ModificationMap.NTerminus()))
            {
                sb.AppendFormat(format, peptide.modifications()[proteome.ModificationMap.NTerminus()].monoisotopicDeltaMass());
            }
            for (int i = 0; i < peptide.sequence.Length; ++i)
            {
                sb.Append(peptide.sequence[i]);
                if (probabilityMap.ContainsKey(i + 1))
                {
                    if (probabilityMap[i + 1] > 0)
                    {
                        sb.AppendFormat("[{0:f0}({1:f0}%)]", config.scoredAA.MassDelta, probabilityMap[i + 1] * 100);
                    }
                    //else
                    //    sb.AppendFormat("({0:f0})", config.scoredAA.MassDelta, probabilityMap[i + 1]);
                }
                else if (peptide.modifications().ContainsKey(i))
                {
                    double modMass = peptide.modifications()[i].monoisotopicDeltaMass();
                    sb.AppendFormat(format, modMass);
                }
            }
            if (peptide.modifications().ContainsKey(proteome.ModificationMap.CTerminus()))
            {
                sb.AppendFormat(format, peptide.modifications()[proteome.ModificationMap.CTerminus()].monoisotopicDeltaMass());
            }
            return(sb.ToString());
        }
示例#33
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="templates"></param>
        protected virtual void AddBaseTemplates(IList <TemplateItem> templates)
        {
            var templateLookup = templates.ToDictionary(t => t.Id, t => t);

            foreach (var template in templates)
            {
                var field = template.Item
                            .SharedFields
                            .FirstOrDefault(f => f.FieldId == FieldIDs.BaseTemplate.ToGuid());

                if (!String.IsNullOrWhiteSpace(field?.Value))
                {
                    var baseTemplateIds = field.Value
                                          .Split(new[] { '|', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)
                                          .Where(ID.IsID)
                                          .Select(ID.Parse)
                                          .ToArray();

                    var baseTemplates = baseTemplateIds
                                        .Where(id => templateLookup.Keys.Contains(id.ToString()))
                                        .Select(id => templateLookup[id.ToString()])
                                        .ToList();
                    var da = baseTemplates.Any();

                    template.BaseTemplates.AddRange(baseTemplates);
                }
            }
        }
示例#34
0
 private IEnumerable <Dictionary <TestItemType, float> > GetMaxResourceAmounts(float maxForAll, int length, IList <TestItemType> tradeItems)
 {
     for (; length > 0; length--)
     {
         yield return(tradeItems.ToDictionary(x => x, x => maxForAll));
     }
 }
示例#35
0
        private bool NoCircularDependencies(IList <ProviderReference> providerReferences)
        {
            var providerReferenceDictionary = providerReferences
                                              .ToDictionary(pr => pr.Id);

            var providerReferenceResolved = providerReferences
                                            .Where(pr => !pr.DependsOn.Any())
                                            .Select(pr => pr.Id)
                                            .ToList();

            var providerReferenceQueue  = new Queue <ProviderReference>(providerReferences.Where(pr => pr.DependsOn.Any()));
            var providerReferencePickup = default(ProviderReference);

            while (providerReferenceQueue.TryDequeue(out var providerReference))
            {
                if (providerReference.DependsOn.All(id => providerReferenceResolved.Contains(id)))
                {
                    providerReferenceResolved.Add(providerReference.Id);
                    providerReferencePickup = default;
                }
                else if (providerReference == providerReferencePickup)
                {
                    // circular dependency detected
                    return(false);
                }
                else
                {
                    providerReferenceQueue.Enqueue(providerReference);
                    providerReferencePickup ??= providerReference;
                }
            }

            return(true);
        }
示例#36
0
        /// <summary>实体列表的下拉列表。多选,自动匹配当前模型的选中项,支持数组类型或字符串类型(自动分割)的选中项</summary>
        /// <param name="Html"></param>
        /// <param name="name"></param>
        /// <param name="list"></param>
        /// <param name="autoPostback">自动回发</param>
        /// <returns></returns>
        public static MvcHtmlString ForListBox(this HtmlHelper Html, String name, IList <IEntity> list, Boolean autoPostback = false)
        {
            var entity = Html.ViewData.Model as IEntity;
            var vs     = entity == null ? WebHelper.Params[name] : entity[name];

            // 如果是字符串,分割为整型数组,全局约定逗号分割
            if (vs is String)
            {
                vs = (vs as String).SplitAsInt();
            }

            var atts = new RouteValueDictionary();

            if (Setting.Current.BootstrapSelect)
            {
                atts.Add("class", "multiselect");
            }
            else
            {
                atts.Add("class", "form-control");
            }
            atts.Add("multiple", "");
            // 处理自动回发
            if (autoPostback)
            {
                atts.Add("onchange", "$(':submit').click();");
            }

            return(Html.ListBox(name, new MultiSelectList(list.ToDictionary(), "Key", "Value", vs as IEnumerable), atts));
        }
示例#37
0
        private void AddAndSetupConverters(SerializedProperty arrayProperty, IList <Type> converterTypes, bool newAreEnabledByDefault)
        {
            var converterTypesByName = converterTypes.ToDictionary(o => o.AssemblyQualifiedName);

            AddMissingConverters(arrayProperty, converterTypesByName.Keys, newAreEnabledByDefault);
            SetupConvertersIntoDictionary(arrayProperty, converterTypesByName);
        }
        private Dictionary <string, int> GetCounts()
        {
            WebpageCount         countAlias    = null;
            Webpage              webpageAlias  = null;
            IList <WebpageCount> webpageCounts = _session.QueryOver(() => webpageAlias)
                                                 .SelectList(
                builder =>
                builder.SelectGroup(() => webpageAlias.DocumentType)
                .WithAlias(() => countAlias.Type)
                .SelectCount(() => webpageAlias.Id)
                .WithAlias(() => countAlias.Count)
                )
                                                 .TransformUsing(Transformers.AliasToBean <WebpageCount>())
                                                 .List <WebpageCount>();

            foreach (
                Type type in
                TypeHelper.GetAllConcreteMappedClassesAssignableFrom <Webpage>()
                .Where(type => !webpageCounts.Select(count => count.Type).Contains(type.FullName)))
            {
                webpageCounts.Add(new WebpageCount {
                    Type = type.FullName, Count = 0
                });
            }
            return(webpageCounts.ToDictionary(count => count.Type, count => count.Count));
        }
示例#39
0
 // Static Methods
 private static Dictionary <string, List <DataType> > GetPrimitiveTypes()
 {
     return(PrimitiveTypes.ToDictionary(type => type.Identifier, type => new List <DataType>()
     {
         type
     }, StringComparer.OrdinalIgnoreCase));
 }
示例#40
0
        private List <SourceRepository> GetEffectiveSourcesCore(ISettings settings, IList <PackageSource> dgSpecSources)
        {
            var sourceObjects              = dgSpecSources.ToDictionary(k => k.Source, v => v, StringComparer.Ordinal);
            var packageSourceProvider      = new PackageSourceProvider(settings);
            var packageSourcesFromProvider = packageSourceProvider.LoadPackageSources();

            foreach (var sourceUri in Sources)
            {
                //DGSpecSources should always match the Sources
                if (!sourceObjects.ContainsKey(sourceUri))
                {
                    Log.LogDebug($"{sourceUri} is in the RestoreArgs Sources but in the passed in dgSpecSources");
                    sourceObjects[sourceUri] = new PackageSource(sourceUri);
                }
            }

            // Use PackageSource objects from the provider when possible (since those will have credentials from nuget.config)
            foreach (var source in packageSourcesFromProvider)
            {
                if (source.IsEnabled && (sourceObjects.ContainsKey(source.Source)))
                {
                    sourceObjects[source.Source] = source;
                }
            }

            if (CachingSourceProvider == null)
            {
                // Create a shared caching provider if one does not exist already
                CachingSourceProvider = new CachingSourceProvider(packageSourceProvider);
            }

            return(sourceObjects.Select(entry => CachingSourceProvider.CreateRepository(entry.Value)).ToList());
        }
示例#41
0
        internal void VerifyExtensionsAreSame(IList <Extension> expectedExtensions, IList <Extension> actualExtensions, bool verifyRolesAppliedTo = false)
        {
            Assert.True(expectedExtensions.Count == actualExtensions.Count, "Number of extensions should be match");
            Dictionary <string, Extension> expectedExtensionMap = expectedExtensions.ToDictionary(e => e.Name, e => e);
            HashSet <string> visitedExtension = new HashSet <string>();

            foreach (Extension actualExtension in actualExtensions)
            {
                Assert.True(visitedExtension.Add(actualExtension.Name), $"Found duplicate extension name {actualExtension.Name} in VSM which is not allowed");
                Assert.True(actualExtension.Properties.ProvisioningState == Microsoft.Azure.Management.Network.Models.ProvisioningState.Succeeded, "provisioningState should be match");
                Assert.True(expectedExtensionMap.ContainsKey(actualExtension.Name), $"Extension {actualExtension.Name} didn't exist in the expectedExtensionMap");
                Extension expectedExtension = expectedExtensionMap[actualExtension.Name];
                Assert.True(expectedExtension.Properties.AutoUpgradeMinorVersion == actualExtension.Properties.AutoUpgradeMinorVersion, "autoUpgradeMinorVersion setting should be same");
                Assert.True(expectedExtension.Properties.Publisher == actualExtension.Properties.Publisher, "publisher setting should be same");
                Assert.True(expectedExtension.Properties.Type == actualExtension.Properties.Type, "extension type should be same");

                if (verifyRolesAppliedTo)
                {
                    Assert.Equal(expectedExtension.Properties.RolesAppliedTo ?? new List <string>()
                    {
                        "*"
                    }, actualExtension.Properties.RolesAppliedTo);
                }
            }
        }
示例#42
0
 /// <nodoc />
 internal DebugLogsAnalyzer(AnalysisInput input, int port, bool enableCaching, bool ensureOrdering)
     : base(input)
 {
     m_port                 = port;
     EnableEvalCaching      = enableCaching;
     EnsureOrdering         = ensureOrdering;
     XlgState               = new XlgDebuggerState(this);
     m_dirData              = new MultiValueDictionary <AbsolutePath, DirectoryMembershipHashedEventData>();
     m_criticalPathAnalyzer = new CriticalPathAnalyzer(input, outputFilePath: null);
     m_lazyCriticalPath     = Lazy.Create(() =>
     {
         m_criticalPathAnalyzer.Analyze();
         return(m_criticalPathAnalyzer.criticalPathData);
     });
     m_state           = new DebuggerState(PathTable, LoggingContext, XlgState.Render, XlgState);
     m_lazyPipPerfDict = new Lazy <Dictionary <PipId, PipExecutionPerformance> >(() =>
     {
         return(m_writeExecutionEntries.ToDictionary(e => e.PipId, e => e.ExecutionPerformance));
     });
     m_lazyPipsBySemiStableHash = new Lazy <Dictionary <long, PipId> >(() =>
     {
         var result = new Dictionary <long, PipId>();
         foreach (var pipId in PipTable.Keys)
         {
             result[PipTable.GetPipSemiStableHash(pipId)] = pipId;
         }
         return(result);
     });
 }
示例#43
0
 public TaskList(IEnumerable<TaskTable> tasks, IEnumerable<CategoryTable> categories, int currentPosition = 0)
 {
     _tasks = tasks.ToList();
     _taskDictionary = _tasks.ToDictionary(task => task.Id);
     _category = categories.ToDictionary(cat => cat.Id);
     _enumerator = new TaskEnumerator(this) { CurrentPosition = currentPosition };
 }
示例#44
0
        /// <inheritdoc />
        public async Task <IList <CompanyIndicatorValues> > GetIndicatorValues(IndicatorType type, IList <int> companyIds, IList <IndicatorProperty> properties)
        {
            var propertiesDict = properties?.ToDictionary(t => t.Name, t => t.Value) ?? new Dictionary <string, int>();
            var indicator      = _indicatorFactory.CreateIndicator(type, propertiesDict);

            return(await GetIndicatorValues(indicator, companyIds));
        }
示例#45
0
        /// <summary>
        /// Parse stream output declarations.
        /// Format is "[slot :] semantic[index][.mask] ; ...".
        /// </summary>
        /// <param name="entries">The parsed entries.</param>
        /// <param name="strides">The output strides.</param>
        /// <param name="streams">The output declarations to parse.</param>
        public static void Parse(IList<ShaderStreamOutputDeclarationEntry> entries, out int[] strides, string[] streams, IList<Variable> fields)
        {
            strides = new int[4];

            var fieldsBySemantic = fields.ToDictionary(x => Semantic.Parse(x.Qualifiers.OfType<Semantic>().Single().Name));

            for (int streamIndex = 0; streamIndex < streams.Length; ++streamIndex)
            {
                // Parse multiple declarations separated by semicolon
                var stream = streams[streamIndex];
                foreach (var streamOutput in stream.Split(';'))
                {
                    // Parse a single declaration: "[slot :] semantic[index][.mask]"
                    var match = streamOutputRegex.Match(streamOutput);
                    if (!match.Success)
                        throw new InvalidOperationException("Could not parse stream output.");

                    var streamOutputDecl = new ShaderStreamOutputDeclarationEntry();

                    // Split semantic into (name, index)
                    var semantic = Semantic.Parse(match.Groups[3].Value);

                    streamOutputDecl.SemanticName = semantic.Key;
                    streamOutputDecl.SemanticIndex = semantic.Value;
                    //if (streamOutputDecl.SemanticName == "$SKIP")
                    //    streamOutputDecl.SemanticName = null;

                    var matchingField = fieldsBySemantic[semantic];
                    var matchingFieldType = matchingField.Type.TypeInference.TargetType ?? matchingField.Type;

                    if (matchingFieldType is VectorType)
                        streamOutputDecl.ComponentCount = (byte)((VectorType)matchingFieldType).Dimension;
                    else if (matchingFieldType is ScalarType)
                        streamOutputDecl.ComponentCount = 1;
                    else
                        throw new InvalidOperationException(string.Format("Could not recognize type of stream output for {0}.", matchingField));
                        
                    var mask = match.Groups[5].Value;
                    ParseMask(mask, ref streamOutputDecl.StartComponent, ref streamOutputDecl.ComponentCount);

                    byte.TryParse(match.Groups[2].Value, out streamOutputDecl.OutputSlot);

                    streamOutputDecl.Stream = streamIndex;

                    strides[streamOutputDecl.OutputSlot] += streamOutputDecl.ComponentCount * sizeof(float);
                    entries.Add(streamOutputDecl);
                }
            }
        }
		public override void UpdateNodeList(IList<Uri> newClusterState, Uri sniffNode = null)
		{
			try
			{
				this._readerWriter.EnterWriteLock();
				this.NodeUris = newClusterState;
				this.UriLookup = newClusterState.ToDictionary(k => k, v => new EndpointState()
				{
					Attemps = v.Equals(sniffNode) ? 1 : 0
				});
			}
			finally
			{
				this._readerWriter.ExitWriteLock();
			}
		}
        public IDictionary<string, IList<string>> Join(IList<string> originalData, IList<string> crushedData)
        {
            var result = originalData.ToDictionary<string, string, IList<string>>(variable => variable,
                variable => new List<string>());

            foreach (var originalString in originalData)
            {
                foreach (var crushedString in crushedData.Where(crushedString => _estimater.Estimate(
                    GetMetrics(originalString, crushedString),
                    originalString.Length, crushedString.Length) > _joiningBorder))
                {
                    result[originalString].Add(crushedString);
                }
            }

            return result;
        }
示例#48
0
        public static IDictionary<string, int> TraverseWithBFS(string start, IList<string> searched)
        {
            Dictionary<string, int> searchedNodesDistances = searched.ToDictionary(node => node, node => -1);
            HashSet<string> visited = new HashSet<string>();
            Queue<string> mainQueue = new Queue<string>();
            int level = 0;

            if (!graph.ContainsKey(start))
            {
                return searchedNodesDistances;
            }

            mainQueue.Enqueue(start);
            visited.Add(start);

            while (mainQueue.Count > 0)
            {
                Queue<string> neighbours = new Queue<string>();
                while (mainQueue.Count > 0)
                {
                    string currentNode = mainQueue.Dequeue();

                    if (searchedNodesDistances.ContainsKey(currentNode) && searchedNodesDistances[currentNode] == -1)
                    {
                        searchedNodesDistances[currentNode] = level;
                    }

                    foreach (var node in graph[currentNode])
                    {
                        if (visited.Contains(node))
                        {
                            continue;
                        }

                        neighbours.Enqueue(node);
                        visited.Add(node);
                    }
                }
                mainQueue = neighbours;
                level++;
            }

            return searchedNodesDistances;
        }
示例#49
0
        public void GuardarRedes(IList<Resultado> lista, string archivo, IList<FichaIndicadores> fichas)
        {
            var map = fichas.ToDictionary(x => x.Nombre);
            var grupos = lista.ToLookup(x => x.Tipo_item);

            using (var pck = new ExcelPackage(new FileInfo(archivo))) {
                try {
                    foreach (var grupo in grupos) {
                        if (!map.ContainsKey(grupo.Key))
                            continue;
                        Ficha = map[grupo.Key];
                        CrearHoja(grupo.ToList(), Ficha.Nombre, pck);
                    }
                    pck.Save();
                } catch (Exception ex) {
                    AppNotifier.Print("Error " + ex.Message, ex);
                }
            }
        }
示例#50
0
		private CalculationListCollection List(IList<AirWaybillData> data)
		{
			var awbs = data.ToDictionary(x => x.Id, x => x);

			var applications = _applications.GetByAirWaybill(awbs.Select(x => x.Key).ToArray()).ToArray();

			var tariffs = _senders.GetTariffs(applications.Select(x => x.SenderId ?? 0).ToArray());

			var items = GetItems(applications, tariffs);

			var info = GetInfo(data, applications, tariffs);

			var groups = GetGroups(data, items);

			return new CalculationListCollection
			{
				Groups = groups.ToArray(),
				Total = _awbs.Count(),
				Info = info,
				TotalBalance = _balances.SumBalance().ToString("N2")
			};
		}
示例#51
0
        public AgileBoardIssues(IList<JiraIssue> issues, IList<RawAgileEpic> epics, IList<RawAgileSprint> sprints)
        {
            Issues = issues;
            Epics = epics;
            Sprints = sprints;

            _issuesByKey = issues.ToDictionary(i => i.Key, i => i);
            _epicsByKey = Epics.ToDictionary(i => i.Key, i => i);

            foreach (var issue in issues)
            {
                foreach (var sprintId in issue.SprintIds)
                {
                    if (_issuesBySprint.ContainsKey(sprintId) == false)
                        _issuesBySprint[sprintId] = new List<JiraIssue>();

                    _issuesBySprint[sprintId].Add(issue);
                }

                issue.EpicName = GetEpicName(issue.EpicLink);
            }
        }
示例#52
0
        private TypeAccessor(Type type)
        {
            this.type = type;

            propertyGetterDic = new Dictionary<string, Func<object, object>>();
            propertySetterDic = new Dictionary<string, Action<object, object>>();

            var properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(o => o.GetIndexParameters().Length == 0).ToList();
            propertyGetterDic = properties.Where(o => o.CanRead).ToDictionary(o => o.Name, o => DelegateAccessor.CreatePropertyGetter(o));
            propertySetterDic = properties.Where(o => o.CanWrite).ToDictionary(o => o.Name, o => DelegateAccessor.CreatePropertySetter(o));

            readWriteProperties = properties.Where(o => o.CanRead && o.CanWrite).ToList();
            readWritePropertyGetters = readWriteProperties.Select(o => propertyGetterDic[o.Name]).ToList();
            readWritePropertySetters = readWriteProperties.Select(o => propertySetterDic[o.Name]).ToList();

            clonePropertyDic = readWriteProperties.ToDictionary(o => o.Name, o => DelegateAccessor.CreatePropertyCloner(o));

            readWriterPropertyCloners = readWriteProperties.Select(o => clonePropertyDic[o.Name]).ToList();

            var fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).ToList();
            fieldGetterDic = fields.ToDictionary(o => o.Name, o => DelegateAccessor.CreateFieldGetter(o));
            fieldSetterDic = fields.ToDictionary(o => o.Name, o => DelegateAccessor.CreateFieldSetter(o));

            cloneFieldDic = fields.Where(o => !o.IsInitOnly).ToDictionary(o => o.Name, o => DelegateAccessor.CreateFieldCloner(o));
            fieldCloners = fields.Where(o => !o.IsInitOnly).Select(o => cloneFieldDic[o.Name]).ToList();

            //Where(o => !o.IsInitOnly).
            var cloneGetters = fields.Select(o => fieldGetterDic[o.Name]).ToArray();
            var cloneSetters = fields.Select(o => fieldSetterDic[o.Name]).ToArray();

            cloneFields = (source, target, fieldHandler) =>
            {
                for (var i = 0; i < cloneGetters.Length; i++)
                {
                    var v = fieldHandler(cloneGetters[i](source));
                    cloneSetters[i](target, v);
                }
            };
        }
示例#53
0
		/// <summary>
		///     Initalizes the Marker with specified protections and packers.
		/// </summary>
		/// <param name="protections">The protections.</param>
		/// <param name="packers">The packers.</param>
		public virtual void Initalize(IList<Protection> protections, IList<Packer> packers) {
			this.protections = protections.ToDictionary(prot => prot.Id, prot => prot, StringComparer.OrdinalIgnoreCase);
			this.packers = packers.ToDictionary(packer => packer.Id, packer => packer, StringComparer.OrdinalIgnoreCase);
		}
        private Dictionary<Webpage, List<MobileFriendlyNavigationChildNode>> GetMobileFriendlyNavigationChildNodes(IList<Webpage> parents)
        {
            Webpage webpageAlias = null;
            MobileFriendlyNavigationChildNode nodeAlias = null;

            var countSubNodes = QueryOver.Of<Webpage>()
                .Where(x => x.Parent.Id == webpageAlias.Id && x.RevealInNavigation && x.PublishOn != null)
                .ToRowCountQuery();

            var parentIds = parents.Select(webpage => webpage.Id).ToList();
            var nodes = _session.QueryOver(() => webpageAlias)
                .Where(node => node.RevealInNavigation && node.Published)
                .Where(node => node.Parent.Id.IsIn(parentIds))
                .OrderBy(x => x.DisplayOrder).Asc
                .SelectList(x => x.Select(y => y.Id).WithAlias(() => nodeAlias.Id)
                    .Select(y => y.Parent.Id).WithAlias(() => nodeAlias.ParentId)
                    .Select(y => y.Name).WithAlias(() => nodeAlias.Name)
                    .Select(y => y.UrlSegment).WithAlias(() => nodeAlias.UrlSegment)
                    .Select(y => y.PublishOn).WithAlias(() => nodeAlias.PublishOn)
                    .Select(y => y.DocumentType).WithAlias(() => nodeAlias.DocumentType)
                    .Select(y => y.DisplayOrder).WithAlias(() => nodeAlias.DisplayOrder)
                    .SelectSubQuery(countSubNodes).WithAlias(() => nodeAlias.ChildCount))
                .TransformUsing(Transformers.AliasToBean<MobileFriendlyNavigationChildNode>())
                .List<MobileFriendlyNavigationChildNode>().ToList()
                .GroupBy(node => node.ParentId)
                .ToDictionary(grouping => grouping.Key, g => g.ToList());
            return parents.ToDictionary(webpage => webpage,
                webpage =>
                    nodes.ContainsKey(webpage.Id) ? nodes[webpage.Id] : new List<MobileFriendlyNavigationChildNode>());
        }
示例#55
0
        public override void UpdateNodeList(IList<Uri> newClusterState, bool fromStartupHint = false)
        {
            if (fromStartupHint)
                this._seenStartup = true;

            try
            {
                this._readerWriter.EnterWriteLock();
                this._nodeUris = newClusterState;
                this._uriLookup = newClusterState.ToDictionary(k => k, v => new EndpointState());
            }
            finally
            {
                this._readerWriter.ExitWriteLock();
            }
        }
示例#56
0
        private static Dictionary<string, List<Card>> DealCards(Stack<Card> deck, IList<string> playerIds)
        {
            var hands = playerIds.ToDictionary(p => p, p => new List<Card>());

            foreach (var playerId in playerIds)
            {
                for (int i = 0; i < 7; i++)
                {
                    var card = deck.Pop();
                    hands[playerId].Add(card);
                }
            }

            return hands;
        }
示例#57
0
        public IrtDb UpdatePeptides(IList<DbIrtPeptide> newPeptides, IList<DbIrtPeptide> oldPeptides)
        {
            var setNew = new HashSet<long>(newPeptides.Select(pep => pep.Id.HasValue ? pep.Id.Value : 0));
            var dictOld = oldPeptides.ToDictionary(pep => pep.PeptideModSeq);

            using (var session = OpenWriteSession())
            using (var transaction = session.BeginTransaction())
            {
                // Remove peptides that are no longer in the list
                foreach (var peptideOld in oldPeptides)
                {
                    if (!peptideOld.Id.HasValue)
                        continue;

                    if (!setNew.Contains(peptideOld.Id.Value))
                        session.Delete(peptideOld);
                }

                // Add or update peptides that have changed from the old list
                foreach (var peptideNew in newPeptides)
                {
                    DbIrtPeptide peptideOld;
                    if (dictOld.TryGetValue(peptideNew.PeptideModSeq, out peptideOld) &&
                            Equals(peptideNew, peptideOld))
                        continue;

                    // Create a new instance, because not doing this causes a BindingSource leak
                    var peptideNewDisconnected = new DbIrtPeptide(peptideNew);
                    session.SaveOrUpdate(peptideNewDisconnected);
                }

                transaction.Commit();
            }

            return ChangeProp(ImClone(this), im => im.LoadPeptides(newPeptides));
        }
示例#58
0
 public FullPathChanges(IList<PathChangeEntry> entries) {
   _entries = entries;
   _map = new Lazy<Dictionary<FullPath, PathChangeKind>>(() => _entries.ToDictionary(x => x.Path, x => x.Kind));
 }
		void RemoveChildrenNotIn(IList<AXmlObject> srcList)
		{
			Dictionary<int, AXmlObject> srcChildren = srcList.ToDictionary(i => i.StartOffset);
			for(int i = 0; i < this.Children.Count;) {
				AXmlObject child = this.Children[i];
				AXmlObject srcChild;
				
				if (srcChildren.TryGetValue(child.StartOffset, out srcChild) && child.CanUpdateDataFrom(srcChild)) {
					// Keep only one item with given offset (we might have several due to deletion)
					srcChildren.Remove(child.StartOffset);
					// If contaner that needs updating
					if (child is AXmlContainer && child.LastUpdatedFrom != srcChild)
						((AXmlContainer)child).RemoveChildrenNotIn(((AXmlContainer)srcChild).Children);
					i++;
				} else {
					RemoveChild(i);
				}
			}
		}
        private void OverrideGenericTextMetadata(IList<Grouping> groupings, IList<IndicatorMetadata> genericIndicatorMetadata)
        {
            IList<IndicatorMetadata> specificIndicatorMetadataList = reader.GetGroupSpecificIndicatorMetadataTextValues(
                groupings, IndicatorMetadataTextProperties);

            if (specificIndicatorMetadataList.Count > 0)
            {
                Dictionary<int, IndicatorMetadata> metadataMap =
                    genericIndicatorMetadata.ToDictionary(indicatorMetadata => indicatorMetadata.IndicatorId);

                foreach (var specificIndicatorMetadata in specificIndicatorMetadataList)
                {
                    int indicatorId = specificIndicatorMetadata.IndicatorId;

                    if (metadataMap.ContainsKey(indicatorId))
                    {
                        IDictionary<string, string> genericText = metadataMap[indicatorId].Descriptive;
                        IDictionary<string, string> specificText = specificIndicatorMetadata.Descriptive;

                        foreach (var key in specificText.Keys)
                        {
                            if (genericText.ContainsKey(key))
                            {
                                genericText[key] = specificText[key];
                            }
                            else
                            {
                                genericText.Add(key, specificText[key]);
                            }
                        }
                    }
                }
            }
        }