public async Task <IActionResult> ShowLeagueStats(int TipTypeId, int LeagueId)
        {
            decimal TotalPlayed = await leagueRepository.GetLeagueTotalPlayed(LeagueId, TipTypeId);

            decimal Wins = await leagueRepository.GetLeagueWins(LeagueId, TipTypeId);

            decimal Odds = await leagueRepository.GetLeagueAverageOdds(LeagueId, TipTypeId);

            decimal Percentage = PercentageCalculator.CalculatePercentage(TotalPlayed, Wins);
            decimal Roi        = PercentageCalculator.CalculateRoi(TotalPlayed, Wins, Odds);

            LeagueViewModel lVM = new LeagueViewModel {
                LeagueTotalPlayed = TotalPlayed,
                LeagueWins        = Wins,
                LeaguePercentage  = Percentage,
                LeagueAverageOdds = Odds,
                LeagueRoi         = Roi,
                League            = await leagueRepository.GetLeagueByIdAsync(LeagueId),
                Predictions       = await leagueRepository.GetPredictionsByLeagueAndTipType(LeagueId, TipTypeId),
                TipStats          = await repository.GetTipStatsByLeague(TipTypeId, LeagueId),
                ControllerName    = "Statistics",
                TipTypeId         = TipTypeId
            };

            ViewData["TipTypeId"] = TipTypeId;
            return(View("League", lVM));
        }
示例#2
0
        private async void InternalFetch()
        {
            // enumerate
            UpdateUi(UiState.Working);
            var paths = Model.DataView.Where(x => !Commons.IsMovieFetched(x.TmdbId))
                        .Select(x => x.FullPath)
                        .ToList();
            var calc = new PercentageCalculator(paths.Count);

            // walk
            foreach (var path in paths)
            {
                try
                {
                    var data = await HelperFetch(path);

                    Model.Invoke(() => Model.DataView.SwapItem(x => x.FullPath == path, data));
                }
                catch (Exception e)
                {
                    Debug.Print("Fetch error: {0}. {1}", path, e.Message);
                }

                UpdateUi(UiState.StatusUpdate, calc.Increment());
                if (IsCancellationRequested)
                {
                    break;
                }
            }

            // update
            UpdateUi(UiState.Ready);
        }
        public async Task <IActionResult> ShowTipsByLeagueAndTip(int TipTypeId, int TipId, int LeagueId)
        {
            decimal TotalPlayed = await leagueRepository.GetLeagueTotalPlayedByTip(LeagueId, TipId);

            decimal Wins = await leagueRepository.GetLeagueWinsByTip(LeagueId, TipId);

            decimal Odds = await leagueRepository.GetLeagueAverageOddsByTip(LeagueId, TipId);

            decimal Percentage = PercentageCalculator.CalculatePercentage(TotalPlayed, Wins);
            decimal Roi        = PercentageCalculator.CalculateRoi(TotalPlayed, Wins, Odds);


            LeagueTipDetailedViewModel VM = new LeagueTipDetailedViewModel
            {
                Tip               = await tipRepository.GetTipByTipId(TipId),
                League            = await leagueRepository.GetLeagueByIdAsync(LeagueId),
                LeagueTotalPlayed = TotalPlayed,
                LeagueWins        = Wins,
                LeagueAverageOdds = Odds,
                LeaguePercentage  = Percentage,
                LeagueRoi         = Roi,
                Predictions       = await leagueRepository.GetPredictionsByLeagueAndTip(LeagueId, TipId),
                ControllerName    = "Statistics",
                TipTypeId         = TipTypeId
            };

            ViewData["TipTypeId"] = TipTypeId;
            return(View("LeagueTipDetailed", VM));
        }
示例#4
0
        private void InternalSavePresistData()
        {
            // enumerate
            UpdateUi(UiState.Working);
            var persistFileManager = _kernel.Get <IPersistFileManager>();
            var calc = new PercentageCalculator(Model.DataView.Count);

            // walk
            foreach (var entry in Model.DataView)
            {
                try
                {
                    persistFileManager.Save(Path.GetDirectoryName(entry.FullPath), entry);
                }
                catch (Exception e)
                {
                    Debug.Print("Save error: {0}. {1}", entry.Title, e.Message);
                }

                UpdateUi(UiState.StatusUpdate, calc.Increment());
                if (IsCancellationRequested)
                {
                    break;
                }
            }

            // finish
            UpdateUi(UiState.Ready);
        }
        private void ReloadData()
        {
            var exerciseDescription = PercentageCalculator.ExerciseDescription(calculator.Exercise);

            ExerciseButton.SetTitle(exerciseDescription, UIControlState.Normal);
            ExerciseButton.SetTitle(exerciseDescription, UIControlState.Selected);
            TableView.ReloadData();
        }
示例#6
0
        public override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            calculator      = new PercentageCalculator(new JsonDataManager(new FileStorage(Context)));
            dataAdapter     = new  PercentageDataAdapter(Context);
            exerciseAdapter = new PercentageExerciseAdapter(Context);
        }
        public LastValueWidgetViewModel(WidgetModel model, TableViewModelFactory vmf,
                                        int?period) : base(model, new LastValueWidgetSettings(model.Properties.ToDictionary(v => v.Key, v => v.Value)))
        {
            _settings = (LastValueWidgetSettings)Settings;
            var vm = vmf.GetVM();

            var column = vm.Headers.First(v =>
                                          v.Provider == _settings.ProviderName &&
                                          (v.AccountName == _settings.AccountName || v.UserFriendlyName == _settings.AccountName));


            var tableRowViewModel = vm.Values.OrderByDescending(v => v.When).FirstOrDefault(v => v.CalculatedCells.GetValueOrDefault(column)?.IsOk == true);

            var matchedCell = tableRowViewModel?.CalculatedCells.GetValueOrDefault(column);

            CurrentValue = matchedCell?.Value;
            CurrentDate  = matchedCell?.Money?.When ?? tableRowViewModel?.When.Date ?? DateTime.MinValue;

            var p = new PercentageCalculator();

            Values = new Dictionary <DateTime, double?>();
            bool first = true;

            foreach (var row in vm.Values.OrderByDescending(v => v.When).Where(v => IsApplicable(v.When, period)))
            {
                var cell = row.CalculatedCells.GetValueOrDefault(column);

                var value = _settings.ExemptTransfers ? cell?.AdjustedValue : cell?.Value;

                if (value == null || double.IsNaN(value.Value))
                {
                    continue;
                }

                p.PushValue(row.When, cell.Value.Value, cell.Adjustment);

                Values[cell.Money?.When ?? row.When.Date] = value;
                IncompleteData |= cell.FailedToResolve.Any();

                if (first)
                {
                    first = false;

                    (Color, Delta) = SetDiffPercenage(cell.DiffPercentage);
                }
            }

            p.Finalize(this);

            IncompleteData |= _settings.NotifyStaleData && (!Values.Any() || Values.Select(v => v.Key).Max() < DateTime.Now.AddHours(-36));

            if (IsCompact)
            {
                Values = null;
            }
        }
示例#8
0
    public override bool Action(GameObject target)
    {
        if (isUnit(target) && target.tag == TagHandler.ENEMY)
        {
            if (PercentageCalculator.isWithinRange(hitChanceInPercent))
            {
                target.GetComponent <UnitController>().damage(damage);
            }
        }

        return(false);
    }
示例#9
0
        public void GetReinforcedConcreteCommercialProperties_ReturnsCorrectResult()
        {
            //First Step: "Arrange" Setup Test Data
            var filePath = TestContext.CurrentContext.TestDirectory + @"\TestData\test_FL_insurance_sample.csv";

            // Second Step: "Act" Execute Code
            var percentage = PercentageCalculator.GetReinforcedConcreteCommercialProperties(filePath);

            // Third Step: "Assert" Verify Assertion
            var expectedPercentage = 0.5;

            Assert.AreEqual(expectedPercentage, percentage);
        }
示例#10
0
        public override View GetView(int position, View convertView, ViewGroup parent)
        {
            var view = convertView;

            if (null == view)
            {
                view = inflater.Inflate(Resource.Layout.spinner_item, null);
            }
            TextView textView = view as TextView;

            if (null != textView)
            {
                textView.Text = PercentageCalculator.ExerciseDescription(data [position]);
            }
            return(view);
        }
示例#11
0
        public override UITableViewCell GetCell(UITableView tableView, Foundation.NSIndexPath indexPath)
        {
            var cell  = tableView.DequeueReusableCell("PercentageExerciseCell", indexPath);
            var value = exercises [indexPath.Row];

            cell.TextLabel.Text = PercentageCalculator.ExerciseDescription(value);
            if (value == exercise)
            {
                cell.Accessory = UITableViewCellAccessory.Checkmark;
            }
            else
            {
                cell.Accessory = UITableViewCellAccessory.None;
            }
            return(cell);
        }
示例#12
0
    public virtual Candidate CastVote(List <Candidate> candidates)
    {
        ShuffleMe(candidates, r);

        List <double> chances = new List <double>();

        foreach (Candidate c in candidates)
        {
            double chance = GetVoteChance(c);
            chances.Add(chance);
            //Console.WriteLine(chance);
        }

        List <double> percents = PercentageCalculator.NormalizePercentages(chances.ToArray());

        //Console.WriteLine($"Candidates {candidates.Count}");
        //Console.WriteLine($"Chances {chances.Count}");
        //Console.WriteLine($"Total {total}");

        int    pick   = r.Next(0, 101);
        int    index  = -1;
        double minval = 0;

        for (int i = 0; i < percents.Count; i++)
        {
            double d = percents[i];
            if (i > 0)
            {
                minval += percents[i - 1];
            }

            if (pick >= minval && pick < minval + d)
            {
                index = i;
            }
            //Console.WriteLine();
        }
        if (index == -1)
        {
            int p = r.Next(candidates.Count);
            return(candidates[p]);
        }
        return(candidates[index]);
    }
        public IActionResult Index(PercentageCalculator model)
        {
            SetViewBagValues();
            if (!ModelState.IsValid)
            {
                return(View());
            }

            String selectedValue = model.SelectedOperation;

            switch (selectedValue)
            {
            case "PercentageOf": model.Result = model.PercentageOf();
                break;

            case "Difference": model.Result = model.PercentageDifference();
                break;
            }

            return(View(model));
        }
示例#14
0
        public Money CalculateDiscount(IPurchaseItem item)
        {
            var applyingRules = discountRules.GetDiscountRules(item);

            var fallbackValue = new List <NoDiscountRule> {
                new NoDiscountRule()
            };
            var result = applyingRules.GetValueOrFallback(fallbackValue);

            decimal calculatedCost;

            LogMessage($"Discounts Are Cummulative: {discountRules.DiscountsAreCumulative}");

            if (!discountRules.DiscountsAreCumulative)
            {
                var discountRule = result.First();


                var fullAmount = item.FullCost.Amount;
                calculatedCost = PercentageCalculator.CalculatePercentageDiscount(fullAmount, discountRule.DiscountPercentage);

                LogMessage($"Let's see... you have {item.Quantity} of {item.Product.ProductName} ({item.FullCost}). The {discountRule.GetType().Name} discount applies\r\n. That's a {discountRule.DiscountPercentage}% discount for you! ({calculatedCost })\r\n");
            }
            else
            {
                //calculate discounts one over the other, as they are cummulative

                //JP: POSSIBLE DONT TALK TO STRANGER VIOLATION HERE, CHECK IF WE NEED TO USE THE NAME OF THE ITEM FOR SMTHNG IF NOT, TAKE MONEY AS PARAMETER
                calculatedCost = item.FullCost.Amount;

                foreach (var rule in result)
                {
                    calculatedCost = PercentageCalculator.CalculatePercentageDiscount(calculatedCost, rule.DiscountPercentage);
                }
            }

            var newCost = new Money(calculatedCost, item.Product.Cost);

            return(newCost);
        }
示例#15
0
        private void InternalRenameMovies()
        {
            // enumerate
            UpdateUi(UiState.Working);
            var entries = Model.DataView.Where(x => Commons.IsMovieFetched(x.TmdbId) &&
                                               !string.IsNullOrWhiteSpace(x.Title)).ToList();
            var calc        = new PercentageCalculator(entries.Count);
            int unprocessed = 0;

            // walk
            foreach (var entry in entries)
            {
                try
                {
                    var path = entry.FullPath;
                    HelperRenameFile(path, entry);
                    HelperRenameDirectory(path, entry);
                }
                catch (Exception e)
                {
                    Debug.Print("Rename error: {0}. {1}", entry.Title, e.Message);
                    unprocessed++;
                }

                // sync
                UpdateUi(UiState.StatusUpdate, calc.Increment());
                if (IsCancellationRequested)
                {
                    break;
                }
            }

            // finished
            UpdateUi(UiState.Ready);
            Model.Invoke(() =>
            {
                Model.DataView.Clear();
                View.ShowMessageBox("Rename completed. Please re-analyze the folder. Errors: " + unprocessed, Strings.AppName);
            });
        }
示例#16
0
        private void InternalThumbnailFolder()
        {
            // enumerate
            UpdateUi(UiState.Working);
            var entries          = Model.DataView.Where(x => x.PosterPath != null).ToList();
            var calc             = new PercentageCalculator(entries.Count);
            var thumbnailManager = _kernel.Get <IThumbnailManager>();

            // walk
            foreach (var entry in entries)
            {
                thumbnailManager.CreateThumbnail(Path.GetDirectoryName(entry.FullPath));
                UpdateUi(UiState.StatusUpdate, calc.Increment());
                if (IsCancellationRequested)
                {
                    break;
                }
            }

            // finish
            UpdateUi(UiState.Ready);
        }
示例#17
0
        private async void InternalDownloadPoster()
        {
            // enumerate
            UpdateUi(UiState.Working);
            var tmdb    = _kernel.Get <ITmdb>();
            var entries = Model.DataView.Where(x => x.PosterPath != null).ToList();
            var calc    = new PercentageCalculator(entries.Count);

            // walk
            foreach (var entry in entries)
            {
                try
                {
                    var url = tmdb.BuildPosterUrl(entry.PosterPath, PosterSize.original);
                    // ReSharper disable once AssignNullToNotNullAttribute
                    var destFile = Path.Combine(Path.GetDirectoryName(entry.FullPath), Commons.PosterFileName);

                    if (File.Exists(destFile))
                    {
                        continue;
                    }
                    await tmdb.DownloadFile(url, destFile);
                }
                catch (Exception e)
                {
                    Debug.Print("Download poster error: {0}. {1}", entry.Title, e.Message);
                }

                UpdateUi(UiState.StatusUpdate, calc.Increment());
                if (IsCancellationRequested)
                {
                    break;
                }
            }

            // finish
            UpdateUi(UiState.Ready);
        }
示例#18
0
    //приведение введенных шансов к процентным шансам.
    private void RecalculateSpawnChances()
    {
        //TODO: подумать как это можно укоротить. А то два абзаца одинакового текста.
        int length = currentDifficultyLevel.StartSpawnChance.Length;

        StartSpawnChances = new int[length];
        int[] SpawnChancesInPecents = PercentageCalculator.ToPercents(currentDifficultyLevel.StartSpawnChance);
        int   previousValue         = 0;

        for (int i = 0; i < length; i++)
        {
            StartSpawnChances[i] = previousValue + SpawnChancesInPecents[i];
            previousValue        = StartSpawnChances[i];
        }
        length = currentDifficultyLevel.IntervalSpawnChance.Length;
        IntervalSpawnChances  = new int[length];
        SpawnChancesInPecents = PercentageCalculator.ToPercents(currentDifficultyLevel.IntervalSpawnChance);
        previousValue         = 0;
        for (int i = 0; i < length; i++)
        {
            IntervalSpawnChances[i] = previousValue + SpawnChancesInPecents[i];
            previousValue           = IntervalSpawnChances[i];
        }
    }
示例#19
0
        /// <summary>
        /// Gets all possible actions for the active character and splits them into offensive and defensive actions,
        /// giving each a priority based on the amount of healing, damage, and/or ai weight provided by the action.
        /// </summary>
        /// <returns>A struct providing the action priorities of offensive and defensive actions.</returns>
        protected virtual ActionPriorities EvaluateActions()
        {
            var defensiveActionsPoints    = new Dictionary <ActionBase, int>();
            var offensiveActionsPoints    = new Dictionary <ActionBase, int>();
            var defensiveActionPriorities = new Dictionary <ActionBase, int>();
            var offensiveActionPriorities = new Dictionary <ActionBase, int>();
            var allActions = new List <ActionBase>();

            allActions.AddRange(_activeCharacter.Attacks);
            allActions.AddRange(_activeCharacter.SpellList);
            allActions.AddRange(_activeCharacter.SkillList);
            var consumables = _activeCharacter.Inventory
                              .Where(item => item is Consumable)
                              .Select(item => ((Consumable)item).ItemSpell);

            allActions.AddRange(consumables);

            // Use average max health as basis for effectiveness of damage and healing
            int averageMaxHealth = 0;

            foreach (var character in AICharacters)
            {
                averageMaxHealth += character.CurrentMaxHealth;
            }
            averageMaxHealth /= AICharacters.Count();

            // Calculate total healing and damage and use it to determine if an action is offensive or defensive
            foreach (var action in allActions)
            {
                int damage         = DamageCalculator.GetDamageAsInt(_activeCharacter, action);
                int healing        = DamageCalculator.GetHealing(_activeCharacter, action);
                int percentHealing = DamageCalculator.GetHealingPercentage(_activeCharacter, action);

                int netDamage = damage - healing;

                if (netDamage < 0 || percentHealing > 0 || !action.IsOffensive)
                {
                    int maxPotential = -netDamage;
                    maxPotential += (percentHealing * averageMaxHealth / 100);
                    defensiveActionsPoints[action] = maxPotential;
                }
                else
                {
                    int maxPotential = netDamage;
                    offensiveActionsPoints[action] = maxPotential;
                }
            }

            int medianHealing = MathExtensions.GetMedian(defensiveActionsPoints.Values.ToList());
            int medianDamage  = MathExtensions.GetMedian(offensiveActionsPoints.Values.ToList());

            // Assign action priorities based on how an action performs on par with other actions

            foreach (var key in defensiveActionsPoints.Keys)
            {
                int healing = defensiveActionsPoints[key];
                defensiveActionPriorities[key] = key.AiWeight;
                if (medianHealing > 0)
                {
                    if (PercentageCalculator.GetPercentage(healing, medianHealing) >= 150)
                    {
                        defensiveActionPriorities[key] += 3;
                    }
                    else if (PercentageCalculator.GetPercentage(healing, medianHealing) >= 120)
                    {
                        defensiveActionPriorities[key] += 2;
                    }
                }
                else
                {
                    defensiveActionPriorities[key] += 1;
                }
            }

            foreach (var key in offensiveActionsPoints.Keys)
            {
                int damage = offensiveActionsPoints[key];
                offensiveActionPriorities[key] = key.AiWeight;
                if (medianDamage > 0)
                {
                    if (PercentageCalculator.GetPercentage(damage, medianDamage) >= 150)
                    {
                        offensiveActionPriorities[key] += 3;
                    }
                    else if (PercentageCalculator.GetPercentage(damage, medianDamage) >= 120)
                    {
                        offensiveActionPriorities[key] += 2;
                    }
                }
                else
                {
                    offensiveActionPriorities[key] += 1;
                }
            }

            return(new ActionPriorities()
            {
                DefensiveActionPriorities = defensiveActionPriorities,
                OffensiveActionPriorities = offensiveActionPriorities
            });
        }
示例#20
0
        private async void InternalOpenDirectory(string path)
        {
            // save states
            UpdateUi(UiState.Working);
            _settings.LastOpenDirectory = path;
            _settings.Save();

            // clear data
            Model.Invoke(() => Model.DataView.Clear());

            // enumerate
            var tmdb = _kernel.Get <ITmdb>();
            var persistFileManager = _kernel.Get <IPersistFileManager>();
            var dirEnumbEnumerable = Directory.EnumerateDirectories(path, "*", SearchOption.TopDirectoryOnly).ToList();
            var calc = new PercentageCalculator(dirEnumbEnumerable.Count);

            // walk
            foreach (var basePath in dirEnumbEnumerable)
            {
                try
                {
                    string currentMoviePath;
                    var    currentFolder = new PowerPath(basePath);

                    // check for ignore pattern
                    var lastName = currentFolder.GetLastDirectoryName();
                    if (lastName.StartsWith("[") && lastName.EndsWith("]"))
                    {
                        continue;
                    }

                    // find first movie
                    if ((currentMoviePath = HelperFindFirstFile(basePath)) == null)
                    {
                        continue;
                    }

                    // find metadata
                    MovieEntry entry;
                    if (persistFileManager.HasPersistentData(Path.GetDirectoryName(currentMoviePath)))
                    {
                        entry = persistFileManager.Load(currentMoviePath);
                    }
                    else
                    {
                        var currentResult = await tmdb.GetByFilename(currentMoviePath);

                        entry = new MovieEntry();
                        entry.SetFullPath(currentMoviePath);
                        entry.SetData(currentResult);
                    }

                    // push to collection
                    Model.Invoke(() => Model.DataView.Add(entry));
                }
                catch (Exception e)
                {
                    Debug.Print("Analyze error: {0}. {1}", basePath, e.Message);
                }

                // sync
                _lastSelectedIndex = -1;
                UpdateUi(UiState.StatusUpdate, calc.Increment());
                if (IsCancellationRequested)
                {
                    break;
                }
            }

            // finish
            UpdateUi(UiState.Ready);
        }
示例#21
0
 public PercentageConverter()
 {
     PercentageCalc = new PercentageCalculator();
     InitializeComponent();
 }