示例#1
0
        public ActionResult Create(int chapterId, CreateTopicModel model)
        {
            try
            {
                Topic topic = new Topic
                {
                    CourseRef = model.CourseId == Constants.NoCourseId ? (int?)null : model.CourseId,
                    ChapterRef = model.ChapterId,
                    TopicTypeRef = model.TopicTypeId,
                    Name = model.TopicName
                };

                AddValidationErrorsToModelState(Validator.ValidateTopic(topic).Errors);

                if (ModelState.IsValid)
                {
                    Storage.AddTopic(topic);

                    return RedirectToAction("Index", new { ChapterId = model.ChapterId });
                }
                else
                {
                    SaveValidationErrors();

                    return RedirectToAction("Create");
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }
示例#2
0
        /// <summary>
        /// Checks if related to topic package has been already uploaded.
        /// In case it was not uploaded - upload package.
        /// Check attempt has been created and get attempt id.
        /// </summary>
        /// <param name="topic">Topic object represents specified topic.</param>
        /// <returns>Long integer value representing attempt id.</returns>
        public long GetAttemptId(Topic topic)
        {
            GetCurrentUserIdentifier();
            AttemptItemIdentifier attemptId = null;
            ActivityPackageItemIdentifier organizationId;
            var packageId = GetPackageIdentifier(topic.CourseRef.Value);

            // in case package has not been uploaded yet.
            if (packageId == null)
            {
                string zipPath = CourseService.Export(topic.CourseRef.Value);
                Package package = new ZipPackage(zipPath);
                package.CourseID = topic.CourseRef.Value;
                packageId = AddPackage(package);
                organizationId = GetOrganizationIdentifier(packageId);
                attemptId = CreateAttempt(organizationId.GetKey(), topic.Id);
            }
            // otherwise check if attempt was created
            else
            {
                organizationId = GetOrganizationIdentifier(packageId);

                AttemptItemIdentifier attId = GetAttemptIdentifier(organizationId, topic.Id);
                if (attId != null)
                {
                    attemptId = attId;
                }
                else
                {
                    attemptId = CreateAttempt(organizationId.GetKey(), topic.Id);
                }
            }

            return attemptId.GetKey();
        }
示例#3
0
 // SelectTopic
 public static List<Topic> FakeTopicsByDisciplineId()
 {
     Topic fakeTopic = new Topic();
     fakeTopic.Id = 1;
     fakeTopic.Name = "Тема1";
     return new List<Topic>() { fakeTopic };
 }
示例#4
0
 public ActionLink BuildLink(Topic topic)
 {
     RouteValueDictionary routeValueDictionary = new RouteValueDictionary();
     routeValueDictionary.Add("id", topic.Id);
     ActionLink actionLink = new ActionLink("Play", "Training", routeValueDictionary);
     return actionLink;
 }
示例#5
0
        public void CalculateSpecializedResultTest()
        {
            User usr = new User() { Username = "******" };
            Topic thm = new Topic() { Name = "Topic One" };
            AttemptResult AR = new AttemptResult(1, usr, thm, CompletionStatus.Completed, AttemptStatus.Completed, SuccessStatus.Passed, DateTime.Now, 0.5f);

            TopicResult topicRes = new TopicResult(usr, thm);
            List<AttemptResult> ARL = new List<AttemptResult>();
            ARL.Add(AR);
            topicRes.AttemptResults = ARL;
            topicRes.GetTopicResultScore();

            DisciplineResult currRes = new DisciplineResult();
            currRes.TopicResult.Add(topicRes);
            Discipline curr = null;
            currRes.CalculateSumAndMax(usr, curr);

            SpecializedResult target = new SpecializedResult();
            target.DisciplineResult.Add(currRes);
            target.CalculateSpecializedResult(usr);

            double? ExpectedSum = 50.0;
            double? ExpectedMax = 100.0;
            double? ExpectedPercent = 50.0;
            char ExpextedECTS = 'F';

            Assert.AreEqual(ExpectedSum, target.Sum);
            Assert.AreEqual(ExpectedMax, target.Max);
            Assert.AreEqual(ExpectedPercent, target.Percent);
            Assert.AreEqual(ExpextedECTS, target.ECTS);
        }
示例#6
0
        public ActionResult Create(int chapterId, CreateTopicModel model)
        {
            var topic = new Topic
            {
                ChapterRef = model.ChapterId,
                Name = model.TopicName,
                TestCourseRef = model.BindTestCourse ? model.TestCourseId : (int?)null,
                TestTopicTypeRef = model.BindTestCourse ? model.TestTopicTypeId : (int?)null,
                TheoryCourseRef = model.BindTheoryCourse ? model.TheoryCourseId : (int?)null,
                TheoryTopicTypeRef = model.BindTheoryCourse ? model.TheoryTopicTypeId : (int?)null
            };

            AddValidationErrorsToModelState(Validator.ValidateTopic(topic).Errors);

            if (ModelState.IsValid)
            {
                Storage.AddTopic(topic);
                return RedirectToAction("Index", new { ChapterId = model.ChapterId });
            }
            else
            {
                SaveValidationErrors();
                return RedirectToAction("Create");
            }
        }
示例#7
0
        /// <summary>
        /// Validates the topic.
        /// </summary>
        /// <param name="data">The topic.</param>
        /// <returns></returns>
        public ValidationStatus ValidateTopic(Topic data)
        {
            var validationStatus = new ValidationStatus();
            if (!string.IsNullOrEmpty(data.Name) && data.Name.Length > Constants.MaxStringFieldLength)
            {
                validationStatus.AddLocalizedError("NameCanNotBeLongerThan", Constants.MaxStringFieldLength);
            }

            if (!data.TestCourseRef.HasValue && !data.TheoryCourseRef.HasValue)
            {
                validationStatus.AddLocalizedError("ChooseAtLeastOneCourse");
            }

            var chapterId = data.Id == 0 ? data.ChapterRef : _storage.GetTopic(data.Id).ChapterRef;
            var topics = _storage.GetTopics(item => item.ChapterRef == chapterId).Where(i => i.Id != data.Id);
            var theoryCourseRefs =
                topics.Select(item => item.TheoryCourseRef).Where(item => item.HasValue && item.Value >= 0);
            var testCourseRefs =
                topics.Select(item => item.TestCourseRef).Where(item => item.HasValue && item.Value >= 0);
            var union = theoryCourseRefs.Union(testCourseRefs);
            if (union.Contains(data.TestCourseRef) || union.Contains(data.TheoryCourseRef) || data.TestCourseRef == data.TheoryCourseRef)
            {
                validationStatus.AddLocalizedError("TopicWithSuchCourseIsPresent");
            }
            return validationStatus;
        }
示例#8
0
        /// <summary>
        /// Validates the topic.
        /// </summary>
        /// <param name="data">The topic.</param>
        /// <returns></returns>
        public ValidationStatus ValidateTopic(Topic data)
        {
            ValidationStatus validationStatus = new ValidationStatus();
            if (String.IsNullOrEmpty(data.Name))
            {
                validationStatus.AddLocalizedError("NameReqiured");
            }
            else if (data.Name.Length > Constants.MaxStringFieldLength)
            {
                validationStatus.AddLocalizedError("NameCanNotBeLongerThan", Constants.MaxStringFieldLength);
            }

            if (!data.TestCourseRef.HasValue && !data.TheoryCourseRef.HasValue)
            {
                validationStatus.AddLocalizedError("ChooseAtLeastOneCourse");
            }
            else
            {
                if (data.TestCourseRef.HasValue)
                {
                    if (data.TestTopicTypeRef == 0)
                    {
                        validationStatus.AddLocalizedError("ChooseTopicType");
                    }
                    else
                    {
                        var testTopicType = Converter.ToTopicType(storage.GetTopicType(data.TestTopicTypeRef.Value));
                        if (testTopicType == TopicTypeEnum.TestWithoutCourse && data.TestCourseRef != Constants.NoCourseId)
                        {
                            validationStatus.AddLocalizedError("TestWithoutCourse");
                        }
                        if (testTopicType != TopicTypeEnum.TestWithoutCourse && (!data.TestCourseRef.HasValue || data.TestCourseRef <= 0))
                        {
                            validationStatus.AddLocalizedError("ChooseTestCourse");
                        }
                    }
                }

                if (data.TheoryCourseRef.HasValue)
                {
                    if (data.TheoryTopicTypeRef == 0)
                    {
                        validationStatus.AddLocalizedError("ChooseTopicType");
                    }
                    else
                    {
                        if (!data.TheoryCourseRef.HasValue || data.TheoryCourseRef <= 0)
                        {
                            validationStatus.AddLocalizedError("ChooseTheoryCourse");
                        }
                    }
                }
            }

            return validationStatus;
        }
示例#9
0
        public IEnumerable<AttemptResult> GetAllAttempts()
        {
            List<AttemptResult> results = new List<AttemptResult>();
            Topic a = new Topic();

            results.Add(new AttemptResult(0, new User { Name = "name1", Id = new Guid("1") }, new Topic { Name = "topic1", Id = 1 }, CompletionStatus.Unknown, AttemptStatus.Suspended, SuccessStatus.Unknown, DateTime.Now, 0.21f));
            results.Add(new AttemptResult(1, new User { Name = "name2", Id = new Guid("2") }, new Topic { Name = "topic2", Id = 2 }, CompletionStatus.NotAttempted, AttemptStatus.Active, SuccessStatus.Unknown, DateTime.Now, null));
            results.Add(new AttemptResult(2, new User { Name = "name3", Id = new Guid("3") }, new Topic { Name = "topic3", Id = 3 }, CompletionStatus.Completed, AttemptStatus.Completed, SuccessStatus.Passed, DateTime.Now, 0.98f));
            results.Add(new AttemptResult(3, new User { Name = "name4", Id = new Guid("4") }, new Topic { Name = "topic4", Id = 4 }, CompletionStatus.Incomplete, AttemptStatus.Completed, SuccessStatus.Failed, DateTime.Now, 0.04f));

            return results;
        }
示例#10
0
        /// <summary>
        /// Validates the topic.
        /// </summary>
        /// <param name="data">The topic.</param>
        /// <returns></returns>
        public ValidationStatus ValidateTopic(Topic data)
        {
            var validationStatus = new ValidationStatus();
            if (!string.IsNullOrEmpty(data.Name) && data.Name.Length > Constants.MaxStringFieldLength)
            {
                validationStatus.AddLocalizedError("NameCanNotBeLongerThan", Constants.MaxStringFieldLength);
            }

            if (!data.TestCourseRef.HasValue && !data.TheoryCourseRef.HasValue)
            {
                validationStatus.AddLocalizedError("ChooseAtLeastOneCourse");
            }
            return validationStatus;
        }
示例#11
0
        public void GetTopicResultScoreTest()
        {
            User usr = new User() { Username = "******" };
            Topic thm = new Topic() { Name = "Topic One" };
            IUDICO.Common.Models.Shared.Statistics.AttemptResult AR = new IUDICO.Common.Models.Shared.Statistics.AttemptResult(1,usr,thm, IUDICO.Common.Models.Shared.Statistics.CompletionStatus.Completed, IUDICO.Common.Models.Shared.Statistics.AttemptStatus.Completed,IUDICO.Common.Models.Shared.Statistics.SuccessStatus.Passed, DateTime.Now, 0.5f);
            
            TopicResult target = new TopicResult(usr, thm);
            List<IUDICO.Common.Models.Shared.Statistics.AttemptResult> ARL = new List<IUDICO.Common.Models.Shared.Statistics.AttemptResult>();
            ARL.Add(AR);
            target.AttemptResults = ARL;

            double? expected = 50.0;
            double? actual;
            actual = target.GetTopicResultScore();
            Assert.AreEqual(expected, actual);
        }
示例#12
0
        public IEnumerable<AttemptResult> GetResults(User user, Topic topic)
        {
            var results = new List<AttemptResult>
                              {
                                  new AttemptResult(0, user, topic, CompletionStatus.Unknown, AttemptStatus.Suspended,
                                                    SuccessStatus.Unknown, DateTime.Now, 0.21f),
                                  new AttemptResult(1, user, topic, CompletionStatus.NotAttempted, AttemptStatus.Active,
                                                    SuccessStatus.Unknown, DateTime.Now, null),
                                  new AttemptResult(2, user, topic, CompletionStatus.Completed, AttemptStatus.Completed,
                                                    SuccessStatus.Passed, DateTime.Now, 0.98f),
                                  new AttemptResult(3, user, topic, CompletionStatus.Incomplete, AttemptStatus.Completed,
                                                    SuccessStatus.Failed, DateTime.Now, 0.04f)
                              };

            return results;
        }
示例#13
0
        private TopicInfoModel() 
        {
            List<AttemptResult> testAttemptList = new List<AttemptResult>();
            List<User> testUserList = new List<User>();
            List<Topic> testTopicList = new List<Topic>();
            float? attemptScore;
            AttemptResult testAttempt;

            User testUser1 = new User();
            testUser1.Name = "user1";
            Topic testTopic1 = new Topic();
            testTopic1.Name = "topic1";
            User testUser2 = new User();
            testUser2.Name = "user2";
            Topic testTopic2 = new Topic();
            testTopic2.Name = "topic2";

            attemptScore = (float?)0.55;
            testAttempt = new AttemptResult(1, testUser1, testTopic1, new CompletionStatus(), new AttemptStatus(), new SuccessStatus(), DateTime.Now, attemptScore);
            testAttemptList.Add(testAttempt);
            
            attemptScore = (float?)0.65;
            testAttempt = new AttemptResult(1, testUser1, testTopic2, new CompletionStatus(), new AttemptStatus(), new SuccessStatus(), null, attemptScore);
            testAttemptList.Add(testAttempt);

            attemptScore = (float?)0.85;
            testAttempt = new AttemptResult(1, testUser2, testTopic1, new CompletionStatus(), new AttemptStatus(), new SuccessStatus(), DateTime.Now, attemptScore);
            testAttemptList.Add(testAttempt);

            attemptScore = (float?)0.95;
            testAttempt = new AttemptResult(1, testUser2, testTopic2, new CompletionStatus(), new AttemptStatus(), new SuccessStatus(), null, attemptScore);
            testAttemptList.Add(testAttempt);

            testUserList.Add(testUser1);
            testTopicList.Add(testTopic1);
            testUserList.Add(testUser2);
            testTopicList.Add(testTopic2);

            this._LastAttempts = testAttemptList;
            this.SelectGroupStudents = testUserList;
            this.SelectDisciplineTopics = testTopicList;
        }
示例#14
0
        public JsonResult Create(CreateTopicModel model)
        {
            try
            {
                var topic = new Topic();
                topic.UpdateFromModel(model);

                AddValidationErrorsToModelState(Validator.ValidateTopic(topic).Errors);
                if (ModelState.IsValid)
                {
                    Storage.AddTopic(topic);
                    var viewTopic = topic.ToViewTopicModel(Storage);
                    return Json(new { success = true, chapterId = model.ChapterId, topicRow = PartialViewAsString("TopicRow", viewTopic) });
                }

                var m = new CreateTopicModel(Storage.GetCourses(), topic);
                return Json(new { success = false, chapterId = model.ChapterId, html = PartialViewAsString("Create", m) });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, html = ex.Message });
            }
        }
示例#15
0
 protected IEnumerable<AttemptResult> GetResults(Topic topic)
 {
     return _LmsService.FindService<ITestingService>().GetResults(topic);
 }
示例#16
0
        public GroupTopicStat GetGroupTopicStatistic(Topic topic, Group group)
        {
            var results = GetResults(topic);

            var groupResults = results.Where(r => r.User.GroupUsers.Select(g => g.GroupRef)
                                      .Contains(group.Id))
                                      .Select(r => new UserRating(r.User, r.Score.ToPercents().Value))
                                      .ToList();
            
            var usersParticipated = groupResults.Select(g => g.User);
            var n = usersParticipated.Count();

            if (n == 0)
            {
                return new GroupTopicStat(0, 0);
            }

            var usersIds = usersParticipated.Select(u => u.Id);

            var groupRatings = group.GroupUsers
                                    .Select(gu => new UserRating(gu.User, 1.0 * gu.User.TestsSum / gu.User.TestsTotal))
                                    .Where(gu => usersIds.Contains(gu.User.Id))
                                    .ToList();

            groupResults.Sort();
            groupRatings.Sort();

            var ratResults = groupResults.Select((r, i) => new { User = r.User, Index = i }).ToDictionary(a => a.User, a => a.Index);
            var ratRatings = groupRatings.Select((r, i) => new { User = r.User, Index = i }).ToDictionary(a => a.User, a => a.Index);

            var ratingDifference = 1.0 * usersParticipated.Sum(u => Math.Abs(ratResults[u] - ratRatings[u]));
            var ratingMax = 2*((n + 1)/2)*(n/2);
            var ratingNormalized = ratingDifference/ratingMax;

            var diffResults = groupResults.ToDictionary(a => a.User, a => a.Score);
            var diffRatings = groupRatings.ToDictionary(a => a.User, a => a.Score);

            var scoreDifference = 1.0 * usersParticipated.Sum(u => Math.Abs(diffResults[u] - diffRatings[u]));
            var scoreMax = n*100;
            var scoreNormalized = scoreDifference / scoreMax;

            return new GroupTopicStat(ratingNormalized, scoreNormalized);
        }
示例#17
0
        protected double PearsonDistance(Topic t1, Topic t2)
        {
            var t1s = t1.UserTopicScores.ToDictionary(t => t.UserId, t => t.Score);
            var t2s = t2.UserTopicScores.ToDictionary(t => t.UserId, t => t.Score);

            var commonUsers = t1s.Select(t => t.Key).Intersect(t2s.Select(t => t.Key));
            var n = commonUsers.Count();

            var t1c = t1s.Where(t => commonUsers.Contains(t.Key)).Select(t => 1.0 * t.Value);
            var t2c = t2s.Where(t => commonUsers.Contains(t.Key)).Select(t => 1.0 * t.Value);

            var sum1 = t1c.Sum();
            var sum2 = t2c.Sum();

            var sum1Sq = t1c.Sum(x => x * x);
            var sum2Sq = t2c.Sum(x => x * x);

            var pSum = commonUsers.Sum(user => (t1s[user]*t2s[user]));

            var num = pSum - (sum1 * sum2 / n);
            var den = Math.Sqrt((sum1Sq - Math.Pow(sum1, 2)/n)*(sum2Sq - Math.Pow(sum2, 2)/n));

            return den == 0 ? 0 : num/den;
        }
示例#18
0
        protected IEnumerable<TopicSimilarity> TopMatches(Topic topic, IEnumerable<Topic> topics, int n)
        {
            var topicStats = topics.Where(t => t.Id != topic.Id).Select(t => new TopicSimilarity(topic.Id, t.Id, PearsonDistance(topic, t))).ToList();
            
            topicStats.Sort();

            return topicStats.Take(n);
        }
示例#19
0
 public double GetMaxResutForTopic(Topic selectTopic)
 {
     return 100;
 }
示例#20
0
 public long GetAttempId(User selectStudent, Topic selectTopic)
 {
     AttemptResult res = _LastAttempts.Find(x => x.User == selectStudent & x.Topic == selectTopic);
     if (res != null)
         return res.AttemptId;
     return -1;
 }
示例#21
0
        protected double CustomDistance(User user, Topic topic)
        {
            using (var d = this.GetDbContext())
            {
                var userTagScores = d.UserScores.Where(s => s.UserId == user.Id).ToDictionary(
                    s => s.TagId, s => s.Score);
                var topicTagScores = d.TopicScores.Where(s => s.TopicId == topic.Id).ToDictionary(
                    s => s.TagId, s => s.Score);

                var commonTags = userTagScores.Select(t => t.Key).Intersect(topicTagScores.Select(t => t.Key)).ToList();

                var sum = commonTags.Sum(tag => Math.Pow(userTagScores[tag] - topicTagScores[tag], 2) * Math.Sign(topicTagScores[tag] - userTagScores[tag]));

                return sum;
            }
        }
示例#22
0
        public double GetTopicTagStatistic(Topic topic)
        {
            var results = this.GetResults(topic).ToList();
            var users = results.Select(r => r.User).ToList();
            if (users.Count == 0 || results.Count == 0)
            {
                return 0;
            }
            // Масив типу : юзер - його теги і їх значення 
            var usersWithTags = new List<UserTags>();
            foreach (var user in users)
            {
                var temp = new UserTags { Id = user.Id };
                temp.Tags = new Dictionary<int, double>();
                if (this.GetUserTagScores(user).Count() == 0)
                {
                    return 0;
                }
                foreach (var tag in this.GetUserTagScores(user))
                {
                    temp.Tags.Add(tag.TagId, tag.Score);
                }
                usersWithTags.Add(temp);
            }

            // Масив типу : тег - ( значення тегу певного юзера, результат тесту того ж юзера) 
            var tagValueScores = new Dictionary<int, List<KeyValuePair<double, double>>>();

            foreach (var userWithTag in usersWithTags)
            {
                if (userWithTag.Tags == null)
                {
                    return 0;
                }
                foreach (var tag in userWithTag.Tags)
                {
                    var item = new KeyValuePair<double, double>(userWithTag.Tags[tag.Key], results.First(x => x.User.Id == userWithTag.Id).Score.ScaledScore.Value * 100);
                    
                    if (!tagValueScores.Keys.Contains(tag.Key))
                    {
                        tagValueScores.Add(tag.Key, new List<KeyValuePair<double, double>> { item });
                    }
                    else
                    {
                        tagValueScores[tag.Key].Add(item);
                    }
                }
            }

            var generalAmount = 0;
            var successAmount = 0;

            foreach (var tagValueScore in tagValueScores)
            {
                tagValueScore.Value.Sort(Comparer);
                for (int i = 0; i < tagValueScore.Value.Count; i++)
                {
                    for (int j = 0; j < tagValueScore.Value.Count; j++)
                    {
                        if (Math.Abs(tagValueScore.Value[i].Key - tagValueScore.Value[j].Key) < 20)
                        {
                            if (Math.Abs(tagValueScore.Value[i].Value - tagValueScore.Value[j].Value) < 20)
                            {
                                successAmount++;
                            }
                            generalAmount++;
                        }
                        
                    }
                }
                
            }

            return 1.0 * successAmount / generalAmount;
        }
示例#23
0
        public double GaussianDistribution(Topic topic)
        {
            var results = this.GetResults(topic).Select(x => (double)x.Score.ScaledScore * 100).ToList();
            if (results == null || results.Count == 0)
            {
                return 0;
            }
            var u = results.Sum() / results.Count;
            var variance = results.Sum(groupResult => Math.Pow(groupResult - u, 2)) / results.Count();
            var a = 1 / (Math.Sqrt(2 * Math.PI) * Math.Sqrt(variance));
            var s = results.Select(groupResult => Math.Pow(Math.E, -Math.Pow(groupResult - Math.Sqrt(variance), 2) / (2 * variance))).Count(b => a * b < 0.001);

            return 1 - (double)s / results.Count;
        }
示例#24
0
        public double GetDiffTopicStatistic(Topic topic, IEnumerable<Group> groups)
        {
            if (groups != null && groups.Count() != 0)
            {
                return groups.Sum(g => this.GetGroupTopicStatistic(topic, g).TopicDifficulty) / groups.Count();
            }

            return 0.0;
        }
示例#25
0
        public double GetCorrTopicStatistic(Topic topic, IEnumerable<Group> groups)
        {
            if (groups != null && groups.Count() != 0)
            {
                return groups.Sum(g => this.GetGroupTopicStatistic(topic, g).RatingDifference) / groups.Count();
            }

            return 0.0;
        }
示例#26
0
 public bool NoData(User selectStudent, Topic selectTopic)
 {
     AttemptResult res = _LastAttempts.Find(x => x.User == selectStudent & x.Topic == selectTopic);
     if (res != null)
         return false;
     return true;
 }
示例#27
0
 public IEnumerable<Topic> AvailebleTopics()
 {
     //User teacherUser = _LmsService.FindService<IUserService>().GetCurrentUser();
     //return _LmsService.FindService<ICurriculumService>().GetTopicsOwnedByUser(teacherUser);
     Topic t = new Topic();
     t.Id = 99999;
     t.Name = "Test topic";
     List<Topic> res = new List<Topic>();
     res.Add(t);
     return res;
 }
示例#28
0
 public IEnumerable<AttemptResult> GetResults(Topic topic)
 {
     throw new NotImplementedException();
 }
示例#29
0
        public GroupTopicStat GetGroupTopicStatistic(Topic topic, Group group)
        {
            //Всі результати по топіку
            var results = this.GetResults(topic);

            //Результати учнів тільки даної групи
            var groupResults = results.Where(r => r.User.GroupUsers.Select(g => g.GroupRef)
                                      .Contains(group.Id))
                                      .Where(s => s.Score.ToPercents()!=null)
                                      .Select(r => new UserRating(r.User, r.Score.ToPercents().Value))
                                      .ToList();
            
            var usersParticipated = groupResults.Select(g => g.User).ToList();
            var n = usersParticipated.Count();

            if (n == 0)
            {
                return new GroupTopicStat(0, 0);
            }

            var usersIds = usersParticipated.Select(u => u.Id);

            var groupRatings = group.GroupUsers
                                    .Select(gu => new UserRating(gu.User, (gu.User.TestsTotal > 0 ? 1.0 * gu.User.TestsSum / gu.User.TestsTotal : 0)))
                                    .Where(gu => usersIds.Contains(gu.User.Id))
                                    .ToList();

            groupResults.Sort();
            groupRatings.Sort();

            var ratResults = groupResults.Select((r, i) => new { User = r.User, Index = i }).ToDictionary(a => a.User.Id, a => a.Index);
            var ratRatings = groupRatings.Select((r, i) => new { User = r.User, Index = i }).ToDictionary(a => a.User.Id, a => a.Index);

            var ratingDifference = 1.0 * usersParticipated.Sum(u => Math.Abs(ratResults[u.Id] - ratRatings[u.Id]));
            
            var ratingMax = (n * n + n) / 2;
            var ratingNormalized = 1 - (ratingDifference / ratingMax);

            var diffResults = groupResults.ToDictionary(a => a.User.Id, a => a.Score);
            var diffRatings = groupRatings.ToDictionary(a => a.User.Id, a => a.Score);

            var scoreDifference = 1.0 * usersParticipated.Sum(u => Math.Abs(diffResults[u.Id] - diffRatings[u.Id]));
            var scoreMax = n * 100;
            var scoreNormalized = 1 - (scoreDifference / scoreMax);

            return new GroupTopicStat(ratingNormalized, scoreNormalized);
        }
示例#30
0
        protected IEnumerable<TopicScore> GetTopicTagScores(Topic topic)
        {
            var topicTags = this.GetTopicTags(t => t.TopicId == topic.Id);
            var attempts = this.GetResults(topic).GroupBy(a => new { UserId = a.User.Id, TopicId = a.CurriculumChapterTopic.TopicRef }).Select(g => g.First());
            var total = 0.0;
            var count = 0;

            foreach (var attempt in attempts)
            {
                var score = attempt.Score.ToPercents();

                if (score == null)
                {
                    continue;
                }

                total += score.Value;
                count++;
            }

            var average = (float)(count > 0 ? total / count : 0);

            var tags = topicTags.Select(t => new TopicScore { TagId = t.TagId, TopicId = t.TopicId, Score = average });

            return tags;
        }