Example #1
0
        static int CalculateScore(Dictionary<Ingredient, int> ingredients)
        {
            int totalCapacity = ingredients.Sum(ig => ig.Value * ig.Key.Capacity);
            int totalDurability = ingredients.Sum(ig => ig.Value * ig.Key.Durability);
            int totalFlavor = ingredients.Sum(ig => ig.Value * ig.Key.Flavor);
            int totalTexture = ingredients.Sum(ig => ig.Value * ig.Key.Texture);

            if (totalCapacity < 0 || totalDurability < 0 || totalFlavor < 0 || totalTexture < 0)
            {
                return 0;
            }

            return totalCapacity * totalDurability * totalFlavor * totalTexture;
        }
    static void Main()
    {
        // Get the frequency of all consecutive pairs of numbers given on a single line
        string command = Console.ReadLine();
        int[] line = command.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries).Select(x => int.Parse(x)).ToArray();

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

        for (int i = 0; i < line.Length - 1; i++) // Iterate through every pair in the given list of numbers
        {
            string pair = line[i] + " " + line[i + 1];
            if (!couples.ContainsKey(pair))
            {
                couples.Add(pair, 1);
            }
            else
            {
                couples[pair] += 1;
            }
        }

        double sum = couples
            .Sum(x => x.Value); // Get all the occurances so i can calculate the percentage

        foreach (var item in couples) // Printing the results
        {
            Console.WriteLine("{0} -> {1:F2}%", item.Key, (item.Value / sum) * 100);
        }
    }
Example #3
0
        public long Solve()
        {
            var primesFactorisation = new Dictionary<long, long>();

            var primes = new Utils.Prime((long)Math.Sqrt(10) + 1).PrimeList;

            foreach (var prime in primes)
            {
                primesFactorisation.Add(prime, 0);
            }

            for (var n = UpperNumber - DownNumber; n <= UpperNumber; n++)
            {
                var number = n;
                foreach (var prime in primes)
                {
                    if (number == 1)
                        break;

                    while (number % prime == 0)
                    {
                        number = number / prime;
                        primesFactorisation[prime]++;
                    }
                }
            }

            return primesFactorisation.Sum(t => t.Key * t.Value);
        }
Example #4
0
        static void Main()
        {
            int n = int.Parse(Console.ReadLine());
            List<int>[] graph = new List<int>[n];

            for (int i = 0; i < n; i++)
            {
                graph[i] = new List<int>();
                string line = Console.ReadLine();
                for (int j = 0; j < line.Length; j++)
                {
                    if (line[j] == 'Y')
                    {
                        graph[i].Add(j);
                    }
                }
            }

            Dictionary<int, decimal> calculatedSalaries = new Dictionary<int, decimal>();
            for (int i = 0; i < n; i++)
            {
                CalculateSalary(graph, i, calculatedSalaries);
            }

            decimal total = calculatedSalaries.Sum(x => x.Value);
            Console.WriteLine(total);
        }
        private decimal GetBagSetTotalAmount(Dictionary<int, ProductModel> basSet)
        {
            decimal totalAmount = basSet.Sum(p => p.Value.Price);
            decimal discountPercent = 1m;

            switch (basSet.Count)
            {
                case 1:
                    discountPercent = 1m;
                    break;
                case 2:
                    discountPercent = 0.95m;
                    break;
                case 3:
                    discountPercent = 0.9m;
                    break;
                case 4:
                    discountPercent = 0.8m;
                    break;
                case 5:
                    discountPercent = 0.75m;
                    break;
                default:
                    break;
            }

            return totalAmount * discountPercent;
        }
        /// <summary>
        /// Prepares an url to visualize the pie chart via Google Chart API
        /// </summary>
        /// <param name="chartQueryResults"></param>
        /// <returns></returns>
        private static string PreparePieChartUrl(Dictionary<string, long> chartQueryResults)
        {
            var other = 0.0;
            var per = "";
            var name = "";
            var sum = chartQueryResults.Sum(item => item.Value);

            foreach (var item in chartQueryResults)
            {
                var temp = item.Value/(sum/100.0);
                if (temp < 1.0)
                {
                    other += temp;
                    continue;
                }
                per += "," + ((int)Math.Round(temp, 0));
                name += "|" + System.Net.WebUtility.UrlEncode(Helpers.FirstLetterToUpper(item.Key));
            }
            if (other > 1.0)
            {
                per += "," + ((int)Math.Round(other, 0));
                name += "|" + System.Net.WebUtility.UrlEncode(Helpers.FirstLetterToUpper(Dict.Other));
            }

            const string str = "https://chart.googleapis.com/chart?cht=p&chd=t:"; // "http://chart.apis.google.com/chart?cht=p&chd=t:";
            var url = str + per.Substring(1) + "&chs=450x250&chco=007acb&chl=" + name.Substring(1);
            return url;
        }
 public RankingEvaluationResult(Dictionary<string,double> defectCodeSizeByFile, string[] predictedDefectFiles)
 {
     DefectCodeSize = defectCodeSizeByFile.Sum(x => x.Value);
     DefectCodeSizeInSelection = defectCodeSizeByFile
         .Where(x => predictedDefectFiles.Any(y => y == x.Key))
         .Sum(x => x.Value);
 }
Example #8
0
    static void Main()
    {
        #if DEBUG
        Console.SetIn(new StreamReader("../../input.txt"));
        #endif

        var input = Console.ReadLine().Split();

        int width = int.Parse(input[0]);
        int height = int.Parse(input[1]);
        int depth = int.Parse(input[2]);

        cube = new char[height, depth, width];

        for (int h = 0; h < height; h++)
        {
            var floor = Console.ReadLine().Split();

            for (int d = 0; d < depth; d++)
            {
                var row = floor[d];

                for (int w = 0; w < width; w++)
                {
                    cube[h, d, w] = row[w];
                }
            }
        }

        var results = new Dictionary<char, int>();

        for (int w = 1; w < width - 1; w++)
        {
            for (int h = 1; h < height - 1; h++)
            {
                for (int d = 1; d < depth - 1; d++)
                {
                    if (IsStar(h, d, w))
                    {
                        var c = cube[h, d, w];

                        if (!results.ContainsKey(c))
                        {
                            results.Add(c, 0);
                        }

                        results[c]++;
                    }
                }
            }
        }

        Console.WriteLine(results.Sum(x => x.Value));

        foreach (var result in results.OrderBy(x => x.Key))
        {
            Console.WriteLine("{0} {1}", result.Key, result.Value);
        }
    }
		internal static async void RemoveDuplicateMatches(bool showDialogIfNoneFound)
		{
			try
			{
				Log.Info("Checking for duplicate matches...");
				var toRemove = new Dictionary<GameStats, List<GameStats>>();
				foreach(var deck in DeckList.Instance.Decks)
				{
					var duplicates =
						deck.DeckStats.Games.Where(x => !string.IsNullOrEmpty(x.OpponentName))
						    .GroupBy(g => new {g.OpponentName, g.Turns, g.PlayerHero, g.OpponentHero, g.Rank});
					foreach(var games in duplicates)
					{
						if(games.Count() > 1)
						{
							var ordered = games.OrderBy(x => x.StartTime);
							var original = ordered.First();
							var filtered = ordered.Skip(1).Where(x => x.HasHearthStatsId).ToList();
							if(filtered.Count > 0)
								toRemove.Add(original, filtered);
						}
					}
				}
				if(toRemove.Count > 0)
				{
					var numMatches = toRemove.Sum(x => x.Value.Count);
					Log.Info(numMatches + " duplicate matches found.");
					var result =
						await
						Core.MainWindow.ShowMessageAsync("Detected " + numMatches + " duplicate matches.",
						                                 "Due to sync issues some matches have been duplicated, click \"fix now\" to see and delete duplicates. Sorry about this.",
						                                 MessageDialogStyle.AffirmativeAndNegativeAndSingleAuxiliary,
						                                 new MessageDialogs.Settings
						                                 {
							                                 AffirmativeButtonText = "fix now",
							                                 NegativeButtonText = "fix later",
							                                 FirstAuxiliaryButtonText = "don't fix"
						                                 });
					if(result == MessageDialogResult.Affirmative)
					{
						var dmw = new DuplicateMatchesWindow();
						dmw.LoadMatches(toRemove);
						dmw.Show();
					}
					else if(result == MessageDialogResult.FirstAuxiliary)
					{
						Config.Instance.FixedDuplicateMatches = true;
						Config.Save();
					}
				}
				else if(showDialogIfNoneFound)
					await Core.MainWindow.ShowMessageAsync("No duplicate matches found.", "");
			}
			catch(Exception e)
			{
				Log.Error(e);
			}
		}
Example #10
0
        /// <summary>Returns numeric indicator of market activity. Higher value means higher activity (i.e. lot of trades with higher volume).</summary>
        /// <param name="tradeHistory">Description of last executed trades of exchange</param>
        /// <param name="now">Current local time of the exchange</param>
        /// <returns>Coeficient in [0.0, 1.0] where 0.0 means totally peacefull market, 1.0 is wild.</returns>
        internal static float GetMadness(List<Trade> tradeHistory, DateTime now)
        {
            //Trades of past 4mins
            List<Trade> trades = tradeHistory.Where(trade => trade.Time >= now.AddSeconds(-240)).ToList();
            if (!trades.Any())
            {
                return 0.0f;
            }

            //Group by time, so that single trade with big volume doesn't look like many trades
            var groupped = new Dictionary<string, Trade>();
            foreach (var trade in trades)
            {
                var key = trade.timestamp + "_" + trade.type;
                if (!groupped.ContainsKey(key))
                {
                    groupped.Add(key, new Trade(trade.price, trade.amount, trade.Type));
                }
                else
                {
                    groupped[key].amount += trade.amount;
                    if (TradeType.BUY == trade.Type && trade.amount > groupped[key].amount)
                        groupped[key].amount = trade.amount;
                    else if (TradeType.SELL == trade.Type && trade.amount < groupped[key].amount)
                        groupped[key].amount = trade.amount;
                }
            }

            //        Console.WriteLine("DEBUG: {0} trades in past 90sec, {1} groupped by time", tradeHistory.Count, groupped.Count);

            const int MIN_TRADES = 4;
            const int MAX_TRADES = 14;
            float intenseCoef;
            if (groupped.Count < MIN_TRADES)        //Too few trades
                intenseCoef = 0.0f;
            else if (groupped.Count >= MAX_TRADES)  //Too many trades
                intenseCoef = 1.0f;
            else
                intenseCoef = (float)(groupped.Count - MIN_TRADES) / (MAX_TRADES - MIN_TRADES);

            const double MIN_AVG_VOLUME = 20;
            const double MAX_AVG_VOLUME = 50;
            float volumeCoef;
            double avgVolume = groupped.Sum(trade => trade.Value.amount) / groupped.Count;
            //        Console.WriteLine("DEBUG: avgVolume={0}", avgVolume);
            if (avgVolume < MIN_AVG_VOLUME)
                volumeCoef = 0.0f;
            else if (avgVolume >= MAX_AVG_VOLUME)
                volumeCoef = 1.0f;
            else
                volumeCoef = (float)((avgVolume - MIN_AVG_VOLUME) / (MAX_AVG_VOLUME - MIN_AVG_VOLUME));

            //        Console.WriteLine("DEBUG: intensityCoef={0}, volumeCoef={1}", intenseCoef, volumeCoef);

            //Average of volume and frequency coeficients
            return (intenseCoef + volumeCoef) / 2;
        }
Example #11
0
        // Calculate the h value used for QF calculation.
        public double CalculateQFBandwidth(string attribute)
        {
            if (workloadCounts[attribute].Count == 0)
                return 0;
            Dictionary<string, double> values = new Dictionary<string, double>();
            int totalCount = 0;
            foreach (KeyValuePair<string, int> row in workloadCounts[attribute])
            {
                totalCount += row.Value;
                values[row.Key] = double.Parse(row.Key); // for calculation of h
            }

            //calculate std.dev.
            double average = values.Sum(d => d.Value * workloadCounts[attribute][d.Key]) / totalCount;
            double sum = values.Sum(d => (d.Value - average) * (d.Value - average) * workloadCounts[attribute][d.Key]);
            double stdDev = Math.Sqrt(sum / totalCount);

            // calculate h
            return 1.06 * stdDev * Math.Pow(totalCount, -0.2);
        }
        public double Calculate(Dictionary<string, int> booksToBuy)
        {
            var totalCount = booksToBuy.Sum(i => i.Value);
            var totalPrice = totalCount * BOOK_UNIT_PRICE;

            if (totalCount > 1)
            {
                totalPrice = totalPrice * TWO_BOOKS_DISCOUNT_RATE;
            }

            return totalPrice;
        }
Example #13
0
        static void Main(string[] args)
        {
            try
            {
                //Set up dictionary
                int currentValueOfCharInDictionary = 0;
                string text = System.IO.File.ReadAllText(args[0]);
                Dictionary<char, int> relHaeufigkeit = new Dictionary<char, int>();
                for (int i = 0; i < text.Length; i++)
                {
                    char currentlySelectedCharFromText = text[i];
                    bool checkIfCharIsInDoctionary = relHaeufigkeit.ContainsKey(currentlySelectedCharFromText);
                    if (checkIfCharIsInDoctionary == true)
                    {
                        relHaeufigkeit.TryGetValue(currentlySelectedCharFromText, out currentValueOfCharInDictionary);
                        currentValueOfCharInDictionary += 1;
                        relHaeufigkeit.Remove(currentlySelectedCharFromText);
                        relHaeufigkeit.Add(currentlySelectedCharFromText, currentValueOfCharInDictionary);
                        currentValueOfCharInDictionary = 0;
                    }
                    else
                    {
                        relHaeufigkeit.Add(currentlySelectedCharFromText, 1);
                    }
                }
                //printdictionary(relHaeufigkeit);
                //Create File to Write
                int j = 0;
                string[] lines = new string[relHaeufigkeit.Count+1];
                double sumOfAllChars = (double)relHaeufigkeit.Sum(val => val.Value);
                foreach (KeyValuePair<char, int> kvp in relHaeufigkeit)
                {
                    Console.WriteLine("Character: " + kvp.Key + " Häufigkeit: " + Math.Round(kvp.Value/sumOfAllChars, 5)*100 + "%");
                    lines[j] = kvp.Key + "\t" + Math.Round(kvp.Value / sumOfAllChars, 5) * 100 + "%";
                    j++;
                }
                //Add in entropy for good Measure:
                double returnedEntropy = calculateEntropy(relHaeufigkeit, sumOfAllChars);
                lines[lines.Length - 1] = "Entropy: " + returnedEntropy.ToString();
                calculateEntropy(relHaeufigkeit, sumOfAllChars);
                //Write File
                System.IO.File.WriteAllLines(args[1], lines);
                Console.ReadLine();

            } catch (Exception e)
            {
                Console.WriteLine("There seems to have been an Error!");
            }
        }
Example #14
0
        int maxHappiness(int[] h, String[] s)
        {
            Dictionary<string, int> dic = new Dictionary<string, int>();
            for (int i=0; i<h.Length; ++i)
            {
                if (dic.ContainsKey(s[i]) && dic[s[i]] > h[i])
                    ;
                else
                {
                    dic[s[i]] = h[i];
                }
            }

            return dic.Sum(x => x.Value);
        }
Example #15
0
        public static void Main()
        {
            var employeesCount = int.Parse(Console.ReadLine());
            var employees = new string[employeesCount];
            for (int i = 0; i < employeesCount; i++)
            {
                employees[i] = Console.ReadLine();
            }

            // Sample input
            // var employeesCount = 6;
            // var employees = new string[]
            // {
            //     "NNNNNN",
            //     "YNYNNY",
            //     "YNNNNY",
            //     "NNNNNN",
            //     "YNYNNN",
            //     "YNNYNN"
            // };

            managers = new Dictionary<int, HashSet<int>>();
            salaries = new Dictionary<int, int>();

            for (int employee = 0; employee < employeesCount; employee++)
            {
                for (int symbolIndex = 0; symbolIndex < employees[employee].Length; symbolIndex++)
                {
                    if (employees[employee][symbolIndex] == 'Y')
                    {
                        if (!managers.ContainsKey(employee))
                        {
                            managers[employee] = new HashSet<int>();
                        }

                        managers[employee].Add(symbolIndex);
                    }
                }
            }

            for (int employee = 0; employee < employees.Length; employee++)
            {
                EstimateSalary(employee);
            }

            Console.WriteLine(salaries.Sum(s => s.Value));
        }
Example #16
0
        public BrowserResponse(int appStatusCode, Stream response)
        {
            if (response == null)
                throw new ArgumentNullException ("response");

            ResponseBody = new MemoryStream();

            using (var reader = new StreamReader(response, System.Text.ASCIIEncoding.ASCII))
            {
                // First line is status code.. something quick and dirty will do
                string line = reader.ReadLine();
                int spaceIdx = line.IndexOf(' ');
                HttpStatusCode = int.Parse(line.Substring(spaceIdx + 1, 3));
                HttpStatusReason = line.Substring(spaceIdx + 4);

                // Reads the headers
                Headers = new Dictionary<string, string>();
                while ((line = reader.ReadLine()) != string.Empty)
                {
                    spaceIdx = line.IndexOf(' ');
                    Console.WriteLine(line);
                    string headerName = line.Substring(0, spaceIdx - 1);
                    string headerValue = line.Substring(spaceIdx + 1);
                    //Console.WriteLine("{0}: {1}", headerName, headerValue);
                    Headers.Add(headerName, headerValue);
                }

                Console.WriteLine ("4");

                // TODO: Why do we need to do this? Something is very strange here!
                response.Position = Headers.Sum (h => h.Key.Length + h.Value.Length + 4) + 2;
                response.Seek("Status: ".Length + HttpStatusCode.ToString().Length + (HttpStatusReason == null ? 0 : HttpStatusReason.Length) + 2, SeekOrigin.Current);
                // Write the response body and rewind the stream
                byte[] buf = new byte[4096];
                int bytesRead;
                while ((bytesRead = response.Read(buf, 0, buf.Length)) > 0)
                {
                    Console.WriteLine("Read {0} bytes", bytesRead);
                    for (int i = 0; i < bytesRead; ++i)
                        Console.Write ((char)buf[i]);
                    ResponseBody.Write(buf, 0, bytesRead);
                }
            }

            ResponseBody.Position = 0;
        }
Example #17
0
        /// <summary>
        /// 设置角色数量,要注意,开始后不能继续加入(Join)
        /// 调用前先通过TheContext获取玩家数量,数组数量总和必须等于玩家数量(警长和情侣游戏中新增的,所以不需要考虑)
        /// 玩家会随机分配角色
        /// </summary>
        /// <param name="roleCounts"></param>
        /// <returns>设定成功与否</returns>
        public bool SetRoleCount(Dictionary<Role, int> roleCounts)
        {
            isGameStarted = true;
            if (TheContext.Players.Count != roleCounts.Sum(kv => kv.Value))
            {
                isGameStarted = false;
                return false;
            }

            //该数组便于随机分派角色
            //随机方法:把所有玩家放数组中,从数组随机取其中一位,删掉取出的那位后继续,直至数组用尽
            var tmpPlayers = new List<Player>(TheContext.Players.Count);
            foreach (var p in TheContext.Players)
                tmpPlayers.Add(p);

            foreach (var rc in roleCounts)
            {
                for (var i = 0; i < rc.Value; i++)
                {
                    var thePlayerIdx = rand.Next(tmpPlayers.Count);
                    var thePlayer = tmpPlayers[thePlayerIdx];
                    tmpPlayers.Remove(thePlayer);
                    thePlayer.theRoles.Add(rc.Key);
                    thePlayer.theStatus = PlayerStatus.Alive;

                    if (!TheContext.DicRolePlayers.ContainsKey(rc.Key))
                    {
                        TheContext.DicRolePlayers[rc.Key] = new List<Player> { thePlayer };
                    }
                    else
                    {
                        var playerList = TheContext.DicRolePlayers[rc.Key];
                        playerList.Add(thePlayer);
                        TheContext.DicRolePlayers[rc.Key] = playerList;
                    }
                }
            }

            Console.WriteLine("角色分配完毕,游戏正式开始。");

            return true;
        }
        public AlgGenetico(Dictionary<string, int> quantidadeAgenciasPorBanco, double latitude, double longitude)
        {
            rand = new Random();
            this.QuantidadeAgenciasPorBanco = quantidadeAgenciasPorBanco;
            this.latitude = latitude;
            this.longitude = longitude;

            quantidadeAgenciasSolicitadas = quantidadeAgenciasPorBanco.Sum(qa => qa.Value);
            agenciasMaisProximas = SelecionarAgenciasMaisProximas(quantidadeAgenciasPorBanco);
            matrizDistancias = new double[quantidadeAgenciasSolicitadas + 1, quantidadeAgenciasSolicitadas + 1];
            //Seta as distancias do individuo à cada uma das agencias
            for (int i = 0; i < quantidadeAgenciasSolicitadas + 1; i++)
            {
                for (int j = 0; j < quantidadeAgenciasSolicitadas + 1; j++)
                {
                    if (i == j)
                        matrizDistancias[i, j] = 0;
                    else if (i == 0 || j == 0)
                        //Distancias entre o individuo e a agencia
                        matrizDistancias[i, j] = agenciasMaisProximas[j + i - 1].Distancia;
                    else
                    {
                        //Distancia entre os bancos
                        double lat1 = agenciasMaisProximas[i - 1].Latitude;
                        double long1 = agenciasMaisProximas[i - 1].Longitude;
                        double lat2 = agenciasMaisProximas[j - 1].Latitude;
                        double long2 = agenciasMaisProximas[j - 1].Longitude;
                        double distanciaBancos = Utils.Distancia.CalcularDistanciaKM(lat1, long1, lat2, long2);
                        matrizDistancias[i, j] = distanciaBancos;
                    }
                }
            }

            caixeirosViajante = new List<CaixeiroViajante>();
            for (int i = 0; i < numeroIndividuos; i++)
            {
                caixeirosViajante.Add(new CaixeiroViajante(matrizDistancias));
            }

            GerarPopulacaoIndividuos();
        }
Example #19
0
		public void Generate(string outFolder, Dictionary<EntryType, IEnumerable<object>> entries) {
			
			var indexDoc = new XDocument(
				new XDeclaration("1.0", "UTF-8", "yes"),
				new XElement(XName.Get("sitemapindex", ns_sitemap)));

			var totalEntries = entries.Sum(e => e.Value.Count());
			var allUrlElements = CreateUrlElements(entries);
			var sitemapCount = Math.Ceiling(totalEntries / (double)maxEntriesPerSitemap);

			for (int sitemapNumber = 1; sitemapNumber <= sitemapCount; ++sitemapNumber) {
				
				var sitemapDoc = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"), 
					new XElement(XName.Get("urlset", ns_sitemap)));

				var begin = (sitemapNumber - 1) * maxEntriesPerSitemap;
				var sitemapElements = allUrlElements.Skip(begin).Take(maxEntriesPerSitemap);

				foreach (var element in sitemapElements) {
					sitemapDoc.Root.Add(element);
				}

				var sitemapFile = string.Format("sitemap-{0}.xml", sitemapNumber);
				var sitemapPath = Path.Combine(outFolder, sitemapFile);
				var sitemapUrl = sitemapRootUrl + sitemapFile;
				sitemapDoc.Save(sitemapPath);

				var sitemapReferenceElement = new XElement(XName.Get("sitemap", ns_sitemap),
					new XElement(XName.Get("loc", ns_sitemap), sitemapUrl)
				);

				indexDoc.Root.Add(sitemapReferenceElement);

			}

			var indexOutPath = Path.Combine(outFolder, "sitemap-index.xml");
			indexDoc.Save(indexOutPath);

		}
Example #20
0
        public void Save(Dictionary<string, List<News>> news)
        {
            decimal min = news.Min(n => n.Value.Min(m => m.RawScore));
            decimal max = news.Max(n => n.Value.Max(m => m.RawScore));

            using (var dbContext = new DistrictsInTownModelContainer())
            {
                foreach (var district in news)
                    AddArticlesToDB(dbContext, district, min, max);

                try
                {
                    dbContext.SaveChanges();
                }
                catch (Exception error)
                {
                    Console.WriteLine(error.StackTrace);
                }

                Console.WriteLine("Total results: {0}", news.Sum(n => n.Value.Count));
            }
        }
Example #21
0
        public static void Initialize(Menu menu, Dictionary<SpellSlot, int[]> manaDictionary)
        {
            menu.Add("ManaBarEnabled", new CheckBox("Draw Mana Indicator"));//, Color.Black);

            Drawing.OnPreReset += DrawingOnOnPreReset;
            Drawing.OnPostReset += DrawingOnOnPostReset;
            AppDomain.CurrentDomain.DomainUnload += CurrentDomainOnDomainUnload;
            AppDomain.CurrentDomain.ProcessExit += CurrentDomainOnDomainUnload;

            Drawing.OnEndScene += eventArgs =>
            {
                if (ObjectManager.Player.IsDead || !menu["ManaBarEnabled"].Cast<CheckBox>().CurrentValue)
                {
                    return;
                }

                var spell = ObjectManager.Player.Spellbook;
                var totalMana = manaDictionary.Sum(kvp => kvp.Value[spell.GetSpell(kvp.Key).Level]);

                DrawManaPercent(
                    totalMana, totalMana > ObjectManager.Player.Mana ? new ColorBGRA(255, 0, 0, 255) : DrawColor);
            };
        }
        public static void Main()
        {
            var couplesFrequency = new Dictionary<string, int>();
            string[] numbers = Console.ReadLine().Split();

            for (int i = 0; i < numbers.Length - 1; i++)
            {
                string currentCouple = numbers[i] + " " + numbers[i + 1];

                if (!couplesFrequency.ContainsKey(currentCouple))
                {
                    couplesFrequency.Add(currentCouple, 0);
                }

                couplesFrequency[currentCouple]++;
            }

            int sum = couplesFrequency.Sum(x => x.Value);
            foreach (var pair in couplesFrequency)
            {
                Console.WriteLine("{0} -> {1:F2}%", pair.Key, (double)pair.Value / sum * 100);
            }
        }
        public static void Initialize(Menu menu, Dictionary<SpellSlot, int[]> manaDictionary)
        {
            _manaBarItem = menu.AddCircle("ManaBarEnabled", "Draw Mana Indicator", Color.Black);
            _manaBarItem.SetTooltip("Draw indicator on mana bar. Red means not enough mana.");

            Drawing.OnPreReset += DrawingOnOnPreReset;
            Drawing.OnPostReset += DrawingOnOnPostReset;
            AppDomain.CurrentDomain.DomainUnload += CurrentDomainOnDomainUnload;
            AppDomain.CurrentDomain.ProcessExit += CurrentDomainOnDomainUnload;

            Drawing.OnEndScene += eventArgs =>
            {
                if (ObjectManager.Player.IsDead || !_manaBarItem.IsActive())
                {
                    return;
                }

                var spell = ObjectManager.Player.Spellbook;
                var totalMana = manaDictionary.Sum(kvp => kvp.Value[spell.GetSpell(kvp.Key).Level]);

                DrawManaPercent(
                    totalMana, totalMana > ObjectManager.Player.Mana ? new ColorBGRA(255, 0, 0, 255) : DrawColor);
            };
        }
Example #24
0
        private static byte[] Handshake(string tag, Dictionary<uint, byte[]> tagValuePairs)
        {
            var bytes = new byte[4 + 2 + 2 + (4+4) * tagValuePairs.Count + tagValuePairs.Sum(p => p.Value.Length)];
            
            // The tag of the message
            var tagBytes = Encoding.UTF8.GetBytes(tag);
            Array.Copy(tagBytes, 0, bytes, 0, 4);

            // A uint16 containing the number of tag - value pairs.
            var pairCountBytes = BitConverter.GetBytes(Convert.ToUInt16(tagValuePairs));
            Array.Copy(pairCountBytes, 0, bytes, 4, 2);

            // Two bytes of padding which should be zero when sent but ignored when received.
            var next = 8;

            uint endOffset = 8;
            foreach (var tvp in tagValuePairs)
            {
                tagBytes = BitConverter.GetBytes(tvp.Key);
                Array.Copy(tagBytes, 0, bytes, next, 4);
                next += 4;

                endOffset += (uint)tvp.Value.Length;
                var endOffsetBytes = BitConverter.GetBytes(endOffset);
                Array.Copy(endOffsetBytes, 0, bytes, next, 4);
                next += 4;
            }

            foreach (var tvp in tagValuePairs)
            {
                Array.Copy(tvp.Value, 0, bytes, next, tvp.Value.Length);
                next += tvp.Value.Length;
            }

            return bytes;
        }
Example #25
0
        public static double CalulatePrjSim(double[] source, double[] compare)
        {
            var frequencies = new Dictionary<double, int>();

              for (var i = 0; i < source.Length; i++)
              {
            var difference = source[i] - compare[i];

            difference = Math.Round(difference, 2);
            difference = Math.Abs(difference);

            if (frequencies.ContainsKey(difference))
              frequencies[difference] = frequencies[difference] + 1;
            else
              frequencies.Add(difference, 1);
              }

              var deviation = frequencies.Sum(value => (value.Key * value.Value));

              deviation /= source.Length;
              deviation = (0.5 - deviation) * 2;

              return deviation;
        }
Example #26
0
        public static void Drawing_OnEndScene(EventArgs args)
        {
            _combodamage = new Dictionary<DamageToUnitDelegate, Color>
            {
                {getComboDamage, Color.DarkRed},
            };

            if (ObjectManager.Player.IsDead && Program.Config.DrawDamageBarIndicator) return;
            foreach (
                var enemy in EntityManager.Heroes.Enemies.Where(enemy => enemy.IsValidTarget(2200) && enemy.IsHPBarRendered)
                )
            {
                var damage = _combodamage.Sum(v => v.Key(enemy));
                if (damage <= 0)
                {
                    continue;
                }

                foreach (var spell in _combodamage)
                {
                    var damagePercentage = ((enemy.Health - damage) > 0 ? (enemy.Health - damage) : 0) /
                                           (enemy.MaxHealth + enemy.AllShield + enemy.AttackShield + enemy.MagicShield);
                    var healthPercentage = enemy.Health /
                                           (enemy.MaxHealth + enemy.AllShield + enemy.AttackShield + enemy.MagicShield);
                    var startPoint = new Vector2(
                        (int)(enemy.HPBarPosition.X + BarOffset.X + damagePercentage * BarWidth),
                        (int)(enemy.HPBarPosition.Y + BarOffset.Y) - 5);
                    var endPoint =
                        new Vector2((int)(enemy.HPBarPosition.X + BarOffset.X + healthPercentage * BarWidth) + 1,
                            (int)(enemy.HPBarPosition.Y + BarOffset.Y) - 5);
                    Drawing.DrawLine(startPoint, endPoint, LineThickness, spell.Value);

                    damage -= spell.Key(enemy);
                }
            }
        }
        public Dictionary<int, int> GetParts(Dictionary<int, int> results)
        {
            Dictionary<int, int> newResults = new Dictionary<int, int>();

            int allAnswers = results.Sum(r => r.Value);
            int sumParts = 0;

            foreach (var result in results)
            {
                double part = allAnswers != 0 ? (double)result.Value / (double)allAnswers : 0;
                int percents = int.Parse(Math.Round(part * 100, 0).ToString());
                newResults.Add(result.Key, percents);
                sumParts += percents;
            }

            if (sumParts != 100 && sumParts != 0)
            {
                var correlation = 100-sumParts;
                var maxPart = newResults.FirstOrDefault(d=>d.Value.Equals(newResults.Max(t=>t.Value)));
                newResults[maxPart.Key] = maxPart.Value + correlation;
            }

            return newResults;
        }
Example #28
0
        public int GetSumOfAmicablePairsUnder(int n)
        {
            var amicableNumbers = new Dictionary<int, int>();

            for(int i = 1; i < n; i++)
            {

                if(amicableNumbers.ContainsKey(i))
                    continue;

                int sum1 = divisorSumCalculator.GetSumOfDivisors(i);

                if (sum1 <= 1 || i == sum1)
                    continue;

                if(IsAmicablePair(i, sum1))
                {
                    if(!amicableNumbers.ContainsKey(i))
                        amicableNumbers.Add(i, sum1);
                }
            }

            return amicableNumbers.Sum(i => i.Value);
        }
Example #29
0
		private void BackgroundSqlReplication()
		{
			int workCounter = 0;
			while (Database.WorkContext.DoWork)
			{
				var config = GetConfiguredReplicationDestinations();
				if (config.Count == 0)
				{
					Database.WorkContext.WaitForWork(TimeSpan.FromMinutes(10), ref workCounter, "Sql Replication");
					continue;
				}
				var localReplicationStatus = GetReplicationStatus();
				var leastReplicatedEtag = GetLeastReplicatedEtag(config, localReplicationStatus);

				if (leastReplicatedEtag == null)
				{
					Database.WorkContext.WaitForWork(TimeSpan.FromMinutes(10), ref workCounter, "Sql Replication");
					continue;
				}

				var relevantConfigs = config.Where(x =>
				{
					if (x.Disabled)
						return false;
					var sqlReplicationStatistics = statistics.GetOrDefault(x.Name);
					if (sqlReplicationStatistics == null)
						return true;
					return SystemTime.UtcNow >= sqlReplicationStatistics.LastErrorTime;
				}) // have error or the timeout expired
						.ToList();

				if (relevantConfigs.Count == 0)
				{
					Database.WorkContext.WaitForWork(TimeSpan.FromMinutes(10), ref workCounter, "Sql Replication");
					continue;
				}

				var documents = prefetchingBehavior.GetDocumentsBatchFrom(leastReplicatedEtag.Value);

				documents.RemoveAll(x => x.Key.StartsWith("Raven/", StringComparison.InvariantCultureIgnoreCase)); // we ignore system documents here

				var deletedDocsByConfig = new Dictionary<SqlReplicationConfig, List<ListItem>>();
				Guid? latestEtag = null;
				if (documents.Count != 0)
					latestEtag = documents[documents.Count - 1].Etag;

				foreach (var relevantConfig in relevantConfigs)
				{
					var cfg = relevantConfig;
					Database.TransactionalStorage.Batch(accessor =>
					{
						deletedDocsByConfig[cfg] = accessor.Lists.Read(GetSqlReplicationDeletionName(cfg),
														  GetLastEtagFor(localReplicationStatus, cfg), 
														  latestEtag, 
														  1024)
											  .ToList();
					});
				}

				// No documents AND there aren't any deletes to replicate
				if (documents.Count == 0 && deletedDocsByConfig.Sum(x => x.Value.Count) == 0)  
				{
					Database.WorkContext.WaitForWork(TimeSpan.FromMinutes(10), ref workCounter, "Sql Replication");
					continue;
				}

				var successes = new ConcurrentQueue<SqlReplicationConfig>();
				try
				{
					BackgroundTaskExecuter.Instance.ExecuteAllInterleaved(Database.WorkContext, relevantConfigs, replicationConfig =>
					{
						try
						{
							var lastReplicatedEtag = GetLastEtagFor(localReplicationStatus, replicationConfig);

							var deletedDocs = deletedDocsByConfig[replicationConfig];
							var docsToReplicate = documents
								.Where(x => ByteArrayComparer.Instance.Compare(lastReplicatedEtag, x.Etag) <= 0) // haven't replicate the etag yet
								.ToList();

							latestEtag = HandleDeletesAndChangesMerging(deletedDocs, docsToReplicate);

							if (ReplicateDeletionsToDestination(replicationConfig, deletedDocs) &&
								ReplicateChangesToDesintation(replicationConfig, docsToReplicate))
							{
								if (deletedDocs.Count > 0)
								{
									Database.TransactionalStorage.Batch(accessor =>
										accessor.Lists.RemoveAllBefore(GetSqlReplicationDeletionName(replicationConfig), deletedDocs[deletedDocs.Count - 1].Etag));
								}
								successes.Enqueue(replicationConfig);
							}
						}
						catch (Exception e)
						{
							log.WarnException("Error while replication to SQL destination: " + replicationConfig.Name, e);
							Database.AddAlert(new Alert
							{
								AlertLevel = AlertLevel.Error,
								CreatedAt = SystemTime.UtcNow,
								Exception = e.ToString(),
								Title = "Sql Replication failure to replication",
								Message = "Sql Replication could not replicate to " + replicationConfig.Name,
								UniqueKey = "Sql Replication could not replicate to " + replicationConfig.Name
							});
						}
					});
					if (successes.Count == 0)
						continue;
					foreach (var cfg in successes)
					{
						var destEtag = localReplicationStatus.LastReplicatedEtags.FirstOrDefault(x => string.Equals(x.Name, cfg.Name, StringComparison.InvariantCultureIgnoreCase));
						if (destEtag == null)
						{
							localReplicationStatus.LastReplicatedEtags.Add(new LastReplicatedEtag
							{
								Name = cfg.Name,
								LastDocEtag = latestEtag ?? Guid.Empty
							});
						}
						else
						{
							destEtag.LastDocEtag = latestEtag ?? destEtag.LastDocEtag;
						}
					}

					var obj = RavenJObject.FromObject(localReplicationStatus);
					Database.Put(RavenSqlreplicationStatus, null, obj, new RavenJObject(), null);
				}
				finally
				{
					AfterReplicationCompleted(successes.Count);
				}
			}
		}
 public static void ReportMethods(Dictionary<MatchMethods, int> methods)
 {
     var total = methods.Sum(i => i.Value);
     foreach(var method in methods)
     {
         Console.WriteLine("Method '{0}' used '{1:P2}'",
             method.Key,
             (double)method.Value / (double)total);
     }
 }