Exemple #1
0
    def most_recent(cls, user, n, batch=None):
        queryset = cls.objects.filter(hidden=False).select_related('author__user') \
            .defer('author__about', 'body').order_by('-id')

        problem_access = CacheDict(lambda code: Problem.objects.get(code=code).is_accessible_by(user))
        contest_access = CacheDict(lambda key: Contest.objects.get(key=key).is_accessible_by(user))

        if user.is_superuser:
            return queryset[:n]
        if batch is None:
            batch = 2 * n
        output = []
        for i in itertools.count(0):
            slice = queryset[i * batch:i * batch + batch]
            if not slice:
                break
            for comment in slice:
                if comment.page.startswith('p:'):
                    try:
                        if problem_access[comment.page[2:]]:
                            output.append(comment)
                    except Problem.DoesNotExist:
                        pass
                elif comment.page.startswith('c:'):
                    try:
                        if contest_access[comment.page[2:]]:
                            output.append(comment)
                    except Contest.DoesNotExist:
                        pass
                else:
                    output.append(comment)
                if len(output) >= n:
                    return output
        return output
Exemple #2
0
    def get_context_data(self, **kwargs):
        context = super(PostList, self).get_context_data(**kwargs)
        context['title'] = self.title or _(
            'Page %d of Posts') % context['page_obj'].number
        context['first_page_href'] = reverse('home')
        context['page_prefix'] = reverse('blog_post_list')
        context['comments'] = Comment.most_recent(self.request.user, 10)
        context['new_problems'] = Problem.objects.filter(
            is_public=True,
            is_organization_private=False).order_by('-date', '-id')[:7]
        context['page_titles'] = CacheDict(
            lambda page: Comment.get_page_title(page))

        context['has_clarifications'] = False
        if self.request.user.is_authenticated:
            participation = self.request.profile.current_contest
            if participation:
                clarifications = ProblemClarification.objects.filter(
                    problem__in=participation.contest.problems.all())
                context['has_clarifications'] = clarifications.count() > 0
                context['clarifications'] = clarifications.order_by('-date')

        context['user_count'] = lazy(Profile.objects.count, int, long)
        context['problem_count'] = lazy(
            Problem.objects.filter(is_public=True).count, int, long)
        context['submission_count'] = lazy(Submission.objects.count, int, long)
        context['language_count'] = lazy(Language.objects.count, int, long)

        context['post_comment_counts'] = {
            int(page[2:]): count
            for page, count in Comment.objects.filter(
                page__in=['b:%d' % post.id for post in context['posts']],
                hidden=False).values_list('page').annotate(
                    count=Count('page')).order_by()
        }

        now = timezone.now()

        visible_contests = Contest.contests_list(
            self.request.user).order_by('start_time')

        context['current_contests'] = visible_contests.filter(
            start_time__lte=now, end_time__gt=now)
        context['future_contests'] = visible_contests.filter(
            start_time__gt=now)

        if self.request.user.is_authenticated:
            context['own_open_tickets'] = Ticket.tickets_list(
                self.request.user, author=self.request.user)
        else:
            context['own_open_tickets'] = []

        # Superusers better be staffs, not the spell-casting kind either.
        if self.request.user.is_staff:
            context['open_tickets'] = Ticket.tickets_list(
                self.request.user)[:10]
        else:
            context['open_tickets'] = []
        return context
Exemple #3
0
 def get_context_data(self, **kwargs):
     context = super().get_context_data(**kwargs)
     context['unseen_count'] = self.unseen_cnt
     context['title'] = _('Notifications (%d unseen)' %
                          context['unseen_count'])
     context['has_notifications'] = self.queryset.exists()
     context['page_titles'] = CacheDict(
         lambda page: Comment.get_page_title(page))
     return context
Exemple #4
0
    def most_recent(cls, user, n, batch=None):
        queryset = cls.objects.filter(hidden=False).select_related('author__user') \
            .defer('author__about', 'body').order_by('-id')

        problem_cache = CacheDict(lambda code: Problem.objects.defer(
            'description', 'summary').get(code=code))
        solution_cache = CacheDict(lambda code: Solution.objects.defer(
            'content').get(problem__code=code))
        contest_cache = CacheDict(
            lambda key: Contest.objects.defer('description').get(key=key))
        blog_cache = CacheDict(
            lambda id: BlogPost.objects.defer('summary', 'content').get(id=id))

        problem_access = CacheDict(
            lambda code: problem_cache[code].is_accessible_by(user))
        solution_access = CacheDict(lambda code: problem_access[
            code] and solution_cache[code].is_accessible_by(user))
        contest_access = CacheDict(
            lambda key: contest_cache[key].is_accessible_by(user))
        blog_access = CacheDict(lambda id: blog_cache[id].can_see(user))

        if batch is None:
            batch = 2 * n
        output = []
        for i in itertools.count(0):
            slice = queryset[i * batch:i * batch + batch]
            if not slice:
                break
            for comment in slice:
                page_key = comment.page[2:]
                try:
                    if comment.page.startswith('p:'):
                        has_access = problem_access[page_key]
                        comment.page_title = problem_cache[page_key].name
                    elif comment.page.startswith('s:'):
                        has_access = solution_access[page_key]
                        comment.page_title = _(
                            'Editorial for %s') % problem_cache[page_key].name
                    elif comment.page.startswith('c:'):
                        has_access = contest_access[page_key]
                        comment.page_title = contest_cache[page_key].name
                    elif comment.page.startswith('b:'):
                        has_access = blog_access[page_key]
                        comment.page_title = blog_cache[page_key].title
                    else:
                        has_access = True
                except ObjectDoesNotExist:
                    pass
                else:
                    if has_access:
                        output.append(comment)
                if len(output) >= n:
                    return output
        return output
Exemple #5
0
    def get_context_data(self, **kwargs):
        if not self.request.user.is_authenticated:
            raise Http404()
        user = self.request.user
        profile = self.request.profile
        context = super(UserDashboard, self).get_context_data(**kwargs)
        context['recently_attempted_problems'] = (Submission.objects.filter(
            user=profile, problem__is_public=True).exclude(
                problem__id__in=user_completed_ids(profile)).values_list(
                    'problem__code', 'problem__name',
                    'problem__points').annotate(
                        points=Max('points'),
                        latest=Max('date')).order_by('-latest'))[:7]
        context['own_comments'] = Comment.most_recent(user, 10, author=user)
        context['page_titles'] = CacheDict(
            lambda page: Comment.get_page_title(page))

        return context
Exemple #6
0
    def get_context_data(self, **kwargs):
        context = super(PostList, self).get_context_data(**kwargs)
        context['title'] = self.title or _('Page %d of Posts') % context['page_obj'].number
        context['first_page_href'] = reverse('home')
        context['page_prefix'] = reverse('blog_post_list')
        context['comments'] = Comment.most_recent(self.request.user, 10)
        context['new_problems'] = Problem.objects.filter(is_public=True, is_organization_private=False) \
                                         .order_by('-date', '-id')[:settings.DMOJ_BLOG_NEW_PROBLEM_COUNT]
        context['page_titles'] = CacheDict(lambda page: Comment.get_page_title(page))

        context['has_clarifications'] = False
        if self.request.user.is_authenticated:
            participation = self.request.profile.current_contest
            if participation:
                clarifications = ProblemClarification.objects.filter(problem__in=participation.contest.problems.all())
                context['has_clarifications'] = clarifications.count() > 0
                context['clarifications'] = clarifications.order_by('-date')

        context['user_count'] = lazy(Profile.objects.count, int, int)
        context['problem_count'] = lazy(Problem.objects.filter(is_public=True).count, int, int)
        context['submission_count'] = lazy(Submission.objects.count, int, int)
        context['language_count'] = lazy(Language.objects.count, int, int)

        context['post_comment_counts'] = {
            int(page[2:]): count for page, count in
            Comment.objects
                   .filter(page__in=['b:%d' % post.id for post in context['posts']], hidden=False)
                   .values_list('page').annotate(count=Count('page')).order_by()
        }

        now = timezone.now()

        # Dashboard stuff
        if self.request.user.is_authenticated:
            user = self.request.profile
            context['recently_attempted_problems'] = (Submission.objects.filter(user=user)
                                                      .exclude(problem__in=user_completed_ids(user))
                                                      .values_list('problem__code', 'problem__name', 'problem__points')
                                                      .annotate(points=Max('points'), latest=Max('date'))
                                                      .order_by('-latest')
                                                      [:settings.DMOJ_BLOG_RECENTLY_ATTEMPTED_PROBLEMS_COUNT])

        visible_contests = Contest.get_visible_contests(self.request.user).filter(is_visible=True) \
                                  .order_by('start_time')

        context['current_contests'] = visible_contests.filter(start_time__lte=now, end_time__gt=now)
        context['future_contests'] = visible_contests.filter(start_time__gt=now)

        if self.request.user.is_authenticated:
            profile = self.request.profile
            context['own_open_tickets'] = (Ticket.objects.filter(user=profile, is_open=True).order_by('-id')
                                           .prefetch_related('linked_item').select_related('user__user'))
        else:
            profile = None
            context['own_open_tickets'] = []

        # Superusers better be staffs, not the spell-casting kind either.
        if self.request.user.is_staff:
            tickets = (Ticket.objects.order_by('-id').filter(is_open=True).prefetch_related('linked_item')
                             .select_related('user__user'))
            context['open_tickets'] = filter_visible_tickets(tickets, self.request.user, profile)[:10]
        else:
            context['open_tickets'] = []
        return context
Exemple #7
0
def RawSQLColumn(model, field=None):
    if isinstance(model, Field):
        field = model
        model = field.model
    if isinstance(field, six.string_types):
        field = model._meta.get_field(field)
    return RawSQL(
        '%s.%s' % (model._meta.db_table, field.get_attname_column()[1]), ())


def make_straight_join_query(QueryType):
    class Query(QueryType):
        def join(self, join, reuse=None):
            alias = super(Query, self).join(join, reuse)
            join = self.alias_map[alias]
            if join.join_type == INNER:
                join.join_type = 'STRAIGHT_JOIN'
            return alias

    return Query


straight_join_cache = CacheDict(make_straight_join_query)


def use_straight_join(queryset):
    if connections[queryset.db].vendor != 'mysql':
        return
    queryset.query = queryset.query.clone(straight_join_cache[type(
        queryset.query)])