Пример #1
0
        public IEnumerable <Results> GetResults(int IdElectoralRoom)
        {
            var us   = _context.Users;
            var cand = _context.Candidates;

            var candidates = from cc in cand
                             join u in us on cc.IdUser equals u.IdUser
                             where cc.IdElectoralRoom == IdElectoralRoom
                             select new
            {
                cc.IdElectoralRoom,
                cc.IdCandidate,
                cc.IdUser,
                u.FirstName,
                u.LastName
            };

            IList <Results> resultList = new List <Results>();

            foreach (var c in candidates)
            {
                int count = VoteCount.Count_Votes(c.IdCandidate);

                Results results = new Results(c.IdCandidate, c.FirstName + " " + c.LastName, count);

                resultList.Add(results);
            }

            return(resultList);
        }
Пример #2
0
        public QuestionPosted VoteUpdate(QuestionPosted question, VoteCount vote)
        {
            var allvotes = question.AllVotes;

            allvotes.Append(vote);
            return(new QuestionPosted(question.QuestionId, question.Question, allvotes.Sum(v => Convert.ToInt32(v)), allvotes));
        }
 private void UnbindFromGame()
 {
     if (_voteCount != null)
     {
         _voteCount.PropertyChanged -= _voteCount_PropertyChanged;
         _voteCount = null;
     }
 }
Пример #4
0
        /// <summary>
        /// Determines whether specified instance of <see cref="BasicInfo" /> is equal to caller
        /// object.
        /// </summary>
        /// <param name="other">Other object to compare.</param>
        /// <returns><c>true</c> if values are memberwise equals, <c>false</c> otherwise.</returns>
        protected bool IsEqual(BasicInfo other)
        {
            const double eps = 1e-6;

            return(ThingId.Equals(other.ThingId) &&
                   string.Equals(Title, other.Title, StringComparison.Ordinal) &&
                   VoteCount.Equals(other.VoteCount) &&
                   Math.Abs(VoteAverage - other.VoteAverage) < eps);
        }
        internal void Clear()
        {
            _item = null;

            Title.ClearValue(TextBlock.TextProperty);
            Avator.ClearValue(Ellipse.FillProperty);
            VoteCount.ClearValue(TextBlock.TextProperty);
            Summary.ClearValue(TextBlock.TextProperty);
        }
Пример #6
0
        public async Task IdentifyPasta(EventContext e)
        {
            Locale locale = Locale.GetEntity(e.Channel.Id.ToDbLong());

            if (string.IsNullOrWhiteSpace(e.arguments))
            {
                await Utils.ErrorEmbed(locale, e.GetResource("infopasta_error_no_arg"))
                .SendToChannel(e.Channel.Id);

                return;
            }

            using (var context = MikiContext.CreateNoCache())
            {
                context.Set <GlobalPasta>().AsNoTracking();

                try
                {
                    GlobalPasta pasta = await context.Pastas.FindAsync(e.arguments);

                    if (pasta == null)
                    {
                        await Utils.ErrorEmbed(locale, e.GetResource("miki_module_pasta_error_null")).SendToChannel(e.Channel);

                        return;
                    }

                    User creator = await context.Users.FindAsync(pasta.creator_id);

                    IDiscordEmbed b = Utils.Embed;

                    b.SetAuthor(pasta.Id.ToUpper(), "", "");
                    b.Color = new IA.SDK.Color(47, 208, 192);

                    if (creator != null)
                    {
                        b.AddInlineField(e.GetResource("miki_module_pasta_identify_created_by"), $"{ creator.Name} [{creator.Id}]");
                    }

                    b.AddInlineField(e.GetResource("miki_module_pasta_identify_date_created"), pasta.date_created.ToShortDateString());

                    b.AddInlineField(e.GetResource("miki_module_pasta_identify_times_used"), pasta.TimesUsed.ToString());

                    VoteCount v = pasta.GetVotes(context);

                    b.AddInlineField(e.GetResource("infopasta_rating"), $"⬆️ { v.Upvotes} ⬇️ {v.Downvotes}");

                    await b.SendToChannel(e.Channel);
                }
                catch (Exception ex)
                {
                    Log.ErrorAt("IdentifyPasta", ex.Message);
                }
            }
        }
Пример #7
0
        public DayTimes(VoteCount voteCount)
        {
            _voteCount = voteCount;
            this.Build();
            txtStartPost.Text = Math.Max(1, _voteCount.StartPost).ToString();
            DateTime eod = _voteCount.EndTime;

            EodDate.Date     = eod;
            spinHour.Value   = eod.Hour;
            spinMinute.Value = eod.Minute;
        }
        private void BindToNewGame(String url)
        {
            url = POG.Utils.Misc.NormalizeUrl(url);
            ThreadReader t = _forum.Reader();

            _voteCount = new VoteCount(_synchronousInvoker, t, _db, _forumURL, url, _forum.PostsPerPage);
            _voteCount.PropertyChanged += new PropertyChangedEventHandler(_voteCount_PropertyChanged);

            _voteCount.Turbo = _turbo;

            _voteCount.ChangeDay(_day);
            _voteCount.Refresh();
            _voteCount.CheckThread();
        }
Пример #9
0
        public async Task <IActionResult> OnGetAsync(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            VoteCount = await _context.VoteCount.FirstOrDefaultAsync(m => m.VoteCountId == id);

            if (VoteCount == null)
            {
                return(NotFound());
            }
            return(Page());
        }
Пример #10
0
        public async Task IdentifyPasta(EventContext e)
        {
            Locale locale = Locale.GetEntity(e.Channel.Id.ToDbLong());

            if (string.IsNullOrWhiteSpace(e.arguments))
            {
                await Utils.ErrorEmbed(locale, e.GetResource("infopasta_error_no_arg"))
                .QueueToChannel(e.Channel.Id);

                return;
            }

            using (var context = new MikiContext())
            {
                GlobalPasta pasta = await context.Pastas.FindAsync(e.arguments);

                if (pasta == null)
                {
                    await Utils.ErrorEmbed(locale, e.GetResource("miki_module_pasta_error_null")).QueueToChannel(e.Channel);

                    return;
                }

                User creator = await context.Users.FindAsync(pasta.CreatorId);

                IDiscordEmbed b = Utils.Embed;

                b.SetAuthor(pasta.Id.ToUpper(), "", "");
                b.Color = new Color(47, 208, 192);

                if (creator != null)
                {
                    b.AddInlineField(e.GetResource("miki_module_pasta_identify_created_by"), $"{ creator.Name} [{creator.Id}]");
                }

                b.AddInlineField(e.GetResource("miki_module_pasta_identify_date_created"), pasta.CreatedAt.ToShortDateString());

                b.AddInlineField(e.GetResource("miki_module_pasta_identify_times_used"), pasta.TimesUsed.ToString());

                VoteCount v = await pasta.GetVotesAsync(context);

                b.AddInlineField(e.GetResource("infopasta_rating"), $"⬆️ { v.Upvotes} ⬇️ {v.Downvotes}");

                await b.QueueToChannel(e.Channel);
            }
        }
Пример #11
0
        public async Task <IActionResult> OnPostAsync(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            VoteCount = await _context.VoteCount.FindAsync(id);

            if (VoteCount != null)
            {
                _context.VoteCount.Remove(VoteCount);
                await _context.SaveChangesAsync();
            }

            return(RedirectToPage("./Index"));
        }
Пример #12
0
        public async Task IdentifyPasta(EventContext e)
        {
            string pastaArg = e.Arguments.Pack.TakeAll();

            if (string.IsNullOrWhiteSpace(pastaArg))
            {
                await e.ErrorEmbed(e.Locale.GetString("infopasta_error_no_arg"))
                .ToEmbed().QueueToChannelAsync(e.Channel);

                return;
            }

            using (var context = new MikiContext())
            {
                GlobalPasta pasta = await context.Pastas.FindAsync(pastaArg);

                if (pasta == null)
                {
                    await e.ErrorEmbed(e.Locale.GetString("miki_module_pasta_error_null")).ToEmbed().QueueToChannelAsync(e.Channel);

                    return;
                }

                User creator = await context.Users.FindAsync(pasta.CreatorId);

                EmbedBuilder b = new EmbedBuilder();

                b.SetAuthor(pasta.Id.ToUpper(), "", "");
                b.Color = new Color(47, 208, 192);

                if (creator != null)
                {
                    b.AddInlineField(e.Locale.GetString("miki_module_pasta_identify_created_by"), $"{ creator.Name} [{creator.Id}]");
                }

                b.AddInlineField(e.Locale.GetString("miki_module_pasta_identify_date_created"), pasta.CreatedAt.ToShortDateString());

                b.AddInlineField(e.Locale.GetString("miki_module_pasta_identify_times_used"), pasta.TimesUsed.ToString());

                VoteCount v = await pasta.GetVotesAsync(context);

                b.AddInlineField(e.Locale.GetString("infopasta_rating"), $"⬆️ { v.Upvotes} ⬇️ {v.Downvotes}");

                await b.ToEmbed().QueueToChannelAsync(e.Channel);
            }
        }
        internal void Clear()
        {
            _item = null;

            Author.ClearValue(TextBlock.TextProperty);
            Verb.ClearValue(TextBlock.TextProperty);
            Avatar.ClearValue(Ellipse.FillProperty);

            Title.ClearValue(TextBlock.TextProperty);

            VoteCount.ClearValue(TextBlock.TextProperty);
            Summary.ClearValue(TextBlock.TextProperty);


            _authorTapped  = null;
            _titleTapped   = null;
            _summaryTapped = null;
        }
Пример #14
0
        public static async Task RunPartitionedChangeFeed(
            [CosmosDBTrigger(
                 databaseName: "%cosmosdbname%",
                 collectionName: "%cosmoscollectionname%",
                 LeaseCollectionPrefix = "partitionedfeed",
                 LeaseCollectionName = "leases",
                 CreateLeaseCollectionIfNotExists = true,
                 ConnectionStringSetting = "cosmosconnectionstring",
                 FeedPollDelay = 1000,
                 MaxItemsPerInvocation = 100)
            ] IReadOnlyList <Document> input,
            [CosmosDB(
                 databaseName: "%cosmosdbname%",
                 collectionName: "%cosmoscollectionname%",
                 ConnectionStringSetting = "cosmosconnectionstring"
                 )] DocumentClient client,
            [SignalR(HubName = "%Region%")] IAsyncCollector <SignalRMessage> signalRMessages,
            ILogger log)
        {
            log.LogInformation("ChangeFeedProcessorPartitioned was called.");

            string _databaseName   = Environment.GetEnvironmentVariable("cosmosdbname");
            string _collectionName = Environment.GetEnvironmentVariable("cosmoscollectionname");

            if (input != null && input.Count > 0)
            {
                log.LogInformation("Documents modified " + input.Count);
                log.LogInformation("First document Id " + input[0].Id);

                SessionResponseStats stats = new SessionResponseStats();

                var answerDocs = input.Where(doc => doc.GetPropertyValue <string>("type").ToLower() == "answer").ToList();
                log.LogInformation($"Found {answerDocs.Count} answer docs in the current changefeed processing iteration");
                var answers = answerDocs.Select(a => JsonConvert.DeserializeObject <Answer>(a.ToString())).ToList();

                var answersBySession = answers.GroupBy(a => a.SessionId);
                foreach (var sessionQuestions in answersBySession)
                {
                    var sessionId = sessionQuestions.Key;
                    log.LogInformation($"Processing session: {sessionId}");

                    // fetch session from cosmos db
                    Document sessionDoc = null;
                    Session  session    = null;

                    var sessionDocPartitionKey = new PartitionKey($"session-{sessionId}");
                    var sessionDocId           = $"{sessionId}";
                    var sessionDocUri          = UriFactory.CreateDocumentUri(_databaseName, _collectionName, sessionDocId);

                    try{
                        sessionDoc = await client.ReadDocumentAsync(sessionDocUri, new RequestOptions()
                        {
                            PartitionKey = sessionDocPartitionKey
                        });

                        session = JsonConvert.DeserializeObject <Session>(sessionDoc.ToString());
                    }
                    catch (DocumentClientException ex) {
                        log.LogError($"Error in retrieving session doc from cosmos for session {sessionId}.");
                        log.LogError(ex.Message);
                        continue; // session does not seem to exist or not retrievable, so just skip/drop the answer submissions for this session
                    }

                    // fetch session results from cosmos db
                    Document       sessionResultsdoc = null;
                    SessionResults sessionResults    = null;

                    var sessionResultsDocPartitionKey = new PartitionKey($"session-{sessionId}");
                    var sessionResultsDocId           = $"sessionresults-{sessionId}";
                    var sessionResultsDocUri          = UriFactory.CreateDocumentUri(_databaseName, _collectionName, sessionResultsDocId);

                    try{
                        sessionResultsdoc = await client.ReadDocumentAsync(sessionResultsDocUri, new RequestOptions()
                        {
                            PartitionKey = sessionResultsDocPartitionKey
                        });

                        sessionResults = JsonConvert.DeserializeObject <SessionResults>(sessionResultsdoc.ToString());
                    }
                    catch (DocumentClientException ex) {
                        if (ex.StatusCode != System.Net.HttpStatusCode.NotFound)
                        {
                            log.LogError("Error in retrieving results doc from cosmos.");
                            log.LogError(ex.Message);
                            throw;
                        }
                    }
                    if (sessionResultsdoc == null)
                    {
                        log.LogInformation($"  Results for session {sessionId} not found yet in cosmos db.  Need to create new results doc.");
                        sessionResultsdoc = new Document();
                        sessionResults    = new SessionResults()
                        {
                            Id          = $"sessionresults-{session.SessionId}",
                            PartitionId = $"session-{session.SessionId}",
                            SessionId   = session.SessionId,
                            SessionName = session.SessionName
                        };
                    }

                    // process all questions (and their answers) for this session:
                    log.LogInformation($"  Processing questions for session: {sessionId}");

                    var answersByQuestionId = sessionQuestions.GroupBy(s => s.QuestionId);
                    foreach (var questionAnswers in answersByQuestionId)
                    {
                        var questionId = questionAnswers.Key;
                        log.LogInformation($"    Processing answers for question {questionId} within session {sessionId}");

                        if (session.Questions.Any(q => q.Id == questionId))
                        {
                            var question        = session.Questions.First(q => q.Id == questionId);
                            var questionResults = sessionResults.Questions.FirstOrDefault(q => q.QuestionId == questionId);
                            if (questionResults == null)
                            {
                                questionResults = new QuestionResults()
                                {
                                    QuestionId = questionId, Title = question.Title
                                };
                                sessionResults.Questions.Add(questionResults);
                            }

                            // TODO: deduplicate multiple entries for the same answer on the same question by the same user:
                            // var answersByAnswerId = questionAnswers.GroupBy(a => a.AnswerId, a => new { AnswerId = a.AnswerId, QuestionId = a.QuestionId, UserId = a.UserId }, (answerId, answersByAllUsers)  => answersByAllUsers.Distinct());
                            var answersByAnswerId = questionAnswers.GroupBy(a => a.AnswerId);
                            foreach (var answersWithSameId in answersByAnswerId)
                            {
                                var answerId = answersWithSameId.Key;
                                log.LogInformation($"      Processing answers with answer id {answersWithSameId.Key} for question {questionId} within session {sessionId}");
                                var answerCount = answersWithSameId.Count();
                                log.LogInformation($"      Answercount is {answerCount} for answer with id {answersWithSameId.Key} for question {questionId} within session {sessionId}");

                                // add votes to the votecount for this answer:
                                var votes = questionResults.Votes.FirstOrDefault(v => v.Id == answerId);
                                if (votes == null)
                                {
                                    votes = new VoteCount()
                                    {
                                        Id = answerId, Votes = answerCount
                                    };
                                    questionResults.Votes.Add(votes);
                                }
                                else
                                {
                                    votes.Votes += answerCount;
                                }
                            }
                        }
                    }

                    // write back updated session results to cosmos:
                    var collectionUri = UriFactory.CreateDocumentCollectionUri(_databaseName, _collectionName);
                    try{
                        var result = await client.UpsertDocumentAsync(collectionUri, sessionResults, new RequestOptions()
                        {
                            PartitionKey = sessionDocPartitionKey
                        });
                    }
                    catch (DocumentClientException ex) {
                        log.LogError($"Failed to update session results for session {sessionId} in cosmos");
                        throw;
                    }
                }
            }
        }
Пример #15
0
        public async Task IdentifyPasta(EventContext e)
        {
            Locale locale = Locale.GetEntity(e.Guild.Id.ToDbLong());

            if (string.IsNullOrWhiteSpace(e.arguments))
            {
                await Utils.ErrorEmbed(locale, "Please state which pasta you'd like to identify.")
                .SendToChannel(e.Channel.Id);

                return;
            }

            using (var context = MikiContext.CreateNoCache())
            {
                context.Set <GlobalPasta>().AsNoTracking();

                try
                {
                    GlobalPasta pasta = await context.Pastas.FindAsync(e.arguments);

                    if (pasta == null)
                    {
                        await e.Channel.SendMessage(Utils.ErrorEmbed(locale, "This pasta doesn't exist!"));

                        return;
                    }

                    User creator = await context.Users.FindAsync(pasta.creator_id);

                    EmbedBuilder b = new EmbedBuilder();
                    b.Author      = new EmbedAuthorBuilder();
                    b.Author.Name = pasta.Id.ToUpper();
                    b.Color       = new Discord.Color(47, 208, 192);

                    if (creator != null)
                    {
                        b.AddField(x =>
                        {
                            x.Name     = "Created by";
                            x.Value    = $"{creator.Name} [{creator.Id}]";
                            x.IsInline = true;
                        });
                    }

                    b.AddField(x =>
                    {
                        x.Name     = "Date Created";
                        x.Value    = pasta.date_created.ToShortDateString();
                        x.IsInline = true;
                    });

                    b.AddInlineField("Times Used", pasta.TimesUsed);

                    b.AddField(x =>
                    {
                        x.Name = "Rating";

                        VoteCount v = pasta.GetVotes(context);

                        x.Value    = $"⬆️ {v.Upvotes} ⬇️ {v.Downvotes}";
                        x.IsInline = true;
                    });

                    await e.Channel.SendMessage(new RuntimeEmbed(b));
                }
                catch (Exception ex)
                {
                    Log.ErrorAt("IdentifyPasta", ex.Message);
                }
            }
        }
        private static ResultsObject createWagonData(List <Day> days, List <Player> allPlayers, bool sortBy, bool simple, bool lSort, int priorVCNumber, string flavorText, string deadlineCode, bool cleanDay, bool isRestCall, string colorCode, ProdTimer prodTimer, string fontOverride, bool areaTagsOn, string dividerOverride, bool showLLevel, bool showZeroCountWagons, List <DayviggedPlayer> dayviggedPlayers, List <ResurrectedPlayer> ressurrectedPlayers, List <Replacement> replacements)
        {
            VoteCount        vc          = null;
            History          history     = null;
            List <VoteCount> allVCs      = new List <VoteCount>();
            string           displayText = "[area=WAGONS(Sort By: " + (sortBy ? "Alphabetical" : "Chronological") + " Data Type: " + (simple ? "Simple" : "Complex") + " LSort: " + (lSort ? "On" : "Off") + ") ] Note from vote counter. These votes include any vote on or off that impacted said wagon.";

            if (days.Count == 0)
            {
                throw new System.Exception("No days found.");
            }

            int treestumpedPlayers = 0;
            int gunnerPlayers      = 0;

            foreach (Player player in allPlayers)
            {
                if (player.IsTreestumped)
                {
                    treestumpedPlayers++;
                }
                if (player.IsGunner)
                {
                    gunnerPlayers++;
                }
            }

            for (int i = 0; i < days.Count; i++)
            {
                days[i].Votes.Sort();

                System.Console.WriteLine("Players In Game: " + allPlayers.Count + " PlayersAlive()/Treestumped: " + allPlayers.numAlive() + "Threshold: " + ((int)(Math.Floor((double)(allPlayers.numAlive() - treestumpedPlayers - gunnerPlayers) / 2)) + 1));
                vc = new VoteCount(days[i].Number, allPlayers, (((int)Math.Floor((double)(allPlayers.numAlive() - treestumpedPlayers - gunnerPlayers) / 2)) + 1), days, isRestCall);



                List <DayviggedPlayer>   tempDayvigs            = new List <DayviggedPlayer>(dayviggedPlayers.DeepClone <List <DayviggedPlayer> >());
                List <ResurrectedPlayer> tempResurrectedPlayers = new List <ResurrectedPlayer>(ressurrectedPlayers.DeepClone <List <ResurrectedPlayer> >());
                foreach (Vote vote in days[i].Votes)
                {
                    foreach (DayviggedPlayer dv in dayviggedPlayers)
                    {
                        if (dv.PostNumber < vote.PostNumber)
                        {
                            tempDayvigs.Remove(dv);
                            Player playerdayvigged = Player.FindPlayerByNameUserAidReplacementsLoop(allPlayers, dv.Player.Name, replacements);
                            if (playerdayvigged.IsAlive)
                            {
                                vc.doVote(new Vote(playerdayvigged, new Player("UNVOTE: "), dv.PostNumber, vote.Timestamp, false, null), vc.MaxThreshold, lSort, sortBy);
                                playerdayvigged.IsAlive = false;
                                playerdayvigged.IsDead  = true;
                                vc.MaxThreshold         = (((int)Math.Floor((double)(allPlayers.numAlive() - treestumpedPlayers - gunnerPlayers) / 2)) + 1);
                            }
                        }
                    }

                    dayviggedPlayers = new List <DayviggedPlayer>();
                    foreach (DayviggedPlayer dvt in tempDayvigs)
                    {
                        dayviggedPlayers.Add(dvt);
                    }
                    foreach (ResurrectedPlayer rt in ressurrectedPlayers)
                    {
                        if (rt.PostNumber < vote.PostNumber)
                        {
                            tempResurrectedPlayers.Remove(rt);
                            Player playerRessurected = Player.FindPlayerByNameUserAidReplacementsLoop(allPlayers, rt.Player.Name, replacements);
                            if (playerRessurected.IsDead)
                            {
                                vc.doVote(new Vote(playerRessurected, new Player("UNVOTE: "), rt.PostNumber, vote.Timestamp, false, null), vc.MaxThreshold, lSort, sortBy);
                                playerRessurected.IsAlive = true;
                                playerRessurected.IsDead  = false;
                                vc.MaxThreshold           = (((int)Math.Floor((double)(allPlayers.numAlive() - treestumpedPlayers - gunnerPlayers) / 2)) + 1);
                            }
                        }
                    }

                    ressurrectedPlayers = new List <ResurrectedPlayer>();
                    foreach (ResurrectedPlayer rpt in tempResurrectedPlayers)
                    {
                        ressurrectedPlayers.Add(rpt);
                    }
                    vc.doVote(vote, vc.MaxThreshold, lSort, sortBy);

                    if (vc.IsHammered)
                    {
                        break;
                    }
                }

                vc.buildLatest(vc.DayNumber, priorVCNumber, flavorText, deadlineCode, (days[vc.DayNumber - 1].DeathsOvernight) != null ? days[vc.DayNumber - 1].DeathsOvernight.Count : 0, colorCode, days[i].PostNumberStart, days[i].PostNumberEnd, prodTimer, fontOverride, areaTagsOn, dividerOverride, showLLevel, showZeroCountWagons);

                days[i].performDeathsOvernight();
                foreach (Player player in allPlayers)
                {
                    foreach (Player deadPlayer in days[i].DeathsOvernight)
                    {
                        if (deadPlayer.Name.Equals(player.Name))
                        {
                            player.IsAlive = false;
                            player.IsDead  = true;
                        }
                    }
                }



                allVCs.Add(vc);
                history     = new History(vc.Wagons, lSort, isRestCall);
                displayText = displayText + history.buildDisplayString(days[i].Number, simple);
            }

            displayText = displayText + "[/area]";

            if (allVCs == null)
            {
                throw new ArgumentNullException("NO VCs generated");
            }

            if (displayText == null)
            {
                throw new ArgumentNullException("No display Text");
            }


            return(new ResultsObject(allVCs, displayText, cleanDay));
        }
Пример #17
0
 private VoteCountResponse ToResponse(VoteCount voteCount) => new VoteCountResponse
 {
     Count     = voteCount.Count,
     SubjectId = voteCount.SubjectId
 };