Esempio n. 1
0
def historical(request, player_id):
    player = get_object_or_404(Player, id=player_id)
    base = base_ctx("Ranking", "Rating history", request, context=player)

    latest = player.rating_set.filter(period__computed=True, decay=0).latest("period")
    historical = (
        player.rating_set.filter(period_id__lte=latest.period_id)
        .prefetch_related("prev__rta", "prev__rtb")
        .select_related("period", "prev")
        .order_by("-period")
    )

    historical = add_counts(historical)

    base.update({"player": player, "historical": historical})

    return render_to_response("historical.djhtml", base)
Esempio n. 2
0
def historical(request, player_id):
    player = get_object_or_404(Player, id=player_id)
    base = base_ctx('Ranking', 'Rating history', request, context=player)

    latest = player.rating_set.filter(period__computed=True,
                                      decay=0).latest('period')
    historical = (player.rating_set.filter(
        period_id__lte=latest.period_id).prefetch_related(
            'prev__rta',
            'prev__rtb').select_related('period', 'prev').order_by('-period'))

    historical = add_counts(historical)

    base.update({
        'player': player,
        'historical': historical,
    })

    return render_to_response('historical.djhtml', base)
Esempio n. 3
0
def historical(request, player_id):
    player = get_object_or_404(Player, id=player_id)
    base = base_ctx('Ranking', 'Rating history', request, context=player)

    latest = player.rating_set.filter(period__computed=True, decay=0).latest('period')
    historical = (
        player.rating_set.filter(period_id__lte=latest.period_id)
            .prefetch_related('prev__rta', 'prev__rtb')
            .select_related('period', 'prev')
            .order_by('-period')
    )

    historical = add_counts(historical)

    base.update({
        'player': player,
        'historical': historical,
    })

    return render_to_response('historical.djhtml', base)
Esempio n. 4
0
def player(request, player_id):
    # {{{ Get player object and base context, generate messages and make changes if needed
    player = get_object_or_404(Player, id=player_id)
    base = base_ctx('Ranking', 'Summary', request, context=player)

    if request.method == 'POST' and base['adm']:
        form = PlayerModForm(request)
        base['messages'] += form.update_player(player)
    else:
        form = PlayerModForm(player=player)

    base['messages'] += generate_messages(player)
    # }}}

    # {{{ Various easy data
    matches = player.get_matchset()
    recent = matches.filter(date__gte=(date.today() - relativedelta(months=2)))

    base.update({
        'player':           player,
        'form':             form,
        'first':            etn(lambda: matches.earliest('date')),
        'last':             etn(lambda: matches.latest('date')),
        'totalmatches':     matches.count(),
        'offlinematches':   matches.filter(offline=True).count(),
        'aliases':          player.alias_set.all(),
        'earnings':         ntz(player.earnings_set.aggregate(Sum('earnings'))['earnings__sum']),
        'team':             player.get_current_team(),
        'total':            count_winloss_player(matches, player),
        'vp':               count_matchup_player(matches, player, P),
        'vt':               count_matchup_player(matches, player, T),
        'vz':               count_matchup_player(matches, player, Z),
        'totalf':           count_winloss_player(recent, player),
        'vpf':              count_matchup_player(recent, player, P),
        'vtf':              count_matchup_player(recent, player, T),
        'vzf':              count_matchup_player(recent, player, Z),
    })

    if player.country is not None:
        base['countryfull'] = transformations.cc_to_cn(player.country)
    # }}}

    # {{{ Recent matches
    matches = player.get_matchset(related=['rta','rtb','pla','plb','eventobj'])[0:10]
    if matches.exists():
        base['matches'] = display_matches(matches, fix_left=player, ratings=True)
    # }}}

    # {{{ Team memberships
    team_memberships = list(player.groupmembership_set.filter(group__is_team=True).select_related('group'))
    team_memberships.sort(key=lambda t: t.id, reverse=True)
    team_memberships.sort(key=meandate, reverse=True)
    team_memberships.sort(key=lambda t: t.current, reverse=True)
    base['teammems'] = team_memberships
    # }}}

    # {{{ If the player has at least one rating
    if player.current_rating:
        ratings = total_ratings(player.rating_set.filter(period__computed=True)).select_related('period')
        base.update({
            'highs': (
                ratings.latest('rating'),
                ratings.latest('tot_vp'),
                ratings.latest('tot_vt'),
                ratings.latest('tot_vz'),
            ),
            'recentchange':  player.get_latest_rating_update(),
            'firstrating':   ratings.earliest('period'),
            'rating':        player.current_rating,
        })

        if player.current_rating.decay >= INACTIVE_THRESHOLD:
            base['messages'].append(Message(msg_inactive % player.tag, 'Inactive', type=Message.INFO))

        base['charts'] = base['recentchange'].period_id > base['firstrating'].period_id
    else:
        base['messages'].append(Message('%s has no rating yet.' % player.tag, type=Message.INFO))
        base['charts'] = False
    # }}}

    # {{{ If the player has enough games to make a chart
    if base['charts']:
        ratings = (
            total_ratings(player.rating_set.filter(period_id__lte=base['recentchange'].period_id))
                .select_related('period__end')
                .prefetch_related('prev__rta', 'prev__rtb')
                .order_by('period')
        )

        # {{{ Add stories and other extra information
        earliest = base['firstrating']
        latest = base['recentchange']

        # Look through team changes
        teampoints = []
        for mem in base['teammems']:
            if mem.start and earliest.period.end < mem.start < latest.period.end:
                teampoints.append({
                    'date':    mem.start,
                    'rating':  interp_rating(mem.start, ratings),
                    'data':    [{'date': mem.start, 'team': mem.group, 'jol': 'joins'}],
                })
            if mem.end and earliest.period.end < mem.end < latest.period.end:
                teampoints.append({
                    'date':    mem.end,
                    'rating':  interp_rating(mem.end, ratings),
                    'data':    [{'date': mem.end, 'team': mem.group, 'jol': 'leaves'}],
                })
        teampoints.sort(key=lambda p: p['date'])

        # Condense if team changes happened within 14 days
        cur = 0
        while cur < len(teampoints) - 1:
            if (teampoints[cur+1]['date'] - teampoints[cur]['date']).days <= 14:
                teampoints[cur]['data'].append(teampoints[cur+1]['data'][0])
                del teampoints[cur+1]
            else:
                cur += 1

        # Sort first by date, then by joined/left
        for point in teampoints:
            point['data'].sort(key=lambda a: a['jol'], reverse=True)
            point['data'].sort(key=lambda a: a['date'])

        # Look through stories
        stories = player.story_set.all().select_related('event__fullname')
        for s in stories:
            if earliest.period.start < s.date < latest.period.start:
                s.rating = interp_rating(s.date, ratings)
            else:
                s.skip = True
        # }}}

        base.update({
            'ratings':     add_counts(ratings),
            'patches':     PATCHES,
            'stories':     stories,
            'teampoints':  teampoints,
        })
    else:
        base['messages'].append(Message(msg_nochart % player.tag, type=Message.INFO))
    # }}}

    base.update({"title": player.tag})

    return render_to_response('player.html', base)
Esempio n. 5
0
def player(request, player_id):
    # {{{ Get player object and base context, generate messages and make changes if needed
    player = get_object_or_404(Player, id=player_id)
    base = base_ctx('Ranking', 'Summary', request, context=player)

    if request.method == 'POST' and 'modplayer' in request.POST and base['adm']:
        modform = PlayerModForm(request)
        base['messages'] += modform.update_player(player)
    else:
        modform = PlayerModForm(player=player)

    base['messages'] += generate_messages(player)
    # }}}

    # {{{ Various easy data
    matches = player.get_matchset()
    recent = matches.filter(date__gte=(date.today() - relativedelta(months=2)))

    base.update({
        'player':
        player,
        'modform':
        modform,
        'first':
        etn(lambda: matches.earliest('date')),
        'last':
        etn(lambda: matches.latest('date')),
        'totalmatches':
        matches.count(),
        'offlinematches':
        matches.filter(offline=True).count(),
        'aliases':
        player.alias_set.all(),
        'earnings':
        ntz(player.earnings_set.aggregate(Sum('earnings'))['earnings__sum']),
        'team':
        player.get_current_team(),
        'total':
        count_winloss_player(matches, player),
        'vp':
        count_matchup_player(matches, player, P),
        'vt':
        count_matchup_player(matches, player, T),
        'vz':
        count_matchup_player(matches, player, Z),
        'totalf':
        count_winloss_player(recent, player),
        'vpf':
        count_matchup_player(recent, player, P),
        'vtf':
        count_matchup_player(recent, player, T),
        'vzf':
        count_matchup_player(recent, player, Z),
    })

    base['riv_nem_vic'] = zip_longest(player.rivals, player.nemesis,
                                      player.victim)

    if player.country is not None:
        base['countryfull'] = transformations.cc_to_cn(player.country)
    # }}}

    # {{{ Recent matches
    matches = player.get_matchset(
        related=['rta', 'rtb', 'pla', 'plb', 'eventobj'])[0:10]
    if matches.exists():
        base['matches'] = display_matches(matches,
                                          fix_left=player,
                                          ratings=True)
    # }}}

    # {{{ Team memberships
    team_memberships = list(
        player.groupmembership_set.filter(
            group__is_team=True).select_related('group'))
    team_memberships.sort(key=lambda t: t.id, reverse=True)
    team_memberships.sort(key=meandate, reverse=True)
    team_memberships.sort(key=lambda t: t.current, reverse=True)
    base['teammems'] = team_memberships
    # }}}

    # {{{ If the player has at least one rating
    if player.current_rating:
        ratings = total_ratings(player.rating_set.filter(
            period__computed=True)).select_related('period')
        base.update({
            'highs': (
                ratings.latest('rating'),
                ratings.latest('tot_vp'),
                ratings.latest('tot_vt'),
                ratings.latest('tot_vz'),
            ),
            'recentchange':
            player.get_latest_rating_update(),
            'firstrating':
            ratings.earliest('period'),
            'rating':
            player.current_rating,
        })

        if player.current_rating.decay >= INACTIVE_THRESHOLD:
            base['messages'].append(
                Message(msg_inactive % player.tag,
                        'Inactive',
                        type=Message.INFO))

        base['charts'] = base['recentchange'].period_id > base[
            'firstrating'].period_id
    else:
        base['messages'].append(
            Message(_('%s has no rating yet.') % player.tag,
                    type=Message.INFO))
        base['charts'] = False
    # }}}

    # {{{ If the player has enough games to make a chart
    if base['charts']:
        ratings = (total_ratings(
            player.rating_set.filter(
                period_id__lte=base['recentchange'].period_id)).select_related(
                    'period').prefetch_related('prev__rta',
                                               'prev__rtb').order_by('period'))

        # {{{ Add stories and other extra information
        earliest = base['firstrating']
        latest = base['recentchange']

        # Look through team changes
        teampoints = []
        for mem in base['teammems']:
            if mem.start and earliest.period.end < mem.start < latest.period.end:
                teampoints.append({
                    'date':
                    mem.start,
                    'rating':
                    interp_rating(mem.start, ratings),
                    'data': [{
                        'date': mem.start,
                        'team': mem.group,
                        'jol': _('joins')
                    }],
                })
            if mem.end and earliest.period.end < mem.end < latest.period.end:
                teampoints.append({
                    'date':
                    mem.end,
                    'rating':
                    interp_rating(mem.end, ratings),
                    'data': [{
                        'date': mem.end,
                        'team': mem.group,
                        'jol': _('leaves')
                    }],
                })
        teampoints.sort(key=lambda p: p['date'])

        # Condense if team changes happened within 14 days
        cur = 0
        while cur < len(teampoints) - 1:
            if (teampoints[cur + 1]['date'] -
                    teampoints[cur]['date']).days <= 14:
                teampoints[cur]['data'].append(teampoints[cur + 1]['data'][0])
                del teampoints[cur + 1]
            else:
                cur += 1

        # Sort first by date, then by joined/left
        for point in teampoints:
            point['data'].sort(key=lambda a: a['jol'], reverse=True)
            point['data'].sort(key=lambda a: a['date'])

        # Look through stories
        stories = player.story_set.all().select_related('event')
        for s in stories:
            if earliest.period.start < s.date < latest.period.start:
                s.rating = interp_rating(s.date, ratings)
            else:
                s.skip = True
        # }}}

        base.update({
            'ratings': add_counts(ratings),
            'patches': PATCHES,
            'stories': stories,
            'teampoints': teampoints,
        })
    else:
        base['messages'].append(
            Message(msg_nochart % player.tag, type=Message.INFO))
    # }}}

    return render_to_response('player.djhtml', base)
Esempio n. 6
0
def player(request, player_id):
    # {{{ Get player object and base context, generate messages and make changes if needed
    player = get_object_or_404(Player, id=player_id)
    base = base_ctx("Ranking", "Summary", request, context=player)

    if request.method == "POST" and "modplayer" in request.POST and base["adm"]:
        modform = PlayerModForm(request)
        base["messages"] += modform.update_player(player)
    else:
        modform = PlayerModForm(player=player)

    base["messages"] += generate_messages(player)
    # }}}

    # {{{ Various easy data
    matches = player.get_matchset()
    recent = matches.filter(date__gte=(date.today() - relativedelta(months=2)))

    base.update(
        {
            "player": player,
            "modform": modform,
            "first": etn(lambda: matches.earliest("date")),
            "last": etn(lambda: matches.latest("date")),
            "totalmatches": matches.count(),
            "offlinematches": matches.filter(offline=True).count(),
            "aliases": player.alias_set.all(),
            "earnings": ntz(player.earnings_set.aggregate(Sum("earnings"))["earnings__sum"]),
            "team": player.get_current_team(),
            "total": count_winloss_player(matches, player),
            "vp": count_matchup_player(matches, player, P),
            "vt": count_matchup_player(matches, player, T),
            "vz": count_matchup_player(matches, player, Z),
            "totalf": count_winloss_player(recent, player),
            "vpf": count_matchup_player(recent, player, P),
            "vtf": count_matchup_player(recent, player, T),
            "vzf": count_matchup_player(recent, player, Z),
        }
    )

    riv = player.rivals or []
    nem = player.nemesis or []
    vic = player.victim or []
    base["riv_nem_vic"] = zip_longest(riv, nem, vic)

    if player.country is not None:
        base["countryfull"] = transformations.cc_to_cn(player.country)
    # }}}

    # {{{ Recent matches
    matches = player.get_matchset(related=["rta", "rtb", "pla", "plb", "eventobj"])[0:10]
    if matches.exists():
        base["matches"] = display_matches(matches, fix_left=player, ratings=True)
    # }}}

    # {{{ Team memberships
    team_memberships = list(player.groupmembership_set.filter(group__is_team=True).select_related("group"))
    team_memberships.sort(key=lambda t: t.id, reverse=True)
    team_memberships.sort(key=meandate, reverse=True)
    team_memberships.sort(key=lambda t: t.current, reverse=True)
    base["teammems"] = team_memberships
    # }}}

    # {{{ If the player has at least one rating
    if player.current_rating:
        ratings = total_ratings(player.rating_set.filter(period__computed=True)).select_related("period")
        base.update(
            {
                "highs": (
                    ratings.latest("rating"),
                    ratings.latest("tot_vp"),
                    ratings.latest("tot_vt"),
                    ratings.latest("tot_vz"),
                ),
                "recentchange": player.get_latest_rating_update(),
                "firstrating": ratings.earliest("period"),
                "rating": player.current_rating,
            }
        )

        if player.current_rating.decay >= INACTIVE_THRESHOLD:
            base["messages"].append(Message(msg_inactive % player.tag, "Inactive", type=Message.INFO))

        base["charts"] = base["recentchange"].period_id > base["firstrating"].period_id
    else:
        base["messages"].append(Message(_("%s has no rating yet.") % player.tag, type=Message.INFO))
        base["charts"] = False
    # }}}

    # {{{ If the player has enough games to make a chart
    if base["charts"]:
        ratings = (
            total_ratings(player.rating_set.filter(period_id__lte=base["recentchange"].period_id))
            .select_related("period__end")
            .prefetch_related("prev__rta", "prev__rtb")
            .order_by("period")
        )

        # {{{ Add stories and other extra information
        earliest = base["firstrating"]
        latest = base["recentchange"]

        # Look through team changes
        teampoints = []
        for mem in base["teammems"]:
            if mem.start and earliest.period.end < mem.start < latest.period.end:
                teampoints.append(
                    {
                        "date": mem.start,
                        "rating": interp_rating(mem.start, ratings),
                        "data": [{"date": mem.start, "team": mem.group, "jol": _("joins")}],
                    }
                )
            if mem.end and earliest.period.end < mem.end < latest.period.end:
                teampoints.append(
                    {
                        "date": mem.end,
                        "rating": interp_rating(mem.end, ratings),
                        "data": [{"date": mem.end, "team": mem.group, "jol": _("leaves")}],
                    }
                )
        teampoints.sort(key=lambda p: p["date"])

        # Condense if team changes happened within 14 days
        cur = 0
        while cur < len(teampoints) - 1:
            if (teampoints[cur + 1]["date"] - teampoints[cur]["date"]).days <= 14:
                teampoints[cur]["data"].append(teampoints[cur + 1]["data"][0])
                del teampoints[cur + 1]
            else:
                cur += 1

        # Sort first by date, then by joined/left
        for point in teampoints:
            point["data"].sort(key=lambda a: a["jol"], reverse=True)
            point["data"].sort(key=lambda a: a["date"])

        # Look through stories
        stories = player.story_set.all().select_related("event__fullname")
        for s in stories:
            if earliest.period.start < s.date < latest.period.start:
                s.rating = interp_rating(s.date, ratings)
            else:
                s.skip = True
        # }}}

        base.update({"ratings": add_counts(ratings), "patches": PATCHES, "stories": stories, "teampoints": teampoints})
    else:
        base["messages"].append(Message(msg_nochart % player.tag, type=Message.INFO))
    # }}}

    return render_to_response("player.djhtml", base)