Exemplo n.º 1
0
        public static MetricTags Concat(MetricTags tags1, Dictionary <string, string> tags2)
        {
            var count1 = tags1.Count;
            var count2 = tags2?.Count ?? 0;

            if (count1 == 0)
            {
                return(new MetricTags(tags2?.Select(t => t.Key).ToArray(), tags2?.Select(t => t.Value).ToArray()));
            }

            if (count2 == 0)
            {
                return(tags1);
            }

            var combinedKeys   = new string[count1 + count2];
            var combinedValues = new string[count1 + count2];

            tags1.Keys.CopyTo(combinedKeys, 0);
            tags2?.Select(t => t.Key).ToArray().CopyTo(combinedKeys, count1);

            tags1.Values.CopyTo(combinedValues, 0);
            tags2?.Select(t => t.Value).ToArray().CopyTo(combinedValues, count1);

            return(new MetricTags(combinedKeys, combinedValues));
        }
        public void Optimize(Dictionary<double, double> values)
        {
            var n = _f.Functions.Count();
              var xs = values.Select(v => v.Key).ToList();
              var ys = values.Select(v => v.Value).ToList();
              var fs = new List<List<double>>(n);

              for (var i = 0; i < n; i++)
              {
            fs[i] = _f.Functions[i].Evaluate(xs);
              }

              var matrix = new DenseMatrix(n, n);
              var vector = new DenseVector(n);
              for (var i = 0; i < n; i++)
              {
            for (var j = 0; j < n; j++)
            {
              matrix[i, j] = fs[i].ScalarProduct(fs[j]);
            }
            vector[i] = ys.ScalarProduct(fs[i]);
              }

              var matrixInverse = matrix.Inverse();

              var result = matrixInverse * vector;

              for (var i = 0; i < n; i++)
              {
            _f.LinearParameters[i].Value = result[i];
              }
        }
        public static void DataUserSelectorListView(BasePage page, String ObjId, Dictionary<Guid, String> SelectedUsers, List<GroupInfo> SelectedGroups, bool DisabledGroupSelector)
        {
            var ids = SelectedUsers != null && SelectedUsers.Count > 0 ? SelectedUsers.Select(i => i.Key).ToArray() : new List<Guid>().ToArray();
            var names = SelectedUsers != null && SelectedUsers.Count > 0 ? SelectedUsers.Select(i => i.Value).ToArray() : new List<string>().ToArray();

            page.RegisterInlineScript(String.Format(" SelectedUsers{0} = {1}; ",
                                                        ObjId,
                                                        JsonConvert.SerializeObject(
                                                            new
                                                            {
                                                                IDs = ids,
                                                                Names = names,
                                                                PeopleImgSrc = WebImageSupplier.GetAbsoluteWebPath("people_icon.png", ProductEntryPoint.ID),
                                                                DeleteImgSrc = WebImageSupplier.GetAbsoluteWebPath("trash_12.png"),
                                                                DeleteImgTitle = CRMCommonResource.DeleteUser,
                                                                CurrentUserID = SecurityContext.CurrentAccount.ID
                                                            })), onReady: false);
            if (!DisabledGroupSelector)
            {
                ids = SelectedGroups != null && SelectedGroups.Count > 0 ? SelectedGroups.Select(i => i.ID).ToArray() : new List<Guid>().ToArray();
                names = SelectedGroups != null && SelectedGroups.Count > 0 ? SelectedGroups.Select(i => i.Name.HtmlEncode()).ToArray() : new List<string>().ToArray();

                page.RegisterInlineScript(String.Format(" SelectedGroups{0} = {1}; ",
                                                            ObjId,
                                                            JsonConvert.SerializeObject(
                                                                    new
                                                                    {
                                                                        IDs = ids,
                                                                        Names = names,
                                                                        GroupImgSrc = WebImageSupplier.GetAbsoluteWebPath("group_12.png"),
                                                                        TrashImgSrc = WebImageSupplier.GetAbsoluteWebPath("trash_12.png"),
                                                                        TrashImgTitle = CRMCommonResource.Delete
                                                                    })), onReady: false);
            }
        }
Exemplo n.º 4
0
 public ModuleCriteria CreateCriteria(int testId, Dictionary<string, string> scormData) {
   //Velka data, zaroven se vypocitaji properties, odvozene z Results
   if (scormData != null) { ScormDataKey = scormData.Select(kv => kv.Key).ToArray(); ScormDataValue = scormData.Select(kv => kv.Value).ToArray(); }
   byte[] encode = Encode();
   //Mala proxy data
   PageResult[] res = Results; Results = null; ScormDataValue = ScormDataKey = null;
   byte[] encodeProxy = Encode();
   Results = res;
   //Uloz do DB
   ModuleCriteria crit = new ModuleCriteria() {
     CourseId = testId,
     DataBin = new IdDataBin() { Id = Id, DataBin = encode },
     ProxyDataBin = new IdDataBin() { Id = Id, DataBin = encodeProxy },
     Status = (short)Status,
     Level = (short)Level
   };
   if (Status == ExerciseStatus.Evaluated) {
     crit.Skill = Skill;
     crit.ElapsedSeconds = (short)(ElapsedTime / 1000);
     crit.Score = (short)Score.ToPercent();
     TestProxy.LevelScore score = TestProxy.GetLevelScore(this);
     crit.AbsLevel = score.absLevel;
     crit.AbsScore = (short) score.absScore;
     crit.GlobalScore = (short)score.globalScore;
   }
   return crit;
 }
Exemplo n.º 5
0
        public StructureVoxelModel(MyObjectBuilder_EntityBase entityBase, string voxelPath)
            : base(entityBase)
        {
            var contentPath = ToolboxUpdater.GetApplicationContentPath();

            if (voxelPath != null)
            {
                VoxelFilepath = Path.Combine(voxelPath, Name + MyVoxelMap.V2FileExtension);
                var previewFile = VoxelFilepath;

                if (!File.Exists(VoxelFilepath))
                {
                    var oldFilepath = Path.Combine(voxelPath, Name + MyVoxelMap.V1FileExtension);
                    if (File.Exists(oldFilepath))
                    {
                        SourceVoxelFilepath = oldFilepath;
                        previewFile = oldFilepath;
                        SpaceEngineersCore.ManageDeleteVoxelList.Add(oldFilepath);
                    }
                }

                ReadVoxelDetails(previewFile);
            }

            var materialList = new Dictionary<string, string>();
            foreach (MyVoxelMaterialDefinition item in SpaceEngineersCore.Resources.VoxelMaterialDefinitions.OrderBy(m => m.Id.SubtypeName))
            {
                string texture = item.GetVoxelDisplayTexture();
                materialList.Add(item.Id.SubtypeName, texture == null ? null : SpaceEngineersCore.GetDataPathOrDefault(texture, Path.Combine(contentPath, texture)));
            }

            GameMaterialList = new List<VoxelMaterialAssetModel>(materialList.Select(m => new VoxelMaterialAssetModel { MaterialName = m.Key, DisplayName = m.Key, TextureFile = m.Value }));
            EditMaterialList = new List<VoxelMaterialAssetModel> { new VoxelMaterialAssetModel { MaterialName = null, DisplayName = "Delete/Remove" } };
            EditMaterialList.AddRange(materialList.Select(m => new VoxelMaterialAssetModel { MaterialName = m.Key, DisplayName = m.Key, TextureFile = m.Value }));
        }
 public void Add_Random_Parameter_Test()
 {
     var dictionary = new Dictionary<string, object>();
     Enumerable.Range(1, 10).ToList().ForEach(x => dictionary.AddWithUniquelyNamedKey(x));
     dictionary.Select(x => x.Key).Distinct().Count().ShouldEqual(10);
     dictionary.Select(x => x.Value).ToList().ForEach(x => x.ShouldBeType(typeof(int)));
     dictionary.Select(x => x.Value).ToList().ForEach(x => x.ShouldBeGreaterThan(0));
 }
Exemplo n.º 7
0
        /// <summary>
        /// Entraine le réseau
        /// </summary>
        /// <param name="maxIteration">Nombre d'itérations max</param>
        /// <param name="pas">Pas d'apprentissage</param>
        /// <param name="lettreCible">Lettre pour laquelle on entraîne le réseau</param>
        /// <param name="jeuEssai">Jeu d'essai pour entraîner le réseau</param>
        /// <param name="biais">Biais initial</param>
        /// <returns>L'erreur du réseau à la fin de son entraînement</returns>
        public double[] Entrainer(Dictionary<string, double[]> jeuEssai, string lettreCible, int maxIteration, double pas, double biais)
        {
            // on entraîne le réseau
            Neurone neurone = Couches[0].Neurones[0]; // un seul neurone dans le Perceptron

            double erreurCible = 0;
            double[] erreurCourante = new double[] { double.MaxValue };
            int iteration = 0;
            // valeurs initiales
            neurone.Poids = new double[neurone.NbEntrees];
            neurone.Biais = biais;

            while (iteration < maxIteration && erreurCourante[0] > erreurCible)
            {
                // pour chaque élément de test
                foreach (string lettre in jeuEssai.Keys)
                {
                    // récupère le jeu d'entraînement courant
                    double[] entraineur = jeuEssai[lettre];
                    // détermine si c'est la valeur cible (1) ou pas (-1)
                    int valeurCible = (lettre == lettreCible) ? 1 : 0; // la fonction de transfert doit donc produire des -1 ou des 1

                    double sortie = neurone.CalculerSortie(entraineur);
                    // de combien la sortie s'écarte de la cible
                    double ecart = valeurCible - sortie;

                    if (ecart != 0)
                    {
                        // réévalue le poids de chaque entrée (règle de RosenBlatt)
                        for (int p = 0; p < neurone.NbEntrees; p++)
                        {
                            neurone.Poids[p] = neurone.Poids[p] + (pas * ecart * entraineur[p]);
                        }
                        // réévalue le biais
                        // le biais est considéré comme une entrée supplémentaire avec un coefficient toujours égal à 1
                        neurone.Biais = neurone.Biais + (pas * ecart);
                    }
                }

                ++iteration;
                Debug.WriteLine("Itération: " + iteration.ToString());

                // on a un biais et un jeu de poids candidat
                // calcule l'erreur faite par le réseau dans l'estimation de notre jeu d'essai avec notre candidat
                double[][] tests = jeuEssai.Select(jeu => jeu.Value).ToArray();
                double[] cibles = jeuEssai.Select(jeu => (jeu.Key == lettreCible) ? 1.0 : 0.0).ToArray();
                double[][] c = jeuEssai.Select(jeu => cibles).ToArray();
                erreurCourante = CalculerErreur(tests, cibles);
            }

            return erreurCourante;
        }
Exemplo n.º 8
0
 public static bool Insert(string table, Dictionary<string,object> vars)
 {
     using (SqlConnection sqlc = new SqlConnection(ConnectionString))
     {
         var sqlcom = sqlc.CreateCommand();
         sqlcom.CommandText = "INSERT INTO " + table + " ";
         sqlcom.CommandText += "(" + String.Join(",", vars.Select(elem => elem.Key)) + ")";
         sqlcom.CommandText += " VALUES (";
         sqlcom.CommandText += String.Join(",", vars.Select(elem => "@" + elem.Key));
         sqlcom = SetValues(vars, sqlcom);
         sqlcom.CommandText += ")";
         return Exec(sqlcom);
     }
 }
Exemplo n.º 9
0
        private void PublishSite(Dictionary<string, string> properties)
        {
            var arguments = "/p:" + string.Join(";", properties.Select(kvp => kvp.Key + "=" + kvp.Value)) + " \"" + ProjectPath + "\"";

            var msBuildProc = new Process();
            msBuildProc.StartInfo = new ProcessStartInfo
                {
                    FileName = Path.Combine(System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory(), "msbuild.exe"),
                    Arguments = arguments,
                    RedirectStandardError = true,
                    RedirectStandardOutput = true,
                    UseShellExecute = false,
                    CreateNoWindow = true,
                };
            msBuildProc.Start();

            var stdout = msBuildProc.StandardOutput.ReadToEnd();
            var stderr = msBuildProc.StandardError.ReadToEnd();
            msBuildProc.WaitForExit();

            var success = msBuildProc.ExitCode == 0;

            if (!success)
            {
                Console.WriteLine("The publish failed.");
                Console.WriteLine(stdout);
                Console.WriteLine(stderr);
                throw new ApplicationException("Build failed.");
            }
            else
            {
                Console.WriteLine("The publish succeeded.");
            }
        }
Exemplo n.º 10
0
        static string _getCompileCode(string code, Dictionary <string, Tuple <Type, object> > args)
        {
            var codeBuilder = new StringBuilder(@"
            using System;
            using System.Text;
            using System.Linq;
            using System.Collections.Generic;

            namespace Eval
            {
                public class Code
                {
                    public static object Run(");

            codeBuilder.Append(string.Join(", ", args?.Select(x => $"{_getType(x.Value.Item1)} {x.Key}") ?? new string[0]));
            codeBuilder.Append(@") {
                        ");
            codeBuilder.Append(code);
            codeBuilder.AppendLine(@";
                    }
                }
            }");

            return(codeBuilder.ToString());
        }
Exemplo n.º 11
0
        public HttpWorker(Uri uri, HttpMethod httpMethod = HttpMethod.Get, Dictionary<string, string> headers = null, byte[] data = null)
        {
            _buffer = new byte[8192];
            _bufferIndex = 0;
            _read = 0;
            _responseType = ResponseType.Unknown;
            _uri = uri;
            IPAddress ip;
            var headersString = string.Empty;
            var contentLength = data != null ? data.Length : 0;

            if (headers != null && headers.Any())
                headersString = string.Concat(headers.Select(h => "\r\n" + h.Key.Trim() + ": " + h.Value.Trim()));

            if (_uri.HostNameType == UriHostNameType.Dns)
            {
                var host = Dns.GetHostEntry(_uri.Host);
                ip = host.AddressList.First(i => i.AddressFamily == AddressFamily.InterNetwork);
            }
            else
            {
                ip = IPAddress.Parse(_uri.Host);
            }

            _endPoint = new IPEndPoint(ip, _uri.Port);
            _request = Encoding.UTF8.GetBytes($"{httpMethod.ToString().ToUpper()} {_uri.PathAndQuery} HTTP/1.1\r\nAccept-Encoding: gzip, deflate, sdch\r\nHost: {_uri.Host}\r\nContent-Length: {contentLength}{headersString}\r\n\r\n");

            if (data == null)
                return;

            var tmpRequest = new byte[_request.Length + data.Length];
            Buffer.BlockCopy(_request, 0, tmpRequest, 0, _request.Length);
            Buffer.BlockCopy(data, 0, tmpRequest, _request.Length, data.Length);
            _request = tmpRequest;
        }
Exemplo n.º 12
0
        public IJwtToken CreateToken(string userId, string role, Dictionary <string, string> claims = null)
        {
            var payload = new List <Claim> {
                new Claim(ClaimTypes.Name, userId),
                new Claim(ClaimTypes.Role, role)
            };

            var customClaims = claims?.Select(claim => new Claim(claim.Key, claim.Value)).ToArray() ??
                               Array.Empty <Claim>();

            payload.AddRange(customClaims);

            var jwt = new JwtSecurityToken(
                issuer: _jwtOptions.Issuer,
                audience: _jwtOptions.Audience,
                claims: payload,
                expires: DateTime.UtcNow.AddMinutes(_jwtOptions.Lifetime),
                signingCredentials: _signingCredentials
                );

            var accessToken = new JwtSecurityTokenHandler().WriteToken(jwt);

            return(new JwtToken()
            {
                AccessToken = accessToken,
                RefreshToken = string.Empty
            });
        }
Exemplo n.º 13
0
        public static void MergeCharacteristics <TCharacteristics>(this ICollection <TCharacteristics> source, List <Characteristic> availableCharacteristics, Dictionary <string, string> characteristics)
            where TCharacteristics : ICharacteristicBase, new()
        {
            characteristics.ClearEmptyCharacteristics();
            source.RemoveAllByKeys(characteristics?.Select(o => o.Key));
            if (characteristics.IsNullOrEmpty())
            {
                return;
            }

            foreach (var characteristic in characteristics)
            {
                var sourceCharacteristic = source.FirstOrDefault(o => o.Characteristic.Code == characteristic.Key);
                if (sourceCharacteristic != null)
                {
                    sourceCharacteristic.Value = characteristic.Value;
                }
                else
                {
                    var newCharacteristic = new TCharacteristics()
                    {
                        Characteristic = availableCharacteristics.FirstOrDefault(o => o.Code == characteristic.Key),
                        Value          = characteristic.Value
                    };
                    source.Add(newCharacteristic);
                }
            }
        }
Exemplo n.º 14
0
        public async Task <T> Execute <T>(string scope, string method, Dictionary <string, object> _params = null)
        {
            var path = string.Format(API_PATH, scope, method, "json");

            var nvc = _params?.Select(x => new KeyValuePair <string, string>(x.Key, x.Value?.ToString()));

            var postdata = nvc == null ? null : new FormUrlEncodedContent(nvc);

            var response = await _client.PostAsync(path, postdata);

            var strResponseBody = await response.Content.ReadAsStringAsync();

            // System.Diagnostics.Debug.WriteLine(responseBody);

            try
            {
                var result = JsonConvert.DeserializeObject <ReturnGeneric <T> >(strResponseBody);

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    throw new ApiException(result.Return.Message, result.Return.Status);
                }

                return(result.Entries);
            }
            catch (HttpException)
            {
                throw;
            }
        }
Exemplo n.º 15
0
        internal override string Build(string name, Dictionary <string, object> argumentsDictionary)
        {
            var arguments = argumentsDictionary
                            ?.Select(argument => $"{argument.Key}: {JsonConvert.SerializeObject(argument.Value)}")
                            ?.ToList() ?? new List <string>();

            var fields = new List <string>();

            foreach (var field in this._fields)
            {
                if (field.Value != null)
                {
                    fields.Add(field.Value.Build(field.Key, null));
                }
                else
                {
                    fields.Add(field.Key);
                }
            }

            var s = name;

            if (arguments.Count > 0)
            {
                s += "(" + string.Join(", ", arguments) + ")";
            }
            if (fields.Count > 0)
            {
                s += " { " + string.Join(", ", fields) + " }";
            }
            return(s);
        }
Exemplo n.º 16
0
 /// <summary>
 /// 解析lamdba,生成Sql查询条件
 /// </summary>
 /// <param name="expression"></param>
 /// <returns></returns>
 public void ResolveToSql(Expression expression)
 {
     this.index = 0;
     this.Argument = new Dictionary<string, object>();
     this.SqlWhere = Resolve(expression);
     this.Paras = Argument.Select(x => new SqlParameter(x.Key, x.Value)).ToArray();
 }
Exemplo n.º 17
0
        static void Main(string[] args)
        {
            var input = Console.In;

            var amount = int.Parse(input.ReadLine());
            var numberOfTypes = int.Parse(input.ReadLine());

            var faceValues = Enumerable.Range(0, numberOfTypes)
                .Select(i => input.ReadLine())
                .Select(int.Parse)
                .OrderByDescending(i => i)
                .ToList();

            var dictionary = new Dictionary<int, int>();

            while (amount > 0)
            {
                var toUse = faceValues.First(i => i <= amount);
                if (!dictionary.ContainsKey(toUse))
                {
                    dictionary.Add(toUse,0);
                }

                dictionary[toUse] = dictionary[toUse] + 1;
                amount -= toUse;
            }

            var result = string.Join(" ", dictionary.Select(pair => pair.Value + " " + pair.Key));

            Console.Write(result);
        }
		public static string GetOptions(this IAudioSettings settings)
		{
			var audioOptions = new Dictionary<string, string>()
			                   	{
			                   		{"-codec:a", settings.CodecName}
			                   	};
			if (settings.BitRate > 0)
			{
				audioOptions.Add("-b:a", settings.BitRate.ToString());
			}
			if (settings.Frequency > 0)
			{
				audioOptions.Add("-ar", settings.Frequency.ToString());
			}
			if (settings.Channels > 0)
			{
				audioOptions.Add("-ac", settings.Channels.ToString());
			}

			var value = audioOptions.Select(x => x.Key + " " + x.Value).Aggregate(new StringBuilder(), (x, y) => x.Append(" " + y));

			if (!string.IsNullOrEmpty(settings.Options))
			{
				if (value.Length > 0)
				{
					value.Append(" ");
				}
				value.Append(settings.Options);
			}

			return value.ToString();
		}
Exemplo n.º 19
0
        /// <summary>
        /// Initializes OpenSMILE with the provided config file and command-line options.
        /// </summary>
        /// <param name="configFile">Path to the config file to load.</param>
        /// <param name="options">Mapping of option names to values.</param>
        /// <param name="logLevel">Log level to set for the logger.</param>
        /// <param name="debug">Whether to enable debug mode (outputs debug-level log messages). SMILEapi must be compiled in debug mode for this to take effect.</param>
        /// <param name="consoleOutput">Whether log messages are printed to the console (useful for debugging).</param>
        /// <exception cref="ObjectDisposedException">
        /// Thrown if the object has already been disposed.
        /// </exception>
        /// <exception cref="InvalidOperationException">
        /// Thrown if openSMILE has already been initialized before.
        /// </exception>
        /// <exception cref="OpenSmileException">
        /// Thrown for internal openSMILE errors.
        /// </exception>
        public void Initialize(string configFile, Dictionary <string, string> options, int logLevel = 2, bool debug = false, bool consoleOutput = false)
        {
            if (disposed)
            {
                throw new ObjectDisposedException(typeof(OpenSMILE).FullName);
            }
            if (smileObj != IntPtr.Zero)
            {
                throw new InvalidOperationException("openSMILE has already been initialized before.");
            }

            smileObj = OpenSmileApi.Smile_new();
            if (smileObj == IntPtr.Zero)
            {
                throw new OpenSmileException(OpenSmileResult.SMILE_FAIL, "Could not create new SMILEapi object");
            }

            logCallback   = OnLogMessage;
            stateCallback = OnStateChanged;
            OpenSmileApi.Smile_set_log_callback(smileObj, logCallback, IntPtr.Zero);
            OpenSmileApi.Smile_set_state_callback(smileObj, stateCallback, IntPtr.Zero);

            smileopt_t[] opts = options?.Select(opt => new smileopt_t(opt.Key, opt.Value)).ToArray();

            CheckSmileResult(OpenSmileApi.Smile_initialize(smileObj, configFile, opts.Length, opts, logLevel, debug ? 1 : 0, consoleOutput ? 1 : 0, null));
        }
        public UserFormAccessList GetAuthorisedForms(SecureSession session, RoleList roleList)
        {
            IEnumerable<string> keys = AssemblyResourceReader.GetResourceKeys();
            string pattern = string.Format("Test_Data.ApplicationPermissions.FORM-([a-z0-9-]*)-USER-{0}", session.AuthenticatedUser.Id);
            Dictionary<string, List<string>> forms = new Dictionary<string, List<string>>();

            foreach (string key in keys)
            {
                Match match = Regex.Match(key, pattern, RegexOptions.IgnoreCase);
                if (!match.Success)
                {
                    continue;
                }

                string content = AssemblyResourceReader.ReadAsString(key);
                string formId = match.Groups[1].Value;

                ApplicationEntitlementList applicationEntitlements = JsonConvert.DeserializeObject<ApplicationEntitlementList>(content);
                foreach (ApplicationEntitlement entitlement in applicationEntitlements)
                {
                    if (entitlement.AccessLevel > AccessLevel.NoAccess)
                    {
                        if (!forms.ContainsKey(formId))
                        {
                            forms.Add(formId, new List<string>());
                        }

                        forms[formId].Add(entitlement.StateName);
                    }
                }
            }

            return new UserFormAccessList(forms.Select(kvp => new UserFormAccess(kvp.Key, kvp.Value.ToList())));
        }
Exemplo n.º 21
0
        public Question CreateNewQuestion()
        {
            var subject = (Subject)_random.Next(Constants.SUBJECTS_COUNT);
            Dictionary<string, TagLib.File> rawOptions = new Dictionary<string, TagLib.File>();
            while (rawOptions.Count < Constants.OPTIONS_COUNT)
            {
                var file = _files[_random.Next(_files.Count)];
                var option = Reencode(Constants.ProjectionBySubject[subject](file.Tag));
                if (rawOptions.ContainsKey(option))
                    continue;
                rawOptions[option] = file;
            }
            var options = rawOptions.Select(kvp => new Option() { Title = kvp.Key, File=kvp.Value, IsCorrect = false }).ToList();
            var title = Constants.QuestionsBySubject[subject];

            int answer = _random.Next(Constants.OPTIONS_COUNT);
            options[answer].IsCorrect = true;
            var musicFile = new MusicFile(options[answer].File);
            return new Question()
                {
                    Title=title,
                    Options=options,
                    File = musicFile
                };
        }
Exemplo n.º 22
0
 private string ConvertToMessage(Dictionary<string, string> message, bool useJson)
 {
     if(useJson)
         return JsonSerializer.SerializeToString(message);
     else
         return string.Join(" ", message.Select(m => String.Format("{0}={1}", m.Key, m.Value)));
 }
Exemplo n.º 23
0
        public async Task <SecurityGroup[]> DescribeSecurityGroupsAsync(List <string> groupIds = null, List <string> groupNames = null, Dictionary <string, List <string> > filters = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            var filterList = filters?.Select(x => new Filter(x.Key, x.Value)).ToList();

            DescribeSecurityGroupsResponse response = null;
            var results = new List <SecurityGroup>();

            while ((response = await _client.DescribeSecurityGroupsAsync(new DescribeSecurityGroupsRequest()
            {
                NextToken = response?.NextToken,
                Filters = filterList,
                MaxResults = 1000,
                GroupIds = groupIds,
                GroupNames = groupNames
            }, cancellationToken).EnsureSuccessAsync()) != null)
            {
                if (!response.SecurityGroups.IsNullOrEmpty())
                {
                    results.AddRange(response.SecurityGroups);
                }

                if (response.NextToken.IsNullOrEmpty())
                {
                    break;
                }

                await Task.Delay(100);
            }

            return(results.ToArray());
        }
		protected IEnumerable<MetaComponent> GetMetaComponents(
			IDictionary<string, IHandler> flatKeyHandlers)
		{
			var lookup = new Dictionary<IHandler, KeyValuePair<string, IList<Type>>>();
			foreach (var handler in flatKeyHandlers)
			{
				var actual = handler.Value;
				var forwarding = handler.Value as ForwardingHandler;
				if (forwarding != null)
				{
					actual = forwarding.Target;
				}
				KeyValuePair<string, IList<Type>> list;
				if (lookup.TryGetValue(actual, out list) == false)
				{
					list = new KeyValuePair<string, IList<Type>>(handler.Key, new List<Type>(4));
					lookup.Add(actual, list);
				}
				if (forwarding != null)
				{
					list.Value.Add(forwarding.Service);
				}
			}
			return lookup.Select(c => new MetaComponent(c.Value.Key, c.Key, c.Value.Value));
		}
Exemplo n.º 25
0
        public History fit(Array x = null, Array y = null, int batch_size = 32, int epochs = 1, int verbose = 1,
                           CallbackList callbacks = null, double validation_split            = 0, IList <Array> validation_data = null, Shuffle shuffle = Shuffle.True,
                           Dictionary <int, double> class_weight = null, Array sample_weight = null, int initial_epoch          = 0, object kwargs      = null, int?nb_epoch = null)
        {
            // Legacy support
            if (nb_epoch != null)
            {
                Trace.TraceWarning("The 'nb_epoch' argument in 'fit' has been renamed 'epochs'.");
                epochs = nb_epoch.Value;
            }

            return(this.fit(
                       x.dict_from_single(),
                       y.dict_from_single(),
                       batch_size,
                       epochs,
                       verbose,
                       callbacks,
                       validation_split,
                       validation_data?.Select(a => a.dict_from_single()).ToList(),
                       shuffle,
                       class_weight?.Select(p => ValueTuple.Create(p.Key.ToString(), p.Value)).ToDictionary(a => a.Item1, b => b.Item2).dict_from_single(),
                       sample_weight.dict_from_single(),
                       initial_epoch,
                       kwargs));
        }
Exemplo n.º 26
0
        static void Main(string[] args)
        {
            var input = Console.ReadLine();

            if (input != null)
            {
                string[] words = input.Split();

                Dictionary<string, int> result = new Dictionary<string, int>();

                for (int i = 0; i < words.Length; i++)
                {
                    string word = words[i];
                    if (result.ContainsKey(word))
                    {
                        result[word]++;
                    }
                    result.Add(word, 1);
                }

                Console.WriteLine("\nWord occurence table:\n{0}\n",
                                      string.Join("\n", result.Select(x => string.Format(@"'{0}' -> {1} time(s)", x.Key, x.Value)).ToArray()));

            }

            throw new ArgumentNullException();
        }
Exemplo n.º 27
0
 public override IObservable<TwitterStatus> Upload(Authorize.AuthenticateInfo authInfo, string status,
     byte[] attachedImageBin, long? in_reply_to_status_id = null,
     double? geo_lat = null, double? geo_long = null)
 {
     var param = new Dictionary<string, object>()
     {
         {"key", ApplicationKey},
         {"message", status},
     }.Parametalize();
     return new MultipartableOAuthClient(ApiEndpoint.DefaultConsumerKey, ApiEndpoint.DefaultConsumerSecret,
         authInfo.AccessToken)
     {
         Url = ApiEndpointUriString,
     }
     .AsOAuthEcho()
     .GetResponse(param.Select(p => new UploadContent(p.Key, p.Value))
         .Append(UploadContent.FromBinary("media", "attach.png", attachedImageBin)))
     .ReadString()
     .Select(s =>
     {
         using (var reader = new StringReader(s))
         {
             var doc = XDocument.Load(reader);
             return doc.Element("image").Element("url").ParseString();
         }
     })
     .SelectMany(s => authInfo.Update(status + " " + s, in_reply_to_status_id, geo_lat, geo_long));
 }
        public void CheckStringsDeclared()
        {
            var names = new List<string>();
            checker.GetAllResourceReferences(names);
            Assert.Greater(names.Count, 600, "Должно быть много ресурсных строчек");
            // убрать исключения и повторы
            names = names.Distinct().Where(n => !exceptionString.Contains(n)).ToList();

            // проверить, есть ли они в файлах ресурсов
            var errorsInFile = new Dictionary<string, List<string>>();
            var resxFileNames = Directory.GetFiles(codeBase + @"\TradeSharp.Localisation\Properties", "*.resx");
            
            foreach (var resxFileName in resxFileNames)
            {
                if (excludedResourcesFiles.Contains(resxFileName.Split('\\').Last())) continue;

                var errors = checker.GetNamesLackInResxFile(resxFileName, names);
                if (errors.Count > 0)
                    errorsInFile.Add(Path.GetFileName(resxFileName), errors);
            }

            if (errorsInFile.Count > 0)
            {
                var errorStr = string.Join("\n", errorsInFile.Select(e => e.Key + ": " + string.Join(", ", e.Value)));
                Assert.Fail(errorStr);
            }
        }
Exemplo n.º 29
0
        public AttachmentModel[] GetAttachments(string token)
        {
            var user = GetSession(token);
            var attachmentRepository = Repository.Get<IAttachmentRepository>();
            var files = new Dictionary<string, List<string>>();
            var catalogs = attachmentRepository.GetDirectories(user.UserId);
            foreach (var catalog in catalogs)
            {
                var list = attachmentRepository.GetFiles(catalog).Select(Path.GetFileName).ToList();
                if (list.Count > 0)
                {
                    if (catalog != null) files.Add(Path.GetFileName(catalog), list);
                }
            }

            return files.Select(file => new AttachmentModel
            {
                Catalog = file.Key,
                Urls = file.Value.Select(name => new AttachmentUrlModel
                {
                    Name = name,
                    Url = GetUrl(user.UserId, file.Key, name)
                }).ToArray()
            }).ToArray();
        }
Exemplo n.º 30
0
        public string PeopleGetPublicPhotos(string userId, 
            string safeSearch = null, string extras = null, 
            int? perPage = null, int? page = null)
        {
            string url = "http://api.flickr.com/services/rest?method=flickr.people.getPublicPhotos&";
            var parameters = new Dictionary<string, string>
                {
                    {"format", "json"},
                    {"nojsoncallback", "1"},
                    {"api_key", _apiKey},
                    {"user_id", userId}
                };
            if (safeSearch != null)
                parameters.Add("safe_search", safeSearch);
            if (extras != null)
                parameters.Add("extras", extras);
            if (perPage != null)
                parameters.Add("per_page", perPage.Value.ToString(CultureInfo.InvariantCulture));
            if (page != null)
                parameters.Add("page", page.Value.ToString(CultureInfo.InvariantCulture));

            var parameterArray = parameters.Select(item => item.Key + "=" + item.Value).ToArray();
            url += string.Join("&", parameterArray);

            using (var webClient = new WebClient())
            using (var stream = webClient.OpenRead(url))
            {
                if (stream == null)
                    return null;
                using (var streamReader = new StreamReader(stream))
                {
                    return streamReader.ReadToEnd();
                }
            }
        }
Exemplo n.º 31
0
 private static string Compose(string apiPath, Dictionary<string,string> extra = null)
 {
     extra = extra ?? new Dictionary<string, string>();
     var list = extra.Select(x => x.Key + "=" + x.Value).ToList();
     list.Add(apikey);
     return baseUrl + apiPath + soSite + string.Join("&", list);
 }
Exemplo n.º 32
0
    static void Main()
    {
        Console.Write("Enter a string: ");
        string input = Console.ReadLine();
        MatchCollection words = Regex.Matches(input, @"\b\w+\b");

        Dictionary<string, int> dict = new Dictionary<string, int>();

        foreach (var word in words)
        {
            if (word.ToString() != string.Empty)
            {
                if (!dict.ContainsKey(word.ToString()))
                {
                    dict.Add(word.ToString(), 1);
                }
                else
                {
                    dict[word.ToString()]++;
                }
            }
        }

        Console.WriteLine(string.Join("\n", dict.Select(x => string.Format(@"{0} - {1}", x.Key, x.Value)).ToArray()));
    }
        /// <summary>
        /// Bildet einen Hashcode für das Wiedererkennen der Information in dem Data-Warehouse
        /// </summary>
        /// <param name="information">Informationssammlung</param>
        /// <returns>Gibt einen Hashcode zurück, der die Inhalte der Informationssammlung in kurzer Form erkennbar macht.</returns>
        public static string GetInformationHashcode(this Dictionary <string, IEnumerable <object> > information)
        {
            var hashcode = default(string);

            hashcode = string.Join(
                string.Empty,
                information?.Select(entry =>
            {
                return(string.Format(
                           "{0}.{1}",
                           //  Hashcode des Dictionary-Key
                           entry.Key.GetHashCode().ToString(),
                           //  Hashcode aller Einträge der Liste unter dem Dictionaryschlüssel
                           string.Join(
                               string.Empty,
                               entry.Value?.Select(token =>
                                                   token.GetHashCode().ToString()
                                                   )
                               ).GetHashCode().ToString()
                           ));
            })
                //  Hashcode aus allen zuvor ermittelten Hashcodes
                ).GetHashCode().ToString();

            return(hashcode);
        }
        public async ValueTask <bool> SendAsync(string receiver, byte[] data, bool forceBytes = true, Dictionary <string, string> headers = null)
        {
            try
            {
                var config = new ProducerConfig {
                    BootstrapServers = _kafkaConfiguration.Bootstrap
                };

                var kHeaders = new Headers();
                headers?.Select(x => new Header(x.Key, Encoding.UTF8.GetBytes(x.Value)))
                .ToList()
                .ForEach(x => kHeaders.Add(x));
                if (forceBytes)
                {
                    kHeaders.Add("ForceBytes", new byte[] { 1 });
                }
                using var producer = new ProducerBuilder <string, byte[]>(config).Build();
                await producer.ProduceAsync(receiver, new Message <string, byte[]>()
                {
                    Value   = data,
                    Headers = kHeaders
                });

                producer.Flush(TimeSpan.FromSeconds(10));
                return(true);
            }
            catch (Exception e)
            {
                _logger.LogError(e, "Can`t send to kafka");
                return(false);
            }
        }
Exemplo n.º 35
0
        public async Task <Reservation[]> DescribeInstancesAsync(List <string> instanceIds = null, Dictionary <string, List <string> > filters = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            var filterList = filters?.Select(x => new Filter(x.Key, x.Value)).ToList();

            DescribeInstancesResponse response = null;
            var results = new List <Reservation>();

            while ((response = await _client.DescribeInstancesAsync(new DescribeInstancesRequest()
            {
                NextToken = response?.NextToken,
                Filters = filterList,
                InstanceIds = instanceIds
            }, cancellationToken).EnsureSuccessAsync()) != null)
            {
                if (!response.Reservations.IsNullOrEmpty())
                {
                    results.AddRange(response.Reservations);
                }

                if (response.NextToken.IsNullOrEmpty())
                {
                    break;
                }

                await Task.Delay(100);
            }

            return(results.ToArray());
        }
Exemplo n.º 36
0
        public IEnumerable<FileInfo> OrderFiles(BundleContext context, IEnumerable<FileInfo> files)
        {
            var workingItems = files.AsParallel().Select(i => new _WorkingItem {
                Path = i.FullName,
                FileInfo = i,
                Dependencies = this._GetDependencies(i.FullName),
            });

            var fileDependencies = new Dictionary<string, _WorkingItem>(_DependencyNameComparer);
            foreach (var item in workingItems) {
                _WorkingItem duplicate;
                if (fileDependencies.TryGetValue(item.Path, out duplicate))
                    throw new ArgumentException(string.Format("During dependency resolution, a collision between '{0}' and '{1}' was detected. Files in a bundle must not collide with respect to the dependency name comparer.", Path.GetFileName(item.Path), Path.GetFileName(duplicate.Path)));

                fileDependencies.Add(item.Path, item);
            }

            foreach (var item in fileDependencies.Values) {
                foreach (var dependency in item.Dependencies) {
                    if (!fileDependencies.ContainsKey(dependency))
                        throw new ArgumentException(string.Format("Dependency '{0}' referenced by '{1}' could not found. Ensure the dependency is part of the bundle and its name can be detected by the dependency name comparer. If the dependency is not supposed to be in the bundle, add it to the list of excluded dependencies.", Path.GetFileName(dependency), Path.GetFileName(item.Path)));
                }
            }

            while (fileDependencies.Count > 0) {
                var result = fileDependencies.Values.FirstOrDefault(f => f.Dependencies.All(d => !fileDependencies.ContainsKey(d)));
                if (result == null)
                    throw new ArgumentException(string.Format("During dependency resolution, a cyclic dependency was detected among the remaining dependencies {0}.", string.Join(", ", fileDependencies.Select(d => "'" + Path.GetFileName(d.Value.Path) + "'"))));
                yield return result.FileInfo;
                fileDependencies.Remove(result.Path);
            }
        }
Exemplo n.º 37
0
		/// <summary>
		/// Generate data for the heatmap that display flash times for each player
		/// </summary>
		/// <returns></returns>
		public async Task<List<FlashbangDataPoint>> GetPlayersFlashTimesData()
		{
			List<FlashbangDataPoint> data = new List<FlashbangDataPoint>();
			await Task.Factory.StartNew(() =>
			{
				foreach (PlayerExtended player in Demo.Players)
				{
					Dictionary<long, float> playerFlashStats = new Dictionary<long, float>();

					foreach (PlayerExtended pl in Demo.Players)
					{
						if (!playerFlashStats.ContainsKey(pl.SteamId)) playerFlashStats.Add(pl.SteamId, 0);
					}

					foreach (PlayerBlindedEvent e in Demo.PlayerBlindedEvents.Where(e => player.SteamId == e.ThrowerSteamId))
					{
						if (!playerFlashStats.ContainsKey(e.VictimSteamId))
							playerFlashStats.Add(e.VictimSteamId, 0);
						playerFlashStats[e.VictimSteamId] += e.Duration;
					}

					data.AddRange(playerFlashStats.Select(playerStats => new FlashbangDataPoint
					{
						Flasher = player.Name,
						Flashed = Demo.Players.First(p => p.SteamId == playerStats.Key).Name,
						Duration = Math.Round((decimal)playerStats.Value, 2, MidpointRounding.AwayFromZero)
					}));
				}
			});

			return data;
		}
Exemplo n.º 38
0
        public LoadMenu(String path, Dictionary<String, String> fileTypes, Window parentWindow)
            : base("Load Menu", Math.Min(6, Console.WindowHeight - 22), (Console.WindowWidth / 2) - 30, 60, 20, parentWindow)
        {
            BackgroundColour = ConsoleColor.White;
            FileTypes = fileTypes;

            fileSelect = new FileBrowser(PostionX + 2, PostionY + 2, 56, 13, path, "fileSelect", this, true, "txt");
            fileSelect.ChangeItem = delegate() { UpdateCurrentlySelectedFileName(); };
            fileSelect.SelectFile = delegate() { LoadFile(); };

            var openLabel = new Label("Open", PostionX + 16, PostionY + 2, "openLabel", this);
            openTxtBox = new TextBox(PostionX + 16, PostionY + 7, "openTxtBox", this, Width - 13) { Selectable = false };

            fileTypeDropdown = new Dropdown(PostionX + 18, PostionY + 40, FileTypes.Select(x => x.Value).ToList(), "fileTypeDropdown", this, 17);
            fileTypeDropdown.OnUnselect = delegate() { UpdateFileTypeFilter(); };

            loadBtn = new Button(PostionX + 18, PostionY + 2, "Load", "loadBtn", this);
            loadBtn.Action = delegate() { LoadFile(); };
            cancelBtn = new Button(PostionX + 18, PostionY + 9, "Cancel", "cancelBtn", this);
            cancelBtn.Action = delegate() { ExitWindow(); };

            Inputs.Add(fileSelect);
            Inputs.Add(loadBtn);
            Inputs.Add(cancelBtn);
            Inputs.Add(openLabel);
            Inputs.Add(openTxtBox);
            Inputs.Add(fileTypeDropdown);

            CurrentlySelected = fileSelect;

            Draw();
            MainLoop();
        }
Exemplo n.º 39
0
 public Prog MakeProgram(IReadOnlyList<Declr> prelude,
     Dictionary<String, IReadOnlyList<IClassItem>> modules)
 {
     var p = MakeModule("prelude", prelude, false);
     var mods = modules.Select(m => MakeModule(m.Key, m.Value));
     return new Prog(MakeModule("global", p.Append(mods).ToList(), false));
 }
Exemplo n.º 40
0
 void ReloadBuilds()
 {
     try
     {
         string res = Util.GetPageSource("http://d3up.com/ajax/builds?username="******"builds"] != null)
         {
             var builds = o["builds"];
             _builds = builds.ToObject<Dictionary<string, string>>();
             var buildNames = _builds.Select(b => b.Value).ToArray();
             this.UIThread(() =>
             {
                 cbDefaultBuild.Items.Clear();
                 cbDefaultBuild.Items.AddRange(buildNames);
             });
             GUI.Log(_builds.Count + " Builds loaded from D3Up.com");
         }
         else
         {
             throw new Exception("No builds");
         }
     }
     catch (Exception ex)
     {
         GUI.Log("Cannot fetch default build. Please check your d3up username.");
     }
 }
Exemplo n.º 41
0
        /// <summary>
        /// Konstruktor okna warunków początkowych
        /// </summary>
        internal InitialCondition(int _mode=SPDAssets.MAX,InitialConditions condition=null)
        {
            _tooltip = -1;
            InitializeComponent();

            Mode = _mode;
            _selectedOperation = Operation.None;
            ComboBox.ItemsSource = SPDAssets.GetBrushRectangles(Mode,InitialConditions.GetTransformation(Mode));
            ComboBox.SelectedIndex = 0;
            DataContext = this;
            _conditionNames = new List<Tuple<string,Tuple<string,bool> > >();
            _conditions = new Dictionary<Tuple<string, bool>, Func<bool, int, int, bool, InitialConditions>>();
            foreach (var T in new[] {false, true})
            {
                _conditions.Add(new Tuple<string, bool>("Donut", T), InitialConditions.DonutFactory);
                _conditions.Add(new Tuple<string, bool>("Circle", T), InitialConditions.CircleFactory);
                _conditions.Add(new Tuple<string,bool>("Diagonal",T),InitialConditions.DiagonalFactory);
                _conditions.Add(new Tuple<string, bool>("NowakMay", T), InitialConditions.NowakMayFactory);
            }
            _conditionNames.AddRange(
                _conditions.Select(
                    k =>
                        new Tuple<string, Tuple<string, bool>>(k.Value(k.Key.Item2, 1,10,false).Name,
                            new Tuple<string, bool>(k.Key.Item1, k.Key.Item2))));
            ComboBoxCopy.ItemsSource = _conditionNames.Select(s=>s.Item1);
            var D = SPDAssets.GenerateLegend(Legend.Height, Mode, InitialConditions.GetTransformation(Mode));
            D.Stretch = Stretch.Fill;

            Legend.Children.Add(D);
            if (condition != null) Condition = condition;
        }
Exemplo n.º 42
0
        public IEnumerable<KeyValuePair<string, IEnumerable<string>>> GetAllTags(IMongoQuery query)
        {
            var dataSet = new Dictionary<string, HashSet<string>>(StringComparer.OrdinalIgnoreCase);

            foreach (var entity in serverProvider.Database.OsmCompoundQuery(query))
            {
                foreach (var tag in entity.Tags)
                {
                    if (!dataSet.ContainsKey(tag.Key))
                    {
                        dataSet.Add(tag.Key, new HashSet<string>(StringComparer.OrdinalIgnoreCase));
                    }

                    var valueSet = dataSet[tag.Key];
                    if (!valueSet.Contains(tag.Value))
                    {
                        valueSet.Add(tag.Value);
                    }
                }
            }

            var result = dataSet.Select(kv => new KeyValuePair<string, IEnumerable<string>>(kv.Key, kv.Value));

            return result;
        }
Exemplo n.º 43
0
        /// <inheritdoc/>
        public ISmsSendResult SendSms(ISms sms)
        {
            try
            {
                if (!sms?.IsValid(_smsServiceConfig) ?? true)
                {
                    throw new Exception("Invalid SMS request.");
                }

                var paramDict = new Dictionary <string, string>();
                paramDict.Add(_smsServiceConfig.MessageMask, sms.Message);
                paramDict.Add(_smsServiceConfig.RecepientMask, sms.Recepient);
                _smsServiceConfig?.RequestParameters?.ToList()?.ForEach(x => paramDict?.Add(x.Key, x.Value));
                HttpWebRequest request   = null;
                string         postData  = null;
                byte[]         postBytes = null;

                switch (_smsServiceConfig.RequestContentType)
                {
                case RequestContentType.FormData:
                    NameValueCollection outgoingQueryString = HttpUtility.ParseQueryString(string.Empty);
                    paramDict?.ToList()?.ForEach(x => outgoingQueryString.Add(x.Key, x.Value));
                    postData            = outgoingQueryString?.ToString();
                    postBytes           = _smsServiceConfig.Encoding.GetBytes(postData);
                    request             = (HttpWebRequest)WebRequest.Create(_smsServiceConfig.BaseUrl);
                    request.ContentType = "application/form-data";
                    break;

                case RequestContentType.JSON:
                    postData            = JsonConvert.SerializeObject(paramDict);
                    postBytes           = _smsServiceConfig.Encoding.GetBytes(postData);
                    request             = (HttpWebRequest)WebRequest.Create(_smsServiceConfig.BaseUrl);
                    request.ContentType = "application/json";
                    break;

                default:    //Handles Enums.RequestContentType.URL too
                    string @params = String.Join("&&", paramDict?.Select(x => $"{x.Key}={x.Value}")?.ToArray());
                    string url     = _smsServiceConfig.BaseUrl + '?' + @params;
                    request = (HttpWebRequest)WebRequest.Create(url);
                    break;
                }

                request.Method = _smsServiceConfig.RequestMethod.Method;
                if (postBytes != null)
                {
                    using (var stream = request.GetRequestStream())
                    {
                        stream.Write(postBytes, 0, postBytes.Length);
                    }
                }

                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                return(new SmsSendResult(sms.Recepient, response.StatusCode, response.GetResponseStream()));
            }
            catch (Exception e)
            {
                return(new SmsSendResult(sms.Recepient, e.Message));
            }
        }
Exemplo n.º 44
0
 private static Dictionary <string, AttributeValue> ConvertToAttributeValues(Dictionary <string, object> items)
 {
     return(items?.Select(i =>
                          new {
         i.Key,
         Value = CreateAttributeValue(i.Value)
     }).ToDictionary(x => x.Key, x => x.Value));
 }
Exemplo n.º 45
0
 private void LogState(Dictionary <string, object> state)
 {
     if (state == null)
     {
         return;
     }
     Debug.Log(string.Join("\n", state?.Select(x => $"{x.Key}_{x.Value}")));
 }
Exemplo n.º 46
0
        private void SetColumnsWhere(Context context, SiteSettings ss, SqlWhereCollection where)
        {
            var prefix       = "ViewFilters_" + ss.ReferenceType + "_";
            var prefixLength = prefix.Length;

            ColumnFilterHash?
            .Select(data => new
            {
                Column     = ss.GetColumn(context: context, columnName: data.Key),
                ColumnName = data.Key,
                data.Value
            })
            .Where(o => o.Column != null)
            .ForEach(data =>
            {
                if (data.ColumnName == "SiteTitle")
                {
                    CsNumericColumns(
                        column: ss.GetColumn(context: context, columnName: "SiteId"),
                        value: data.Value,
                        where : where);
                }
                else
                {
                    switch (data.Column.TypeName.CsTypeSummary())
                    {
                    case Types.CsBool:
                        CsBoolColumns(
                            column: data.Column,
                            value: data.Value,
                            where : where);
                        break;

                    case Types.CsNumeric:
                        CsNumericColumns(
                            column: data.Column,
                            value: data.Value,
                            where : where);
                        break;

                    case Types.CsDateTime:
                        CsDateTimeColumns(
                            context: context,
                            column: data.Column,
                            value: data.Value,
                            where : where);
                        break;

                    case Types.CsString:
                        CsStringColumns(
                            column: data.Column,
                            value: data.Value,
                            where : where);
                        break;
                    }
                }
            });
        }
 // Provide priorProb <=> use Laplace correction; leave priorProb as null <=> do not use Laplace correction
 public void CalcLeafProbDist(Dictionary <string, double>?priorProb)
 {
     foreach (string?label in priorProb?.Select(kvp => kvp.Key) ?? InstancesIn.Select(i => i.LabelValue).Distinct())
     {
         LeafProbDist.Add(label ?? throw new NullReferenceException("Unlabeled instances used in growing a tree. "), priorProb is null
             ? InstancesIn.Count(i => i.LabelValue == label) / (double)InstancesIn.Count
             : (InstancesIn.Count(i => i.LabelValue == label) + priorProb[label]) / (InstancesIn.Count + priorProb.Sum(kvp => kvp.Value)));
     }
 }
Exemplo n.º 48
0
        public string[] GetDataSets()
        {
            if (_allDataSetsInfo == null)
            {
                _allDataSetsInfo = GetDataSetTree();
            }

            return(_allDataSetsInfo?.Select(n => n.Key).ToArray());
        }
Exemplo n.º 49
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SearchConfigurationModel" /> class.
 /// </summary>
 /// <param name="fieldId">Contains the field identity used for filtering.</param>
 /// <param name="displayName">Contains the user interface field display name.</param>
 /// <param name="type">Contains the data type of the field.</param>
 /// <param name="validValues">Contains an optional list of valid values for the field.</param>
 /// <param name="compareExists">Contains a value indicating whether this is an existence comparison (not null).</param>
 /// <param name="overrideOperators">Contains an optional list of valid operators for the field.</param>
 public SearchConfigurationModel(string fieldId, string displayName, SearchConfigurationDataType type = SearchConfigurationDataType.String, List <KeyValuePair <string, string> > validValues = null, bool compareExists = false, Dictionary <SearchExpressionOperator, string> overrideOperators = null)
 {
     this.FieldId       = fieldId;
     this.DisplayName   = displayName;
     this.DataType      = type;
     this.CompareExists = compareExists;
     this.Operators     = overrideOperators?.Select(d => new KeyValuePair <SearchExpressionOperator, string>(d.Key, d.Value)).ToList() ?? SearchConfigurationDefaults.TypeOperators(type);
     this.ValidValues   = validValues ?? new List <KeyValuePair <string, string> >();
 }
 public override async Task <IEnumerable <Model.Roulette> > FindByStringsFiltersAsync(Dictionary <string, string> filters)
 {
     return(await _mongoDb.GetItemsAsync <Model.Roulette>(filters?.Select(x => new MongoDbFilter
     {
         FieldName = x.Key,
         Value = x.Value,
         Operator = FilterOperator.Equal
     }).ToList(), _rouletteMongoDbSettings));
 }
Exemplo n.º 51
0
        public bool Subscribe(string listId, MailAddress email, string name, Dictionary <string, string> customFields, string apiKey)
        {
            var emailAddress = email.Address;

            var uri = new Uri($"https://api.createsend.com/api/v3.1/subscribers/{listId}.json");

            var client = new WebClient
            {
                Encoding = Encoding.UTF8
            };

            // set JSON content type
            client.Headers[HttpRequestHeader.ContentType] = "application/json";

            // basic auth, base64 encode of username:password
            var credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{apiKey}:-"));

            client.Headers[HttpRequestHeader.Authorization] = $"Basic {credentials}";

            var customFieldsData = customFields?.Select(kvp => new CustomField
            {
                Key   = kvp.Key,
                Value = kvp.Value
            }).ToArray() ?? new CustomField[0];

            try
            {
                var data = Serialize(new SubscriptionData
                {
                    EmailAddress = emailAddress,
                    Name         = string.IsNullOrWhiteSpace(name) ? emailAddress : name,
                    CustomFields = customFieldsData
                });

                var response = client.UploadString(uri, "POST", data);
                return(emailAddress.Equals(response, StringComparison.OrdinalIgnoreCase));
            }
            catch (WebException wex)
            {
                var responseStream = wex.Response?.GetResponseStream();
                if (responseStream != null)
                {
                    using (var reader = new StreamReader(responseStream))
                    {
                        var response = reader.ReadToEnd();
                        Log.Error(wex, $"An error occurred while trying to subscribe the email: {emailAddress}. Error details: {response}");
                    }
                }
                return(false);
            }
            catch (Exception ex)
            {
                Log.Error(ex, $"An error occurred while trying to subscribe the email: {emailAddress}.");
                return(false);
            }
        }
Exemplo n.º 52
0
        /// <summary>
        /// Запись системных логов информационного характера
        /// </summary>
        /// <param name="message">сообщение</param>
        /// <param name="properties">свойства</param>
        public void SystemInfo(string message, Dictionary <object, object> properties = null)
        {
            List <string> strings = new List <string>()
            {
            };
            var str  = (properties?.Select(x => x.Key.ToString() + "," + x.Value.ToString())) ?? strings;
            var str2 = String.Join(",", str);

            CommonLog(message + " " + str2, "System_Info", "SYSTEM_INFO");
        }
Exemplo n.º 53
0
 /// <summary>
 /// Convert table to localized text
 /// </summary>
 /// <param name="table"></param>
 /// <returns></returns>
 private static ApplicationDocument.LocalizedText[] GetLocalizedText(
     Dictionary <string, string> table)
 {
     return(table?
            .Select(kv => new ApplicationDocument.LocalizedText {
         Locale = kv.Key,
         Name = kv.Value
     })
            .ToArray());
 }
Exemplo n.º 54
0
        public static async Task <TaskDefinition> RegisterFargateTaskAsync(this ECSHelper ecs,
                                                                           string executionRoleArn,
                                                                           string family,
                                                                           int cpu,
                                                                           int memory,
                                                                           string name,
                                                                           string image,
                                                                           Dictionary <string, string> envVariables,
                                                                           string logGroup,
                                                                           IEnumerable <int> ports,
                                                                           CancellationToken cancellationToken = default(CancellationToken))
        {
            var env = envVariables?.Select(x => new Amazon.ECS.Model.KeyValuePair()
            {
                Name = x.Key, Value = x.Value
            })?.ToList();
            var lc = new LogConfiguration()
            {
                LogDriver = new LogDriver("awslogs"),
                Options   = new Dictionary <string, string>()
                {
                    { "awslogs-group", logGroup },
                    { "awslogs-region", ecs.Client.GetRegionName() },
                    { "awslogs-stream-prefix", "ecs" }
                }
            };

            var pmTCP = ports.Select(x => new PortMapping()
            {
                ContainerPort = x, HostPort = x, Protocol = TransportProtocol.Tcp
            });

            var cd = new ContainerDefinition()
            {
                Name              = name,
                Image             = image,
                Environment       = env,
                LogConfiguration  = lc,
                PortMappings      = pmTCP.ToList(),
                MemoryReservation = (int)(memory * 4) / 5
            };

            var response = await ecs.RegisterTaskDefinitionAsync(
                executionRoleArn,
                executionRoleArn,
                family,
                new string[] { "FARGATE" },
                new List <ContainerDefinition>() { cd },
                cpu,
                memory,
                NetworkMode.Awsvpc,
                cancellationToken);

            return(response.TaskDefinition);
        }
Exemplo n.º 55
0
        public ActionResult CreateView(TechnicianGroupEditViewModel model)
        {
            try
            {
                if (MethodHelper.IsNullOrEmpty(model.CompCd, model.VendorCd))
                {
                    throw new ArgumentNullException($"移至新增群組畫面,没有傳入對應信息");
                }

                Dictionary <string, string> tvndzo = _vendorFactory.GetVenderZo(model.CompCd, model.VendorCd);

                List <TvenderTechnician> technicians = _vendorFactory.GetTechnicians(model.CompCd, model.VendorCd);


                return(View("Edit", new TechnicianGroupEditViewModel()
                {
                    CompCd = model.CompCd,
                    VendorCd = model.VendorCd,
                    ActionType = AuthNodeType.Create,
                    AccountDualBoxList = technicians?.Select(x =>
                    {
                        return new SelectListItem()
                        {
                            Text = x.Name,
                            Value = x.Account,
                            Selected = false
                        };
                    }),
                    DoDualBoxList = new List <SelectListItem>(),

                    VenderZoDualBoxList = tvndzo?.Select(x =>
                    {
                        return new SelectListItem()
                        {
                            Text = x.Value,
                            Value = x.Key,
                            Selected = false
                        };
                    })
                }));
            }
            catch (Exception ex)
            {
                _logger.Error(ex.Message);
                if (ex.InnerException != null)
                {
                    _logger.Error(ex.InnerException.Message);
                    if (ex.InnerException.InnerException != null)
                    {
                        _logger.Error(ex.InnerException.InnerException.Message);
                    }
                }
                return(View());
            }
        }
Exemplo n.º 56
0
        public IEnumerable <Award> GetAll()
        {
            using (StreamReader fileJson = new StreamReader(_path))
            {
                var stringJson = fileJson.ReadToEnd();
                //yield ??77?
                FakeDaoAward = JsonConvert.DeserializeObject <Dictionary <int, Award> >(stringJson);
                _id          = FakeDaoAward?.Count() ?? 0;

                return(FakeDaoAward?.Select(x => x.Value));
            }
        }
        /// <summary>
        /// This method updates the security statistics.
        /// </summary>
        /// <param name="statistics">The statistics.</param>
        protected override void StatisticsRecalculate(SecurityContainerStatistics statistics)
        {
            base.StatisticsRecalculate(statistics);

            try
            {
                statistics.AuthenticationHandlers = mAuthenticationHandlers?.Select((h) => $"{h.Key}: {h.Value.Name}").ToArray();
                statistics.EncryptionHandlers     = mEncryptionHandlers?.Select((h) => $"{h.Key}: {h.Value.Name}").ToArray();;
            }
            catch (Exception)
            {
            }
        }
Exemplo n.º 58
0
        void ShowStartupAppsFromSelectedComputersExecute(object param)
        {
            var dataToShow = new List <NodeItem>();

            var computers = DomainComputers?.Where(x => x.IsSelected).ToList();

            foreach (var computer in computers)
            {
                // Add ping here also
                using (_registryEditor = new RegistryEditor(computer?.Name, LookupSource, StartRemoteRegistryServiceIfNeeded))
                {
                    Dictionary <string, string> apps = null;

                    try
                    {
                        apps = _registryEditor.GetAllStartupAppsFromRegistry(SkippableSource);
                    }
                    catch
                    {
                    }

                    var data = apps?.Select(x => new KeyValuePair <string, string>(x.Key, x.Value)).ToList();

                    string name = string.Empty;

                    if (data == null)
                    {
                        name = $"{computer?.Name} / (Not available)";
                    }
                    else if (!data.Any())
                    {
                        name = $"{computer?.Name} / NO EXTRA APPS";
                    }
                    else
                    {
                        name = $"{computer?.Name}";
                    }

                    dataToShow.Add(new NodeItem
                    {
                        ComputerName = name,
                        Data         = new ObservableCollection <KeyValuePair <string, string> >(data ?? new List <KeyValuePair <string, string> >())
                    });
                }
            }
            var window    = new StartupAppsWindow();
            var viewModel = new StartupAppsWindowViewModel(dataToShow);

            window.DataContext = viewModel;
            window.Show();
        }
Exemplo n.º 59
0
        public static async Task <string> GetAsync(string url, Dictionary <string, string> prms, string contentType, bool contentTypeAddCharsetUtf8 = false)
        {
            if (url == null)
            {
                throw new ArgumentNullException(nameof(url));
            }
            url = url + str.JoinTitle("?", str.Join("&", prms?.Select(a => $"{a.Key}={a.Value}")));

            var req = CreateHttpWebRequest("GET", url, contentType: contentType, contentTypeAddCharsetUtf8: contentTypeAddCharsetUtf8);

            var responseString = await ReadAsStringAsync(req);

            return(responseString);
        }
Exemplo n.º 60
0
        public static Dictionary <string, string> ToRouteData(this HttpRequest request, Dictionary <string, string> append = null)
        {
            var fields = request.Query.Keys.Except(append?.Select(kp => kp.Key) ?? Enumerable.Empty <string>());
            var result = fields.ToDictionary(field => field, field => request.Query[field].First());

            if (append != null)
            {
                foreach (var kp in append)
                {
                    result.Add(kp.Key, kp.Value);
                }
            }

            return(result);
        }