Пример #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;
        }
 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);
 }
Пример #3
0
        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;
        }
Пример #4
0
        /// <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;
        }
    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);
        }
    }
Пример #6
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);
        }
Пример #7
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);
        }
Пример #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);
			}
		}
Пример #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;
        }
Пример #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;
        }
Пример #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!");
            }
        }
Пример #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);
        }
Пример #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));
        }
Пример #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;
        }
Пример #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;
        }
Пример #18
0
        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();
        }
Пример #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);

		}
Пример #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));
            }
        }
Пример #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);
            }
        }
Пример #23
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;
        }
Пример #24
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);
        }
Пример #25
0
        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);
            };
        }
Пример #26
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;
        }
Пример #27
0
        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;
        }
Пример #28
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);
                }
            }
        }
Пример #29
0
        public VisitorStatistics(IEnumerable <VisitorStat> stats, DateTime date_start, DateTime date_end)
        {
            pageViews     = stats.Sum(x => x.pageViews);
            visitorsTotal = stats.Sum(x => x.visitCount);
            if (pageViews > 0 && visitorsTotal > 0)
            {
                pagesPerVisit  = Decimal.Round((decimal)pageViews / visitorsTotal, 1);
                visitorsPerDay = visitorsTotal / ((date_end - date_start).Days);

                var timespent = new TimeSpan(0, 0, (int)Math.Round(stats.Sum(x => x.timeOnSite) / visitorsTotal));
                if (timespent.Minutes < 1)
                {
                    averageTimeSpent = string.Format("<strong>{0}</strong> seconds", timespent.Seconds);
                }
                else
                {
                    averageTimeSpent = string.Format("<strong>{0}</strong> minutes <strong>{1}</strong> seconds",
                                                     timespent.Minutes, timespent.Seconds);
                }
            }
            else
            {
                averageTimeSpent = "NO DATA";
            }

            var referrer  = new Dictionary <string, int>();
            var keywords  = new Dictionary <string, int>();
            var countries = new Dictionary <string, int>();

            visitGraphData = new Dictionary <DateTime, int>();
            foreach (var stat in stats)
            {
                var visits = stat.visitCount;

                // graph
                int visitCount;
                if (!visitGraphData.TryGetValue(stat.visitDate, out visitCount))
                {
                    visitGraphData.Add(stat.visitDate, visits);
                }
                else
                {
                    visitGraphData[stat.visitDate] = visits + visitCount;
                }

                // traffic
                if (stat.referrerHostname.IndexOf("direct") != -1)
                {
                    directTraffic += visits;
                }
                else if (stat.referrerHostname.IndexOf("google") != -1)
                {
                    googleTraffic += visits;
                }
                else
                {
                    referrerTraffic += visits;
                }

                // referrer
                if (stat.referrerPath.IndexOf("not set") == -1)
                {
                    var refererPath = string.Format("<a target='_blank' href='http://{0}{1}'>{0}{1}</a>", stat.referrerHostname, stat.referrerPath);
                    int referrerCount;
                    if (!referrer.TryGetValue(refererPath, out referrerCount))
                    {
                        referrer.Add(refererPath, visits);
                    }
                    else
                    {
                        referrer[refererPath] = referrerCount + visits;
                    }
                }

                // countries
                int countryCount;
                if (!countries.TryGetValue(stat.country, out countryCount))
                {
                    countries.Add(stat.country, visits);
                }
                else
                {
                    countries[stat.country] = countryCount + visits;
                }

                // keyword
                if (stat.keyword.IndexOf("not set") == -1)
                {
                    int keywordCount;
                    if (!keywords.TryGetValue(stat.keyword, out keywordCount))
                    {
                        keywords.Add(stat.keyword, visits);
                    }
                    else
                    {
                        keywords[stat.keyword] = keywordCount + visits;
                    }
                }
            }

            // process graph data
            var sb_graph       = new StringBuilder();
            var sb_graph_ticks = new StringBuilder();

            sb_graph_ticks.Append("[");
            sb_graph.Append("[");
            date_start = new DateTime(date_start.Year, date_start.Month, date_start.Day);
            for (int i = 0; i < (date_end - date_start).Days; i++)
            {
                var date = date_start.AddDays(i);
                int visits;
                if (!visitGraphData.TryGetValue(date, out visits))
                {
                    visits = 0;
                }
                if (i != 0)
                {
                    sb_graph_ticks.Append(",");
                    sb_graph.Append(",");
                }
                sb_graph_ticks.AppendFormat("\"{0}\"", date.ToString("ddd dd MMM"));
                sb_graph.AppendFormat("[{0}, {1}]", i, visits);
            }
            sb_graph_ticks.Append("]");
            sb_graph.Append("]");
            graphdata      = sb_graph.ToString();
            graphticksdata = sb_graph_ticks.ToString();

            // process referrers
            var sb_referrer = new StringBuilder();

            sb_referrer.Append("<table>");
            foreach (var entry in referrer.OrderByDescending(x => x.Value).Take(REFERRERCOUNT))
            {
                sb_referrer.AppendFormat("<tr><td>{0}</td><td>{1}</td></tr>", entry.Value, entry.Key);
            }
            sb_referrer.Append("</table>");
            referrerStats = sb_referrer.ToString();

            // process trafficOverview
            var sb_traffic   = new StringBuilder();
            var trafficTotal = directTraffic + referrerTraffic + googleTraffic;

            sb_traffic.Append("<table>");
            sb_traffic.AppendFormat("<tr><td>{0}%</td><td>Direct</td></tr>", directTraffic == 0? 0: Math.Round(directTraffic * 100.0 / trafficTotal, 2));
            sb_traffic.AppendFormat("<tr><td>{0}%</td><td>Referring Sites</td></tr>", referrerTraffic == 0 ? 0: Math.Round(referrerTraffic * 100.0 / trafficTotal, 2));
            sb_traffic.AppendFormat("<tr><td>{0}%</td><td>Google</td></tr>", googleTraffic == 0 ? 0: Math.Round(googleTraffic * 100.0 / trafficTotal, 2));
            sb_traffic.Append("</table>");
            trafficOverviewStats = sb_traffic.ToString();

            var count = 0;
            // procces countries
            var sb_countries   = new StringBuilder();
            var countriesTotal = countries.Sum(x => x.Value);

            sb_countries.Append("<table>");
            foreach (var entry in countries.OrderByDescending(x => x.Value))
            {
                sb_countries.AppendFormat("<tr><td>{0}%</td><td>{1}</td></tr>", Math.Round(entry.Value * 100.0 / countriesTotal, 2), entry.Key);
                if (count++ == 5)
                {
                    break;
                }
            }
            sb_countries.Append("</table>");
            countriesStats = sb_countries.ToString();

            // process keyword
            var sb_keyword = new StringBuilder();

            sb_keyword.Append("<table>");
            count = 0;
            foreach (var entry in keywords.OrderByDescending(x => x.Value))
            {
                sb_keyword.AppendFormat("<tr><td>{0}</td><td>{1}</td></tr>", entry.Value, entry.Key);
                if (count++ == 5)
                {
                    break;
                }
            }
            sb_keyword.Append("</table>");
            searchKeywordStats = sb_keyword.ToString();
        }
Пример #30
0
        static void Main(string[] args)
        {
            ulong thirtySixBitMask = 68719476735;
            ulong currentMask      = 0x00; //1100
            ulong activeMask       = 0x00; //0110 parts of the current mask to apply

            ulong[] ram = new ulong[100000];
            using (StreamReader sr = new StreamReader("puzzleinput.txt"))
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    if (line.StartsWith("mask = "))
                    {
                        foreach (var c in line.Substring("mask = ".Length))
                        {
                            activeMask = activeMask << 1;
                            if (c != 'X')    //C# wont let me |= for some reason
                            {
                                activeMask |= 1;
                            }
                            activeMask  = activeMask & thirtySixBitMask; // trim
                            currentMask = currentMask << 1;
                            if (c == '1')
                            {
                                currentMask |= 1;
                            }
                            currentMask = currentMask & thirtySixBitMask; // trim
                        }
                    }
                    else if (line.StartsWith("mem["))
                    {
                        var   eb          = line.IndexOf("]");
                        int   memoryIndex = int.Parse(line.Substring(4, eb - 4));
                        ulong value       = ulong.Parse(line.Substring(eb + 4));

                        //Postive combine - every 1 and applied gets forced to 1
                        var postiveMask = currentMask & activeMask;
                        value |= postiveMask;

                        //Negative override - everything 0 and active gets forced to 0
                        var negativeMask = ~((~currentMask) & activeMask);
                        value           &= negativeMask;
                        ram[memoryIndex] = value;
                    }
                }
            }
            ulong total = 0;

            foreach (var l in ram)   //Linq Sum does not work with ulong :(
            {
                total += l;
            }

            Console.WriteLine($"Part 1: {total}");

            currentMask = 0x00;
            ulong floatingMask = 0x00;

            Dictionary <string, long> ramP2 = new Dictionary <string, long>();

            using (StreamReader sr = new StreamReader("puzzleinput.txt"))
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    if (line.StartsWith("mask = "))
                    {
                        foreach (var c in line.Substring("mask = ".Length))
                        {
                            floatingMask = floatingMask << 1;
                            if (c == 'X')
                            {
                                floatingMask |= 1;
                            }
                            floatingMask = floatingMask & thirtySixBitMask; // trim to 36bits
                            currentMask  = currentMask << 1;
                            if (c == '1')
                            {
                                currentMask |= 1;
                            }
                            currentMask = currentMask & thirtySixBitMask; // trim to 36bits
                        }
                    }
                    else if (line.StartsWith("mem["))
                    {
                        var   eb          = line.IndexOf("]");
                        ulong memoryIndex = ulong.Parse(line.Substring(4, eb - 4));
                        long  value       = long.Parse(line.Substring(eb + 4));

                        memoryIndex = memoryIndex | currentMask;
                        foreach (ulong memoryAddress in StartFindPermutations(memoryIndex, floatingMask))
                        {
                            var dictionaryKey = Convert.ToString((long)memoryAddress, 2);
                            ramP2[dictionaryKey] = value;
                        }
                    }
                }
            }
            Console.WriteLine($"Part 2: {ramP2.Sum(t => t.Value)}");
        }
Пример #31
0
        // Déroulement de la compétition
        public Dictionary <IBattleshipOpponent, int> RunCompetition()
        {
            var rand = new Random();

            var opponents = new Dictionary <int, IBattleshipOpponent> (); // Joueurs
            var scores    = new Dictionary <int, int> ();                 // Scores des joueurs : Nb de parties gagnées
            var times     = new Dictionary <int, Stopwatch> ();           // Temps pris par chaque joueur sur une partie
            var ships     = new Dictionary <int, List <Ship> > ();        // bateaux des joueurs
            var shots     = new Dictionary <int, List <Point> > ();       // Mémoire des coups tirés par les joueurs

            var first  = 0;                                               // Le joueur 1 est celui d'indice 0 dans opponents
            var second = 1;                                               // Le joueur 2 est celui d'indice 1 dans opponents

            // Initialisation des variables
            opponents [first]  = this.op1;
            opponents [second] = this.op2;
            scores [first]     = 0;
            scores [second]    = 0;
            times [first]      = new Stopwatch();
            times [second]     = new Stopwatch();
            shots [first]      = new List <Point> ();
            shots [second]     = new List <Point> ();

            // Choix aléatoire du joueur qui commence : 1 chance sur 2 d'inverser l'ordre
            if (rand.NextDouble() >= 0.5)               // rand.NextDouble() génère un nombre aléatoire entre 0 et 1
            {
                var swap = first;
                first  = second;
                second = swap;
            }

            // Nouveau match pour chacun des joueurs
            opponents [first].NewMatch(opponents [second].Name + " " + opponents [second].Version.ToString());
            opponents [second].NewMatch(opponents [first].Name + " " + opponents [first].Version.ToString());

            bool success;

            // Déroulement de la compétition
            while (true)
            {
                /* Condition d'arrêt de la compétition
                 * Si playout = false : on s'arrête lorsqu'un joueur a gagné "wins" parties
                 * Si playout = true : on joue toutes les parties soit (wins * 2 - 1) parties.
                 */
                if ((!this.playOut && scores.Where(p => p.Value >= this.wins).Any()) || (this.playOut && scores.Sum(s => s.Value) >= (this.wins * 2 - 1)))
                {
                    break;
                }

                // À chaque nouvelle partie on change le joueur qui commence
                {
                    var swap = first;
                    first  = second;
                    second = swap;
                }

                // Réinitialisation des temps et des tirs enregistrés
                times [first].Reset();
                times [second].Reset();
                shots [first].Clear();
                shots [second].Clear();

                // Nouvelle partie pour chacun des joueurs
                times [first].Start();                          // Départ compteur de temps
                opponents [first].NewGame(this.boardSize, this.timePerGame);
                times [first].Stop();                           // Arrêt compteur de temps
                if (times [first].Elapsed > this.timePerGame)   // Si temps dépassé, le joueur a perdu la partie
                {
                    RecordWin(second, first, scores, opponents);
                    continue;
                }

                times [second].Start();
                opponents [second].NewGame(this.boardSize, this.timePerGame);
                times [second].Stop();
                if (times [second].Elapsed > this.timePerGame)
                {
                    RecordWin(first, second, scores, opponents);
                    continue;
                }

                // Placement des bateaux pour le 1er joueur
                success = false;
                do
                {
                    // Création de la liste des bateaux du premier joueur à partir des tailles "shipSizes"
                    ships [first] = (from s in this.shipSizes
                                     select new Ship(s)).ToList();

                    times [first].Start();
                    // Placement des bateaux avec la méthode propre au joueur
                    opponents [first].PlaceShips(ships [first].AsReadOnly());
                    times [first].Stop();
                    if (times [first].Elapsed > this.timePerGame)
                    {
                        break;
                    }

                    // Vérifications du placement (déjà vérifié dans défense pour Dreadnought, nécessaire pour Random)
                    bool allPlacedValidly = true;
                    for (int i = 0; i < ships[first].Count; i++)
                    {
                        if (!ships [first] [i].IsPlaced || !ships [first] [i].IsValid(this.boardSize))
                        {
                            allPlacedValidly = false;
                            break;
                        }
                    }

                    if (!allPlacedValidly)                              // Si invalide : on recommence
                    {
                        continue;
                    }

                    bool noneConflict = true;
                    for (int i = 0; i < ships[first].Count; i++)
                    {
                        for (int j = i + 1; j < ships[first].Count; j++)
                        {
                            if (ships [first] [i].ConflictsWith(ships [first] [j]))
                            {
                                noneConflict = false;
                                break;
                            }
                        }

                        if (!noneConflict)
                        {
                            break;
                        }
                    }

                    if (!noneConflict)                          // Si comflit : on recommence
                    {
                        continue;
                    }
                    else
                    {
                        success = true;                                 // Placement correct, on peut sortir de la boucle
                    }
                } while (!success);

                if (times [first].Elapsed > this.timePerGame)
                {
                    RecordWin(second, first, scores, opponents);
                    continue;
                }

                // Placement des bateaux pour le 2ème joueur : même méthode
                success = false;
                do
                {
                    ships [second] = (from s in this.shipSizes
                                      select new Ship(s)).ToList();

                    times [second].Start();
                    opponents [second].PlaceShips(ships [second].AsReadOnly());
                    times [second].Stop();
                    if (times [second].Elapsed > this.timePerGame)
                    {
                        break;
                    }

                    bool allPlacedValidly = true;
                    for (int i = 0; i < ships[second].Count; i++)
                    {
                        if (!ships [second] [i].IsPlaced || !ships [second] [i].IsValid(this.boardSize))
                        {
                            allPlacedValidly = false;
                            break;
                        }
                    }

                    if (!allPlacedValidly)
                    {
                        continue;
                    }

                    bool noneConflict = true;
                    for (int i = 0; i < ships[second].Count; i++)
                    {
                        for (int j = i + 1; j < ships[second].Count; j++)
                        {
                            if (ships [second] [i].ConflictsWith(ships [second] [j]))
                            {
                                noneConflict = false;
                                break;
                            }
                        }

                        if (!noneConflict)
                        {
                            break;
                        }
                    }

                    if (!noneConflict)
                    {
                        continue;
                    }
                    else
                    {
                        success = true;
                    }
                } while (!success);

                if (times [second].Elapsed > this.timePerGame)
                {
                    RecordWin(first, second, scores, opponents);
                    continue;
                }

                // Déroulement de la partie
                var current = first;
                while (true)
                {
                    times [current].Start();
                    Point shot = opponents [current].GetShot();                         // Récupération d'un point de tir par la méthode du joueur
                    times [current].Stop();
                    if (times [current].Elapsed > this.timePerGame)
                    {
                        RecordWin(1 - current, current, scores, opponents);
                        break;
                    }

                    // Si le joueur a déjà tiré sur ce point, on recommence (utile pour joueur Random)
                    if (shots [current].Where(s => s.X == shot.X && s.Y == shot.Y).Any())
                    {
                        continue;
                    }

                    // Mémorisation du point de tir
                    shots [current].Add(shot);

                    times [1 - current].Start();
                    opponents [1 - current].OpponentShot(shot);                         // On effectue le tir sur l'adversaire [1-current]
                    times [1 - current].Stop();
                    if (times [1 - current].Elapsed > this.timePerGame)
                    {
                        RecordWin(current, 1 - current, scores, opponents);
                        break;
                    }

                    // Variable indiquant s'il y a un bateau au point de tir sur la grille adverse
                    var ship = (from s in ships [1 - current]
                                where s.IsAt(shot)
                                select s).SingleOrDefault();

                    // S'il y a un bateau...
                    if (ship != null)
                    {
                        var sunk = ship.IsSunk(shots [current]);                          // Indique si le bateau est coulé

                        times [current].Start();
                        opponents [current].ShotHit(shot, sunk);                                // Notifie le joueur qu'il a touché un bateau en ce point
                        times [current].Stop();
                        if (times [current].Elapsed > this.timePerGame)
                        {
                            RecordWin(1 - current, current, scores, opponents);
                            break;
                        }
                    }

                    // Si pas de bateau
                    else
                    {
                        times [current].Start();
                        opponents [current].ShotMiss(shot);                             // Notifie le joueur que son tir est manqué
                        times [current].Stop();
                        if (times [current].Elapsed > this.timePerGame)
                        {
                            RecordWin(1 - current, current, scores, opponents);
                            break;
                        }
                    }

                    // Indique s'il reste des bateaux non coulés
                    var unsunk = (from s in ships [1 - current]
                                  where !s.IsSunk(shots [current])
                                  select s);

                    // Si tous les bateaux sont coulés, le joueur courant a gagné, fin de la partie
                    if (!unsunk.Any())
                    {
                        RecordWin(current, 1 - current, scores, opponents);
                        break;
                    }

                    current = 1 - current; // On change de joueur courant pour le tour suivant
                }                          // fin de la boucle de la partie
            }                              // fin de la boucle de la compétition

            // On notifie les joueur de la fin du match
            opponents [first].MatchOver();
            opponents [second].MatchOver();

            // On retourne les scores des joueurs
            return(scores.Keys.ToDictionary(s => opponents [s], s => scores [s]));
        }
Пример #32
0
        public async Task GiveReputationAsync(EventContext e)
        {
            using (var context = new MikiContext())
            {
                User giver = await context.Users.FindAsync(e.Author.Id.ToDbLong());

                var repObject = await Global.RedisClient.GetAsync <ReputationObject>($"user:{giver.Id}:rep");

                if (repObject == null)
                {
                    repObject = new ReputationObject()
                    {
                        LastReputationGiven  = DateTime.Now,
                        ReputationPointsLeft = 3
                    };

                    await Global.RedisClient.UpsertAsync(
                        $"user:{giver.Id}:rep",
                        repObject,
                        DateTime.UtcNow.AddDays(1).Date - DateTime.UtcNow
                        );
                }

                ArgObject arg = e.Arguments.FirstOrDefault();

                if (arg == null)
                {
                    TimeSpan pointReset = (DateTime.Now.AddDays(1).Date - DateTime.Now);

                    new EmbedBuilder()
                    {
                        Title       = (e.Locale.GetString("miki_module_accounts_rep_header")),
                        Description = (e.Locale.GetString("miki_module_accounts_rep_description"))
                    }.AddInlineField(e.Locale.GetString("miki_module_accounts_rep_total_received"), giver.Reputation.ToString())
                    .AddInlineField(e.Locale.GetString("miki_module_accounts_rep_reset"), pointReset.ToTimeString(e.Locale).ToString())
                    .AddInlineField(e.Locale.GetString("miki_module_accounts_rep_remaining"), repObject.ReputationPointsLeft.ToString())
                    .ToEmbed().QueueToChannel(e.Channel);
                    return;
                }
                else
                {
                    Dictionary <IDiscordUser, short> usersMentioned = new Dictionary <IDiscordUser, short>();

                    EmbedBuilder embed = new EmbedBuilder();

                    int  totalAmountGiven = 0;
                    bool mentionedSelf    = false;

                    while (true || totalAmountGiven <= repObject.ReputationPointsLeft)
                    {
                        if (arg == null)
                        {
                            break;
                        }

                        IDiscordUser u = await arg.GetUserAsync(e.Guild);

                        short amount = 1;

                        if (u == null)
                        {
                            break;
                        }

                        arg = arg?.Next();

                        if ((arg?.AsInt() ?? -1) != -1)
                        {
                            amount = (short)arg.AsInt().Value;
                            arg    = arg.Next();
                        }
                        else if (Utils.IsAll(arg))
                        {
                            amount = repObject.ReputationPointsLeft;
                            arg    = arg.Next();
                        }

                        if (u.Id == e.Author.Id)
                        {
                            mentionedSelf = true;
                            continue;
                        }

                        totalAmountGiven += amount;

                        if (usersMentioned.Keys.Where(x => x.Id == u.Id).Count() > 0)
                        {
                            usersMentioned[usersMentioned.Keys.Where(x => x.Id == u.Id).First()] += amount;
                        }
                        else
                        {
                            usersMentioned.Add(u, amount);
                        }
                    }

                    if (mentionedSelf)
                    {
                        embed.Footer = new EmbedFooter()
                        {
                            Text = e.Locale.GetString("warning_mention_self"),
                        };
                    }

                    if (usersMentioned.Count == 0)
                    {
                        return;
                    }
                    else
                    {
                        if (totalAmountGiven <= 0)
                        {
                            e.ErrorEmbedResource("miki_module_accounts_rep_error_zero")
                            .ToEmbed().QueueToChannel(e.Channel);
                            return;
                        }

                        if (usersMentioned.Sum(x => x.Value) > repObject.ReputationPointsLeft)
                        {
                            e.ErrorEmbedResource("error_rep_limit", usersMentioned.Count, usersMentioned.Sum(x => x.Value), repObject.ReputationPointsLeft)
                            .ToEmbed().QueueToChannel(e.Channel);
                            return;
                        }
                    }

                    embed.Title       = (e.Locale.GetString("miki_module_accounts_rep_header"));
                    embed.Description = (e.Locale.GetString("rep_success"));

                    foreach (var user in usersMentioned)
                    {
                        User receiver = await User.GetAsync(context, user.Key);

                        receiver.Reputation += user.Value;

                        embed.AddInlineField(
                            receiver.Name,
                            string.Format("{0} => {1} (+{2})", receiver.Reputation - user.Value, receiver.Reputation, user.Value)
                            );
                    }

                    repObject.ReputationPointsLeft -= (short)usersMentioned.Sum(x => x.Value);

                    await Global.RedisClient.UpsertAsync(
                        $"user:{giver.Id}:rep",
                        repObject,
                        DateTime.UtcNow.AddDays(1).Date - DateTime.UtcNow
                        );

                    embed.AddInlineField(e.Locale.GetString("miki_module_accounts_rep_points_left"), repObject.ReputationPointsLeft.ToString())
                    .ToEmbed().QueueToChannel(e.Channel);

                    await context.SaveChangesAsync();
                }
            }
        }
Пример #33
0
        static void Main(string[] args)
        {
            var input = Console.ReadLine().Split("; ").ToArray();

            var groups     = new Dictionary <string, List <string> >();
            var groupsTime = new Dictionary <string, int>();

            while (input[0] != "start of concert")
            {
                string bandName = input[1];

                if (input[0] == "Add")
                {
                    var member = input[2].Split(", ").ToList();

                    if (!groups.ContainsKey(bandName))
                    {
                        groups.Add(bandName, new List <string>());
                    }
                    for (int i = 0; i < member.Count; i++)
                    {
                        if (!groups[bandName].Contains(member[i]))
                        {
                            groups[bandName].Add(member[i]);
                        }
                    }
                }
                else if (input[0] == "Play")
                {
                    int time = int.Parse(input[2]);

                    if (!groupsTime.ContainsKey(bandName))
                    {
                        groupsTime.Add(bandName, time);
                    }
                    else
                    {
                        groupsTime[bandName] += time;
                    }
                }

                input = Console.ReadLine().Split("; ").ToArray();
            }
            string group = Console.ReadLine();

            Console.WriteLine($"Total time: {groupsTime.Sum(x => x.Value)}");

            foreach (var kvp in groupsTime.OrderByDescending(x => x.Value).ThenBy(x => x.Key))
            {
                Console.WriteLine($"{kvp.Key} -> {kvp.Value}");
            }
            foreach (var kvp in groups)
            {
                if (kvp.Key == group)
                {
                    Console.WriteLine(group);
                    var listOfMembers = kvp.Value;
                    foreach (var member in listOfMembers)
                    {
                        Console.WriteLine($"=> {member}");
                    }
                    break;
                }
            }
        }
Пример #34
0
        internal void ReleaseAllResources()
        {
            Logger.Log("resource pool", "release all resources...");

            int count =
                cachedPens.Count +

#if WINFORM
                hatchBrushes.Count + fonts.Values.Sum(f => f.Count) +
#endif
                /*images.Count +*/ cachedBrushes.Count
#if WPF
                + typefaces.Sum(t => t.Value.Count)
#endif
            ;

            // pens
            foreach (var plist in cachedPens.Values)
            {
#if WINFORM
                foreach (var p in plist)
                {
                    p.Dispose();
                }
#endif // WINFORM
                plist.Clear();
            }

            cachedPens.Clear();

#if WINFORM
            // fonts
            foreach (var fl in fonts.Values)
            {
                foreach (var f in fl)
                {
                    f.FontFamily.Dispose();
                    f.Dispose();
                }
                fl.Clear();
            }

            fonts.Clear();

            foreach (var hb in this.hatchBrushes.Values)
            {
                hb.Dispose();
            }

            hatchBrushes.Clear();

            foreach (var sb in this.cachedBrushes.Values)
            {
                sb.Dispose();
            }
#elif WPF
            foreach (var list in typefaces)
            {
                list.Value.Clear();
            }
#endif // WPF

            cachedBrushes.Clear();

#if WINFORM
            //if (cachedGDIGraphics != null) cachedGDIGraphics.Dispose();
            //if (bitmapForCachedGDIGraphics != null) bitmapForCachedGDIGraphics.Dispose();
#endif // WINFORM

            Logger.Log("resource pool", count + " objects released.");
        }
Пример #35
0
        public void Part2(string input, int?expected)
        {
            input ??= realData;
            var result = 0;

            var(tree, weights) = GetTreeAndWeights(input);

            var treebase = "";

            foreach (var treeItem in tree)
            {
                if (!tree.Any(x => x.Value.Contains(treeItem.Key)))
                {
                    treebase = treeItem.Key;
                    break;
                }
            }

            var invalidLeaves = new Dictionary <string, int>();

            int SumAllLeaves(string leaf)
            {
                var childSums = new Dictionary <string, int>();

                if (tree.ContainsKey(leaf))
                {
                    foreach (var subLeaf in tree[leaf])
                    {
                        childSums.Add(subLeaf, SumAllLeaves(subLeaf));
                    }

                    var childGroups = childSums.GroupBy(x => x.Value);
                    if (childGroups.Count() > 1)
                    {
                        var invalidLeaf  = "";
                        var invaildtotal = 0;
                        var validtotal   = 0;
                        foreach (var childGroup in childGroups)
                        {
                            if (childGroup.Count() == 1)
                            {
                                invalidLeaf  = childGroup.First().Key;
                                invaildtotal = childGroup.First().Value;
                            }
                            else
                            {
                                validtotal = childGroup.First().Value;
                            }
                        }

                        var invalidLeafValue = weights[invalidLeaf];
                        var difference       = invaildtotal - validtotal;
                        invalidLeaves.Add(invalidLeaf, invalidLeafValue - difference);
                    }
                }

                return(weights[leaf] + childSums.Sum(x => x.Value));
            }

            SumAllLeaves(treebase);

            result = invalidLeaves.FirstOrDefault().Value;

            if (expected != null)
            {
                Assert.AreEqual(expected, result);
            }

            Console.WriteLine(result);
        }
Пример #36
0
 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);
     }
 }
        // RimWorld.PawnGroupKindWorker_Normal
        public static void GeneratePawns_PostFix(PawnGroupMakerParms parms, PawnGroupMaker groupMaker,
                                                 bool errorOnZeroResults, ref List <Pawn> __result)
        {
            //Anyone special?
            if (__result?.Count > 0 &&
                __result.FindAll(x => x.TryGetComp <CompAbilityUser>() is CompAbilityUser cu && cu.CombatPoints() > 0) is
                List <Pawn> specialPawns && specialPawns?.Count > 0)
            {
                //Log.Message("Special Pawns Detected");
                //Log.Message("------------------");

                //Points
                var previousPoints = parms.points;
                //Log.Message("Points: " +  previousPoints);

                //Log.Message("Average Characters");
                //Log.Message("------------------");

                //Anyone average?
                int avgPawns        = 0;
                var avgCombatPoints = new Dictionary <Pawn, float>();
                if (__result.FindAll(x => x.TryGetComp <CompAbilityUser>() == null) is List <Pawn> averagePawns)
                {
                    avgPawns = averagePawns.Count;
                    averagePawns.ForEach(x =>
                    {
                        avgCombatPoints.Add(x, x.kindDef.combatPower);
                        //Log.Message(x.LabelShort + " : " + x.kindDef.combatPower);
                    });
                }

                //Log.Message("------------------");
                //Log.Message("Special Characters");
                //Log.Message("------------------");

                //What's your powers?
                var specCombatPoints = new Dictionary <Pawn, float>();
                specialPawns.ForEach(x =>
                {
                    var combatValue = x.kindDef.combatPower;
                    foreach (var thingComp in x.AllComps.FindAll(y => y is CompAbilityUser))
                    {
                        //var compAbilityUser = (CompAbilityUser) thingComp;
                        var val      = Traverse.Create(thingComp).Method("CombatPoints").GetValue <float>();
                        combatValue += val; //compAbilityUser.CombatPoints();
                    }
                    specCombatPoints.Add(x, combatValue);
                    //Log.Message(x.LabelShort + " : " + combatValue);
                });

                //Special case -- single raider/character should not be special to avoid problems (e.g. Werewolf raid destroys everyone).
                if (avgPawns == 0 && specCombatPoints.Sum(x => x.Value) > 0 && specialPawns.Count == 1)
                {
                    //Log.Message("Special case called: Single character");
                    specialPawns.First().TryGetComp <CompAbilityUser>().DisableAbilityUser();
                    return;
                }

                //Special case -- no special characters.
                if (specialPawns?.Count <= 0)
                {
                    return;
                }

                //Should we rebalance?
                int tryLimit             = avgPawns + specialPawns.Count + 1;
                int initTryLimit         = tryLimit;
                var tempAvgCombatPoints  = new Dictionary <Pawn, float>(avgCombatPoints);
                var tempSpecCombatPoints = new Dictionary <Pawn, float>(specCombatPoints);
                var removedCharacters    = new List <Pawn>();
                while (previousPoints < tempAvgCombatPoints.Sum(x => x.Value) + tempSpecCombatPoints.Sum(x => x.Value))
                {
                    //Log.Message("------------------");
                    //Log.Message("Rebalance Attempt # " + (initTryLimit - tryLimit + 1));
                    //Log.Message("------------------");
                    //Log.Message("Scenario Points: " + previousPoints + ". Total Points: " + tempAvgCombatPoints.Sum(x => x.Value) + tempSpecCombatPoints.Sum(x => x.Value));

                    //In-case some stupid stuff occurs
                    --tryLimit;
                    if (tryLimit < 0)
                    {
                        break;
                    }

                    //If special characters outnumber the avg characters, try removing some of the special characters instead.
                    if (tempSpecCombatPoints.Count >= tempAvgCombatPoints.Count)
                    {
                        var toRemove = tempSpecCombatPoints?.Keys?.RandomElement();
                        if (toRemove != null)
                        {
                            //Log.Message("Removed: " + toRemove.LabelShort + " : " + tempSpecCombatPoints[toRemove]);
                            removedCharacters.Add(toRemove);
                            tempSpecCombatPoints.Remove(toRemove);
                        }
                    }
                    //If average characters outnumber special characters, then check if the combat value of avg is greater.
                    else if (tempSpecCombatPoints.Count < tempAvgCombatPoints.Count)
                    {
                        //Remove a random average character if the average characters have more combat points for a score
                        if (tempAvgCombatPoints.Sum(x => x.Value) > tempSpecCombatPoints.Sum(x => x.Value))
                        {
                            var toRemove = tempAvgCombatPoints?.Keys?.RandomElement();
                            if (toRemove != null)
                            {
                                //Log.Message("Removed: " + toRemove.LabelShort + " : " + tempSpecCombatPoints[toRemove]);
                                removedCharacters.Add(toRemove);
                                tempAvgCombatPoints.Remove(toRemove);
                            }
                        }
                        else
                        {
                            var toRemove = tempSpecCombatPoints?.Keys?.RandomElement();
                            //Log.Message("Removed: " + toRemove.LabelShort + " : " + tempSpecCombatPoints[toRemove]);
                            if (toRemove != null)
                            {
                                removedCharacters.Add(toRemove);
                                tempSpecCombatPoints.Remove(toRemove);
                            }
                        }
                    }
                }
                avgCombatPoints  = tempAvgCombatPoints;
                specCombatPoints = tempSpecCombatPoints;

//                Log.Message("------------");
//                Log.Message("Final Report");
//                Log.Message("------------");
//                Log.Message("Scenario Points: " + previousPoints + ". Total Points: " + tempAvgCombatPoints.Sum(x => x.Value) + tempSpecCombatPoints.Sum(x => x.Value));
//                Log.Message("------------");
//                Log.Message("Characters");
//                Log.Message("------------------");
                __result.ForEach(x =>
                {
                    var combatValue = x.kindDef.combatPower + x?.TryGetComp <CompAbilityUser>()?.CombatPoints() ?? 0f;
                    //Log.Message(x.LabelShort + " : " + combatValue);
                });
                foreach (var x in removedCharacters)
                {
                    if (x.TryGetComp <CompAbilityUser>() is CompAbilityUser cu && cu.CombatPoints() > 0)
                    {
                        cu.DisableAbilityUser();
                    }
Пример #38
0
    /// <summary>
    /// 洗牌
    /// </summary>
    /// <param name="auto">If set manually</param>
    public void Shuffle(bool auto = false)
    {
        Checked(false, 20000, Vector3.zero);

        AudioManager.Instance.PlaySE(DataModel.Sound.Sound_SHUFFLE);

        //Step 1:登记现有所有牌组信息
        //equal to UpdateUseableStatus(true);
        _curCanUseCardIndex.Clear();
        _shuffuleAllCards.Clear();
        _shuffleAllIndex.Clear();
        _shuffleAllLayer.Clear();
        foreach (var item in _currentAllLevelsCards.Values)
        {
            foreach (var baseCardsDict in item)
            {
                if (CenterIndexCanUse(baseCardsDict.Key, baseCardsDict.Value.Layer))
                {
                    baseCardsDict.Value.Status = CardStatus.CanUse;

                    if (_curCanUseCardIndex.ContainsKey(baseCardsDict.Value.Layer))
                    {
                        _curCanUseCardIndex[baseCardsDict.Value.Layer].Add(baseCardsDict.Key);
                    }
                    else
                    {
                        _curCanUseCardIndex.Add(baseCardsDict.Value.Layer, new List <int>()
                        {
                            baseCardsDict.Key
                        });
                    }
                }
                else
                {
                    baseCardsDict.Value.Status = CardStatus.Fixed;
                }

                EffectUpdateCardsStatus(baseCardsDict.Value, true);

                //temple for restore the card info
                _shuffuleAllCards.Add(baseCardsDict.Value);
                _shuffleAllLayer.Add(baseCardsDict.Value.Layer);
                _shuffleAllIndex.Add(baseCardsDict.Value.Index);
            }
        }

        //Step 2:清除所有网格信息
        for (int i = 0; i < _shuffuleAllCards.Count; i++)
        {
            RemoveFromDict(_shuffuleAllCards[i].Layer, _shuffuleAllCards[i]);
        }

        //Step 3:优先配对放置,取最小可放置数目
        //赶时间,笨办法
        List <int> layerCanUseList = new List <int>();
        List <int> indexCanUseList = new List <int>();

        foreach (var item in _curCanUseCardIndex)
        {
            foreach (var index in item.Value)
            {
                indexCanUseList.Add(index);
                layerCanUseList.Add(item.Key);
            }
        }

        //Step 33:对于只剩下一个柱状排布时特殊处理,linq少用
        var resultList = indexCanUseList.GroupBy(e => e);

        if (resultList.Count() > 1)
        {
            //maintain can-use index list
            Debug.Log(_curCanUseCardIndex.Count);

            //指定配对组合
            int canPairNum    = _canPairNum;
            int canUsePairNum = Mathf.FloorToInt(_curCanUseCardIndex.Sum((arg1) => { return(arg1.Value.Count); }) * .5f);
            canPairNum = Mathf.Min(canUsePairNum, canPairNum);

            for (int q = 0; q < canPairNum; q++)
            {
                int             randomIndex = UnityEngine.Random.Range(0, _shuffuleAllCards.Count);
                int             randomID    = _shuffuleAllCards[randomIndex].ID;
                List <BaseCard> sameIDCards;
                try
                {
                    //牌均取两张,前面的条件已保证此处可以正常获取不会越界
                    sameIDCards = _shuffuleAllCards.Where(e => { return(e.ID == randomID); }).ToList();
                    var card0     = sameIDCards[0];
                    var card1     = sameIDCards[1];
                    var layer0    = layerCanUseList[layerCanUseList.Count - 1];
                    var layer1    = layerCanUseList[layerCanUseList.Count - 2];
                    var useIndex0 = indexCanUseList[indexCanUseList.Count - 1];
                    var useIndex1 = indexCanUseList[indexCanUseList.Count - 2];

                    MoveCardsLogicalTo(card0, useIndex0, layer0, false);
                    EffectMoveTo(card0, !auto);

                    MoveCardsLogicalTo(card1, useIndex1, layer1, false);
                    EffectMoveTo(card1, !auto);

                    layerCanUseList.RemoveAt(layerCanUseList.Count - 1);
                    layerCanUseList.RemoveAt(layerCanUseList.Count - 1);
                    indexCanUseList.RemoveAt(indexCanUseList.Count - 1);
                    indexCanUseList.RemoveAt(indexCanUseList.Count - 1);
                    //删除备选项
                    _shuffuleAllCards.Remove(card0); _shuffuleAllCards.Remove(card1);
                    _shuffleAllLayer.Remove(layer0); _shuffleAllLayer.Remove(layer1);
                    _shuffleAllIndex.RemoveAt(_shuffleAllIndex.LastIndexOf(useIndex0)); _shuffleAllIndex.RemoveAt(_shuffleAllIndex.LastIndexOf(useIndex1));
                }
                catch (Exception ex)
                {
                    Debug.Log(":" + ex.Message);
                }
            }

            //Step 4:剩下的随机放置
            for (int i = 0; i < _shuffuleAllCards.Count; i++)
            {
                int      randomindex  = UnityEngine.Random.Range(0, _shuffleAllIndex.Count);
                BaseCard randomTarget = _shuffuleAllCards[i];

                Debug.Log("index: " + randomTarget.Index + " => " + _shuffleAllIndex[randomindex]);
                Debug.Log("layer: " + randomTarget.Layer + " => " + _shuffleAllLayer[randomindex]);

                MoveCardsLogicalTo(randomTarget, _shuffleAllIndex[randomindex], _shuffleAllLayer[randomindex], false);
                EffectMoveTo(randomTarget, !auto);

                _shuffleAllIndex.RemoveAt(randomindex);
                _shuffleAllLayer.RemoveAt(randomindex);
            }
        }
        else
        {
            //全部放到最底层2个一组并排排列
            int rowIndex        = -1;
            int centerIndex     = 0;
            int baseCenterIndex = ( int )(_colPointsNum - 1) / 2;
            for (int q = 0; q < _shuffuleAllCards.Count; q++)
            {
                if (q % 2 == 0)
                {
                    rowIndex   += 2;
                    centerIndex = baseCenterIndex + rowIndex * _colPointsNum;
                }
                else
                {
                    centerIndex += 2;
                }
                //Debug.Log( "==========================" + centerIndex );
                MoveCardsLogicalTo(_shuffuleAllCards[q], centerIndex, 0, false);
                EffectMoveTo(_shuffuleAllCards[q], !auto);
            }
        }
        _shuffuleAllCards.Clear();
        _shuffleAllIndex.Clear();
        _shuffleAllLayer.Clear();

        CheckCameraPos();

        UpdateUseableStatus(true);
    }
Пример #39
0
        /// <summary>
        /// Calculates size of each cell, taking into account their preferred size, expansion/fill requests, and the available space.
        /// Calculation is done only for the provided orientation (either height or width).
        /// </summary>
        /// <param name="mode">Mode.</param>
        /// <param name="availableSize">Total size available</param>
        /// <param name="calcOffsets"></param>
        void CalcCellSizes(CellSizeVector cellSizes, double availableSize, bool calcOffsets)
        {
            TablePlacement[]         visibleChildren  = cellSizes.visibleChildren;
            Dictionary <int, double> fixedSizesByCell = cellSizes.fixedSizesByCell;

            double[]    sizes       = cellSizes.sizes;
            double      spacing     = cellSizes.spacing;
            Orientation orientation = cellSizes.orientation;

            // Get the total natural size
            double naturalSize = fixedSizesByCell.Values.Sum();

            double remaining = availableSize - naturalSize - spacing;

            if (availableSize - spacing <= 0)
            {
                foreach (var i in fixedSizesByCell.Keys.ToArray())
                {
                    fixedSizesByCell [i] = 0;
                }
            }
            else if (remaining < 0)
            {
                // The box is not big enough to fit the widgets using its natural size.
                // We have to shrink the cells. We do a proportional reduction

                // List of cell indexes that we have to shrink
                var toShrink = new List <int> (fixedSizesByCell.Keys);

                // The total amount we have to shrink
                double splitSize = (availableSize - spacing) / toShrink.Count;

                // We have to reduce all cells proportionally, but if a cell is much bigger that
                // its proportionally allocated space, then we reduce this one before the others

                var smallCells     = fixedSizesByCell.Where(c => c.Value < splitSize);
                var belowSplitSize = smallCells.Sum(c => splitSize - c.Value);

                var bigCells      = fixedSizesByCell.Where(c => c.Value > splitSize);
                var overSplitSize = bigCells.Sum(c => c.Value - splitSize);

                ReduceProportional(fixedSizesByCell, bigCells.Select(c => c.Key), overSplitSize - belowSplitSize);

                var newNatural = fixedSizesByCell.Sum(c => c.Value);
                ReduceProportional(fixedSizesByCell, fixedSizesByCell.Keys, (availableSize - spacing) - newNatural);

                RoundSizes(fixedSizesByCell);
            }
            else
            {
                // Distribute remaining space among the extensible widgets
                HashSet <int> cellsWithExpand = cellSizes.cellsWithExpand;
                int           nexpands        = cellsWithExpand.Count;
                var           expandRemaining = new SizeSplitter(remaining, nexpands);
                foreach (var c in cellsWithExpand)
                {
                    double ws;
                    fixedSizesByCell.TryGetValue(c, out ws);
                    ws += expandRemaining.NextSizePart();
                    fixedSizesByCell [c] = ws;
                }
            }

            // Calculate the offset of each widget, relative to the cell (so 0 means at the left/top of the cell).

            for (int n = 0; n < visibleChildren.Length; n++)
            {
                var    bp            = visibleChildren[n];
                double allocatedSize = 0;
                double cellOffset    = 0;

                int start = GetStartAttach(bp, orientation);
                int end   = GetEndAttach(bp, orientation);
                for (int i = start; i < end; i++)
                {
                    double ws;
                    fixedSizesByCell.TryGetValue(i, out ws);
                    allocatedSize += ws;
                    if (i != start)
                    {
                        allocatedSize += GetSpacing(i, orientation);
                    }
                }

                var al = bp.GetAlignmentForOrientation(orientation);
                if (!double.IsNaN(al))
                {
                    double s = sizes[n];
                    if (s < allocatedSize)
                    {
                        cellOffset    = (allocatedSize - s) * al;
                        allocatedSize = s;
                    }
                }

                // cellOffset is the offset of the widget inside the cell. We store it in NextX/Y, and
                // will be used below to calculate the total offset of the widget

                if (orientation == Orientation.Vertical)
                {
                    bp.NextHeight = allocatedSize;
                    bp.NextY      = cellOffset;
                }
                else
                {
                    bp.NextWidth = allocatedSize;
                    bp.NextX     = cellOffset;
                }
            }

            if (calcOffsets)
            {
                // Calculate the final offset of each widget, relative to the table origin
                var    sortedChildren = visibleChildren.OrderBy(c => GetStartAttach(c, orientation)).ToArray();
                var    cells          = fixedSizesByCell.OrderBy(c => c.Key);
                double offset         = 0;
                int    n = 0;
                foreach (var c in cells)
                {
                    if (c.Key > 0)
                    {
                        offset += GetSpacing(c.Key, orientation);
                    }
                    while (n < sortedChildren.Length && GetStartAttach(sortedChildren[n], orientation) == c.Key)
                    {
                        // In the loop above we store the offset of the widget inside the cell in the NextX/Y field
                        // so now we have to add (not just assign) the offset of the cell to NextX/Y
                        if (orientation == Orientation.Vertical)
                        {
                            sortedChildren[n].NextY += offset;
                        }
                        else
                        {
                            sortedChildren[n].NextX += offset;
                        }
                        n++;
                    }
                    offset += c.Value;
                }
            }
        }
Пример #40
0
 public double CalculateTotalPrice()
 {
     return(totalProductCount.Sum(product => product.Key.CalculateTotal(product.Value)));
 }
Пример #41
0
        public void DrawConnection(List <NodeGUI> nodes, Dictionary <string, List <AssetReference> > assetGroups)
        {
            var startNode = nodes.Find(node => node.Id == OutputNodeId);

            if (startNode == null)
            {
                return;
            }

            var endNode = nodes.Find(node => node.Id == InputNodeId);

            if (endNode == null)
            {
                return;
            }

            var startPoint = m_outputPoint.GetGlobalPosition(startNode);
            var startV3    = new Vector3(startPoint.x, startPoint.y, 0f);

            var endPoint = m_inputPoint.GetGlobalPosition(endNode);
            var endV3    = new Vector3(endPoint.x, endPoint.y, 0f);

            var centerPoint   = startPoint + ((endPoint - startPoint) / 2);
            var centerPointV3 = new Vector3(centerPoint.x, centerPoint.y, 0f);

            var pointDistanceX = Model.Settings.GUI.CONNECTION_CURVE_LENGTH;

            var startTan = new Vector3(startPoint.x + pointDistanceX, centerPoint.y, 0f);
            var endTan   = new Vector3(endPoint.x - pointDistanceX, centerPoint.y, 0f);

            var totalAssets = 0;
            var totalGroups = 0;

            if (assetGroups != null)
            {
                totalAssets = assetGroups.Sum(v => v.Value == null ? 0 : v.Value.Count);
                totalGroups = assetGroups.Keys.Count;
            }

            Color lineColor;
            var   lineWidth = (totalAssets > 0) ? 3f : 2f;

            if (IsSelected)
            {
                lineColor = Model.Settings.GUI.COLOR_ENABLED;
            }
            else
            {
                lineColor = (totalAssets > 0) ? Model.Settings.GUI.COLOR_CONNECTED : Model.Settings.GUI.COLOR_NOT_CONNECTED;
            }

            ConnectionGUIUtility.HandleMaterial.SetPass(0);
            Handles.DrawBezier(startV3, endV3, startTan, endTan, lineColor, null, lineWidth);

            // draw connection label if connection's label is not normal.
            GUIStyle labelStyle = new GUIStyle("WhiteMiniLabel");

            labelStyle.alignment = TextAnchor.MiddleLeft;

            switch (Label)
            {
            case Model.Settings.DEFAULT_OUTPUTPOINT_LABEL: {
                // show nothing
                break;
            }

            case Model.Settings.BUNDLECONFIG_BUNDLE_OUTPUTPOINT_LABEL: {
                var labelWidth   = labelStyle.CalcSize(new GUIContent(Model.Settings.BUNDLECONFIG_BUNDLE_OUTPUTPOINT_LABEL));
                var labelPointV3 = new Vector3(centerPointV3.x - (labelWidth.x / 2), centerPointV3.y - 24f, 0f);
                Handles.Label(labelPointV3, Model.Settings.BUNDLECONFIG_BUNDLE_OUTPUTPOINT_LABEL, labelStyle);
                break;
            }

            default: {
                var labelWidth   = labelStyle.CalcSize(new GUIContent(Label));
                var labelPointV3 = new Vector3(centerPointV3.x - (labelWidth.x / 2), centerPointV3.y - 24f, 0f);
                Handles.Label(labelPointV3, Label, labelStyle);
                break;
            }
            }

            string connectionLabel;

            //if(totalGroups > 1) {
            connectionLabel = $"{totalAssets}:{totalGroups}";
            // } else {
            //  connectionLabel = $"{totalAssets}";
            // }

            var style = new GUIStyle(m_connectionButtonStyle);

            var labelSize = style.CalcSize(new GUIContent(connectionLabel));

            m_buttonRect = new Rect(centerPointV3.x - labelSize.x / 2f, centerPointV3.y - labelSize.y / 2f, labelSize.x, 30f);

            if (
                Event.current.type == EventType.ContextClick ||
                (Event.current.type == EventType.MouseUp && Event.current.button == 1)
                )
            {
                var rightClickPos = Event.current.mousePosition;
                if (m_buttonRect.Contains(rightClickPos))
                {
                    var menu = new GenericMenu();
                    menu.AddItem(
                        new GUIContent("Delete"),
                        false,
                        () => {
                        Delete();
                    }
                        );
                    menu.ShowAsContext();
                    Event.current.Use();
                }
            }

            if (GUI.Button(m_buttonRect, connectionLabel, style))
            {
                this.m_assetGroups = assetGroups;
                ConnectionGUIUtility.ConnectionEventHandler(new ConnectionEvent(ConnectionEvent.EventType.EVENT_CONNECTION_TAPPED, this));
            }
        }
Пример #42
0
        static void Main(string[] args)
        {
            var input = Console.ReadLine();

            var bands = new Dictionary <string, List <string> >();

            var playTime = new Dictionary <string, int>();

            while (input != "start of concert")
            {
                var command = input.Split("; ");

                switch (command[0])
                {
                case "Add":
                    if (!bands.ContainsKey(command[1]))
                    {
                        bands.Add(command[1], new List <string>());
                    }

                    if (!playTime.ContainsKey(command[1]))
                    {
                        playTime.Add(command[1], 0);
                    }

                    var musicians = command[2].Split(", ");

                    foreach (var musician in musicians)
                    {
                        if (!bands[command[1]].Contains(musician))
                        {
                            bands[command[1]].Add(musician);
                        }
                    }
                    break;

                case "Play":
                    if (!bands.ContainsKey(command[1]))
                    {
                        bands.Add(command[1], new List <string>());
                    }

                    if (!playTime.ContainsKey(command[1]))
                    {
                        playTime.Add(command[1], 0);
                    }

                    playTime[command[1]] += int.Parse(command[2]);
                    break;
                }
                input = Console.ReadLine();
            }
            playTime = playTime.OrderByDescending(p => p.Value).ThenBy(p => p.Key).ToDictionary(p => p.Key, p => p.Value);

            var bandName = Console.ReadLine();

            Console.WriteLine($"Total time: {playTime.Sum(p => p.Value)}");

            foreach (var band in playTime)
            {
                Console.WriteLine($"{band.Key} -> {band.Value}");
            }

            var bandToShow = bands.First(b => b.Key == bandName);

            Console.WriteLine(bandName);

            foreach (var member in bandToShow.Value)
            {
                Console.WriteLine($"=> {member}");
            }
        }
Пример #43
0
        /// <summary>
        /// Compares fill amouns to determine if fill is complete
        /// </summary>
        /// <returns></returns>
        public bool IsCompleted()
        {
            var quantity = _messages.Sum(m => m.Value.AmountExecuted);

            return(quantity >= _order.Quantity);
        }
Пример #44
0
    void UpdateResourceVisual()
    {
        int numResources = resources.Sum(x => x.Value);

        resourceBarFill.fillAmount = numResources / (float)resourceCapacity;
    }
Пример #45
0
 public double TotalReturn()
 {
     return(_ladder.Sum(
                price => Math.Round((price.Key * price.Value) - price.Value, 2)));
 }
Пример #46
0
        static void Main(string[] args)
        {
            // init
            var passes      = 0;
            var unsupported = new Dictionary <string, List <ITestCase> >();

            // create tests
            var tests = new ITest[]
            {
                new Fixtures.Test("Debugging", "Debugging"),
                //new CodeTesting.IntegrationTest(),
                new Fixtures.Test("Basic Tests - v1.0", "v10.BasicTests"),
                new Fixtures.Test("Bugs - v1.0", "v10.Bugs"),
                new Fixtures.Test("CSL Test Suite - v1.0", "v10.CslTestSuite"),
            }
            .Where(x => x.Cases.Length > 0)
            .ToArray();

            // padding
            var total = tests
                        .SelectMany(x => x.Cases)
                        .Count();
            var padding = tests
                          .SelectMany(x => x.Cases)
                          .Select(x => x.Name.Length)
                          .Max() + 2;

            // log
            var logpath = string.Format("testrun {0:yyyyMMdd HHmm}.txt", DateTime.Now);

            // execute
            int index = 0;

            using (var log = new System.IO.StreamWriter(logpath))
            {
                foreach (var test in tests)
                {
                    // init
                    Console.ForegroundColor = ConsoleColor.White;
                    Console.WriteLine(test.Name);

                    // cases
                    foreach (var @case in test.Cases)
                    {
                        // write name
                        Console.ResetColor();
                        Console.Write(" ");
                        Console.Write(@case.Name.PadRight(padding));

                        // progress
                        var left = Console.CursorLeft;
                        var top  = Console.CursorTop;
                        Console.Write(string.Format("{0}/{1}", index, total));
                        Console.SetCursorPosition(left, top);

                        // execute
                        var start = DateTime.Now;
                        try
                        {
                            // execute
                            var result = @case.Execute(log);

                            // show result
                            if (result)
                            {
                                // write
                                Console.ForegroundColor = ConsoleColor.Green;
                                Console.Write("Pass");

                                // add
                                passes++;
                            }
                            else
                            {
                                // write
                                Console.ForegroundColor = ConsoleColor.Red;
                                Console.Write("Fail");
                            }
                        }
                        catch (FeatureNotSupportedException ex)
                        {
                            // process
                            if (!unsupported.ContainsKey(ex.Feature))
                            {
                                unsupported.Add(ex.Feature, new List <ITestCase>());
                            }
                            unsupported[ex.Feature].Add(@case);

                            // write
                            Console.ForegroundColor = ConsoleColor.Yellow;
                            Console.Write("N/S ");
                        }

                        // done
                        var duration = DateTime.Now.Subtract(start).TotalMilliseconds;

                        // duration
                        Console.ResetColor();
                        Console.Write("  ({0:0} ms)", duration);
                        Console.WriteLine();

                        // next
                        index++;
                    }
                }

                // summary
                Console.WriteLine();
                Console.ForegroundColor = ConsoleColor.White;
                Console.Write("Summary".PadRight(padding + 1));
                Console.WriteLine();

                // log
                log.WriteLine();
                log.WriteLine();
                log.WriteLine("".PadRight(80, '-'));
                log.WriteLine("-- Summary".PadRight(78).PadRight(80, '-'));
                log.WriteLine("".PadRight(80, '-'));

                // totals
                var notsupported = unsupported.Sum(x => x.Value.Count());
                WriteTotal(log, ConsoleColor.Green, "Pass", padding, passes, total);
                WriteTotal(log, ConsoleColor.Yellow, "N/S ", padding, notsupported, total);
                WriteTotal(log, ConsoleColor.Red, "Fail", padding, (total - passes - notsupported), total);
                log.WriteLine("".PadRight(80, '-'));

                //
                Console.ForegroundColor = ConsoleColor.White;
                Console.Write("Totals".PadRight(padding + 1));
                Console.Write(string.Format("{0:0.0}%", (double)passes / (double)(total - notsupported) * 100d));
                Console.WriteLine();

                // log
                log.WriteLine(string.Format("     {0:0.0}%", (double)passes / (double)(total - notsupported) * 100d));
                log.WriteLine("".PadRight(80, '-'));

                // unsupported
                foreach (var entry in unsupported.OrderByDescending(x => x.Value.Count))
                {
                    // header
                    log.WriteLine("{0}{1}", entry.Key.PadRight(40), entry.Value.Count);
                }
            }

            // done
            Console.ReadKey(true);
        }
        public static IEnumerable <Point> GetCollectorPoint(string engineName, string performanceCounterGroup, int counters, Dictionary <string, long> timeInfo, double?elapseOffsetMs)
        {
            var tags = new Dictionary <string, string>
            {
                { "counter", "readCount" },
                { "hostname", Environment.MachineName },
                { "version", Assembly.GetExecutingAssembly().GetName().Version.ToString() },
                { "action", "collect" },
                { "performanceCounterGroup", performanceCounterGroup },
                { "engineName", engineName },
            };

            var fields = new Dictionary <string, object>
            {
                { "value", (decimal)counters },
                //{ "readCount", counters }
            };

            if (elapseOffsetMs != null)
            {
                fields.Add("elapseOffsetTimeMs", (decimal)elapseOffsetMs.Value);
            }

            var totalTimeMs = timeInfo.Sum(x => x.Value);

            fields.Add("totalTimeMs", (decimal) new TimeSpan(totalTimeMs).TotalMilliseconds);

            var now = DateTime.UtcNow;

            yield return(new Point
            {
                Name = Constants.ServiceName + "-Metadata",
                Tags = tags,
                Fields = fields,
                Precision = TimeUnit.Milliseconds,
                Timestamp = now
            });

            var index = 0;

            foreach (var ti in timeInfo)
            {
                index++;

                fields = new Dictionary <string, object>
                {
                    { "value", (decimal) new TimeSpan(ti.Value).TotalMilliseconds },
                    //{ "readTime", (decimal)new TimeSpan(ti.Value).TotalMilliseconds }
                };

                tags = new Dictionary <string, string>
                {
                    { "counter", "readTime" },
                    { "hostname", Environment.MachineName },
                    { "version", Assembly.GetExecutingAssembly().GetName().Version.ToString() },
                    { "action", "collect" },
                    { "performanceCounterGroup", performanceCounterGroup },
                    { "engineName", engineName },
                    { "step", index + "-" + ti.Key },
                };

                yield return(new Point
                {
                    Name = Constants.ServiceName + "-Metadata",
                    Tags = tags,
                    Fields = fields,
                    Precision = TimeUnit.Milliseconds,
                    Timestamp = now
                });
            }
        }
Пример #48
0
        static void Main(string[] args)
        {
            GlobalValues.DiscreteBoardX   = 10;
            GlobalValues.DiscreteBoardY   = 10;
            GlobalValues.InitialBallX     = 0.5;
            GlobalValues.InitialBallY     = 0.5;
            GlobalValues.InitialVelocityX = 0.03;
            GlobalValues.InitialVelocityY = 0.01;
            GlobalValues.PaddleHeight     = 0.2;
            GlobalValues.RandomVelocityX  = 0.015;
            GlobalValues.RandomVelocityY  = 0.03;
            Random rand = new Random();

            double boardX = 1.0;
            double boardY = 1.0;
            //double ball_x = 0.5;
            //double ball_y = 0.5;
            //double vel_x = 0.03;
            //double vel_y = 0.01;
            //double paddleHeight = 0.2;
            //double randomVelX = 0.015;
            //double randomVelY = 0.03;

            int    totalTrials      = 600000;
            double learningConstant = 30; //30
            double discountFactor   = .9; //.4
            int    explorationLimit = 1;  //300

            Ball   initialBall = new Ball(GlobalValues.InitialBallX, GlobalValues.InitialBallY, GlobalValues.InitialVelocityX, GlobalValues.InitialVelocityY, GlobalValues.DiscreteBoardX, GlobalValues.DiscreteBoardY, false);
            Player rP          = new Player(1, 0.5 - (GlobalValues.PaddleHeight / 2), learningConstant, discountFactor, Tuple.Create(initialBall.DiscreteBallX, initialBall.DiscreteBallY, initialBall.DiscreteVelocityX, initialBall.DiscreteVelocityY, (int)Math.Floor(GlobalValues.DiscreteBoardY * (0.5 - (GlobalValues.PaddleHeight / 2)) / (1 - GlobalValues.PaddleHeight))), GlobalValues.DiscreteBoardX, GlobalValues.DiscreteBoardY, explorationLimit);

            //rP.Memory = ReadQ(@"C:\Users\mabiscoc\Documents\Visual Studio 2013\Projects\SaveDictionary\SaveDictionary\Q.txt");
            //rP.MemoryVisited = ReadN(@"C:\Users\mabiscoc\Documents\Visual Studio 2013\Projects\SaveDictionary\SaveDictionary\N.txt");

            int maxDeflections   = 0;
            int totalTrialLength = 0;

            DateTime start = DateTime.Now;

            for (int numTrial = 0; numTrial < totalTrials; numTrial++)
            {
                Write(rP.Memory, @"I:\Backup\Masters\UIUC\2016\Fall\CS_440\Homework\4\CS440-HW4\Pong10\Pong\Q.txt");
                Write(rP.MemoryVisited, @"I:\Backup\Masters\UIUC\2016\Fall\CS_440\Homework\4\CS440-HW4\Pong10\Pong\N.txt");

                // initial state of the ball
                Ball b = new Ball(GlobalValues.InitialBallX, GlobalValues.InitialBallY, GlobalValues.InitialVelocityX, GlobalValues.InitialVelocityY, GlobalValues.DiscreteBoardX, GlobalValues.DiscreteBoardY, false);
                rP.PaddleY         = 0.5 - (GlobalValues.PaddleHeight / 2);
                rP.DiscretePaddleY = rP.getDiscretePaddleY();
                rP.PrevAction      = "N/A";
                //totalTrials = 300000;
                //learningConstant = 450000;
                //explorationLimit = 50000;
                var currentStateTuple    = Tuple.Create(b.BallX, b.BallY, b.VelocityX, b.VelocityY, rP.PaddleY);
                var currentDiscreteTuple = Tuple.Create(b.DiscreteBallX, b.DiscreteBallY, b.DiscreteVelocityX, b.DiscreteVelocityY, rP.DiscretePaddleY);
                var prevStateTuple       = Tuple.Create(b.BallX, b.BallY, b.VelocityX, b.VelocityY, rP.PaddleY);

                // Epsiode/Trial Loop
                int trialIterations = 0;
                rP.addGamesPlayed();
                while (true)
                {
                    trialIterations++;

                    // Previous Discrete Values
                    //int prevDiscreteBallX = b.DiscreteBallX;
                    //int prevDiscreteBallY = b.DiscreteBallY;
                    //int prevDiscretePaddleX = rP.DiscretePaddleX;
                    //int prevDiscretePaddleY = rP.DiscretePaddleY;
                    //int prevDiscreteVelX = b.DiscreteVelocityX;
                    //int prevDiscreteVelY = b.DiscreteVelocityY;

                    //var prevDiscreteState = Tuple.Create(prevDiscreteBallX, prevDiscreteBallY, prevDiscreteVelX, prevDiscreteVelY, prevDiscretePaddleX, prevDiscretePaddleY);
                    prevStateTuple = currentStateTuple;
                    b.MoveBall();
                    currentStateTuple = Tuple.Create(b.BallX, b.BallY, b.VelocityX, b.VelocityY, rP.PaddleY);

                    //DrawPong(GlobalValues.DiscreteBoardX, GlobalValues.DiscreteBoardY, null, rP, b, numTrial, trialIterations);
                    if (goalState(currentStateTuple, rP, null))
                    {
                        if (deflectionDetected(currentStateTuple, prevStateTuple, rP, null, b))
                        {
                            if (rP.Deflections >= 9)
                            {
                                Console.WriteLine("HERE");
                            }

                            b.BallX = 2 * rP.PaddleX - b.BallX;
                            double randomXVel = rand.NextDouble() * (GlobalValues.RandomVelocityX - (-1 * GlobalValues.RandomVelocityX)) + (-1 * GlobalValues.RandomVelocityX);
                            double randomYVel = rand.NextDouble() * (GlobalValues.RandomVelocityY - (-1 * GlobalValues.RandomVelocityY)) + (-1 * GlobalValues.RandomVelocityY);

                            if (Math.Abs(randomXVel) > 0.015)
                            {
                                ;
                            }
                            if (Math.Abs(randomYVel) > .03)
                            {
                                ;
                            }

                            b.VelocityX = b.VelocityX * -1 + randomXVel;
                            b.VelocityY = b.VelocityY + randomYVel;

                            if (Math.Abs(b.VelocityX) < 0.03)
                            {
                                if (b.VelocityX < 0)
                                {
                                    b.VelocityX = -0.03;
                                    //b.VelocityX = b.VelocityX * -1;
                                }
                                else
                                {
                                    b.VelocityX = 0.03;
                                }
                            }
                            // TODO: Put direction?
                            if (Math.Abs(b.VelocityX) > 1)
                            {
                                if (b.VelocityX < 0)
                                {
                                    b.VelocityX = -1;
                                }
                                else
                                {
                                    b.VelocityX = 1;
                                }
                            }
                            if (Math.Abs(b.VelocityY) > 1)
                            {
                                if (b.VelocityY < 0)
                                {
                                    b.VelocityY = -1;
                                }
                                else
                                {
                                    b.VelocityY = 1;
                                }
                            }
                        }
                        else
                        {
                            if (rP.Deflections >= 9)
                            {
                                Console.WriteLine("HERE");
                            }
                            rP.addGamesLost();
                            //rP.updateQ(b, rP.PrevAction, rP, null, GlobalValues.DiscreteBoardX, GlobalValues.DiscreteBoardY, GlobalValues.PaddleHeight, GlobalValues.LearningRate, GlobalValues.DiscountFactor, int stateReward);
                            break;
                        }
                    }

                    // Draw Board
                    //DrawPong(GlobalValues.DiscreteBoardX, GlobalValues.DiscreteBoardY, null, rP, b, numTrial, trialIterations);

                    //DrawPong(GlobalValues.DiscreteBoardX, GlobalValues.DiscreteBoardY, null, rP, b, numTrial);
                    // Right Player Makes Decision
                    //rP.MoveRightPaddle(b);

                    // Move Ball
                    //b.MoveBall();

                    rP.MoveRightPaddle(b);
                    //DrawPong(GlobalValues.DiscreteBoardX, GlobalValues.DiscreteBoardY, null, rP, b, numTrial, trialIterations);

                    rP.tdUpdate3(b, prevStateTuple, currentStateTuple);



                    //// Current Discrete Values
                    //int currDiscreteBallX = b.DiscreteBallX;
                    //int currDiscreteBallY = b.DiscreteBallY;
                    //int currDiscretePaddleX = rP.DiscretePaddleX;
                    //int currDiscretePaddleY = rP.DiscretePaddleY;
                    //int currDiscreteVelX = b.DiscreteVelocityX;
                    //int currDiscreteVelY = b.DiscreteVelocityY;

                    //var currDiscreteState = Tuple.Create(currDiscreteBallX, currDiscreteBallY, currDiscreteVelX, currDiscreteVelY, currDiscretePaddleX, currDiscretePaddleY);

                    //// Check if there was a change, if so, update Q
                    //if (prevDiscreteBallX != currDiscreteBallX ||
                    //    prevDiscreteBallY != currDiscreteBallY ||
                    //    prevDiscretePaddleX != currDiscretePaddleX ||
                    //    prevDiscretePaddleY != currDiscretePaddleY ||
                    //    prevDiscreteVelX != currDiscreteVelX ||
                    //    prevDiscreteVelY != currDiscreteVelY)
                    //{
                    //    rP.tdUpdate2(b, prevDiscreteState, currDiscreteState);
                    //}


                    //DrawPong(GlobalValues.DiscreteBoardX, GlobalValues.DiscreteBoardY, null, rP, b, numTrial);
                    // Add new State
                    //prevStateTuple = currentStateTuple;
                    //currentStateTuple = Tuple.Create(b.BallX, b.BallY, b.VelocityX, b.VelocityY, rP.PaddleY);
                }
                if (rP.Deflections > maxDeflections)
                {
                    maxDeflections = rP.Deflections;
                }
                totalTrialLength         = totalTrialLength + trialIterations;
                rP.TotalTrialDeflections = rP.TotalTrialDeflections + rP.Deflections;
                Console.WriteLine("*********************************");
                Console.WriteLine("Trial: " + numTrial);
                Console.WriteLine("Trial Length: " + trialIterations);
                Console.WriteLine("Number of deflections: " + rP.Deflections);
                Console.WriteLine("Avg Trial number of deflections: " + (double)rP.TotalTrialDeflections / rP.GamesPlayed);
                Console.WriteLine("Avg Trial length: " + (double)totalTrialLength / rP.GamesPlayed);
                if ((double)rP.TotalTrialDeflections / rP.GamesPlayed > 9)
                {
                    Console.WriteLine("Agent may have found an optimal policy!");
                }
                Console.WriteLine("Max number of deflections: " + maxDeflections);
                Console.WriteLine("*********************************");
                rP.Deflections = 0;
            }

            DateTime end = DateTime.Now;

            Console.WriteLine("*************SUMMARY:*************");
            Console.WriteLine("Training start: " + start);
            Console.WriteLine("Training end: " + end);
            Console.WriteLine("Training duration: " + (end - start));

            do
            {
                Console.WriteLine("Press p to play, 1 player");
            } while (Console.ReadKey().KeyChar != 'p');


            int totalGames = 10;

            //double learningConstant = 5;
            //double discountFactor = .9;
            maxDeflections = 0;

            Dictionary <int, int> gameDeflections = new Dictionary <int, int>();

            rP.Deflections      = 0;
            rP.ExplorationLimit = 1;
            DateTime startGame = DateTime.Now;

            for (int numGame = 0; numGame < totalGames; numGame++)
            {
                Ball b = new Ball(GlobalValues.InitialBallX, GlobalValues.InitialBallY, GlobalValues.InitialVelocityX, GlobalValues.InitialVelocityY, GlobalValues.DiscreteBoardX, GlobalValues.DiscreteBoardY, false);

                // initial state of the ball, make random velocity, ball in the middle, paddleY is in the middle
                //Ball b = new Ball(GlobalValues.InitialBallX, GlobalValues.InitialBallY, GlobalValues.InitialVelocityX + rand.NextDouble() * (GlobalValues.RandomVelocityX - (-1 * GlobalValues.RandomVelocityX)) + (-1 * GlobalValues.RandomVelocityX), rand.NextDouble() * (GlobalValues.RandomVelocityY - (-1 * GlobalValues.RandomVelocityY)) + (-1 * GlobalValues.RandomVelocityY), GlobalValues.DiscreteBoardX, GlobalValues.DiscreteBoardY, false);
                rP.PaddleY         = 0.5 - (GlobalValues.PaddleHeight / 2);
                rP.DiscretePaddleY = rP.getDiscretePaddleY();
                rP.PrevAction      = "N/A";

                var currentStateTuple    = Tuple.Create(b.BallX, b.BallY, b.VelocityX, b.VelocityY, rP.PaddleY);
                var currentDiscreteTuple = Tuple.Create(b.DiscreteBallX, b.DiscreteBallY, b.DiscreteVelocityX, b.DiscreteVelocityY, rP.DiscretePaddleY);
                var prevStateTuple       = Tuple.Create(b.BallX, b.BallY, b.VelocityX, b.VelocityY, rP.PaddleY);

                // Epsiode/Trial Loop
                int gameIterations = 0;
                rP.addGamesPlayed();
                while (true)
                {
                    gameIterations++;

                    prevStateTuple = currentStateTuple;
                    b.MoveBall();
                    currentStateTuple = Tuple.Create(b.BallX, b.BallY, b.VelocityX, b.VelocityY, rP.PaddleY);

                    DrawPong(GlobalValues.DiscreteBoardX, GlobalValues.DiscreteBoardY, null, rP, b, numGame, gameIterations);

                    if (goalState(currentStateTuple, rP, null))
                    {
                        if (deflectionDetected(currentStateTuple, prevStateTuple, rP, null, b))
                        {
                            b.BallX = 2 * rP.PaddleX - b.BallX;
                            double randomXVel = rand.NextDouble() * (GlobalValues.RandomVelocityX - (-1 * GlobalValues.RandomVelocityX)) + (-1 * GlobalValues.RandomVelocityX);
                            double randomYVel = rand.NextDouble() * (GlobalValues.RandomVelocityY - (-1 * GlobalValues.RandomVelocityY)) + (-1 * GlobalValues.RandomVelocityY);

                            if (Math.Abs(randomXVel) > 0.015)
                            {
                                ;
                            }
                            if (Math.Abs(randomYVel) > .03)
                            {
                                ;
                            }

                            b.VelocityX = b.VelocityX * -1 + randomXVel;
                            b.VelocityY = b.VelocityY + randomYVel;

                            if (Math.Abs(b.VelocityX) < 0.03)
                            {
                                if (b.VelocityX < 0)
                                {
                                    b.VelocityX = -0.03;
                                    //b.VelocityX = b.VelocityX * -1;
                                }
                                else
                                {
                                    b.VelocityX = 0.03;
                                }
                            }
                            // TODO: Put direction?
                            if (Math.Abs(b.VelocityX) > 1)
                            {
                                if (b.VelocityX < 0)
                                {
                                    b.VelocityX = -1;
                                }
                                else
                                {
                                    b.VelocityX = 1;
                                }
                            }
                            if (Math.Abs(b.VelocityY) > 1)
                            {
                                if (b.VelocityY < 0)
                                {
                                    b.VelocityY = -1;
                                }
                                else
                                {
                                    b.VelocityY = 1;
                                }
                            }
                        }
                        else
                        {
                            rP.addGamesLost();
                            //rP.updateQ(b, rP.PrevAction, rP, null, GlobalValues.DiscreteBoardX, GlobalValues.DiscreteBoardY, GlobalValues.PaddleHeight, GlobalValues.LearningRate, GlobalValues.DiscountFactor, int stateReward);
                            break;
                        }
                    }
                    // Draw Board
                    DrawPong(GlobalValues.DiscreteBoardX, GlobalValues.DiscreteBoardY, null, rP, b, numGame, gameIterations);

                    rP.MoveRightPaddle(b);
                    DrawPong(GlobalValues.DiscreteBoardX, GlobalValues.DiscreteBoardY, null, rP, b, numGame, gameIterations);

                    rP.tdUpdate3(b, prevStateTuple, currentStateTuple);

                    //DrawPong(GlobalValues.DiscreteBoardX, GlobalValues.DiscreteBoardY, null, rP, b, numTrial);
                    // Add new State
                    //prevStateTuple = currentStateTuple;
                    //currentStateTuple = Tuple.Create(b.BallX, b.BallY, b.VelocityX, b.VelocityY, rP.PaddleY);
                }
                gameDeflections.Add(numGame, rP.Deflections);
                if (rP.Deflections > maxDeflections)
                {
                    maxDeflections = rP.Deflections;
                }
                Console.WriteLine("*********************************");
                Console.WriteLine("Game: " + numGame);
                Console.WriteLine("Game Length: " + gameIterations);
                Console.WriteLine("Number of deflections: " + rP.Deflections);
                Console.WriteLine("Max number of deflections: " + maxDeflections);
                double avgDeflections = (double)gameDeflections.Sum(v => v.Value) / (double)gameDeflections.Count;
                Console.WriteLine("Average number of deflections: " + avgDeflections.ToString());
                Console.WriteLine("*********************************");

                rP.Deflections = 0;
            }


            DateTime endGame = DateTime.Now;

            Console.WriteLine("*************SUMMARY:*************");
            Console.WriteLine("Games start: " + startGame);
            Console.WriteLine("Games end: " + endGame);
            Console.WriteLine("Games duration: " + (endGame - startGame));

            do
            {
                Console.WriteLine("Press p to play, 2 player");
            } while (Console.ReadKey().KeyChar != 'p');

            totalGames = 1000;
            //double learningConstant = 5;
            //double discountFactor = .9;
            maxDeflections      = 0;
            rP.GamesLost        = 0;
            rP.GamesPlayed      = 0;
            rP.Deflections      = 0;
            rP.ExplorationLimit = 1;

            Player lP = new Player(0, 0.5 - (GlobalValues.PaddleHeight / 2), learningConstant, discountFactor, Tuple.Create(initialBall.DiscreteBallX, initialBall.DiscreteBallY, initialBall.DiscreteVelocityX, initialBall.DiscreteVelocityY, (int)Math.Floor(GlobalValues.DiscreteBoardY * (0.5 - (GlobalValues.PaddleHeight / 2)) / (1 - GlobalValues.PaddleHeight))), GlobalValues.DiscreteBoardX, GlobalValues.DiscreteBoardY, explorationLimit);

            DateTime start2PlayerGame = DateTime.Now;

            for (int numGame = 0; numGame < totalGames; numGame++)
            {
                Ball b = new Ball(GlobalValues.InitialBallX, GlobalValues.InitialBallY, GlobalValues.InitialVelocityX, GlobalValues.InitialVelocityY, GlobalValues.DiscreteBoardX, GlobalValues.DiscreteBoardY, true);
                // initial state of the ball, make random velocity, ball in the middle, paddleY is in the middle
                //Ball b = new Ball(GlobalValues.InitialBallX, GlobalValues.InitialBallY, GlobalValues.InitialVelocityX + rand.NextDouble() * (GlobalValues.RandomVelocityX - (-1 * GlobalValues.RandomVelocityX)) + (-1 * GlobalValues.RandomVelocityX), rand.NextDouble() * (GlobalValues.RandomVelocityY - (-1 * GlobalValues.RandomVelocityY)) + (-1 * GlobalValues.RandomVelocityY), GlobalValues.DiscreteBoardX, GlobalValues.DiscreteBoardY, true);
                rP.PaddleY         = 0.5 - (GlobalValues.PaddleHeight / 2);
                rP.DiscretePaddleY = rP.getDiscretePaddleY();
                rP.PrevAction      = "N/A";

                lP.PaddleY         = 0.5 - (GlobalValues.PaddleHeight / 2);
                lP.DiscretePaddleY = lP.getDiscretePaddleY();
                lP.PrevAction      = "N/A";

                var currentStateTuple    = Tuple.Create(b.BallX, b.BallY, b.VelocityX, b.VelocityY, rP.PaddleY);
                var currentDiscreteTuple = Tuple.Create(b.DiscreteBallX, b.DiscreteBallY, b.DiscreteVelocityX, b.DiscreteVelocityY, rP.DiscretePaddleY);
                var prevStateTuple       = Tuple.Create(b.BallX, b.BallY, b.VelocityX, b.VelocityY, rP.PaddleY);

                // Epsiode/Trial Loop
                int gameIterations = 0;
                rP.addGamesPlayed();
                while (true)
                {
                    gameIterations++;

                    prevStateTuple = currentStateTuple;
                    b.MoveBall();
                    currentStateTuple = Tuple.Create(b.BallX, b.BallY, b.VelocityX, b.VelocityY, rP.PaddleY);

                    DrawPong(GlobalValues.DiscreteBoardX, GlobalValues.DiscreteBoardY, lP, rP, b, numGame, gameIterations);

                    if (goalState(currentStateTuple, rP, lP))
                    {
                        if (deflectionDetected(currentStateTuple, prevStateTuple, rP, lP, b))
                        {
                            if (b.BallX < 0.5 * boardX)
                            {
                                b.BallX = 2 * lP.PaddleX - b.BallX;
                            }
                            else
                            {
                                b.BallX = 2 * rP.PaddleX - b.BallX;
                            }
                            double randomXVel = rand.NextDouble() * (GlobalValues.RandomVelocityX - (-1 * GlobalValues.RandomVelocityX)) + (-1 * GlobalValues.RandomVelocityX);
                            double randomYVel = rand.NextDouble() * (GlobalValues.RandomVelocityY - (-1 * GlobalValues.RandomVelocityY)) + (-1 * GlobalValues.RandomVelocityY);

                            if (Math.Abs(randomXVel) > 0.015)
                            {
                                ;
                            }
                            if (Math.Abs(randomYVel) > .03)
                            {
                                ;
                            }

                            b.VelocityX = b.VelocityX * -1 + randomXVel;
                            b.VelocityY = b.VelocityY + randomYVel;

                            if (Math.Abs(b.VelocityX) < 0.03)
                            {
                                if (b.VelocityX < 0)
                                {
                                    b.VelocityX = -0.03;
                                    //b.VelocityX = b.VelocityX * -1;
                                }
                                else
                                {
                                    b.VelocityX = 0.03;
                                }
                            }
                            // TODO: Put direction?
                            if (Math.Abs(b.VelocityX) > 1)
                            {
                                if (b.VelocityX < 0)
                                {
                                    b.VelocityX = -1;
                                }
                                else
                                {
                                    b.VelocityX = 1;
                                }
                            }
                            if (Math.Abs(b.VelocityY) > 1)
                            {
                                if (b.VelocityY < 0)
                                {
                                    b.VelocityY = -1;
                                }
                                else
                                {
                                    b.VelocityY = 1;
                                }
                            }
                        }
                        else
                        {
                            // Who lost?
                            if (currentStateTuple.Item1 >= rP.PaddleX)
                            {
                                rP.addGamesLost();
                            }
                            if (currentStateTuple.Item1 <= lP.PaddleX)
                            {
                                lP.addGamesLost();
                            }
                            //rP.updateQ(b, rP.PrevAction, rP, null, GlobalValues.DiscreteBoardX, GlobalValues.DiscreteBoardY, GlobalValues.PaddleHeight, GlobalValues.LearningRate, GlobalValues.DiscountFactor, int stateReward);
                            break;
                        }
                    }
                    // Draw Board
                    DrawPong(GlobalValues.DiscreteBoardX, GlobalValues.DiscreteBoardY, lP, rP, b, numGame, gameIterations);

                    rP.MoveRightPaddle(b);
                    lP.MoveLeftPaddle(b);

                    DrawPong(GlobalValues.DiscreteBoardX, GlobalValues.DiscreteBoardY, lP, rP, b, numGame, gameIterations);

                    rP.tdUpdate3(b, prevStateTuple, currentStateTuple);
                }

                Console.WriteLine("*********************************");
                Console.WriteLine("Game: " + numGame);
                Console.WriteLine("Game Length: " + gameIterations);
                Console.WriteLine("Number of deflections for right player: " + rP.Deflections);
                Console.WriteLine("Number of deflections for left player: " + (lP.Deflections));
                Console.WriteLine("*********************************");

                rP.Deflections = 0;
            }


            DateTime end2PlayerGame = DateTime.Now;

            Console.WriteLine("*************SUMMARY:*************");
            Console.WriteLine("Games start: " + start2PlayerGame);
            Console.WriteLine("Games end: " + end2PlayerGame);
            Console.WriteLine("Games won by agent: " + (rP.GamesPlayed - rP.GamesLost));
            Console.WriteLine("Winning Percentage of agent: " + (double)(rP.GamesPlayed - rP.GamesLost) / rP.GamesPlayed);
            Console.WriteLine("Games duration: " + (end2PlayerGame - start2PlayerGame));

            do
            {
                Console.WriteLine("Press q to quit");
            } while (Console.ReadKey().KeyChar != 'q');
        }
Пример #49
0
        /// <summary>
        /// Porovnanim (pres CRC) souboru z lokalniho disku a souboru z Flickeru dohleda nove soubory na lokalu
        ///
        /// + kvulu rychlosti rovnou dohledam i seznam souboru, ktere patri k Photo instancim, ktere j*z na Flickru jsou, ale nejsou zarazeny do Photoseto
        /// (coz obvykle nastane prerusenim prenosu mezi uploadem fotky a zarazeni do setu)
        /// </summary>
        /// <param name="sourcePaths">seznam zdrojovych adresaru ze soubory</param>
        /// <param name="flupFlickrPhotos">seznam FLUP souboru z Flickeru</param>
        /// <returns></returns>
        private void FindNewLocalFiles(Dictionary <DirectoryInfo, List <FileInfo> > sourcePaths,
                                       List <Photo> flupFlickrPhotos,
                                       List <Photo> photosWithoutSet,
                                       out List <PathWithFlickrFiles> newLocalFiles,
                                       out List <PathWithFlickrFiles> filesWithoutSet)
        {
            _logger.Write("Looking for new local files...");

            var flupFlickrPhotosCrcSet = GetNumericCRC(flupFlickrPhotos);
            var photosWithoutSetCrcSet = GetNumericCRC(photosWithoutSet);

            var startTime      = DateTime.Now;
            var filesTotal     = sourcePaths.Sum(p => p.Value.Count);
            var filesProcessed = 0;
            var bytesTotal     = sourcePaths.Sum(p => p.Value.Sum(f => f.Length));
            var bytesProcessed = 0L;

            newLocalFiles   = new List <PathWithFlickrFiles>();
            filesWithoutSet = new List <PathWithFlickrFiles>();

            foreach (var sourcePath in sourcePaths)
            {
                // ze souboru v directory zalozim set File4Flickr se spoctenym CRC - paralelne to je o dost rychlejsi
                var f4fSet = sourcePath.Value.AsParallel()
                             .Select(fileInfo => new File4Flickr(fileInfo, _ini.SourcePath, _ini.NumberOfBytesForCRC).PrepareCrc())
                             .ToList();

                var newInPath  = new List <File4Flickr>();
                var withoutSet = new List <File4Flickr>();
                foreach (var f4f in f4fSet)
                {
                    // uz existuje na flickru? (poznam pres tag FLUPCRCxxxxx u fotky)
                    var crcExistsOnFlickr = flupFlickrPhotosCrcSet.Contains(f4f.Crc);
                    if (crcExistsOnFlickr)
                    {
                        var withoutPhotoset = photosWithoutSetCrcSet.Contains(f4f.Crc);
                        if (withoutPhotoset)
                        {
                            withoutSet.Add(f4f); // soubor/photo j*z na flickeru je, neni vsak v zadnem photosetu
                        }
                    }
                    else
                    {
                        newInPath.Add(f4f); // jeste na flickru neexistuje
                    }
                }
                // nejake nove soubory v adresari?
                if (newInPath.Any())
                {
                    var directoryWithPhotos = new PathWithFlickrFiles(sourcePath.Key, newInPath);
                    newLocalFiles.Add(directoryWithPhotos);
                }
                // nejake soubory/photo bez photosetu?
                if (withoutSet.Any())
                {
                    var unassignedPhotos = new PathWithFlickrFiles(sourcePath.Key, withoutSet);
                    filesWithoutSet.Add(unassignedPhotos);
                }

                bytesProcessed += f4fSet.Sum(p => p.Length);
                filesProcessed += f4fSet.Count;
                GetNewLocalFilesPrintProgress(startTime, filesTotal, filesProcessed, bytesTotal, bytesProcessed);
            }

            GetNewLocalFilesPrintFinalMessage(newLocalFiles);
        }
Пример #50
0
        public async Task WoodcuttingLevel()
        {
            //Okay let's get the User
            Woodcutting wc;

            using (var uow = DBHandler.UnitOfWork())
            {
                wc = uow.Woodcutting.GetOrCreateWoodcutting(Context.User.Id);
            }

            //New list of stuff
            Dictionary <string, int> CutLogs = new Dictionary <string, int>()
            {
                { "Achey", wc.AcheyTrees },
                { "Arctic Pine", wc.ArcticTrees },
                { "Hollow", wc.HollowTrees },
                { "Magic", wc.MagicTrees },
                { "Mahogany", wc.MahoganyTrees },
                { "Maple", wc.MapleTrees },
                { "Normal", wc.NormalTrees },
                { "Oak", wc.OakTrees },
                { "Redwood", wc.RedwoodTrees },
                { "Sulliuscep", wc.SullTrees },
                { "Teak", wc.TeakTrees },
                { "Yew", wc.YewTrees }
            };

            //List sorted
            List <KeyValuePair <string, int> > logList = CutLogs.ToList();

            logList = logList.OrderByDescending(x => x.Value).ToList();

            //What's their axe level
            string axetype = "";

            foreach (int key in AxeLevel.Keys)
            {
                if (axetype != "")
                {
                    break;
                }
                else if (wc.Level >= key)
                {
                    axetype = AxeLevel[key];
                }
            }

            EmbedBuilder emb = new EmbedBuilder().WithTitle($"Wooductting XP | User: {Context.User.Username}").WithOkColour().WithDescription($"Level: {wc.Level} | Total XP: {wc.XP} | Axe Type: {axetype}");

            EmbedFieldBuilder embF = new EmbedFieldBuilder().WithName("Amount of Logs Chopped");

            string str = "";

            foreach (KeyValuePair <string, int> Tree in logList)
            {
                str += $"{Tree.Key} trees: {Tree.Value}\n";
            }

            str += $"\nTotal Logs: {CutLogs.Sum(x => x.Value)}";

            embF = embF.WithValue(str);

            //Add to emb
            Embed embdone = emb.AddField(embF).Build();

            //Send
            await Context.Channel.BlankEmbedAsync(embdone);
        }
Пример #51
0
        private void formLists(string groupName)
        {
            this.lastColored = -1;

            Table.Controls.Clear();

            List <ObjBelbinResults> list = ObjBelbinResults.getList(groupName).OrderBy(t => t.roles == null).ToList();

            for (int i = 0; i < list.Count; i++)
            {
                ObjBelbinResults obj = list[i];

                string name = obj.name;

                string role1 = string.Empty;
                string role2 = string.Empty;
                string role3 = string.Empty;
                string role4 = string.Empty;
                string role5 = string.Empty;
                string role6 = string.Empty;
                string role7 = string.Empty;
                string role8 = string.Empty;

                if (obj.roles != null)
                {
                    Dictionary <string, int> roles = obj.roles;

                    int sum = roles.Sum(t => t.Value);

                    role1 = $"{Math.Round(double.Parse(roles["Генератор идей"].ToString()) / sum, 4) * 100}%";
                    role2 = $"{Math.Round(double.Parse(roles["Коллективист"].ToString()) / sum, 4) * 100}%";
                    role3 = $"{Math.Round(double.Parse(roles["Оценщик"].ToString()) / sum, 4) * 100}%";
                    role4 = $"{Math.Round(double.Parse(roles["Реализатор"].ToString()) / sum, 4) * 100}%";
                    role5 = $"{Math.Round(double.Parse(roles["Исполнитель"].ToString()) / sum, 4) * 100}%";
                    role6 = $"{Math.Round(double.Parse(roles["Координатор"].ToString()) / sum, 4) * 100}%";
                    role7 = $"{Math.Round(double.Parse(roles["Исследователь"].ToString()) / sum, 4) * 100}%";
                    role8 = $"{Math.Round(double.Parse(roles["Творец"].ToString()) / sum, 4) * 100}%";

                    var sorted = from t in roles orderby t.Value descending select t;

                    int sec1 = roles["Генератор идей"] + roles["Коллективист"] + roles["Оценщик"];
                    int sec2 = roles["Реализатор"] + roles["Исполнитель"];
                    int sec3 = roles["Координатор"] + roles["Исследователь"] + roles["Творец"];

                    int max = (new int[] { sec1, sec2, sec3 }).Max();

                    Utils.fillRow(

                        Table,
                        new Control[]
                    {
                        Utils.buildLabel(name),
                        Utils.buildLabel(role1, getColor(sec1, max, 1)),
                        Utils.buildLabel(role2, getColor(sec1, max, 1)),
                        Utils.buildLabel(role3, getColor(sec1, max, 1)),
                        Utils.buildLabel(role4, getColor(sec2, max, 2)),
                        Utils.buildLabel(role5, getColor(sec2, max, 2)),
                        Utils.buildLabel(role6, getColor(sec3, max, 3)),
                        Utils.buildLabel(role7, getColor(sec3, max, 3)),
                        Utils.buildLabel(role8, getColor(sec3, max, 3))
                    },
                        i

                        );

                    this.lastColored = -1;

                    continue;
                }


                Utils.fillRow(

                    Table,
                    new Control[]
                {
                    Utils.buildLabel(name),
                    Utils.buildLabel(role1, Color.Tomato),
                    Utils.buildLabel(role2, Color.Tomato),
                    Utils.buildLabel(role3, Color.Tomato),
                    Utils.buildLabel(role4, Color.Tomato),
                    Utils.buildLabel(role5, Color.Tomato),
                    Utils.buildLabel(role6, Color.Tomato),
                    Utils.buildLabel(role7, Color.Tomato),
                    Utils.buildLabel(role8, Color.Tomato)
                },
                    i

                    );
            }
        }
Пример #52
0
        object PartTwo(string input)
        {
            var   lines  = input.Lines();
            ulong zeroes = ulong.MaxValue;
            ulong ones   = ulong.MinValue;

            int[] unknownBits = new int[0];
            var   memory      = new Dictionary <ulong, ulong>();
            var   maskMatcher = new Regex(@"^mask = ([01X]{36})$");
            var   memMatcher  = new Regex(@"^mem\[(\d+)\] = (\d+)$");

            foreach (var l in lines)
            {
                if (maskMatcher.IsMatch(l))
                {
                    var m = maskMatcher.Match(l).Groups[1].Value;

                    var zeroString = m.Replace('X', '1');
                    zeroes = Convert.ToUInt64(zeroString, 2);
                    var oneString = m.Replace('X', '0');
                    ones = Convert.ToUInt64(oneString, 2);
                    var bit = 0;
                    var set = new HashSet <int>();
                    foreach (var c in m.Reverse())
                    {
                        if (c == 'X')
                        {
                            set.Add(bit);
                        }
                        bit++;
                    }
                    unknownBits = set.ToArray();
                }
                else if (memMatcher.IsMatch(l))
                {
                    var match   = memMatcher.Match(l);
                    var address = ulong.Parse(match.Groups[1].Value);
                    var value   = ulong.Parse(match.Groups[2].Value);

                    // Apply the masks to the address.
                    address = address | ones;

                    IEnumerable <ulong> Permutations(int[] unknowns, ulong address)
                    {
                        if (unknowns.Length == 0)
                        {
                            yield break;
                        }

                        var bit = unknowns[0];
                        var lowerPermutations = Permutations(unknowns.Skip(1).ToArray(), address);

                        foreach (var a in lowerPermutations)
                        {
                            // Turn this bit to 0
                            yield return(a & ~(1UL << bit));

                            // Turn this bit to 1
                            yield return(a | 1UL << bit);
                        }

                        yield return(address & ~(1UL << bit));

                        yield return(address | 1UL << bit);
                    }

                    var addressPermutations = Permutations(unknownBits.ToArray(), address).Distinct().ToArray();
                    foreach (var a in addressPermutations)
                    {
                        memory[a] = value;
                    }
                }
                else
                {
                    throw new Exception("Unexpected input");
                }
            }

            return(memory.Sum(kvp => (decimal)kvp.Value));
        }
Пример #53
0
        static void Main(string[] args)
        {
            string data = File.ReadAllText("data.txt", Encoding.GetEncoding("iso-8859-9"));

            string[] splitted = data.Split(' ');
            for (int i = 0; i < splitted.Length; i++)
            {
                splitted[i] = WordNormalizer(splitted[i]);       //.Trim(',', ' ', '-', ';', ':', '(', ')').ToLower(); silmeye kıyamadım gereksiz aslında burdaki yorum satırında yazan kodlar
            }
            Dictionary <string, int> returnValue = new Dictionary <string, int>();

            for (int i = 0; i < splitted.Length; i++)
            {
                MyDictionaryAdd(returnValue, splitted[i]);
            }
            returnValue = returnValue.OrderBy(i => i.Key).ToDictionary(mc => mc.Key, mc => mc.Value);

            string[] content = new string[returnValue.Count + 1];
            for (int i = 0; i < returnValue.Count; i++)
            {
                content[i] = returnValue.ElementAt(i).Key + " " + returnValue.ElementAt(i).Value;
            }
            content[returnValue.Count] = string.Format("{0} {1} {2} {3}", "total word count=", returnValue.Sum(item => item.Value), "total distinct word count", returnValue.Count);

            File.WriteAllLines("log.txt", content);
        }
Пример #54
0
 public int GetCount(bool onlyCurrentCoord = true)
 {
     return(onlyCurrentCoord ? GetCurrentOverlayTextures().Count : _allOverlayTextures.Sum(x => x.Value.Count));
 }
Пример #55
0
 public int GetPointsLeft()
 {
     return(costs.Sum(p => Math.Max(0, p.Value - Player.me.expertises[p.Key])));
 }
Пример #56
0
        private void BackgroundSqlReplication()
        {
            int workCounter = 0;

            while (Database.WorkContext.DoWork)
            {
                IsRunning = !IsHotSpare() && !shouldPause;

                if (!IsRunning)
                {
                    Database.WorkContext.WaitForWork(TimeSpan.FromMinutes(10), ref workCounter, "Sql Replication");

                    continue;
                }

                var config = GetConfiguredReplicationDestinations();
                if (config.Count == 0)
                {
                    Database.WorkContext.WaitForWork(TimeSpan.FromMinutes(10), ref workCounter, "Sql Replication");
                    continue;
                }
                var localReplicationStatus = GetReplicationStatus();

                // remove all last replicated statuses which are not in the config
                UpdateLastReplicatedStatus(localReplicationStatus, config);

                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.SuspendUntil);
                }) // have error or the timeout expired
                                      .ToList();

                var configGroups = SqlReplicationClassifier.GroupConfigs(relevantConfigs, c => GetLastEtagFor(localReplicationStatus, c));

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

                var usedPrefetchers = new ConcurrentSet <PrefetchingBehavior>();

                var groupedConfigs = configGroups
                                     .Select(x =>
                {
                    var result = new SqlConfigGroup
                    {
                        LastReplicatedEtag = x.Key,
                        ConfigsToWorkOn    = x.Value
                    };

                    SetPrefetcherForIndexingGroup(result, usedPrefetchers);

                    return(result);
                })
                                     .ToList();

                var successes   = new ConcurrentQueue <Tuple <SqlReplicationConfigWithLastReplicatedEtag, Etag> >();
                var waitForWork = new bool[groupedConfigs.Count];
                try
                {
                    BackgroundTaskExecuter.Instance.ExecuteAll(Database.WorkContext, groupedConfigs, (sqlConfigGroup, i) =>
                    {
                        Database.WorkContext.CancellationToken.ThrowIfCancellationRequested();

                        var prefetchingBehavior = sqlConfigGroup.PrefetchingBehavior;
                        var configsToWorkOn     = sqlConfigGroup.ConfigsToWorkOn;

                        List <JsonDocument> documents;
                        using (prefetchingBehavior.DocumentBatchFrom(sqlConfigGroup.LastReplicatedEtag, changesBatchSize, out documents))
                        {
                            Etag latestEtag = null, lastBatchEtag = null;
                            if (documents.Count != 0)
                            {
                                lastBatchEtag = documents[documents.Count - 1].Etag;
                            }

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

                            if (documents.Count != 0)
                            {
                                latestEtag = documents[documents.Count - 1].Etag;
                            }

                            documents.RemoveAll(x => prefetchingBehavior.FilterDocuments(x) == false);

                            var deletedDocsByConfig = new Dictionary <SqlReplicationConfig, List <ListItem> >();

                            foreach (var configToWorkOn in configsToWorkOn)
                            {
                                var cfg = configToWorkOn;

                                Database.TransactionalStorage.Batch(accessor =>
                                {
                                    deletedDocsByConfig[cfg] = accessor.Lists.Read(GetSqlReplicationDeletionName(cfg),
                                                                                   cfg.LastReplicatedEtag,
                                                                                   latestEtag,
                                                                                   MaxNumberOfDeletionsToReplicate + 1)
                                                               .ToList();
                                });
                            }

                            // No documents AND there aren't any deletes to replicate
                            if (documents.Count == 0 && deletedDocsByConfig.Sum(x => x.Value.Count) == 0)
                            {
                                // so we filtered some documents, let us update the etag about that.
                                if (latestEtag != null)
                                {
                                    foreach (var configToWorkOn in configsToWorkOn)
                                    {
                                        successes.Enqueue(Tuple.Create(configToWorkOn, latestEtag));
                                    }
                                }
                                else
                                {
                                    waitForWork[i] = true;
                                }

                                return;
                            }

                            var itemsToReplicate = documents.Select(x =>
                            {
                                JsonDocument.EnsureIdInMetadata(x);
                                var doc = x.ToJson();
                                doc[Constants.DocumentIdFieldName] = x.Key;

                                return(new ReplicatedDoc
                                {
                                    Document = doc,
                                    Etag = x.Etag,
                                    Key = x.Key,
                                    SerializedSizeOnDisk = x.SerializedSizeOnDisk
                                });
                            }).ToList();

                            try
                            {
                                BackgroundTaskExecuter.Instance.ExecuteAllInterleaved(Database.WorkContext, configsToWorkOn, replicationConfig =>
                                {
                                    try
                                    {
                                        var startTime = SystemTime.UtcNow;
                                        var spRepTime = new Stopwatch();
                                        spRepTime.Start();
                                        var lastReplicatedEtag = replicationConfig.LastReplicatedEtag;

                                        var deletedDocs     = deletedDocsByConfig[replicationConfig];
                                        var docsToReplicate = itemsToReplicate
                                                              .Where(x => lastReplicatedEtag.CompareTo(x.Etag) < 0); // haven't replicate the etag yet

                                        if (deletedDocs.Count >= MaxNumberOfDeletionsToReplicate + 1)
                                        {
                                            docsToReplicate = docsToReplicate.Where(x => EtagUtil.IsGreaterThan(x.Etag, deletedDocs[deletedDocs.Count - 1].Etag) == false);
                                        }

                                        var docsToReplicateAsList = docsToReplicate.ToList();

                                        var currentLatestEtag = HandleDeletesAndChangesMerging(deletedDocs, docsToReplicateAsList);
                                        if (currentLatestEtag == null && itemsToReplicate.Count > 0 && docsToReplicateAsList.Count == 0)
                                        {
                                            currentLatestEtag = lastBatchEtag;
                                        }

                                        int countOfReplicatedItems = 0;
                                        if (ReplicateDeletionsToDestination(replicationConfig, deletedDocs) &&
                                            ReplicateChangesToDestination(replicationConfig, docsToReplicateAsList, out countOfReplicatedItems))
                                        {
                                            if (deletedDocs.Count > 0)
                                            {
                                                Database.TransactionalStorage.Batch(accessor =>
                                                                                    accessor.Lists.RemoveAllBefore(GetSqlReplicationDeletionName(replicationConfig), deletedDocs[deletedDocs.Count - 1].Etag));
                                            }
                                            successes.Enqueue(Tuple.Create(replicationConfig, currentLatestEtag));

                                            changesBatchSize = Math.Min(changesBatchSize * 2, MaxBatchSizeToReturnToNormal);

                                            //if we successfully replicated multiple times, return to normal batch size
                                            if (changesBatchSize >= MaxBatchSizeToReturnToNormal)
                                            {
                                                changesBatchSize = MaxNumberOfChangesToReplicate;
                                            }
                                        }
                                        else
                                        {
                                            changesBatchSize = 1; //failed replicating deletes or changes, so next time try small batch
                                        }

                                        spRepTime.Stop();
                                        var elapsedMicroseconds = (long)(spRepTime.ElapsedTicks * SystemTime.MicroSecPerTick);

                                        var sqlReplicationMetricsCounters = GetSqlReplicationMetricsManager(replicationConfig);
                                        sqlReplicationMetricsCounters.SqlReplicationBatchSizeMeter.Mark(countOfReplicatedItems);
                                        sqlReplicationMetricsCounters.SqlReplicationBatchSizeHistogram.Update(countOfReplicatedItems);
                                        sqlReplicationMetricsCounters.SqlReplicationDurationHistogram.Update(elapsedMicroseconds);

                                        UpdateReplicationPerformance(replicationConfig, startTime, spRepTime.Elapsed, docsToReplicateAsList.Count);
                                    }
                                    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
                                        });
                                        changesBatchSize = 1;
                                    }
                                });
                            }
                            finally
                            {
                                prefetchingBehavior.CleanupDocuments(lastBatchEtag);
                                prefetchingBehavior.UpdateAutoThrottler(documents, replicationDuration.Elapsed);
                            }
                        }
                    });

                    if (successes.Count == 0)
                    {
                        if (waitForWork.All(x => x))
                        {
                            Database.WorkContext.WaitForWork(TimeSpan.FromMinutes(10), ref workCounter, "Sql Replication");
                        }

                        continue;
                    }

                    foreach (var t in successes)
                    {
                        var cfg = t.Item1;
                        var currentLatestEtag = t.Item2;
                        //If a reset was requested we don't want to update the last replicated etag.
                        //If we do register the success the reset will become a noop.
                        bool isReset;
                        if (ResetRequested.TryGetValue(t.Item1.Name, out isReset) && isReset)
                        {
                            continue;
                        }

                        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 = currentLatestEtag ?? Etag.Empty
                            });
                        }
                        else
                        {
                            var lastDocEtag = destEtag.LastDocEtag;
                            if (currentLatestEtag != null && EtagUtil.IsGreaterThan(currentLatestEtag, lastDocEtag))
                            {
                                lastDocEtag = currentLatestEtag;
                            }

                            destEtag.LastDocEtag = lastDocEtag;
                        }
                    }
                    //We are done recording success for this batch so we can clear the reset dictionary
                    ResetRequested.Clear();
                    SaveNewReplicationStatus(localReplicationStatus);
                }
                finally
                {
                    AfterReplicationCompleted(successes.Count);
                    RemoveUnusedPrefetchers(usedPrefetchers);
                }
            }
        }
Пример #57
0
 public int Count()
 {
     return(inventory.Sum(s => s.Value));;
 }
Пример #58
0
            // Generates the system prefab from the configuration
            void IParserEventSubscriber.PostApply(ConfigNode node)
            {
                //Set of items seen while loading, to prevent duplicate loggers being created (throws IOExceptions)
                HashSet <String> seen = new HashSet <String>();

                // Dictionary of bodies generated
                Dictionary <String, Body> bodies = new Dictionary <String, Body>();

                Logger logger = new Logger();

                // Load all of the bodies
                foreach (ConfigNode bodyNode in node.GetNodes(bodyNodeName))
                {
                    if (seen.Contains(bodyNode.GetValue("name")))
                    {
                        Logger.Default.Log("[Kopernicus::PostApply] Skipped duplicate body " + bodyNode.GetValue("name"));
                        continue; //next body, please
                    }
                    else
                    {
                        seen.Add(bodyNode.GetValue("name"));
                    }

                    try
                    {
                        // Create a logfile for this body
                        logger.SetFilename(bodyNode.GetValue("name") + ".Body");
                        logger.SetAsActive();

                        // Attempt to create the body
                        currentBody = new Body();
                        Parser.LoadObjectFromConfigurationNode(currentBody, bodyNode, "Kopernicus"); //logs to active logger
                        bodies.Add(currentBody.name, currentBody);
                        Events.OnLoaderLoadBody.Fire(currentBody, bodyNode);
                        Logger.Default.Log("[Kopernicus]: Configuration.Loader: Loaded Body: " + currentBody.name);

                        // Restore default logger
                        Logger.Default.SetAsActive();
                        logger.Close(); //implicit flush
                    }
                    catch (Exception e)
                    {
                        logger.LogException(e);
                        logger.Close(); //implicit flush
                        Logger.Default.Log("[Kopernicus]: Configuration.Loader: Failed to load Body: " + bodyNode.GetValue("name") + ": " + e.Message);
                        throw new Exception("Failed to load Body: " + bodyNode.GetValue("name"));
                    }
                }
                seen.Clear();

                // Event
                Events.OnLoaderLoadedAllBodies.Fire(this, node);

                // Load all of the asteroids
                foreach (ConfigNode asteroidNode in node.GetNodes(asteroidNodeName))
                {
                    if (seen.Contains(asteroidNode.GetValue("name")))
                    {
                        Logger.Default.Log("[Kopernicus::PostApply] Skipped duplicate asteroid " + asteroidNode.GetValue("name"));
                        continue; //next roid, please
                    }
                    else
                    {
                        seen.Add(asteroidNode.GetValue("name"));
                    }
                    try
                    {
                        // Create a logfile for this asteroid
                        logger.SetFilename(asteroidNode.GetValue("name") + ".Asteroid");
                        logger.SetAsActive();

                        // Attempt to create the Asteroid
                        Asteroid asteroid = Parser.CreateObjectFromConfigNode <Asteroid>(asteroidNode, "Kopernicus"); //logs to active logger
                        DiscoverableObjects.asteroids.Add(asteroid);
                        Events.OnLoaderLoadAsteroid.Fire(asteroid, asteroidNode);
                        Logger.Default.Log("[Kopernicus]: Configuration.Loader: Loaded Asteroid: " + asteroid.name);

                        // Restore default logger
                        Logger.Default.SetAsActive();
                        logger.Close(); //implicit flush
                    }
                    catch (Exception e)
                    {
                        Logger.Default.Log("[Kopernicus]: Configuration.Loader: Failed to load Asteroid: " + asteroidNode.GetValue("name") + ": " + e.Message);
                        logger.LogException(e);
                        logger.Close();
                        throw new Exception("Failed to load Asteroid: " + asteroidNode.GetValue("name"));
                    }
                }
                seen.Clear();
                logger.Close();
                logger = null;

                // Load all of the PQS Presets
                foreach (ConfigNode presetNode in node.GetNodes(presetNodeName))
                {
                    // Attempt to create the Preset
                    try
                    {
                        PQSCache.PQSPreset preset = new PQSCache.PQSPreset();
                        preset.Load(presetNode);
                        if (PQSCache.PresetList.presets.Any(p => p.name == preset.name))
                        {
                            Logger.Default.Log("[Kopernicus]: Configuration.Loader: Failed to load Preset: " + preset.name);
                            continue;
                        }
                        PQSCache.PresetList.presets.Add(preset);

                        // Display name
                        String displayName = preset.name;
                        if (presetNode.HasValue("displayName"))
                        {
                            displayName = presetNode.GetValue("displayName");
                        }
                        Templates.PresetDisplayNames.Add(displayName);
                        Logger.Default.Log("[Kopernicus]: Configuration.Loader: Loaded Preset: " + preset.name);
                    }
                    catch
                    {
                        Logger.Default.Log("[Kopernicus]: Configuration.Loader: Failed to load Preset: " + presetNode.GetValue("name"));
                        throw new Exception("Failed to load Asteroid: " + presetNode.GetValue("name"));
                    }
                }

                // Register UBIs for all bodies
                CelestialBody[] localBodies = bodies.Values.Select(b => b.generatedBody.celestialBody).ToArray();
                foreach (KeyValuePair <String, Body> body in bodies)
                {
                    // Register the primary UBI
                    if (!String.IsNullOrEmpty(body.Value.identifier))
                    {
                        UBI.RegisterUBI(body.Value.celestialBody, body.Value.identifier, localBodies: localBodies);
                    }

                    // Register all implemented UBIs
                    foreach (String ubi in body.Value.implements.SelectMany(u => u.Value).Distinct())
                    {
                        if (!String.IsNullOrEmpty(ubi))
                        {
                            UBI.RegisterUBI(body.Value.celestialBody, ubi, isAbstract: true, localBodies: localBodies);
                        }
                    }
                }

                // Glue all the orbits together in the defined pattern
                foreach (KeyValuePair <String, Body> body in bodies)
                {
                    // If this body is in orbit around another body
                    if (body.Value.orbit != null)
                    {
                        // Convert a UBI reference into a normal one
                        String referenceBody = UBI.GetName(body.Value.orbit.referenceBody, localBodies: localBodies);

                        // Get the Body object for the reference body
                        if (!bodies.TryGetValue(referenceBody, out Body parent))
                        {
                            throw new Exception("Reference body for \"" + body.Key + "\" could not be found. Missing body name is \"" + body.Value.orbit.referenceBody + "\".");
                        }

                        // Setup the orbit of the body
                        parent.generatedBody.children.Add(body.Value.generatedBody);
                        body.Value.generatedBody.orbitDriver.referenceBody       = parent.generatedBody.celestialBody;
                        body.Value.generatedBody.orbitDriver.orbit.referenceBody = parent.generatedBody.celestialBody;
                    }

                    // Parent the generated body to the PSystem
                    body.Value.generatedBody.transform.parent = systemPrefab.transform;

                    // Delete ghost space centers
                    if (!body.Value.generatedBody.celestialBody.isHomeWorld && body.Value.generatedBody.pqsVersion != null)
                    {
                        SpaceCenter[] centers = body.Value.generatedBody.pqsVersion.GetComponentsInChildren <SpaceCenter>(true);
                        if (centers != null)
                        {
                            foreach (SpaceCenter c in centers)
                            {
                                UnityEngine.Object.Destroy(c);
                            }
                        }
                    }

                    // Event
                    Events.OnLoaderFinalizeBody.Fire(body.Value);
                }

                // Elect root body
                systemPrefab.rootBody = bodies.First(p => p.Value.orbit == null).Value.generatedBody;

                // Try to find a home world
                Body home = bodies.Values.FirstOrDefault(p => p.generatedBody.celestialBody.isHomeWorld);

                if (home == null)
                {
                    throw new Exception("Homeworld body could not be found.");
                }

                // Sort by distance from parent (discover how this effects local bodies)
                RecursivelySortBodies(systemPrefab.rootBody);

                // Fix doubled flightGlobals
                List <Int32> numbers = new List <Int32>()
                {
                    0, 1
                };
                Int32 index = bodies.Sum(b => b.Value.generatedBody.flightGlobalsIndex);

                PatchFGI(ref numbers, ref index, systemPrefab.rootBody);

                // We're done
                currentBody.generatedBody = null;

                // Event
                Events.OnLoaderPostApply.Fire(this, node);
            }
Пример #59
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);
				}
			}
		}
Пример #60
0
        /// <summary>
        /// Gets the ratio, as a decimal, of the moles for the given gas in the atmospheric average.
        /// </summary>
        /// <returns>(decimal) moles ratio</returns>
        public float GetGasRatio(GasSO gas)
        {
            var sum = gasMolesSum.Sum(kvp => kvp.Value);

            return(sum == 0 ? 0 : gasMolesSum[gas] / sum);
        }