public ExpressionTree BuildExpressionTree(List<AssignStatement> expressions, string calcForWire)
        {
            Dictionary<string, AssignStatement> variableMapping = expressions.ToDictionary(x => x.Variable.Identifier, y => y);
            Dictionary<AssignStatement, IEnumerable<VariableExpression>> dependencyMapping = expressions.ToDictionary(x => x, y => y.Value.GetDependencies());

            return CreateFor(calcForWire, variableMapping, dependencyMapping, new Dictionary<string, ExpressionTree>());
        }
Example #2
0
        public ControlFlowGraph2(MethodBody body)
        {
            _body = body;
            _basicBlocks = new ControlFlowGraph(body).ToList();
            _entries = _basicBlocks.ToDictionary(b => b.Entry, b => b);
            _exits = _basicBlocks.ToDictionary(b => b.Exit, b => b);
            _entryInstructions = _basicBlocks.Select(b => b.Entry).ToList();

            IncludeExceptionHandlers(body);
        }
Example #3
0
        public XMLOpcodeLookup(XDocument document)
        {
            XContainer root = document.Element("BlamScript");

            // Script execution types
            var scriptTypes = from element in root.Element("scriptTypes").Descendants("type")
                              select new
                              {
                                  Opcode = (ushort)XMLUtil.GetNumericAttribute(element, "opcode"),
                                  Name = XMLUtil.GetStringAttribute(element, "name")
                              };
            _scriptTypeNameLookup = scriptTypes.ToDictionary(t => t.Opcode, t => t.Name);
            _scriptTypeOpcodeLookup = scriptTypes.ToDictionary(t => t.Name, t => t.Opcode);

            // Value types
            var valueTypes = new List<ScriptValueType>();
            foreach (var element in root.Element("valueTypes").Descendants("type"))
            {
                var name = XMLUtil.GetStringAttribute(element, "name");
                var opcode = (ushort)XMLUtil.GetNumericAttribute(element, "opcode");
                var size = XMLUtil.GetNumericAttribute(element, "size");
                var quoted = XMLUtil.GetBoolAttribute(element, "quoted", false);
                var tag = XMLUtil.GetStringAttribute(element, "tag", null);

                valueTypes.Add(new ScriptValueType(name, opcode, size, quoted, tag));
            }
            _typeLookupByOpcode = valueTypes.ToDictionary(t => t.Opcode);
            _typeLookupByName = valueTypes.ToDictionary(t => t.Name);

            // Functions
            foreach (var element in root.Element("functions").Descendants("function"))
            {
                var name = XMLUtil.GetStringAttribute(element, "name");
                if (name == "")
                    continue;

                var opcode = (ushort)XMLUtil.GetNumericAttribute(element, "opcode");
                var returnType = XMLUtil.GetStringAttribute(element, "returnType", "void");
                var flags = (uint)XMLUtil.GetNumericAttribute(element, "flags", 0);
                var parameterTypes = element.Descendants("arg").Select(e => XMLUtil.GetStringAttribute(e, "type")).ToArray();

                var info = new ScriptFunctionInfo(name, opcode, returnType, flags, parameterTypes);
                List<ScriptFunctionInfo> functions;
                if (!_functionLookupByName.TryGetValue(name, out functions))
                {
                    functions = new List<ScriptFunctionInfo>();
                    _functionLookupByName[name] = functions;
                }
                functions.Add(info);
                _functionLookupByOpcode[opcode] = info;
            }
        }
Example #4
0
        public Rulebook(List<IRule> rules, List<IModifier> modifiers, Type interactionType)
        {
            this.interactionType = interactionType;

            foreach (IRule rule in rules)
            {
                string interaction = rule.Interaction;

                if (!this.rules.ContainsKey(interaction)) 	this.rules.Add(interaction, new Section(rule));
                else 										this.rules[interaction].Add(rule);
            }

            this.Modifiers = modifiers.ToDictionary<IModifier, string>(i => i.Target);

            // Merge sections that descend from other sections. This means that the hierarchy does not
            // need to be negotiated when looking up rules in a section. For example, if you have some
            // generic "Move" rules and then you have a specific "Move.Run" rule section, the "Move.Run"
            // will have all of the rules in "Move" added to it. Since rules are selected in list order
            // the specific "Move.Run" rules will be checked first before moving on to the generic "Move" rules.
            foreach (KeyValuePair<string, Section> kvp in this.rules)
            {
                string interaction 	= kvp.Key;
                int trim 			= interaction.LastIndexOf('.');

                if (trim > 0)
                {
                    interaction = interaction.Remove(trim);
                    if (this.rules.ContainsKey(interaction)) kvp.Value.Merge(this.rules[interaction]);
                }
            }
        }
Example #5
0
 public IEnumerable<MouseDragAction> GetDrawInstructions(List<ColorSpot> colorPalette, IDictionary<string, string> options = null, IBrushChanger brushChanger = null)
 {
     if (!colorPalette.Any())
     {
         throw new ArgumentException("I need some colors. Give me some colors. Thanks!");
     }
     var output = new List<MouseDragAction>();
     var colorPixels = colorPalette.ToDictionary(colorSpot => colorSpot, colorSpot => new List<Point>());
     using (var bitmap = new Bitmap(_bitmapPath))
     {
         bitmap.LoopThroughPixels((point, color) =>
             {
                 var selectedColor = colorPalette.OrderBy(c => c.Color.DifferenceTo(color)).FirstOrDefault();
                 if (selectedColor == null || !colorPixels.ContainsKey(selectedColor) ||
                     selectedColor.Color.DifferenceTo(Color.White) == 0)
                 {
                     return;
                 }
                 colorPixels[selectedColor].Add(point);
             });
     }
     foreach (var colorPixel in colorPixels.Where(colorPixel => colorPixel.Value.Any()))
     {
         output.Add(new MouseDragAction(new List<Point> { colorPixel.Key.Point }, true, colorPixel.Key.Color));
         var actions = colorPixel.Value.Select(point => new MouseDragAction(new List<Point> { point })).ToList();
         if (options.GetBoolValueOrDefault("MixPoints", false))
         {
             actions = actions.Shuffle().ToList();
         }
         output.AddRange(actions);
     }
     return output.ToArray();
 }
        /// <summary>
        /// NEED TO REFACTOR THIS TO A REPORT
        /// </summary>
        /// <param name="interventionTypeId"></param>
        /// <param name="year"></param>
        /// <param name="diseaseId"></param>
        /// <param name="customAggRule"></param>
        /// <returns></returns>
        public List<AdminLevelIndicators> GetDistrictIndicatorTrees(int interventionTypeId, int year, int diseaseId, Func<AggregateIndicator, object, object> customAggRule, int reportingLevel)
        {
            List<AdminLevelIndicators> list = new List<AdminLevelIndicators>();
            Dictionary<int, AdminLevelIndicators> dic = new Dictionary<int, AdminLevelIndicators>();
            OleDbConnection connection = new OleDbConnection(DatabaseData.Instance.AccessConnectionString);
            using (connection)
            {
                connection.Open();
                OleDbCommand command = new OleDbCommand();
                list = GetAdminLevels(command, connection, false);
                dic = list.ToDictionary(n => n.Id, n => n);
                AddIntvIndicators(interventionTypeId, year, dic, command, connection, customAggRule);
                AddSurveyIndicators(diseaseId, year, dic, command, connection, customAggRule);
                AddDistroIndicators(diseaseId, year, dic, command, connection, customAggRule);
            }

            var rootNodes = new List<AdminLevelIndicators>();
            foreach (var node in list)
            {
                if (node.ParentId.HasValue && node.ParentId.Value > 0)
                {
                    AdminLevelIndicators parent = dic[node.ParentId.Value];
                    node.Parent = parent;
                    parent.Children.Add(node);
                }
                else
                {
                    rootNodes.Add(node);
                }
            }
            return list.Where(a => a.LevelNumber == reportingLevel).ToList();
        }
Example #7
0
 public CountryCodeHelper(List<Country> countries)
 {
     _countryCodes = countries.ToDictionary(x => x.Name, x => x.CountryCode);
     _currencyCodes = countries
         .Distinct((x, y) => x.CountryCode == y.CountryCode)
         .ToDictionary(x => x.CountryCode, x => x.CurrencyCode);
 }
Example #8
0
        public override void SetDataValues(List <TypedValue> values, Document doc)
        {
            var dictValues = values?.ToDictionary();

            Height           = dictValues.GetValue("Height", 0d);
            IsVisualIllumsOn = dictValues.GetValue("IsVisualIllumsOn", true);
        }
        private static void SetExecuted(List<MigrationInfo> migrations)
        {
            MigrationLogic.EnsureMigrationTable<SqlMigrationEntity>();

            var first = migrations.FirstOrDefault();

            var executedMigrations = Database.Query<SqlMigrationEntity>().Select(m => m.VersionNumber).OrderBy().ToList().Where(d => first == null || first.Version.CompareTo(d) <= 0).ToList();

            var dic = migrations.ToDictionary(a => a.Version, "Migrations in folder");

            foreach (var ver in executedMigrations)
            {
                var m = dic.TryGetC(ver);
                if (m != null)
                    m.IsExecuted = true;
                else
                    migrations.Add(new MigrationInfo
                    {
                        FileName = null,
                        Comment = ">> In Database Only <<",
                        IsExecuted = true,
                        Version = ver
                    });

            }

            migrations.Sort(a => a.Version);
        }
Example #10
0
        public PluginEntity GetPluginEntity(Assembly _Assembly, string _Url, out List<Function> _Functions)
        {
            //this.Functions.ForEach(x => { x.Url = _Url; x.Assembly = _Assembly; });  // x 是临时的~~ 修改不了

            //for (int i = 0; i < this.Functions.Count; i++)   // 这样写赋值不上
            //{

            //    //Functions[i].Url = _Url;
            //    this.Functions[i].Url = "asdfasdf";
            //    this.Functions[i].Assembly = _Assembly;
            //}

            _Functions = Functions.Select(x => new Function()
                {
                    Action = x.Action,
                    Assembly = _Assembly,
                    Controller = x.Controller,
                    NameSpace = x.NameSpace,
                    ControllerType = x.ControllerType,
                    Name = x.Name,
                    Url = _Url
                }).ToList();

            return new PluginEntity(
                        Name: this.Name,
                        Author: this.Author,
                        Description: this.Description,
                        Functions: _Functions.ToDictionary(x => x.Name), // 通过Function对象的Name属性作为key
                        Assembly: _Assembly
                       );
        }
Example #11
0
        public void Read(IConfiguration configuration)
        {
            var value = configuration["RetryCount"];
            if (!string.IsNullOrEmpty(value))
            {
                RetryCount = int.Parse(value);
            }
			value = configuration["DefaultAdBlock"];
            if (!string.IsNullOrEmpty(value))
            {
                DefaultAdBlock = value;
            }

            var items = new List<AdBlock>();
            foreach (var subConfig in configuration.GetSection("AdBlock").GetChildren())
            {
                var item = new AdBlock { Name = subConfig.Key };
				value = subConfig["Origin"];
                if (!string.IsNullOrEmpty(value))
                {
                    item.Origin = value;
                }
				value = subConfig["ProductCode"];
                if (!string.IsNullOrEmpty(value))
                {
                    item.ProductCode = value;
                }
                items.Add(item);
            }
            AdBlocks = items.ToDictionary(
                item => item.Name, 
                item => item,
                StringComparer.OrdinalIgnoreCase);
        }
Example #12
0
        private void ActualizarPantalla(List<Pasaje> pasajes)
        {
            var diccionarioDePasajes = new Dictionary<int, Pasaje>();

            #region Cargar el diccionario a mostrar en la grilla

            if (pasajes == null)
            {

            }
            else
            {
                //El datasource se carga con la lista de pasajes recibida por parámetro
                diccionarioDePasajes = pasajes.ToDictionary(p => p.ID, p => p);
            }

            //Muestra en la grilla el contenido de los pasajes que se encuentran cargados en el diccionario
            var bind = diccionarioDePasajes.Values.Select(p => new
            {
                Codigo_Pasaje = p.Codigo_Pasaje,
                Pasajero = p.ID_Cliente,
                Numero_Butaca = p.ID_Butaca,
                Precio = p.Precio
            });

            #endregion

            DgvPasaje.DataSource = bind.ToList();
            AgregarBotonesDeColumnas();

            DgvPasaje.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
        }
 private void GetInstanceStates()
 {
     var loadBalancer = command.Parameters[0];
     var elb = new ELB();
     this.states = elb.InstanceState(loadBalancer);
     this.stateMap = states.ToDictionary(k => k.InstanceId, v => v.State);
 }
Example #14
0
        public void Read(IConfiguration configuration)
        {
            string value;
            if (configuration.TryGet("RetryCount", out value))
            {
                RetryCount = int.Parse(value);
            }
            if (configuration.TryGet("DefaultAdBlock", out value))
            {
                DefaultAdBlock = value;
            }

            var items = new List<AdBlock>();
            foreach (var subConfig in configuration.GetSubKeys("AdBlock"))
            {
                var item = new AdBlock { Name = subConfig.Key };
                if (subConfig.Value.TryGet("Origin", out value))
                {
                    item.Origin = value;
                }
                if (subConfig.Value.TryGet("ProductCode", out value))
                {
                    item.ProductCode = value;
                }
                items.Add(item);
            }
            AdBlocks = items.ToDictionary(
                item => item.Name,
                item => item,
                StringComparer.OrdinalIgnoreCase);
        }
Example #15
0
        public ApiObjectConstructor(CpuBlock c, string name, List <CpuApiProperty> staticProps) : base(c.Interp, new JsString(name))
        {
            cpu   = c;
            Props = staticProps?.ToDictionary(x => x.Name);
            var properties = new PropertyDictionary(Props?.Count ?? 0, checkExistingKeys: false);

            if (Props != null)
            {
                foreach (var kp in Props)
                {
                    if (kp.Value is CpuApiFunc f)
                    {
                        if (f.Name == ConstructorMethodName)
                        {
                            Constructor = f.Implementation;
                        }
                        else
                        {
                            properties[kp.Key] = new PropertyDescriptor(new ClrFunctionInstance(Engine, kp.Key, (t, a) => WrappedApi(t, a, f.Implementation), f.Arguments.Count, PropertyFlag.Configurable), PropertyFlag.Configurable);
                        }
                    }
                    else if (kp.Value is CpuApiValue v)
                    {
                        properties[kp.Key] = new PropertyDescriptor(v.Value, PropertyFlag.Configurable);
                    }
                }
            }
            SetProperties(properties);
        }
 public AppenderConfigProperties(List<pt.sapo.gis.trace.configuration.Appender.Property> properties)
 {
     if (properties != null)
     {
         this.properties = properties.ToDictionary(p => p.Name, p => p.Content);
     }
 }
Example #17
0
        public static void FillNodePropertyValues(
            this Tree<ItemModel> tree,
            List<UnitPropertyModel> propertyModels,
            IEnumerable<UnitPropertyValueModel> propertyValues)
        {
            var propDict = propertyModels.GroupBy(p => p.UnitId).ToDictionary(p => p.Key, p => p.ToList());
            var propNameDict = propertyModels.ToDictionary(p => p.Id, p => p.Name);
            var propValsDict = propertyValues
                .GroupBy(p => p.UnitId)
                .ToDictionary(p => p.Key,
                    p => p.GroupBy(g => g.PropertyId).ToDictionary(g => propNameDict[g.Key], g => g.FirstOrDefault()));
            foreach (var node in tree.FlatNodes)
            {
                if (!propDict.ContainsKey(node.Value.Id))
                    continue;
                var nodeProps = propDict[node.Value.Id];
                foreach (var prop in nodeProps)
                {
                    var clone = prop.Clone();
                    if (!node.Children.Any())
                        clone.PropertyValue = propValsDict[node.Value.Id][clone.Name];
                    node.Value.Properties.Add(clone.Name, clone);
                }
            }

            foreach (var root in tree.Roots)
            {
                SetNodeProps(root, root.Value.Properties, propValsDict);
            }
        }
Example #18
0
        public void SetDataValues(List <TypedValue> values, Document doc)
        {
            var dictValues = values?.ToDictionary();

            TileSize    = dictValues.GetValue("TileSize", 1d);
            Transparent = dictValues.GetValue("Transparent", (byte)60);
        }
Example #19
0
        public void Weave()
        {
            Type aspectAttributes = null;
            var fieldBuilders = new List<FieldBuilder>();
            var typeBuilder = typeof(object).DefineType("Aspects".ToUniqueName(), attributes: TypeAttributes.Sealed | TypeAttributes.Abstract);
            var cctor = typeBuilder.DefineConstructor(MethodAttributes.Private | MethodAttributes.Static | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName, CallingConventions.Standard, Type.EmptyTypes).GetILGenerator();

            aspectTypes.ForEach((aspect, i) => {
                var fieldBuilder = typeBuilder.DefineField("Aspect_{0}".Fmt(i).ToUniqueName(), aspect, FieldAttributes.Private | FieldAttributes.FamANDAssem | FieldAttributes.Static);
                var ctor = fieldBuilder.FieldType.GetConstructor(Type.EmptyTypes);

                if (ctor.IsNull()) {
                    throw new AspectWeavingException(Resources.AspectsDefaultCtorHasNotBeenFound.Fmt(fieldBuilder.FieldType.FullName));
                }

                cctor.Emit(OpCodes.Newobj, ctor);
                cctor.Emit(OpCodes.Stsfld, fieldBuilder);
                fieldBuilders.Add(fieldBuilder);
            });

            cctor.Emit(OpCodes.Ret);
            aspectAttributes = typeBuilder.CreateType();

            aspects = fieldBuilders.ToDictionary(builder => builder.FieldType, builder => {
                return aspectAttributes.GetField(builder.Name, BindingFlags.Static | BindingFlags.NonPublic);
            });
        }
Example #20
0
        public bool Refresh(ProviderMember aMember, List<ProviderCategory> categoryList)
        {
            CategoryList = new List<SelectList>();
            AlternateCategoryMapList = new List<AlternateCategoryMapVM>();

            List<KeyValuePair<long, string>> ddList = new List<KeyValuePair<long, string>>();
            ddList.Add(_nullCategory);
            ddList.AddRange(categoryList.ToDictionary(aCategory => aCategory.Id.Value, aCategory => aCategory.Title));

            foreach (ProviderAlternateCategoryId altCategory in aMember.AlternateCategoryList)
            {
                if(!string.IsNullOrEmpty(altCategory.DisplayName))
                {
                    long selectedCatId = altCategory.CategoryId ?? -1;
                    AlternateCategoryMapList.Add(new AlternateCategoryMapVM
                    {
                        AlternateTitle = altCategory.DisplayName,
                        AlternateId = altCategory.AlternateId,
                        MapId = selectedCatId
                    });

                    CategoryList.Add(new SelectList(ddList, "key", "value", selectedCatId));
                }
            }
            return true;
        }
Example #21
0
        private void btn_OK_Click(object sender, EventArgs e)
        {
            if (!ValidateForm())
            {
                return;
            }

            Options.ApiKey                = textApiKey.Text;
            Options.ClientId              = txtClientId.Text;
            Options.PersistGoogleKey      = chkSaveKey.Checked;
            Options.PersistMicrosoftCreds = chkSaveCred.Checked;
            Options.SendPlainTextOnly     = chkPlainTextOnly.Checked;
            Options.SelectedProvider      = MtTranslationOptions.GetProviderType(comboProvider.Text);
            Options.UseCatID              = chkCatId.Checked;
            Options.CatId              = txtCatId.Text;
            Options.ResendDrafts       = chkResendDrafts.Checked;
            Options.UsePreEdit         = chkUsePreEdit.Checked;
            Options.UsePostEdit        = chkUsePostEdit.Checked;
            Options.PreLookupFilename  = txtPreEditFileName.Text;
            Options.PostLookupFilename = txtPostEditFileName.Text;
            Options.LanguagesSupported = _correspondingLanguages?.ToDictionary(lp => lp.TargetCultureName,
                                                                               lp => Options.SelectedProvider.ToString());

            this.DialogResult = DialogResult.OK;
            this.Close();             //dispose????
        }
Example #22
0
        private void ActualizarPantalla(List<Encomienda> encomienda)
        {
            var diccionarioDeEncimiendas = new Dictionary<int, Encomienda>();

            #region Cargar el diccionario a mostrar en la grilla

            if (encomienda == null)
            {

            }
            else
            {
                //El datasource se carga con la lista de pasajes recibida por parámetro
                diccionarioDeEncimiendas = encomienda.ToDictionary(e => e.ID, e => e);
            }

            //Muestra en la grilla el contenido de los pasajes que se encuentran cargados en el diccionario
            var bind = diccionarioDeEncimiendas.Values.Select(e => new
            {
                Codigo_Pasaje = e.Codigo_Encomienda,
                Numero_Butaca = e.KG,
                Precio = e.Precio
            });

            #endregion

            DgvEncomiendas.DataSource = bind.ToList();
            AgregarBotonesDeColumnas();

            DgvEncomiendas.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
        }
Example #23
0
        public DrinksContainer LoadDrinks(string source)
        {
            using (StringReader stringReader = new StringReader(source))
            {
                List<Drink> trainingSet = new List<Drink>();

                string line = stringReader.ReadLine();
                string[] columnNames = line.Split(';').Skip(COLUMNS_TO_SKIP).ToArray();

                while ((line = stringReader.ReadLine()) != null)
                {
                    string[] values = line.Split(';');
                    int id = int.Parse(values[0]);
                    string drinkName = values[1],
                           url = values[2],
                           imageUrl = values[3];

                    double[] trainingRow = new double[values.Length - COLUMNS_TO_SKIP];

                    for (int i = 0; i < trainingRow.Length - 1; i++)
                    {
                        trainingRow[i] = double.Parse(values[i + COLUMNS_TO_SKIP], System.Globalization.CultureInfo.InvariantCulture);
                    }

                    trainingSet.Add(new Drink(id, drinkName, url, trainingRow, imageUrl));
                }

                return new DrinksContainer(trainingSet.ToDictionary(r => r.ID, r => r), columnNames);
            }
        }
Example #24
0
        static Utils()
        {
            var oneByte = new List<OpCode>();
            var twoByte = new List<OpCode>();

            foreach (var field in typeof(OpCodes).GetFields(BindingFlags.Public | BindingFlags.Static))
            {
                var op = (OpCode)field.GetValue(null);

                if (op.Size == 1)
                {
                    oneByte.Add(op);
                    continue;
                }

                if (op.Size == 2)
                {
                    twoByte.Add(op);
                    continue;
                }

                throw new Exception("Unexpected op size for " + op);
            }

            OneByteOps = oneByte.ToDictionary(d => (int)d.Value, d => d);
            TwoByteOps = twoByte.ToDictionary(d => (int)(d.Value & 0xFF), d => d);
        }
Example #25
0
 // This is created by reflection, so be careful when changing/adding parameters
 public InMemoryRuntimeConfiguration(IInMemoryResourceConfiguration resourceConfiguration, List <TResource> initialData)
     : base(resourceConfiguration)
 {
     initialData = initialData ?? new List <TResource>();
     _data       = new ConcurrentDictionary <string, TResource>(initialData?.ToDictionary(x => GetPrimaryKeyValue(x).ToString()));
     PropertyConfigurationBuilderExtensions.SetGlobalPrimaryKeyInteger(GetMaxPrimaryKeyIntegerValueOrDefault());
 }
Example #26
0
        public void SetDataValues(List <TypedValue> values, Document doc)
        {
            var dictValues = values?.ToDictionary();

            Name            = dictValues.GetValue("Name", $"Площадка {(PlaceModel?.Places?.Count + 1) ?? 1}");
            isVisualPlaceOn = dictValues.GetValue("IsVisualPlaceOn", true);
        }
Example #27
0
        public void SetDataValues(List <TypedValue> values, Document doc)
        {
            var dictValues = values?.ToDictionary();

            StepCalcPointInFront = dictValues.GetValue("StepCalcPointInFront", 0.4);
            LineFrontWidth       = dictValues.GetValue("LineFrontWidth", 0.8);
        }
Example #28
0
        public ActionResult Index()
        {
            var currentUser = this.userService.GetCurrentUser();

            var sharedCourses = this.storage.GetCourses(currentUser.Id);
            var courses = this.storage.GetCourses(User.Identity.Name);
            var all = sharedCourses.Union(courses);

            var owners = all.Select(i => i.Owner).Distinct().ToList();

            var users = new List<User>();
            foreach (var owner in owners)
            {
                var copy = owner;
                users.AddRange(this.userService.GetUsers(i => i.Username == copy));
            }
            var dic = users.ToDictionary(i => i.Username, j => j.Username);


            var viewCourses = all.Select(i => new ViewCourseModel
            {
                Id = i.Id,
                Name = i.Name,
                Created = i.Created,
                Updated = i.Updated,
                Locked = i.Locked ?? false,
                Shared = i.Owner != currentUser.Username,
                OwnerName = dic.ContainsKey(i.Owner) ? dic[i.Owner] : i.Owner,
                UpdatedByName = i.UpdatedBy
            });
            return View(viewCourses.OrderByDescending(i => i.Updated).AsEnumerable());
        }
 public AdsBlock(int blockId, List<string> baseRefsList)
 {
     BlockPositionStats = new BlockPositionStats(blockId);
     _blockId = blockId;
     _baseRefsList = baseRefsList;
     _targetSamplesForBGroup = TargetSamplesPerAd * baseRefsList.Count;
     _refPerfomanceStats = _baseRefsList.ToDictionary(x => x, x => new AdStats());
 }
        public void SetDataValues(List <TypedValue> values, Document doc)
        {
            var dictValues = values?.ToDictionary();
            var constr     = WindowConstructions[0];

            Name  = dictValues.GetValue("Name", constr.Name);
            Depth = dictValues.GetValue("Depth", constr.Depth);
        }
Example #31
0
        public void Compile(string src)
        {
            // todo1[ak] check args
            string[] lines = src.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);

            _routines = this.CompileLines(lines);
            _routinesByName = _routines.ToDictionary(r => r.Name, r => r);
        }
Example #32
0
        private static Dictionary<string, string> ReadTranslationData()
        {
            List<UserData> userStringList = new List<UserData>();

            XmlSerializer serializer = new XmlSerializer(userStringList.GetType());
            userStringList = (List<UserData>)serializer.Deserialize(XmlReader.Create(SettingsPath));
            return userStringList.ToDictionary(n => n.Tag, n => n.Text.Replace("__BREAK__", Environment.NewLine));
        }
Example #33
0
        private static Dictionary<PrimeUsbDataType, PrimeUsbDataHeader> GetHeaders()
        {
            var t = new List<PrimeUsbDataHeader>(new[]
            {new PrimeUsbDataHeader {Header = new byte[]{0x00, 0x00, 0xf7, 0x01}, Type = PrimeUsbDataType.File},
            new PrimeUsbDataHeader {Header = new byte[]{0x00, 0x00, 0xf2, 0x01}, Type = PrimeUsbDataType.Message}});

            return t.ToDictionary(header => header.Type);
        }
Example #34
0
        public void SetDataValues(List <TypedValue> values, Document doc)
        {
            var dictValues = values?.ToDictionary();

            IsVisualIllumsOn         = dictValues.GetValue("IsVisualIllumsOn", false);
            IsVisualTreeOn           = dictValues.GetValue("IsVisualTreeOn", false);
            isVisualTreeOnOffForLoad = dictValues.GetValue("isVisualTreeOnOffForLoad", false);
        }
Example #35
0
        public void SetDataValues(List <TypedValue> values, Document doc)
        {
            var dictValues = values?.ToDictionary();

            HouseName  = dictValues.GetValue("HouseName", "");
            HouseId    = dictValues.GetValue("HouseId", 0);
            FrontLevel = dictValues.GetValue("FrontLevel", 0);
        }
Example #36
0
        public void SetDataValues(List <TypedValue> values, Document doc)
        {
            var dictValues = values?.ToDictionary();

            Name            = dictValues.GetValue("Name", "Группа");
            IsVisualFrontOn = dictValues.GetValue("IsVisualFrontOn", true);
            FrontLevel      = dictValues.GetValue("FrontLevel", 2);
        }
        public InitialComponentsInjecter(
            DiContainer container, List<Component> injectableComponents)
        {
            _container = container;
            _componentMap = injectableComponents.ToDictionary(x => x, x => new ComponentInfo(x));

            // Installers are always injected just before calling Install()
            Assert.That(injectableComponents.Where(x => x.GetType().DerivesFrom<MonoInstaller>()).IsEmpty());
        }
Example #38
0
 public void set_colors(List<category_colors> colors, info_type column) {
     try {
         colors_ = colors.ToDictionary(x => x.name, x => x);
     } catch {
         colors_ = null;
         logger.Error("invalid color names " + util.concatenate(colors.Select(x => x.name), ", ") );
     }
     column_ = column;
 }
Example #39
0
        private void ActualizarPantalla(List<Ruta> rutas)
        {
            //Borro lo que esta actualmente en la grilla
            BorrarDataGridView();
            var rutasDictionary = new Dictionary<int, Ruta>();

            #region Cargar comboBox
            CmbTipoServicio.DataSource = ServicioPersistencia.ObtenerTodos();
            CmbTipoServicio.ValueMember = "ID_Servicio";
            CmbTipoServicio.DisplayMember = "Nombre";

            CmbCiudadOrigen.DataSource = CiudadPersistencia.ObtenerTodos();
            CmbCiudadOrigen.ValueMember = "ID";
            CmbCiudadOrigen.DisplayMember = "Nombre";

            CmbCiudadDestino.DataSource = CiudadPersistencia.ObtenerTodos();
            CmbCiudadDestino.ValueMember = "ID";
            CmbCiudadDestino.DisplayMember = "Nombre";
            #endregion

            #region Obtengo el diccionario de rutas

            //El datasource debe ser todos los registros de rutas almacenadas en la base de datos
            if (rutas == null)
            {
                BorrarFiltrosUI();
                _rutas = RutaPersistencia.ObtenerTodas();
                //Convierto todas las rutas a un diccionario con entradas de la forma: (ID, Objeto)
                rutasDictionary = _rutas.ToDictionary(a => a.ID, a => a);
            }
            else
            {
                CmbTipoServicio.Text = "SERVICIO";
                CmbCiudadOrigen.Text = "CIUDAD ORIGEN";
                CmbCiudadDestino.Text = "CIUDAD DESTINO";
                //Convierto la lista de rutas a un diccionario con entradas de la forma: (ID, Objeto)
                rutasDictionary = rutas.ToDictionary(a => a.ID, a => a);
            }

            #endregion

            //Creo un bind para luego setearselo directamente a la DataGridView
            var bind = rutasDictionary.Values.Select(a => new
            {
                CodigoRuta = a.Codigo_Ruta,
                TipoServicio = RutaPersistencia.ObtenerServicioPorID(a.ID_Servicio),
                CiudadOrigen = RutaPersistencia.ObtenerCiudadPorID(a.ID_Ciudad_Origen),
                CiudadDestino = RutaPersistencia.ObtenerCiudadPorID(a.ID_Ciudad_Destino),
                PrecioBaseKg = a.Precio_Base_KG,
                PrecioBasePasaje = a.Precio_Base_Pasaje,
                Habilitado = a.Habilitado
            });
            DgvRuta.DataSource = bind.ToList();

            //Agrego los botones a cada fila para poder modificar/borrar cada ruta
            AgregarBotonesColumnas();
        }
 public void ProcessModelActivities(List<IActivitySchedule> activities)
 {
     RootJobs = new List<IJob>();
     _schedulableActivities = new ConcurrentDictionary<Guid, IActivitySchedule>(activities.ToDictionary(x => x.ScheduledItem.UID, x => x));
     foreach (var activity in activities.Where(x => x.ScheduledItem.DefaultPredecessors.Count == 0))
     {
         ProcessSchedulableActivity(activity);
     }
 }
        internal static OutputColumns GetOutputColumns <T>(DbContext context, bool hasInserts, bool hasUpdates,
                                                           RefreshMode refreshMode, Dictionary <string, PropertyInfo> columns, ICollection <string> keys,
                                                           Dictionary <string, bool> computedCols)
        {
            List <string> keyList = null;
            List <string> colList = null;

            switch (refreshMode)
            {
            case RefreshMode.None:
                return(null);

            case RefreshMode.Identity:
                //No need to return identity if there're no inserts
                if (hasInserts)
                {
                    keyList = computedCols.Where(x => x.Value).Select(x => x.Key).ToList();
                }
                break;

            case RefreshMode.All:
                if (hasInserts)
                {
                    keyList = computedCols.Where(x => x.Value).Select(x => x.Key).ToList();
                }
                //Return computed columns if there're an inserts/updates
                if (hasInserts || hasUpdates)
                {
                    var computedColumns = computedCols.Where(x => !x.Value).Select(x => x.Key).ToList();
                    if (computedColumns.Count > 0 && keyList != null && keyList.Count == 0)
                    {
                        //If there're only computed columns and no identities, we need to include the primary key to identify the values.
                        keyList = keys.ToList();
                    }
                    colList = computedColumns;
                }
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(refreshMode), refreshMode, null);
            }

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

            var outKeys = keyList.ToDictionary(x => x, y => columns[y]);
            var outCols = colList?.ToDictionary(x => x, y => columns[y]);

            var tableName = GetTempTableName <T>() + "OutValues";
            var tableSql  = context.GetOutTableDdl(tableName, outKeys, outCols);
            var result    = new OutputColumns(outKeys, outCols, tableName, tableSql);

            return(result);
        }
Example #42
0
        public void SetDataValues(List <TypedValue> values, Document doc)
        {
            var dictValues = values?.ToDictionary();
            var defWin     = Default;

            Width         = dictValues.GetValue("Width", defWin.Width);
            Quarter       = dictValues.GetValue("Quarter", defWin.Quarter);
            ShadowAngle   = dictValues.GetValue("ShadowAngle", defWin.ShadowAngle);
            IsCustomAngle = dictValues.GetValue("IsCustomAngle", defWin.IsCustomAngle);
        }
Example #43
0
 public DataProcessor(List<FrameQueue> queues, IBrocker brocker, WorkersRepository workersRepository)
 {
     _brocker = brocker;
     _unlockedQueues = queues.ToDictionary(queue => queue.Id, queue => true);
     _queues = queues;
     foreach (var worker in workersRepository.GetAll())
     {
         worker.Ready += WorkerOnReady;
     }
 }
Example #44
0
        public void SetDataValues(List <TypedValue> values, Document doc)
        {
            var dictValues = values?.ToDictionary();
            //TileSize = dictValues.GetValue("TileSize", 1);
            //ShadowDegreeStep = dictValues.GetValue("ShadowDegreeStep", 1);
            var id = dictValues.GetValue("ProjectId", 0);

            Project = DbService.FindProject(id);
            EnableCheckDublicates = dictValues.GetValue("EnableCheckDublicates", true);
        }
        public DataFormSettingsParameters
        (
            [NameValue(AttributeNames.DEFAULTVALUE, "Title")]
            [Comments("Header field on the form")]
            string title,

            [Comments("Input validation messages for each field.")]
            List <ValidationMessageParameters> validationMessages,

            [Comments("List of fields and form groups for this form.")]
            List <FormItemSettingsParameters> fieldSettings,

            [Comments("Click the Variable button and select the configured FormType enum field.")]
            FormType formType,

            [Comments("The model type for the object being edited. Click the function button and use the configured GetType function.  Use the Assembly qualified type name for the type argument.")]
            Type modelType,

            [Comments("Multibindings list for the form header field - typically used in edit mode.")]
            MultiBindingParameters headerBindings = null,

            [Comments("Includes the URL's for create, read, and update.")]
            FormRequestDetailsParameters requestDetails = null,

            [Comments("Conditional directtives for each field.")]
            List <VariableDirectivesParameters> conditionalDirectives = null,

            [Comments("Multibindings list for the form header field.")]
            MultiBindingParameters subtitleBindings = null,

            [Comments("Defines a filter to find a selected item on a subsequent form e.g. to edit the selected item.")]
            ItemFilterGroupParameters itemFilterGroup = null

        )
        {
            Title              = title;
            RequestDetails     = requestDetails;
            ValidationMessages = validationMessages.ToDictionary
                                 (
                vm => vm.Field,
                vm => vm.Rules ?? new List <ValidationRuleParameters>()
                                 );
            FieldSettings         = fieldSettings;
            FormType              = formType;
            ModelType             = modelType;
            ConditionalDirectives = conditionalDirectives?.ToDictionary
                                    (
                cd => cd.Field,
                cd => cd.ConditionalDirectives ?? new List <DirectiveParameters>()
                                    );
            HeaderBindings   = headerBindings;
            SubtitleBindings = subtitleBindings;
            ItemFilterGroup  = itemFilterGroup;
        }
Example #46
0
        public void SetDataValues(List <TypedValue> values, Document doc)
        {
            var dictValues = values?.ToDictionary();
            var regDef     = InsService.Settings.Regions.FirstOrDefault(r => r.City.Equals("Москва", StringComparison.OrdinalIgnoreCase))
                             ?? InsService.Settings.Regions[0];

            RegionPart = dictValues.GetValue("RegionPart", regDef.RegionPart);
            RegionName = dictValues.GetValue("RegionName", regDef.RegionName);
            City       = dictValues.GetValue("City", regDef.City);
            Latitude   = dictValues.GetValue("Latitude", regDef.Latitude);
        }
Example #47
0
        public void SetDataValues(List <TypedValue> values, Document doc)
        {
            var dictValues = values?.ToDictionary();

            TotalTimeH = dictValues.GetValue("TotalTimeH", 3d);
            byte a = dictValues.GetValue("A", (byte)0);
            byte r = dictValues.GetValue("R", (byte)255);
            byte g = dictValues.GetValue("G", (byte)255);
            byte b = dictValues.GetValue("B", (byte)0);

            Color = Color.FromArgb(a, r, g, b);
        }
Example #48
0
        /// <summary>
        /// 組合頁面權限
        /// </summary>
        /// <param name="roleAuth">使用者本身的</param>
        /// <param name="userAuth">系統設定的</param>
        /// <returns></returns>
        private List <AuthItem> CulcPageAuth(List <AuthItem> roleAuth, List <AuthItem> userAuth)
        {
            //準備要回傳的
            List <AuthItem> AuthList = new List <AuthItem>();


            if (userAuth != null && userAuth.Count > 0)
            {
                AuthList.AddRange(userAuth);
            }

            //角色權限-篩選清單
            var userAuthDic = roleAuth.ToDictionary(x => string.Format("{0}-{1}-{2}", x.GroupName, x.AuthType, x.isDeny));

            //以使用者選擇的清單為主,對NetRole 做比對
            foreach (var viewItem in userAuth ?? new List <AuthItem>())
            {
                string key = string.Format("{0}-{1}-{2}", viewItem.GroupName, viewItem.AuthType, viewItem.isDeny);

                //如果一樣的,就從新增清單刪除
                if (userAuthDic.ContainsKey(key))
                {
                    AuthList.Remove(userAuthDic[key]);
                }
                else  //若角色權限沒有,使用者選擇的清單有,為白名單
                {
                    AuthList.Where(x => string.Format("{0}-{1}-{2}", x.GroupName, x.AuthType, x.isDeny) == key).SingleOrDefault().isDeny = false;
                }
            }

            //選擇的權限-篩選清單
            var viewAuthDic = userAuth?.ToDictionary(x => string.Format("{0}-{1}", x.GroupName, x.isDeny));

            //將選擇的權限清單與角色權限做比對
            foreach (var userItem in roleAuth)
            {
                string key = string.Format("{0}-{1}", userItem.GroupName, userItem.isDeny);

                //若系統角色權限有,畫面的權限沒有,新增為黑名單
                if (!viewAuthDic.ContainsKey(key))
                {
                    AuthList.Add(new AuthItem()
                    {
                        AuthType  = userItem.AuthType,
                        GroupName = userItem.GroupName,
                        isDeny    = true,
                    });
                }
            }

            return(AuthList);
        }
Example #49
0
        private static List <Parameter> MergeParameters(List <Parameter> parameters, Dictionary <string, string> overrides)
        {
            var result = parameters?.ToDictionary(param => param.ParameterKey, param => param.ParameterValue) ?? new Dictionary <string, string>();

            overrides = overrides ?? new Dictionary <string, string>();

            foreach (var entry in overrides)
            {
                result[entry.Key] = entry.Value;
            }

            return(result.Select(entry => new Parameter {
                ParameterKey = entry.Key, ParameterValue = entry.Value
            }).ToList());
        }
Example #50
0
        public NsfwManager()
        {
            serializer = new XmlSerializer(typeof(List <NsfwPair>));
            List <NsfwPair> entries = null;

            try
            {
                using (FileStream stream = File.Open(Misaki.ConfigPath + "HentaiImgurAlbums.txt", FileMode.OpenOrCreate, FileAccess.Read))
                {
                    entries = (List <NsfwPair>)serializer.Deserialize(stream);
                }
            }
            catch { }
            nsfwServerEntries = entries?.ToDictionary(entry => entry.Server, entry => entry.Entry) ?? new Dictionary <string, NsfwEntry>();
        }
Example #51
0
        /// 4.5.1 https://docs.microsoft.com/en-us/azure/azure-functions/functions-scenario-database-table-cleanup

        //public async Task<DataResponse> RunQueryAsync(SqlConnectionParams cParams, DataRequest req) {
        //  var str = $"Server=tcp:{cParams.Host}.database.windows.net,1433;Database={cParams.Database};User ID={cParams.Username};Password={cParams.Password};Trusted_Connection=False;Encrypt=True;";
        //}

        public async Task <DataResponse> RunQueryAsync(string sqlConnStr, string tableName, IEnumerable <Field> projectionFields, List <SchemaField> fields, List <List <DimensionsFilter> > filters)
        {
            var dataResponse = new DataResponse()
            {
                FiltersApplied = ((filters?.Count() ?? 0) > 0) ? true : false,
                Schema         = projectionFields.Select(f => fields.FirstOrDefault(ff => ff.FieldName == f.Name)).ToList(),
                Rows           = new List <GDS.Gateway.Models.Io.DataRow>()
            };
            var fieldMap  = fields?.ToDictionary(k => k.FieldName, v => v);
            var filterStr = BuildFilter(filters, fieldMap);

            using (var conn = new SqlConnection(sqlConnStr))
            {
                var fieldList   = " * ";
                var maybeFields = (string.Join(", ", (projectionFields?.Select(f => f.Name)) ?? new string[0]));
                fieldList = string.IsNullOrWhiteSpace(maybeFields) ? fieldList : maybeFields;
                var sqlStr = $"SELECT {fieldList} FROM { tableName} " + (string.IsNullOrWhiteSpace(filterStr) ? "" : "WHERE " + filterStr);
                using (var reader = await conn.ExecuteReaderAsync(sqlStr))
                {
                    var len = reader.FieldCount;
                    while (reader.Read())
                    {
                        var dr = new GDS.Gateway.Models.Io.DataRow()
                        {
                            Values = new string[len]
                        };
                        for (int i = 0; i < len; i++)
                        {
                            var t = reader.GetFieldType(i);
                            if (t == typeof(DateTime))
                            {
                                dr.Values[i] = reader.GetDateTime(i).ToString("yyyyMMdd");
                            }
                            else
                            {
                                dr.Values[i] = Convert.ToString(reader.GetValue(i));
                            }
                        }
                        dataResponse.Rows.Add(dr);
                    }
                }
            }

            return(dataResponse);
        }
Example #52
0
        public ValidatorDescription
        (
            [Comments("Class name")]
            [NameValue(AttributeNames.DEFAULTVALUE, "Validators")]
            string className,

            [Comments("Function")]
            [NameValue(AttributeNames.DEFAULTVALUE, "required")]
            string functionName,

            [Comments("Where applicable, use a list of validator arguments as parameters to the validator function.")]
            List <ValidatorArgument> arguments = null
        )
        {
            ClassName    = className;
            FunctionName = functionName;
            Arguments    = arguments?.ToDictionary(kvp => kvp.Name, kvp => kvp.Value);
        }
        public ValidatorDefinitionParameters
        (
            [Comments("Validation class name.")]
            [NameValue(AttributeNames.DEFAULTVALUE, "RequiredRule")]
            [Domain("IsLengthValidRule,IsMatchRule,IsPatternMatchRule,IsValidEmailRule,IsValidPasswordRule,IsValueTrueRule,MustBeIntegerRule,MustBeNumberRule,MustBePositiveNumberRule,RangeRule,RequiredRule,AtLeastOneRequiredRule")]
            string className,

            [Comments("Function to call on the validation class.")]
            [NameValue(AttributeNames.DEFAULTVALUE, "Check")]
            string functionName,

            [Comments("Where applicable, add arguments for the validator function e.g. min, max vallues.")]
            List <ValidatorArgumentParameters> arguments = null
        )
        {
            ClassName    = className;
            FunctionName = functionName;
            Arguments    = arguments?.ToDictionary(arg => arg.Name);
        }
Example #54
0
        public DirectiveDescriptionParameters
        (
            [Comments("Class name")]
            [NameValue(AttributeNames.DEFAULTVALUE, "Directives")]
            string className,

            [Comments("Function")]
            [NameValue(AttributeNames.DEFAULTVALUE, "hideIf")]
            [Domain("disableIf,hideIf,validateIf")]
            string functionName,

            [Comments("Where applicable, add arguments for the directive function.")]
            List <DirectiveArgumentParameters> arguments = null
        )
        {
            ClassName    = className;
            FunctionName = functionName;
            Arguments    = arguments?.ToDictionary(kvp => kvp.Name, kvp => kvp.Value);
        }
Example #55
0
        public RequestDetailsParameters
        (
            [ParameterEditorControl(ParameterControlType.TypeAutoComplete)]
            [NameValue(AttributeNames.DEFAULTVALUE, "Contoso.Domain.Entities")]
            [Comments("Fully qualified class name for the model type.")]
            string modelType,

            [ParameterEditorControl(ParameterControlType.TypeAutoComplete)]
            [NameValue(AttributeNames.DEFAULTVALUE, "Contoso.Data.Entities")]
            [Comments("Fully qualified class name for the data type.")]
            string dataType,

            string dataSourceUrl = "/api/Generic/GetData",
            string getUrl        = "/api/Generic/GetSingle",
            string addUrl        = "/api/Generic/Add",
            string updateUrl     = "/api/Generic/Update",
            string deleteUrl     = "/api/Generic/Delete",

            [ListEditorControl(ListControlType.HashSetForm)]
            [ParameterEditorControl(ParameterControlType.ParameterSourcedPropertyInput)]
            [NameValue(AttributeNames.PROPERTYSOURCEPARAMETER, "modelType")]
            string[] includes = null,

            [ListEditorControl(ListControlType.HashSetForm)]
            List <SelectParameters> selects = null,
            bool?distinct = null,

            [Comments("Defines and navigation properties to include in the edit model")]
            SelectExpandDefinitionParameters selectExpandDefinition = null
        )
        {
            ModelType              = modelType;
            DataType               = dataType;
            DataSourceUrl          = dataSourceUrl;
            GetUrl                 = getUrl;
            AddUrl                 = addUrl;
            UpdateUrl              = updateUrl;
            DeleteUrl              = deleteUrl;
            Includes               = includes;
            Selects                = selects?.ToDictionary(s => s.FieldName, s => s.SourceMember);
            Distinct               = distinct;
            SelectExpandDefinition = selectExpandDefinition;
        }
        public DirectiveDefinitionParameters
        (
            [Comments("Class name for the directive.")]
            [Domain("DisableIf,HideIf,ValidateIf")]
            [NameValue(AttributeNames.DEFAULTVALUE, "HideIf")]
            string className,

            [Comments("Function name.")]
            [NameValue(AttributeNames.DEFAULTVALUE, "Check")]
            [Domain("Check")]
            string functionName,

            [Comments("Where applicable, add arguments for the directive evaluation function.")]
            List <DirectiveArgumentParameters> arguments = null
        )
        {
            ClassName    = className;
            FunctionName = functionName;
            Arguments    = arguments?.ToDictionary(arg => arg.Name);
        }
Example #57
0
        /// <summary>
        /// Check that connector parameters are valid
        /// </summary>
        /// <param name="id">The connector ID</param>
        /// <param name="request">The connector parameters</param>
        /// <returns>an object with the info of which parameters are wrong</returns>
        public async Task <ValidationResult> ValidateCredentials(long id, List <ItemParameter> credentials)
        {
            try
            {
                return(await httpService.PostAsync <ValidationResult>(
                           URL_CONNECTORS + "/{id}/validate",
                           credentials?.ToDictionary(x => x.Name, x => x.Value),
                           null,
                           HTTP.Utils.GetSegment(id.ToString())
                           ));
            }
            catch (ApiException e)
            {
                if (e.ApiError != null && e.ApiError.Errors != null)
                {
                    throw new ValidationException(e.StatusCode, e.ApiError);
                }

                throw e;
            }
        }
Example #58
0
        /// <summary>
        /// Метод расчета итогового значения формулы. Перед вызовом выражение должно быть приведено к форме ОПЗ
        /// </summary>
        /// <param name="formulas">Список формул для подстановки вместо переменных</param>
        /// <returns></returns>
        public double Calculate(List <ServerFormula> formulas)
        {
            if (!isRPNConfigured)
            {
                throw new InvalidOperationException("Перед расчетом значения выражения, необходимо привести его к виду ОПЗ");
            }

            Stack <double> stack = new Stack <double>();

            ReplaceFormula(formulas?.ToDictionary(f => f.Name, f => f.Value)); // Заменяем переменные на числовые токены

            List <ITokenCalculator> tokenCalculators = _innerList              // Получаем список токенов, участвующих в расчете
                                                       .Select(token => token as ITokenCalculator)
                                                       .Where(token => token != null)
                                                       .ToList();

            foreach (var token in tokenCalculators)
            {
                token.Calculate(stack);
            }

            return(stack.Pop()); // Результат
        }
Example #59
0
    private void MapHistoryCleanup(Dictionary <int, IContentTypeComposition> contentTypes)
    {
        // get templates
        Sql <ISqlContext>?sql1 = Sql()?
                                 .Select <ContentVersionCleanupPolicyDto>()
                                 .From <ContentVersionCleanupPolicyDto>()
                                 .OrderBy <ContentVersionCleanupPolicyDto>(x => x.ContentTypeId);

        List <ContentVersionCleanupPolicyDto>?contentVersionCleanupPolicyDtos =
            Database?.Fetch <ContentVersionCleanupPolicyDto>(sql1);

        var contentVersionCleanupPolicyDictionary =
            contentVersionCleanupPolicyDtos?.ToDictionary(x => x.ContentTypeId);

        foreach (IContentTypeComposition c in contentTypes.Values)
        {
            if (!(c is ContentType contentType))
            {
                continue;
            }

            var historyCleanup = new HistoryCleanup();

            if (contentVersionCleanupPolicyDictionary is not null &&
                contentVersionCleanupPolicyDictionary.TryGetValue(
                    contentType.Id,
                    out ContentVersionCleanupPolicyDto? versionCleanup))
            {
                historyCleanup.PreventCleanup = versionCleanup.PreventCleanup;
                historyCleanup.KeepAllVersionsNewerThanDays   = versionCleanup.KeepAllVersionsNewerThanDays;
                historyCleanup.KeepLatestVersionPerDayForDays = versionCleanup.KeepLatestVersionPerDayForDays;
            }

            contentType.HistoryCleanup = historyCleanup;
        }
    }
 public Device(string name, List <DataUsage>?dataUsages = null, decimal dataInGbUsedPerDay = 0)
 {
     Name               = name ?? throw new ArgumentNullException(nameof(name));
     DataUsages         = dataUsages?.ToDictionary(u => u.For, u => u);
     DataInGbUsedPerDay = dataInGbUsedPerDay;
 }