public UserStatistics GetUserStatistics()
        {
            var fromCache = _cache.Value.GetItem(nameof(this.GetUserStatistics));
            if (fromCache != null)
            {
                return (UserStatistics)(fromCache);
            }
            var date = DateTime.Now.AddDays(-20);
            var userlist = _user.Where(X => X.RegisterDate >= date).GroupBy(X => new { Year = X.RegisterDate.Year, Month = X.RegisterDate.Month, Day = X.RegisterDate.Day })
                        .Select(group => new
                        {
                            RegisterPersianDate = group.Key,
                            Count = group.Count()
                        })
                        .OrderBy(x => x.RegisterPersianDate);
            string studentCountList = string.Empty;
            foreach (var item in userlist)
            {
                studentCountList += $"{item.Count},";
            }
            studentCountList += "0";
            var data = new UserStatistics
            {
                CommentCount = "0",
                CommentCountList = "0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0",

                StudentCount = _user.Count(X => X.IsActive && X.IsTeacher == false).ToString(),
                StudentCountList = studentCountList,

                UserCount = _user.Count(X => X.IsActive).ToString(),
                UserCountList = studentCountList,

                WebSiteVisitCount = "0",
                WebSiteVisitCountList = "0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0",
            };
            _cache.Value.PutItem(nameof(this.GetUserStatistics), data, null, DateTime.Now.AddDays(5));
            return data;
        }
示例#2
0
文件: RankGraph.cs 项目: yansaan/osu
        private void updateStatistics(UserStatistics statistics)
        {
            placeholder.FadeIn(fade_duration, Easing.Out);

            if (statistics?.Ranks.Global == null)
            {
                graph.FadeOut(fade_duration, Easing.Out);
                ranks = null;
                return;
            }

            int[] userRanks = statistics.RankHistory?.Data ?? new[] { statistics.Ranks.Global.Value };
            ranks = userRanks.Select((x, index) => new KeyValuePair <int, int>(index, x)).Where(x => x.Value != 0).ToArray();

            if (ranks.Length > 1)
            {
                placeholder.FadeOut(fade_duration, Easing.Out);

                graph.DefaultValueCount = ranks.Length;
                graph.Values            = ranks.Select(x => - (float)Math.Log(x.Value));
            }

            graph.FadeTo(ranks.Length > 1 ? 1 : 0, fade_duration, Easing.Out);
        }
示例#3
0
        public static async Task AddUserStatistics(User user)
        {
            using (var dataBase = new NameThatTuneDatabase())
            {
                if (await dataBase.Users.AnyAsync(o => o.ChatId == user.ChatId &&
                                                  o.MessengerClass == user.MessengerClass))
                {
                    throw new Exception($"User {user.ChatId} - {user.MessengerClass} already exists");
                }

                ;
                var newUser = user;
                await dataBase.Users.AddAsync(newUser);

                await dataBase.SaveChangesAsync();

                var userStat = new UserStatistics {
                    UserId = newUser.Id, Id = newUser.Id
                };
                await dataBase.UserStatistics.AddAsync(userStat);

                await dataBase.SaveChangesAsync();
            }
        }
示例#4
0
        public string CreateToken(StudentViewModel objViewModel, long userId, long organizationId)
        {
            int recordAffected = 0;

            DBConnectionString.RegistrationToken registrationToken = new DBConnectionString.RegistrationToken();
            registrationToken.OrganizationId = organizationId;
            registrationToken.CourseId       = (int)objViewModel.CourseId;
            registrationToken.ClassId        = objViewModel.ClassId;
            registrationToken.SectionId      = objViewModel.SectionId;
            if (objViewModel.DepartmentId != null)
            {
                registrationToken.DepartmentId = (int)objViewModel.DepartmentId;
            }
            registrationToken.Token      = UserStatistics.GenerateToken();
            registrationToken.CreatedBy  = userId;
            registrationToken.InsertedOn = DateTime.Now;
            registrationToken.RoleId     = (int)UserRoles.Student;
            recordAffected = Convert.ToInt32(registrationToken.Insert());
            if (recordAffected > 0)
            {
                return(registrationToken.Token);
            }
            return(string.Empty);
        }
        public async Task GetUserStatisticsAsync_Uses_Given_CancellationToken(string username, int averageSpeed, long uploadCount, int fileCount, int directoryCount)
        {
            var cancellationToken = new CancellationToken();
            var result            = new UserStatistics(username, averageSpeed, uploadCount, fileCount, directoryCount);

            var waiter = new Mock <IWaiter>();

            waiter.Setup(m => m.Wait <UserStatistics>(It.IsAny <WaitKey>(), null, It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(result));

            var serverConn = new Mock <IMessageConnection>();

            serverConn.Setup(m => m.WriteAsync(It.IsAny <IOutgoingMessage>(), It.IsAny <CancellationToken>()))
            .Returns(Task.CompletedTask);

            using (var s = new SoulseekClient(waiter: waiter.Object, serverConnection: serverConn.Object))
            {
                s.SetProperty("State", SoulseekClientStates.Connected | SoulseekClientStates.LoggedIn);

                await s.GetUserStatisticsAsync(username, cancellationToken);
            }

            serverConn.Verify(m => m.WriteAsync(It.IsAny <IOutgoingMessage>(), cancellationToken));
        }
示例#6
0
        public bool OpenConnection(string connectionString)
        {
            if (string.IsNullOrWhiteSpace(connectionString))
            {
                Logger.Log(this, "Unable to connect to the SQL database: No connection specified.", LogLevel.Error);
                return(false);
            }
            internalState         = ConnectionState.Connecting;
            connection            = PostgreSQLTools.CreateDataConnection(connectionString);
            internalState         = ConnectionState.Open;
            connection.OnClosing += (sender, args) => internalState = ConnectionState.Closed;
            connection.OnClosed  += (sender, args) => internalState = ConnectionState.Closed;
            metadata              = connection.GetTable <Metadata>();
            try
            {
                var version = from entry in metadata
                              where entry.Key == "version"
                              select entry.Value;

                var count = version.Count();
                if (count != 1)
                {
                    Logger.Log(this, "Zero or multiple 'version' entries found in the Metadata table. The database connection will be dropped.", LogLevel.Error);
                    HandleConnectionFailure();
                    return(false);
                }

                if (version.First() != Bot.DatabaseVersion)
                {
                    Logger.Log(this, $"Bot and database version do not match (bot is at {Bot.DatabaseVersion}, database is at {version.First()}). The database will now be upgraded.", LogLevel.Info);
                    if (!UpgradeDatabase(version.First()))
                    {
                        Logger.Log(this, "Upgrade failed. The database connection will be dropped.", LogLevel.Warning);
                        HandleConnectionFailure();
                        return(false);
                    }
                }
            }
            catch (NpgsqlException e)
            {
                if (e.Message.ToLower().Contains("metadata") && e.Message.ToLower().Contains("does not exist"))
                {
                    Logger.Log(this, "Metadata table not found. A new tableset will be created.", LogLevel.Warning);
                    try
                    {
                        DropTables();
                        CreateTables();
                    }
                    catch (NpgsqlException f)
                    {
                        Logger.Log(this, $"Unable to create a new tableset: An exception occurred({f.GetType()}: {f.Message}). The database connection will be dropped.", LogLevel.Error);
                        HandleConnectionFailure();
                        return(false);
                    }
                    AddMetadata();
                    Logger.Log(this, "Writing metadata...", LogLevel.Info);
                }
                else
                {
                    Logger.Log(this, $"Unable to retrieve the database version: An exception occurred ({e.GetType()}: {e.Message}). The database connection will be dropped.", LogLevel.Error);
                    HandleConnectionFailure();
                    return(false);
                }
            }

            //UserCredentials = connection.GetTable<UserCredential>();
            Quotes         = connection.GetTable <Quote>();
            UserStatistics = connection.GetTable <UserStatistic>();
            Emoticons      = connection.GetTable <UsedEmoticon>();
            KeyValuePairs  = connection.GetTable <KeyValuePair>();
            LinkedUrls     = connection.GetTable <LinkedUrl>();
            Users          = connection.GetTable <User>();
            Words          = connection.GetTable <UsedWord>();
            ChatLog        = connection.GetTable <ChatLog>();
            MiscData       = connection.GetTable <MiscData>();

            try
            {
                // These methods are actually not pure, because they'll throw an exception
                // if their backing database tables are not found. It's a bit of a hack,
                // but this is the easiest way to check whether those tables exist.

                // ReSharper disable ReturnValueOfPureMethodIsNotUsed
                //UserCredentials.FirstOrDefault();
                Quotes.FirstOrDefault();
                UserStatistics.FirstOrDefault();
                Emoticons.FirstOrDefault();
                KeyValuePairs.FirstOrDefault();
                LinkedUrls.FirstOrDefault();
                Users.FirstOrDefault();
                Words.FirstOrDefault();
                ChatLog.FirstOrDefault();
                MiscData.FirstOrDefault();
                // ReSharper restore ReturnValueOfPureMethodIsNotUsed
            }
            catch (Exception e)
            {
                Logger.Log(this, $"Database integrity check failed ({e.GetType().Name}: {e.Message})", LogLevel.Error);
                HandleConnectionFailure();
                return(false);
            }

            return(true);
        }
示例#7
0
        /// <summary>
        /// 往用户统计表跑数据
        /// </summary>
        public void AddUserStatistics()
        {
            var websiteList = GetList <WebsiteInfo>();

            LogHelper.WriteLog("访客统计", "总" + websiteList.Count + "条", true);

            var index = 0;

            foreach (var item in websiteList)
            {
                index++;
                LogHelper.WriteLog("访客统计", "站点:" + item.WebsiteOwner + "," + index, true);

                string        nowDay    = DateTime.Now.ToString("yyyy/MM/dd");
                int           total     = 0;
                List <string> timeArray = new List <string> {
                    "day", "week", "month"
                };
                try
                {
                    for (int j = 0; j < timeArray.Count; j++)
                    {
                        List <DashboardMonitorInfo> dashList = bllDashboard.GetDashboardMonitorInfoList(int.MaxValue, 1, timeArray[j], out total, item.WebsiteOwner);
                        //LogHelper.WriteLog("访客统计", "dashList:" + dashList.Count, true);


                        if (dashList.Count <= 0)
                        {
                            continue;
                        }
                        int number = 0;
                        if (timeArray[j] == "day")
                        {
                            number = -1;
                        }
                        else if (timeArray[j] == "week")
                        {
                            number = -7;
                        }
                        else
                        {
                            number = -30;
                        }
                        for (int i = 0; i < dashList.Count; i++)
                        {
                            //访问次数
                            int visitCount = bllDashboard.GetCount <MonitorEventDetailsInfo>(string.Format(" WebsiteOwner='{0}'  AND EventDate>=DateAdd(dd,{3},'{1}') AND EventDate<'{1}' AND EventUserID='{2}' ", item.WebsiteOwner, nowDay, dashList[i].EventUserID, number));
                            //LogHelper.WriteLog("访客统计", "访问次数" + visitCount, true);
                            //文章访问次数
                            int articleBrowseCount = bllDashboard.GetCount <MonitorEventDetailsInfo>(string.Format(" WebsiteOwner='{0}' AND EventDate>=DateAdd(dd,{4},'{1}') AND EventDate<'{1}' AND EventUserID='{2}' AND ModuleType='{3}' ", item.WebsiteOwner, nowDay, dashList[i].EventUserID, "article", number));
                            //LogHelper.WriteLog("访客统计", "文章访问次数" + articleBrowseCount, true);
                            //活动访问次数
                            int activityBrowseCount = bllDashboard.GetCount <MonitorEventDetailsInfo>(string.Format(" WebsiteOwner='{0}' AND EventDate>=DateAdd(dd,{4},'{1}') AND EventDate<'{1}' AND EventUserID='{2}' AND ModuleType='{3}' ", item.WebsiteOwner, nowDay, dashList[i].EventUserID, "activity", number));
                            //LogHelper.WriteLog("访客统计", "活动访问次数" + activityBrowseCount, true);
                            //活动报名次数
                            int activitySignUpCount = bllDashboard.GetCount <ActivityDataInfo>(string.Format(" WebsiteOwner='{0}' AND InsertDate>=DateAdd(dd,{3},'{1}') AND InsertDate<'{1}' AND UserId='{2}' ", item.WebsiteOwner, nowDay, dashList[i].EventUserID, number));
                            //LogHelper.WriteLog("访客统计", "活动报名次数" + activitySignUpCount, true);
                            //下单次数
                            int orderCount = bllDashboard.GetCount <WXMallOrderInfo>(string.Format(" WebsiteOwner='{0}' AND InsertDate>=DateAdd(dd,{3},'{1}') AND InsertDate<'{1}' AND OrderUserID='{2}' AND PaymentStatus=1 ", item.WebsiteOwner, nowDay, dashList[i].EventUserID, number));
                            //LogHelper.WriteLog("访客统计", "下单次数" + orderCount, true);
                            //积分记录
                            int score = Convert.ToInt32(ZentCloud.ZCBLLEngine.BLLBase.GetSingle(string.Format(" SELECT SUM(SCORE) FROM [ZCJ_UserScoreDetailsInfo] where WebsiteOwner='{0}' AND UserID='{1}' and AddTime>=DATEADD(dd,{3},'{2}') and AddTime<'{2}' AND Score>0", item.WebsiteOwner, dashList[i].EventUserID, nowDay, number)));
                            //LogHelper.WriteLog("访客统计", "积分记录" + score, true);
                            //其它访问次数
                            int otherCount = visitCount - articleBrowseCount - activityBrowseCount;
                            //LogHelper.WriteLog("访客统计", "其它访问次数" + otherCount, true);

                            UserStatistics userStatistics = bllDashboard.Get <UserStatistics>(string.Format(" WebsiteOwner='{0}' AND DateType='{1}' AND UserId='{2}' ", item.WebsiteOwner, timeArray[j], dashList[i].EventUserID));

                            if (userStatistics != null)
                            {
                                //LogHelper.WriteLog("访客统计", "已存在", true);
                                if (!string.IsNullOrEmpty(dashList[i].EventUserWXNikeName))
                                {
                                    userStatistics.WXNickName = dashList[i].EventUserWXNikeName;
                                }
                                if (!string.IsNullOrEmpty(dashList[i].EventUserWXImg))
                                {
                                    userStatistics.WXHeadimgurl = dashList[i].EventUserWXImg;
                                }
                                if (!string.IsNullOrEmpty(dashList[i].EventUserTrueName))
                                {
                                    userStatistics.TrueName = dashList[i].EventUserTrueName;
                                }
                                userStatistics.UserId              = dashList[i].EventUserID;
                                userStatistics.WebsiteOwner        = item.WebsiteOwner;
                                userStatistics.UpdateDate          = DateTime.Now;
                                userStatistics.VisitCount          = visitCount;
                                userStatistics.ArticleBrowseCount  = articleBrowseCount;
                                userStatistics.ActivityBrowseCount = activityBrowseCount;
                                userStatistics.ActivitySignUpCount = activitySignUpCount;
                                userStatistics.OrderCount          = orderCount;
                                userStatistics.Score            = score;
                                userStatistics.OtherBrowseCount = otherCount;
                                //LogHelper.WriteLog("访客统计", "Update", true);
                                bool isEdit = bllDashboard.Update(userStatistics);
                                //LogHelper.WriteLog("访客统计", "isEdit:" + isEdit, true);
                            }
                            else
                            {
                                //LogHelper.WriteLog("访客统计", "新的", true);
                                userStatistics = new UserStatistics();
                                if (!string.IsNullOrEmpty(dashList[i].EventUserWXNikeName))
                                {
                                    userStatistics.WXNickName = dashList[i].EventUserWXNikeName;
                                }
                                if (!string.IsNullOrEmpty(dashList[i].EventUserWXImg))
                                {
                                    userStatistics.WXHeadimgurl = dashList[i].EventUserWXImg;
                                }
                                if (!string.IsNullOrEmpty(dashList[i].EventUserTrueName))
                                {
                                    userStatistics.TrueName = dashList[i].EventUserTrueName;
                                }
                                userStatistics.UserId              = dashList[i].EventUserID;
                                userStatistics.WebsiteOwner        = item.WebsiteOwner;
                                userStatistics.DateType            = timeArray[j];
                                userStatistics.UpdateDate          = DateTime.Now;
                                userStatistics.VisitCount          = visitCount;
                                userStatistics.ArticleBrowseCount  = articleBrowseCount;
                                userStatistics.ActivityBrowseCount = activityBrowseCount;
                                userStatistics.ActivitySignUpCount = activitySignUpCount;
                                userStatistics.OrderCount          = orderCount;
                                userStatistics.Score            = score;
                                userStatistics.OtherBrowseCount = otherCount;
                                bool isAdd = bllDashboard.Add(userStatistics);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.WriteLog("访客统计", "异常:" + ex.Message, true);
                    //throw new Exception("异常", ex);
                    continue;
                }

                LogHelper.WriteLog("访客统计", "完毕:" + item.WebsiteOwner, true);
            }
        }
示例#8
0
        public async Task RunAsync(ActivityAddedMessage message, IDurableOrchestrationClient durableClient)
        {
            var activity = await activityRepository.GetActivityAsync(message.ActivityId);

            logger.LogInformation($"Handling added activity [{activity}] ...");

            var currentUser = await userRepository.GetUserAsync(activity.UserId);

            try
            {
                // Notifying user makes only sense when he provided push infos
                if (activity.ActivityType == ActivityType.Drink && currentUser.PushInfo != null)
                {
                    await HandleMonitoringAsync(durableClient, currentUser.Id);
                }

                bool           shouldUpdate = false;
                UserStatistics userStats    = null;
                try
                {
                    // Immediately update Stats for current user
                    userStats = await statisticUpdateService.UpdateStatisticsAsync(currentUser.Id, currentUser.Gender, currentUser.Weight);

                    if (activity.ActivityType == ActivityType.Drink)
                    {
                        await statisticUpdateService.UpdateRankingAsync(currentUser.Id);

                        activity.UpdateStats(userStats.CurrentNightDrinks, userStats.CurrentAlcoholization);

                        shouldUpdate = true;
                    }
                }
                catch (Exception ex)
                {
                    logger.LogError(ex, $"Failed to update stats for user [{currentUser}]");
                }

                if (activity.Location != null && activity.Location.IsValid())
                {
                    await HandleLocationUpdateAsync(activity);

                    shouldUpdate = true;
                }

                var entity = activity.ToEntity();

                if (shouldUpdate)
                {
                    await activityRepository.UpdateActivityAsync(entity);
                }

                await this.activityDistributionService.DistributeActivitiesAsync(currentUser, entity);

                await SendActivityUpdateAsync(currentUser, activity, userStats);

                // check for drink events
                try
                {
                    if (activity.ActivityType == ActivityType.Drink)
                    {
                        await this.drinkEventHandlingService.HandleDrinkEventsAsync(activity, currentUser);
                    }
                }
                catch (Exception ex)
                {
                    logger.LogError(ex, "Error handling drink events!");
                }

                // send out push notifications
                var notifications = BuildNotifications(currentUser, activity, userStats);
                if (notifications.Any())
                {
                    await pushNotificationService.NotifyAsync(notifications);
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "Processing failed unexpectedly!");
            }
        }
 protected override Drawable[] CreateUniqueContent(UserStatistics item) => new Drawable[]
 {
     new RowText {
         Text = $@"{item.PP:N0}",
     }
 };
示例#10
0
    private void DisplayUserStatistics(UserStatistics userStatistics)
    {
        int count = 0;
        TableHeaderRow headerRow = new TableHeaderRow();
        headerRow.BackColor = Color.MistyRose;

        int previousForumID = 0;
        int forumCount = 0;

        foreach (XmlNode post in userStatistics.RootElement.SelectNodes(@"USERSTATISTICS/FORUM/THREAD/POST"))
        {
            XmlNode thread = post.ParentNode;
            XmlNode forum = thread.ParentNode;
            if (count == 0)
            {
                TableHeaderCell headerSiteCell = new TableHeaderCell();
                headerSiteCell.Text = "Site";
                headerSiteCell.Scope = TableHeaderScope.Column;
                headerRow.Cells.Add(headerSiteCell);

                TableHeaderCell headerForumTitleCell = new TableHeaderCell();
                headerForumTitleCell.Text = "ForumTitle";
                headerForumTitleCell.Scope = TableHeaderScope.Column;
                headerRow.Cells.Add(headerForumTitleCell);

                TableHeaderCell headerFirstSubjectCell = new TableHeaderCell();
                headerFirstSubjectCell.Text = "Conversation First Subject";
                headerFirstSubjectCell.Scope = TableHeaderScope.Column;
                headerRow.Cells.Add(headerFirstSubjectCell);

                TableHeaderCell headerPostSubjectCell = new TableHeaderCell();
                headerPostSubjectCell.Text = "Post Subject";
                headerPostSubjectCell.Scope = TableHeaderScope.Column;
                headerRow.Cells.Add(headerPostSubjectCell);

                TableHeaderCell headerPostTextCell = new TableHeaderCell();
                headerPostTextCell.Text = "Post Text";
                headerPostTextCell.Scope = TableHeaderScope.Column;
                headerRow.Cells.Add(headerPostTextCell);

                TableHeaderCell headerDatePostedCell = new TableHeaderCell();
                headerDatePostedCell.Text = "Date Posted";
                headerDatePostedCell.Scope = TableHeaderScope.Column;
                headerRow.Cells.Add(headerDatePostedCell);

                TableHeaderCell headerComplainCell = new TableHeaderCell();
                headerComplainCell.Text = "Complain";
                headerComplainCell.Scope = TableHeaderScope.Column;
                headerRow.Cells.Add(headerComplainCell);
            }

            TableRow row = new TableRow();

            string forumID = forum.SelectSingleNode(@"@FORUMID").InnerText;
            int currentForumID = Convert.ToInt32(forumID);
            if (currentForumID != previousForumID)
            {
                forumCount++;
                previousForumID = currentForumID;
            }

            if (forumCount % 2 == 0)
                row.BackColor = Color.LightGray;
            else
                row.BackColor = Color.Linen;

            string siteID = forum.SelectSingleNode(@"SITEID").InnerText;
            string siteName = forum.SelectSingleNode(@"SITENAME").InnerText;

            string commentURL = String.Empty;
            bool isComment = false;
            if (forum.SelectSingleNode(@"URL") != null && forum.SelectSingleNode(@"URL").InnerText != String.Empty)
            {
                commentURL = forum.SelectSingleNode(@"URL").InnerText;
                isComment = true;
            }

            TableCell siteCell = new TableCell();
            siteCell.HorizontalAlign = HorizontalAlign.Center;
            siteCell.Text = siteName;
            row.Cells.Add(siteCell);

            TableCell forumTitleCell = new TableCell();
            forumTitleCell.HorizontalAlign = HorizontalAlign.Center;
            string subject = forum.SelectSingleNode(@"SUBJECT").InnerText;
            forumTitleCell.Text = subject;

            HyperLink forumTitleLink = new HyperLink();
            if (!isComment)
            {
                forumTitleLink.NavigateUrl = GetBaseUrl() + siteName + @"/F" + forumID;
            }
            else
            {
                forumTitleLink.NavigateUrl = commentURL;
            }
            forumTitleLink.Text = subject;
            forumTitleCell.Controls.Add(forumTitleLink);
            row.Cells.Add(forumTitleCell);

            TableCell firstSubjectCell = new TableCell();
            firstSubjectCell.HorizontalAlign = HorizontalAlign.Center;
            string firstSubject = thread.SelectSingleNode(@"SUBJECT").InnerText;
            firstSubjectCell.Text = firstSubject;

            string threadID = thread.SelectSingleNode(@"@THREADID").InnerText;

            HyperLink firstSubjectLink = new HyperLink();
            if (!isComment)
            {
                firstSubjectLink.NavigateUrl = GetBaseUrl() + siteName + @"/F" + forumID + "?thread=" + threadID;
            }
            else
            {
                firstSubjectLink.NavigateUrl = commentURL;
            }
            firstSubjectLink.Text = firstSubject;
            firstSubjectCell.Controls.Add(firstSubjectLink);
            row.Cells.Add(firstSubjectCell);

            TableCell postSubjectCell = new TableCell();
            postSubjectCell.HorizontalAlign = HorizontalAlign.Center;
            string postSubject = post.SelectSingleNode(@"SUBJECT").InnerText;
            postSubjectCell.Text = postSubject;

            string postID = post.SelectSingleNode(@"@POSTID").InnerText;

            HyperLink postLink = new HyperLink();
            if (!isComment)
            {
                postLink.NavigateUrl = GetBaseUrl() + siteName + @"/F" + forumID + "?thread=" + threadID + @"&post=" + postID + "#p" + postID;
            }
            else
            {
                string postIndex = post.SelectSingleNode(@"POSTINDEX").InnerText;
                postLink.NavigateUrl = commentURL + "#" + postIndex;
            }
            postLink.Text = postSubject;
            postSubjectCell.Controls.Add(postLink);
            row.Cells.Add(postSubjectCell);

            TableCell postTextCell = new TableCell();
            postTextCell.HorizontalAlign = HorizontalAlign.Center;
            string text = post.SelectSingleNode(@"BODY").InnerText;
            postTextCell.Text = text;
            row.Cells.Add(postTextCell);

            TableCell datePostedCell = new TableCell();
            datePostedCell.HorizontalAlign = HorizontalAlign.Center;
            string dateposted = post.SelectSingleNode(@"DATEPOSTED/DATE/@RELATIVE").InnerText;
            datePostedCell.Text = dateposted;
            row.Cells.Add(datePostedCell);

            TableCell complaintCell = new TableCell();
            complaintCell.HorizontalAlign = HorizontalAlign.Center;
            string path = @"/dnaimages/boards/images/complain.gif";

            HyperLink complaintLink = new HyperLink();
            complaintLink.NavigateUrl = GetBaseUrl() + siteName + @"/comments/UserComplaintPage?s_start=1&PostID=" + postID;
            complaintLink.ImageUrl = path;
            complaintLink.Target = "_blank";
            complaintCell.Controls.Add(complaintLink);

            row.Cells.Add(complaintCell);

            tblResults.Rows.Add(row);
            count++;
        }

        XmlNode totalPosts = userStatistics.RootElement.SelectSingleNode(@"USERSTATISTICS/@TOTAL");

        _total = 0;
        if (totalPosts != null)
        {
            Int32.TryParse(totalPosts.InnerText, out _total);
        }

        if (count == 0)
        {
            TableRow nodatarow = new TableRow();
            TableCell nodataCell = new TableCell();
            nodataCell.ColumnSpan = 4;
            nodataCell.Text = @"No data for those details";
            nodatarow.Cells.Add(nodataCell);
            tblResults.Rows.Add(nodatarow);
            Count.Text = "";
        }
        else
        {
            Count.Text = String.Format(@"{0} entries out of {1} in total.", count.ToString(), _total.ToString());
        }

        tblResults.Rows.AddAt(0, headerRow);

        tblResults.CellSpacing = 5;
        tblResults.BorderWidth = 2;
        tblResults.BorderStyle = BorderStyle.Outset;

        ShowHideResultControls(true);
        UpdatePagingControls();
        StoreValues();
    }
示例#11
0
 public static DT.UserStatistics ToDto(UserStatistics source) {
   if (source == null) return null;
   return new DT.UserStatistics {
     Id = source.StatisticsId,
     UserId = source.UserId,
     UsedCores = source.UsedCores,
     ExecutionTime = TimeSpan.FromMilliseconds(source.ExecutionTimeMs),
     ExecutionTimeFinishedJobs = TimeSpan.FromMilliseconds(source.ExecutionTimeMsFinishedJobs),
     StartToEndTime = TimeSpan.FromMilliseconds(source.StartToEndTimeMs)
   };
 }
示例#12
0
        /// <summary>
        /// Provides statistical data based user skills and domains and aggregated information about other users.
        /// </summary>
        public async Task <UserStatistics> GetUserStatistics(string userId)
        {
            if (String.IsNullOrEmpty(userId))
            {
                throw new ArgumentException("User id must be set.");
            }

            UserStatistics result = new UserStatistics();
            IEnumerable <UserSkillInfo>  currentUserSkills  = null;
            IEnumerable <UserDomainInfo> currentUserDomains = null;
            IEnumerable <UserSkillInfo>  otherUserSkills    = null;
            IEnumerable <UserDomainInfo> otherUserDomains   = null;

            await Task.Run(() => {
                currentUserSkills = (from d in domainUnitOfWork.UserProfileSkills.GetAll()
                                     join s in domainUnitOfWork.Skill.GetAll() on d.SkillId equals s.Id
                                     where d.UserProfileID == userId && d.SkillLevel != (int)SkillLevel.None
                                     select new UserSkillInfo()
                {
                    SkillName = s.Name, SkillLevel = d.SkillLevel
                }).ToList();
            });

            await Task.Run(() => {
                currentUserDomains = (from s in domainUnitOfWork.UserProfileSkills.GetAll()
                                      join d in domainUnitOfWork.Domain.GetAll() on s.DomainId equals d.Id
                                      where s.UserProfileID == userId && s.SkillLevel != (int)SkillLevel.None
                                      group s by new { s.DomainId, d.Name } into g
                                      select new UserDomainInfo()
                {
                    DomainName = g.Key.Name, SkillLevelSum = g.Sum(m => m.SkillLevel)
                }).ToList();
            });

            await Task.Run(() => {
                otherUserSkills = (from d in domainUnitOfWork.UserProfileSkills.GetAll()
                                   join s in domainUnitOfWork.Skill.GetAll() on d.SkillId equals s.Id
                                   where d.UserProfileID != userId && d.SkillLevel != (int)SkillLevel.None
                                   group d by new { d.SkillId, s.Name } into g
                                   select new UserSkillInfo()
                {
                    SkillName = g.Key.Name, SkillLevel = g.Sum(x => x.SkillLevel)
                }).ToList();
            });

            await Task.Run(() => {
                otherUserDomains = (from s in domainUnitOfWork.UserProfileSkills.GetAll()
                                    join d in domainUnitOfWork.Domain.GetAll() on s.DomainId equals d.Id
                                    where s.UserProfileID != userId && s.SkillLevel != (int)SkillLevel.None
                                    group s by new { s.DomainId, d.Name } into g
                                    select new UserDomainInfo()
                {
                    DomainName = g.Key.Name, SkillLevelSum = g.Sum(m => m.SkillLevel)
                }).ToList();
            });

            if (currentUserSkills == null)
            {
                currentUserSkills = new List <UserSkillInfo>();
            }

            if (currentUserDomains == null)
            {
                currentUserDomains = new List <UserDomainInfo>();
            }

            if (otherUserSkills == null)
            {
                otherUserSkills = new List <UserSkillInfo>();
            }

            if (otherUserDomains == null)
            {
                otherUserDomains = new List <UserDomainInfo>();
            }

            result.CurrentUserSkillInfo  = currentUserSkills;
            result.CurrentUserDomainInfo = currentUserDomains;
            result.OtherUserSkillInfo    = otherUserSkills;
            result.OtherUserDomainInfo   = otherUserDomains;

            return(result);
        }
示例#13
0
        private async Task SendActivityUpdateAsync(User currentUser, Activity activity, UserStatistics userStats)
        {
            var friendsAndMeUserIds = currentUser.GetVisibleFriendUserIds(true);

            var activityStats = new ActivityStatsDTO(activity.ToDto(), userStats?.ToDto());

            // send Realtime-Notification via SignalR
            await this.notificationService.SendSignalRMessageAsync(
                friendsAndMeUserIds,
                Constants.SignalR.NotificationHubName,
                Constants.SignalR.ActivityReceivedMethodName,
                activityStats);
        }
示例#14
0
 public UserStatisticsMessage(UserStatistics statistics) : base(MessageType.UserStatistics)
 {
     Statistics = statistics;
 }
示例#15
0
        public string GetAnalizes()
        {
            #region Organizando dados para humanos lerem

            foreach (var w in WeaponTargetStatistics)
            {
                w.MagazineStatistics = w.MagazineStatistics.OrderBy(m => m.TimeToLoad).ToList();
                SlotStatistics.AddRange(w.MagazineStatistics);
            }

            TargetStatistics = TargetStatistics.OrderBy(t => t.InitialTimeInFov).ToList();
            foreach (var t in TargetStatistics)
            {
                t.BulletReceiverShotStatistics = t.BulletReceiverShotStatistics.OrderBy(b => b.TimeOfShot).ToList();
                ShotStatistics.AddRange(t.BulletReceiverShotStatistics);
            }

            UserStatistics = UserStatistic.Instance.Statistics;
            Name           = UserStatistic.Instance.Name;

            #endregion

            foreach (var target in TargetStatistics)
            {
                var      shots = target.BulletReceiverShotStatistics.Select(s => s.TimeOfShot).ToList();
                var      diferencasMilisegundos = new List <int>();
                DateTime?tempDate = null;
                foreach (var shotTime in shots)
                {
                    if (tempDate.HasValue)
                    {
                        var s = (shotTime - tempDate.Value).Milliseconds;
                        diferencasMilisegundos.Add(s);
                    }
                    tempDate = shotTime;
                }
                IntervaloEntreDisparosTodos.AddRange(diferencasMilisegundos);
            }

            int count = 0;
            foreach (var intervalo in IntervaloEntreDisparosTodos)
            {
                IntervaloEntreDisparosMedia += intervalo;
                count++;
            }
            IntervaloEntreDisparosMedia = IntervaloEntreDisparosMedia / count;


            //  a=todas(bulletsInicial-bulletsfinal) ---100
            //  b=(alvos-inimigos.quantidadedebalas)  --- x
            // mediadeacertos =  (bX100)/a
            int NumeroDeBalasAtiradas = 0;



            foreach (var w in WeaponTargetStatistics)
            {
                ErroTirosComArmaApenasAlimentada += w.ShotsWithoutMagazine.Count;
                w.MagazineStatistics.ForEach(m => ErroTirosComArmaAberta += m.TimeOpenedTrigger.Count);
                QuantidadeDeRecargasDeEmergencia += w.MagazineStatistics.Select(m => m.NumberOfBullets < 5).ToList().Count;
                QuantidadeDeRecargasTaticas      += w.MagazineStatistics.Select(m => m.NumberOfBullets >= 5).ToList().Count;

                w.MagazineStatistics.Select(b => b.StartNumberOfBullets - b.NumberOfBullets).ToList().ForEach(c => NumeroDeBalasAtiradas += c);
            }
            decimal NumeroDeBalasQueAtingiramUmInimigo = 0;
            decimal NumeroDeBalasQueAtingiramUmRefem   = 0;

            List <float> RaioDePrecisao = new List <float>();


            foreach (var t in TargetStatistics)
            {
                if (t.TypeOfTarget == ETargetType.Enemy)
                {
                    NumeroDeBalasQueAtingiramUmInimigo += t.BulletReceiverShotStatistics.Count;
                    t.BulletReceiverShotStatistics.Select(b =>
                                                          Vector3.Distance(b.PointOfCollision, b.PointTargetPosition)).ToList().ForEach(d => RaioDePrecisao.Add(d));
                }
                else
                {
                    NumeroDeBalasQueAtingiramUmRefem += t.BulletReceiverShotStatistics.Count;
                }

                // (shotTime - tempDate.Value).Milliseconds;
                var tempoDeReacao = (t.BulletReceiverShotStatistics.Select(c => c.TimeOfShot).FirstOrDefault() - t.InitialTimeTargetInFocus).Milliseconds;
                TemposDeReacao.Add(tempoDeReacao);
                var tempoDeAquisicao = (t.InitialTimeInFov - t.InitialTimeTargetInFocus).Milliseconds;
                TemposDeAquisicao.Add(tempoDeAquisicao);
            }
            PercentualDeAcertos = (NumeroDeBalasQueAtingiramUmInimigo * 100) / NumeroDeBalasAtiradas;

            float precisaototal = 0f;
            RaioDePrecisao.ForEach(d => precisaototal += d);
            RaioDePrecisaoMedia         = precisaototal / RaioDePrecisao.Count;
            RaiosDePrecisaoMediaPorAlvo = RaioDePrecisao;

            var reacaototal = 0f;
            TemposDeReacao.ForEach(d => reacaototal += d);
            var reacaoMedia = reacaototal / TemposDeReacao.Count;
            PercentualTempoDeReacaoMedia = reacaoMedia;

            var aquisicaototal = 0f;
            TemposDeAquisicao.ForEach(d => aquisicaototal += d);
            var aquisicaoMedia = aquisicaototal / TemposDeAquisicao.Count;
            PercentualTempoDeAquisicaoMedia = aquisicaoMedia;


            NumeroDeAbates = UserStatistics.NumberOfKills;


            review = new StatisticReview(Name, IntervaloEntreDisparosTodos.ToArray(), IntervaloEntreDisparosMedia, PercentualDeAcertos, RaioDePrecisaoMedia, RaiosDePrecisaoMediaPorAlvo.ToArray(), TemposDeReacao.ToArray(), TemposDeAquisicao.ToArray(), PercentualTempoDeReacaoMedia, PercentualTempoDeAquisicaoMedia, QuantidadeDeRecargasTaticas, QuantidadeDeRecargasDeEmergencia, ErroTirosComArmaApenasAlimentada, ErroTirosComArmaAberta, NumeroDeAbates);

            return(review.ToString());
        }
示例#16
0
        internal void WatchEpisode(Episode episode)
        {
            if (Settings.Default.OpenMediaInApp)
            {
                MediaPlayerForm mediaPLayerForm = new MediaPlayerForm();
                mediaPLayerForm.Show();
                mediaPLayerForm.UpdateView(episode);
            }
            else
            {
                string mediaPlayer = Settings.Default.ExternalMediaPlayerPath;

                if (mediaPlayer != null)
                {
                    Process.Start(mediaPlayer, "\"" + Files.GetEpisodeFile(episode) + "\"");

                    Thread.Sleep(1000);

                    switch (MessageBox.Show("Have you finished the episode?", "", MessageBoxButtons.YesNo))
                    {
                    case DialogResult.Yes:

                        // marks episode finished and sets seconds watched (not punctual)
                        FilmographyToUser toUser = episode.ToUser;
                        toUser.Finished       = true;
                        toUser.SecondsWatched = episode.Season.Series.EpisodeRunTime * 60;                                      // in seconds
                        DbManager.Connection.Update(toUser);

                        // if episode is last ine is season, marks season finished
                        if (DbManager.IsLastEpisodeInSeason(episode))
                        {
                            FilmographyToUser sToUser = episode.Season.ToUser;
                            sToUser.Finished = true;
                            DbManager.Connection.Update(sToUser);
                        }

                        // updates user statistics
                        string date = DateTime.Today.ToShortDateString();
                        TableQuery <UserStatistics> query = DbManager.Connection.Table <UserStatistics>()
                                                            .Where(us => us.UserId == User.Id && us.Date == date);
                        UserStatistics stat = query != null && query.Count() > 0 ? query.First() : null;

                        if (stat == null)
                        {
                            stat        = new UserStatistics();
                            stat.UserId = User.GetId();
                            stat.SetDate(DateTime.Today);
                            stat.TimeWatching = 0;
                        }

                        stat.TimeWatching += toUser.SecondsWatched;
                        DbManager.Connection.InsertOrReplace(stat);

                        // udpates series panel (new next episode)
                        mainForm.UpdatePanel(PanelId.Series, episode.Season.Series, true);
                        break;
                    }
                }
                else
                {
                    MessageBox.Show("Please select external media player in Settings page.");
                }
            }
        }
示例#17
0
 public static void ToEntity(DT.UserStatistics source, UserStatistics target) {
   if ((source != null) && (target != null)) {
     target.StatisticsId = source.Id;
     target.UserId = source.UserId;
     target.UsedCores = source.UsedCores;
     target.ExecutionTimeMs = source.ExecutionTime.TotalMilliseconds;
     target.ExecutionTimeMsFinishedJobs = source.ExecutionTimeFinishedJobs.TotalMilliseconds;
     target.StartToEndTimeMs = source.StartToEndTime.TotalMilliseconds;
   }
 }
示例#18
0
 public static UserStatistics ToEntity(DT.UserStatistics source) {
   if (source == null) return null;
   var entity = new UserStatistics(); ToEntity(source, entity);
   return entity;
 }
示例#19
0
 protected override Drawable[] CreateUniqueContent(UserStatistics item) => new Drawable[]
 {
     new RowText {
         Text = item.PP?.ToLocalisableString(@"N0"),
     }
 };
 public static async Task AddOrUpdateAsync(this IMongoCollection <UserStatistics> userStatistics, UserStatistics user)
 => await userStatistics.ReplaceOneAsync(x => x.UserId == user.UserId, user, new UpdateOptions
 {
     IsUpsert = true
 });
示例#21
0
文件: RankGraph.cs 项目: zi-jing/osu
 private void updateStatistics(UserStatistics statistics)
 {
     int[] userRanks = statistics?.RankHistory?.Data;
     Data = userRanks?.Select((x, index) => new KeyValuePair <int, int>(index, x)).Where(x => x.Value != 0).ToArray();
 }
        public ActionResult Statistics()
        {
            var userStatistics = new UserStatistics(User.Identity.GetUserId(), true);

            return(View(userStatistics));
        }
示例#23
0
    /// <summary>
    /// Function that is always called to recreate the table
    private void GetUserStatistics(bool purexml)
    {
        tblResults.Rows.Clear();
        Count.Text = "";
        lblEntryError.Text = String.Empty;
        if (txtEntry.Text != String.Empty)
        {
            int userID = 0;
            userID = Convert.ToInt32(txtEntry.Text);

            DateTime startDateTime = startDate.SelectedDate;
            DateTime endDateTime = endDate.SelectedDate;
            endDateTime = endDateTime.AddDays(1);

            UserStatistics userStatistics = new UserStatistics(_basePage);
            userStatistics.TryCreateUserStatisticsXML(userID, _skip, _show, 1, startDateTime, endDateTime);

            if (!purexml)
            {
                DisplayUserStatistics(userStatistics);
            }
            else
            {
                //Replace an existing node
                if (_basePage.WholePageBaseXmlNode.SelectSingleNode("/USERSTATISTICS") != null)
                {
                    XmlNode userstats = _basePage.WholePageBaseXmlNode.SelectSingleNode("/USERSTATISTICS");

                    _basePage.WholePageBaseXmlNode.ReplaceChild(userstats, _basePage.WholePageBaseXmlNode.OwnerDocument.ImportNode(userStatistics.RootElement.FirstChild, true));
                }
                else
                {
                    _basePage.WholePageBaseXmlNode.FirstChild.AppendChild(_basePage.WholePageBaseXmlNode.OwnerDocument.ImportNode(userStatistics.RootElement.FirstChild, true));
                }
            }

        }
    }
示例#24
0
 public SerializedException SendUserStatistics(ClientInfo ci, out UserStatistics stats)
 {
     stats = new UserStatistics();
     engine.LogClientAction(ci, CWClientActions.LogSendUserStatistics);
     return(engine.SelectUserStatistics(ci, ref stats));
 }
示例#25
0
 /// <summary>
 ///     Converts <see cref="Soulseek.UserStatistics"/> to <see cref="Statistics"/>.
 /// </summary>
 /// <param name="u">The UserStatistics instance to convert.</param>
 /// <returns>The converted instance.</returns>
 public static Statistics ToStatistics(this UserStatistics u) => new()
示例#26
0
文件: Extensions.cs 项目: slskd/slskd
 /// <summary>
 ///     Creates a new instance of <see cref="UserStatisticsState"/> from this instance of <see cref="UserStatistics"/>.
 /// </summary>
 /// <param name="stats">The UserStatistics instance from which to copy data.</param>
 /// <returns>The new instance.</returns>
 public static UserStatisticsState ToUserStatisticsState(this UserStatistics stats) => new()
示例#27
0
 protected override Drawable[] CreateUniqueContent(UserStatistics item) => new Drawable[]
示例#28
0
 public static void Add(UserStatistics obj)
 {
     db.UserStatics.Add(obj);
     db.SaveChanges();
 }
示例#29
0
        public static UserStatistics GetCountryBasedUserStatistics()
        {
            DateTime lastSyncTime = Utility.ConvertLocalToUtc(Convert.ToDateTime(DbManager.GetLastSyncTime()));

            var userStats = new UserStatistics(lastSyncTime);

            try
            {
                DataTable dtAllRegisteredUsers = DbManager.GetAllRegisteredUsers();
                UpdateActiveUsersCount(lastSyncTime, userStats);
                var countryCodeDictionary = new Dictionary <string, string>();

                if (File.Exists(FilePath))
                {
                    string fileContent = File.ReadAllText(FilePath);
                    if (!Utility.IsNullOrEmpty(fileContent))
                    {
                        countryCodeDictionary =
                            JsonConvert.DeserializeObject <Dictionary <string, string> >(fileContent);
                    }
                }
                else
                {
                    countryCodeDictionary = new Dictionary <string, string>();
                }

                if (dtAllRegisteredUsers.Rows.Count > 0)
                {
                    int countryCode = 0;
                    for (int i = 0; i < dtAllRegisteredUsers.Rows.Count; i++)
                    {
                        //try
                        //{
                        var devicePlatform = (DevicePlatform)Convert.ToInt16(dtAllRegisteredUsers.Rows[i]["devicePlatform"]);
                        var creationDate   = Convert.ToDateTime(dtAllRegisteredUsers.Rows[i]["creationDate"]);
                        countryCode = Utility.GetCountry(dtAllRegisteredUsers.Rows[i]["username"].ToString());

                        if (userStats.CountryStats.ContainsKey(countryCode))
                        {
                            var countryStats = userStats.CountryStats[countryCode];
                            UpdateCountryStatisticsForPlatform(devicePlatform, creationDate, countryStats);
                        }
                        else
                        {
                            var countryStats = new CountryStatistics(lastSyncTime);

                            if (countryCodeDictionary.ContainsKey(countryCode.ToString()))
                            {
                                countryStats.CountryName = countryCodeDictionary[countryCode.ToString()];
                            }
                            else
                            {
                                countryStats.CountryName = Utility.GetCountryNameOnline(countryCode.ToString(),
                                                                                        FilePath, countryCodeDictionary);
                            }
                            UpdateCountryStatisticsForPlatform(devicePlatform, creationDate, countryStats);
                            userStats.CountryStats.Add(countryCode, countryStats);
                        }
                        //}
                        //catch (ApplicationException applicationException)
                        //{
                        //}
                        //catch (Exception exception)
                        //{
                        //}
                    }
                }
            }
            catch (Exception exception)
            {
                LogManager.CurrentInstance.ErrorLogger.LogError(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, exception.Message, exception, System.Reflection.MethodBase.GetCurrentMethod().Name);
                throw new ApplicationException("Opertaion failed due to some internal error");
            }

            return(userStats);
        }
示例#30
0
        private List <NotificationBase> BuildNotifications(User currentUser, Activity activity, UserStatistics userStats)
        {
            var friendsUserIds = currentUser.GetVisibleFriendUserIds(false);

            List <NotificationBase> notifications = new List <NotificationBase>();

            // remind only first and every 5th drink this night to avoid spamming
            if (ShouldNotifyUsers(activity, userStats))
            {
                notifications.AddRange(friendsUserIds.Select(u => new ActivityNotification(u, activity)));
            }

            return(notifications);
        }
示例#31
0
 public Statistics(ContentStatitsics content, UserStatistics users, PropertyStatistics properties)
 {
     Content    = content;
     Users      = users;
     Properties = properties;
 }
 public async Task AddOrUpdateAsync(UserStatistics statistics)
 => await _database.UserStatistics().AddOrUpdateAsync(statistics);