示例#1
0
def db(request):
    base = base_ctx('About', 'Database', request)

    base.update({
        'nmatches':      Match.objects.all().count(),
        'nuntreated':    Match.objects.filter(treated=False).count(),
        'ngames':        sum(count_winloss_games(Match.objects.all())),

        'nwol':          Match.objects.filter(game=WOL).count(),
        'nhots':         Match.objects.filter(game=HOTS).count(),
        'nlotv':         Match.objects.filter(game=LOTV).count(),
        'nwolgames':     sum(count_winloss_games(Match.objects.filter(game=WOL))),
        'nhotsgames':    sum(count_winloss_games(Match.objects.filter(game=HOTS))),
        'nlotvgames':    sum(count_winloss_games(Match.objects.filter(game=LOTV))),

        'nonline':       Match.objects.filter(offline=False).count(),
        'nonlinegames':  sum(count_winloss_games(Match.objects.filter(offline=False))),

        'npartial':      Match.objects.exclude(eventobj__isnull=True, event='').count(),
        'nfull':         Match.objects.filter(eventobj__isnull=False).count(),

        'nplayers':      Player.objects.all().count(),
        'nkoreans':      Player.objects.filter(country='KR').count(),
        'nteams':        Group.objects.filter(is_team=True).count(),
        'nactive':       Group.objects.filter(active=True, is_team=True).count(),

        'submitters':    [
            u for u in User.objects.all().annotate(nmatches=Count('match')).order_by('-nmatches')
            if u.nmatches > 0
        ],

        'dump':          os.path.exists(DUMP_PATH),
        'updated':       datetime.fromtimestamp(os.stat(PROJECT_PATH + 'update').st_mtime),

        'dbtables':      DBTABLES,
    })

    base.update({
        'noffline':       base['nmatches'] - base['nonline'],
        'nofflinegames':  base['ngames']   - base['nonlinegames'],
        'nuncatalogued':  base['nmatches'] - base['nfull'],
        'ninactive':      base['nteams']   - base['nactive'],
    })

    if base['dump']:
        stat = os.stat(os.path.join(DUMP_PATH, 'aligulac.sql'))
        base.update({
            'megabytes':  stat.st_size / 1048576,
            'modified':   datetime.fromtimestamp(stat.st_mtime),
        })
        stat = os.stat(os.path.join(DUMP_PATH, 'aligulac.sql.gz'))
        base.update({
            'gz_megabytes':  stat.st_size / 1048576
        })

    base.update({'title': _('Database status')})

    return render_to_response('db.html', base)
示例#2
0
def db(request):
    base = base_ctx("About", "Database", request)

    base.update(
        {
            "nmatches": Match.objects.all().count(),
            "nuntreated": Match.objects.filter(treated=False).count(),
            "ngames": sum(count_winloss_games(Match.objects.all())),
            "nwol": Match.objects.filter(game=WOL).count(),
            "nhots": Match.objects.filter(game=HOTS).count(),
            "nlotv": Match.objects.filter(game=LOTV).count(),
            "nwolgames": sum(count_winloss_games(Match.objects.filter(game=WOL))),
            "nhotsgames": sum(count_winloss_games(Match.objects.filter(game=HOTS))),
            "nlotvgames": sum(count_winloss_games(Match.objects.filter(game=LOTV))),
            "nonline": Match.objects.filter(offline=False).count(),
            "nonlinegames": sum(count_winloss_games(Match.objects.filter(offline=False))),
            "npartial": Match.objects.exclude(eventobj__isnull=True, event="").count(),
            "nfull": Match.objects.filter(eventobj__isnull=False).count(),
            "nplayers": Player.objects.all().count(),
            "nkoreans": Player.objects.filter(country="KR").count(),
            "nteams": Group.objects.filter(is_team=True).count(),
            "nactive": Group.objects.filter(active=True, is_team=True).count(),
            "submitters": [
                u for u in User.objects.all().annotate(nmatches=Count("match")).order_by("-nmatches") if u.nmatches > 0
            ],
            "dump": os.path.exists(DUMP_PATH),
            "updated": datetime.fromtimestamp(os.stat(PROJECT_PATH + "update").st_mtime),
            "dbtables": DBTABLES,
        }
    )

    base.update(
        {
            "noffline": base["nmatches"] - base["nonline"],
            "nofflinegames": base["ngames"] - base["nonlinegames"],
            "nuncatalogued": base["nmatches"] - base["nfull"],
            "ninactive": base["nteams"] - base["nactive"],
        }
    )

    if base["dump"]:
        stat = os.stat(os.path.join(DUMP_PATH, "aligulac.sql"))
        base.update({"megabytes": stat.st_size / 1048576, "modified": datetime.fromtimestamp(stat.st_mtime)})
        stat = os.stat(os.path.join(DUMP_PATH, "aligulac.sql.gz"))
        base.update({"gz_megabytes": stat.st_size / 1048576})

    return render_to_response("db.djhtml", base)
示例#3
0
def db(request):
    base = base_ctx('About', 'Database', request)

    base.update({
        'nmatches':
        Match.objects.all().count(),
        'nuntreated':
        Match.objects.filter(treated=False).count(),
        'ngames':
        sum(count_winloss_games(Match.objects.all())),
        'nwol':
        Match.objects.filter(game=WOL).count(),
        'nhots':
        Match.objects.filter(game=HOTS).count(),
        'nlotv':
        Match.objects.filter(game=LOTV).count(),
        'nwolgames':
        sum(count_winloss_games(Match.objects.filter(game=WOL))),
        'nhotsgames':
        sum(count_winloss_games(Match.objects.filter(game=HOTS))),
        'nlotvgames':
        sum(count_winloss_games(Match.objects.filter(game=LOTV))),
        'nonline':
        Match.objects.filter(offline=False).count(),
        'nonlinegames':
        sum(count_winloss_games(Match.objects.filter(offline=False))),
        'npartial':
        Match.objects.exclude(eventobj__isnull=True, event='').count(),
        'nfull':
        Match.objects.filter(eventobj__isnull=False).count(),
        'nplayers':
        Player.objects.all().count(),
        'nkoreans':
        Player.objects.filter(country='KR').count(),
        'nteams':
        Group.objects.filter(is_team=True).count(),
        'nactive':
        Group.objects.filter(active=True, is_team=True).count(),
        'submitters': [
            u for u in User.objects.all().annotate(
                nmatches=Count('match')).order_by('-nmatches')
            if u.nmatches > 0
        ],
        'dump':
        os.path.exists(DUMP_PATH),
        'updated':
        datetime.fromtimestamp(os.stat(PROJECT_PATH + 'update').st_mtime),
        'dbtables':
        DBTABLES,
    })

    base.update({
        'noffline': base['nmatches'] - base['nonline'],
        'nofflinegames': base['ngames'] - base['nonlinegames'],
        'nuncatalogued': base['nmatches'] - base['nfull'],
        'ninactive': base['nteams'] - base['nactive'],
    })

    if base['dump']:
        stat = os.stat(os.path.join(DUMP_PATH, 'aligulac.sql'))
        base.update({
            'megabytes': stat.st_size / 1048576,
            'modified': datetime.fromtimestamp(stat.st_mtime),
        })
        stat = os.stat(os.path.join(DUMP_PATH, 'aligulac.sql.gz'))
        base.update({'gz_megabytes': stat.st_size / 1048576})

    return render_to_response('db.djhtml', base)
示例#4
0
def events(request, event_id=None):
    # {{{ Get base context, redirect if necessary
    if 'goto' in request.GET:
        return redirect('/results/events/' + request.GET['goto'])

    base = base_ctx('Results', 'By Event', request)
    # }}}

    # {{{ Display the main table if event ID is not given
    if event_id is None:
        root_events = (
            Event.objects
                  .annotate(num_uplinks=Count("uplink"))
                  .filter(num_uplinks=1)
                  .order_by('name')
                  .only('id', 'name', 'big', 'category', 'fullname')
        )
        base.update({
            'bigs': (
                list(root_events.filter(big=True, category=CAT_INDIVIDUAL)) +
                list(root_events.filter(big=True, category=CAT_TEAM)) +
                list(root_events.filter(big=True, category=CAT_FREQUENT))
            ),
            'smalls': (
                list(root_events.filter(big=False, category=CAT_INDIVIDUAL).order_by('name')) +
                list(root_events.filter(big=False, category=CAT_TEAM).order_by('name')) +
                list(root_events.filter(big=False, category=CAT_FREQUENT).order_by('name'))
            )
        })

        base['messages'].append(Message(
            _('The events are organized in a hierarchical fashion. Thus, all GSL tournaments '
              'are filed under GSL, all Code S under their respective seasons, all groups under '
              'their respective Code S event, and so on.'),
            type=Message.INFO
        ))

        return render_to_response('events.djhtml', base)
    # }}}

    # {{{ Get object, generate messages, and ensure big is set. Find familial relationships.
    event = get_object_or_404(Event, id=event_id)
    base['messages'] += generate_messages(event)

    matches = event.get_matchset()
    if matches.count() > 200 and not event.big:
        event.set_big(True)

    base.update({
        'event':            event,
        'siblings':         event.get_parent().get_immediate_children().exclude(id=event.id)
                                if event.get_parent() else None,
        'path':             event.get_ancestors(id=True),
        'children':         event.get_immediate_children(),
    })
    # }}}

    # {{{ Make forms
    if base['adm']:
        def check_form(formname, cl, check):
            if request.method == 'POST' and check in request.POST:
                f = cl(request=request, event=event)
                base['messages'] += f.update_event(event)
            else:
                f = cl(event=event)
            base[formname] = f

        check_form('form', EventModForm, 'modevent')
        check_form('addform', AddForm, 'addevent')
        if event.has_children():
            check_form('reorderform', ReorderForm, 'reorder')
        if event.type == TYPE_EVENT:
            check_form('ppform', PrizepoolModForm, 'modpp')
            check_form('wcsform', WCSModForm, 'modwcs')
        if not event.has_children() and event.get_immediate_matchset().exists():
            check_form('stform', StoriesForm, 'modstory')

        if 'close' in request.GET and request.GET['close'] == '1':
            event.close()
            base['messages'].append(Message(_('Sucessfully closed event.'), type=Message.SUCCESS))
    # }}}

    # {{{ Prizepool information for the public
    total_earnings = Earnings.objects.filter(event__uplink__parent=event)

    local_earnings = Earnings.objects.filter(event=event)

    ranked_prize = local_earnings.exclude(placement=0)\
                                 .order_by('-earnings', 'placement')
    unranked_prize = list(
        local_earnings.filter(placement=0).order_by('-earnings')
    )

    placements = get_placements(event)
    prize_pool_table = list()
    for k, g in groupby(ranked_prize, key=lambda x: x.earnings):
        gl = list(g)
        prize_pool_table.append((k, placements[k], gl, len(gl)))

    if len(prize_pool_table) > 0:
        base['ranked_prize'] = prize_pool_table
    if len(unranked_prize) > 0:
        base['unranked_prize'] = unranked_prize

    currencies = list({r['currency'] for r in total_earnings.values('currency').distinct()})
    base.update({
        'prizepool':     total_earnings.aggregate(Sum('earnings'))['earnings__sum'],
        'nousdpp':       len(currencies) > 1 or len(currencies) == 1 and currencies[0] != 'USD',
        'prizepoolorig': [{
            'pp':  total_earnings.filter(currency=k).aggregate(Sum('origearnings'))['origearnings__sum'],
            'cur': k,
        } for k in currencies],
    })
    # }}}

    # {{{ Other easy statistics

    add_links = request.user.is_authenticated() and request.user.is_staff

    base.update({
        'game':      etn(lambda: dict(GAMES)[matches.values('game').distinct()[0]['game']]),
        'nmatches':  matches.count(),
        'ngames':    sum(count_winloss_games(matches)),
        'pvp_games': count_mirror_games(matches, 'P'),
        'tvt_games': count_mirror_games(matches, 'T'),
        'zvz_games': count_mirror_games(matches, 'Z'),
        'matches':   display_matches(
            matches.prefetch_related('message_set')
                .prefetch_related('pla', 'plb', 'eventobj')
                .annotate(Count('eventobj__match'))
                .order_by('-eventobj__latest', '-eventobj__idx', '-date', '-id')[0:200],
            eventcount=True,
            add_links=add_links
        ),
        'nplayers':  Player.objects.filter(
            Q(id__in=matches.values('pla')) | Q(id__in=matches.values('plb'))
        ).count(),
    })

    offlines = list(matches.values('offline').distinct())
    if len(offlines) > 1:
        base['offline'] = _('Both')
    elif len(offlines) == 1:
        base['offline'] = _('Offline') if offlines[0]['offline'] else _('Online')

    base['pvt_wins'], base['pvt_loss'] = count_matchup_games(matches, 'P', 'T')
    base['pvz_wins'], base['pvz_loss'] = count_matchup_games(matches, 'P', 'Z')
    base['tvz_wins'], base['tvz_loss'] = count_matchup_games(matches, 'T', 'Z')
    base['tot_mirror'] = base['pvp_games'] + base['tvt_games'] + base['zvz_games']
    # }}}

    return render_to_response('eventres.djhtml', base)
示例#5
0
def match(request):
    base = base_ctx('Inference', 'Predict', request=request)

    # {{{ Get data, set up and simulate
    form = SetupForm(request.GET)
    if not form.is_valid():
        return redirect('/inference/')

    result = MatchPredictionResult(
        dbpl=form.cleaned_data['ps'],
        bos=form.cleaned_data['bo'],
        s1=get_param(request, 's1', 0),
        s2=get_param(request, 's2', 0),
    )
    # }}}

    # {{{ Postprocessing
    base.update({
        'form': form,
        'dbpl': result.dbpl,
        'rta': result.rta,
        'rtb': result.rtb,
        'proba': result.proba,
        'probb': result.probb,
        'match': result.obj,
    })

    base.update({
        'max': max(base['proba'], base['probb']),
        'fav': result.dbpl[0] if base['proba'] > base['probb'] else result.dbpl[1],
    })

    resa = [oc for oc in result.outcomes if oc['sca'] > oc['scb']]
    resb = [oc for oc in result.outcomes if oc['scb'] > oc['sca']]
    if len(resa) < len(resb):
        resa = [None] * (len(resb) - len(resa)) + resa
    else:
        resb = [None] * (len(resa) - len(resb)) + resb
    base['res'] = list(zip(resa, resb))
    # }}}

    # {{{ Scores and other data
    dbpl = result.dbpl
    thr = date.today() - relativedelta(months=2)
    pla_matches = dbpl[0].get_matchset()
    plb_matches = dbpl[1].get_matchset()
    base['tot_w_a'], base['tot_l_a'] = count_winloss_player(pla_matches, dbpl[0])
    base['frm_w_a'], base['frm_l_a'] = count_winloss_player(pla_matches.filter(date__gte=thr), dbpl[0])
    base['tot_w_b'], base['tot_l_b'] = count_winloss_player(plb_matches, dbpl[1])
    base['frm_w_b'], base['frm_l_b'] = count_winloss_player(plb_matches.filter(date__gte=thr), dbpl[1])
    if dbpl[1].race in 'PTZ':
        base['mu_w_a'], base['mu_l_a'] = count_matchup_player(pla_matches, dbpl[0], dbpl[1].race)
        base['fmu_w_a'], base['fmu_l_a'] = count_matchup_player(
            pla_matches.filter(date__gte=thr), dbpl[0], dbpl[1].race
        )
    if dbpl[0].race in 'PTZ':
        base['mu_w_b'], base['mu_l_b'] = count_matchup_player(plb_matches, dbpl[1], dbpl[0].race)
        base['fmu_w_b'], base['fmu_l_b'] = count_matchup_player(
            plb_matches.filter(date__gte=thr), dbpl[1], dbpl[0].race
        )
    wa_a, wb_a = count_winloss_games(Match.objects.filter(pla=dbpl[0], plb=dbpl[1]))
    wb_b, wa_b = count_winloss_games(Match.objects.filter(pla=dbpl[1], plb=dbpl[0]))
    base['vs_a'] = wa_a + wa_b
    base['vs_b'] = wb_a + wb_b

    base['matches'] = display_matches(
        Match.objects.filter(Q(pla=dbpl[0], plb=dbpl[1]) | Q(plb=dbpl[0], pla=dbpl[1]))
            .select_related('period', 'pla', 'plb')
            .order_by('-date', 'id'),
        fix_left=dbpl[0],
    )
    # }}}

    postable_match(base, request)

    return render_to_response('pred_match.djhtml', base)
示例#6
0
def events(request, event_id=None):
    # {{{ Get base context, redirect if necessary
    if 'goto' in request.GET:
        return redirect('/results/events/' + request.GET['goto'])

    base = base_ctx('Results', 'By Event', request)
    # }}}

    # {{{ Display the main table if event ID is not given
    if event_id is None:
        root_events = (
            Event.objects
                .annotate(num_uplinks=Count("uplink"))
                .filter(num_uplinks=1)
                .order_by('name')
                .only('id', 'name', 'big', 'category', 'fullname')
        )
        base.update({
            'ind_bigs':    collect(root_events.filter(big=True, category=CAT_INDIVIDUAL), 2),
            'ind_smalls':  root_events.filter(big=False, category=CAT_INDIVIDUAL).order_by('name'),
            'team_bigs':   collect(root_events.filter(big=True, category=CAT_TEAM), 2),
            'team_smalls': root_events.filter(big=False, category=CAT_TEAM).order_by('name'),
            'freq_bigs':   collect(root_events.filter(big=True, category=CAT_FREQUENT), 2),
            'freq_smalls': root_events.filter(big=False, category=CAT_FREQUENT).order_by('name'),
        })

        return render_to_response('events.html', base)
    # }}}

    # {{{ Get object, generate messages, and ensure big is set. Find familial relationships.
    event = get_object_or_404(Event, id=event_id)
    base['messages'] += generate_messages(event)

    matches = event.get_matchset()
    if matches.count() > 200 and not event.big:
        event.set_big(True)

    base.update({
        'event':            event,
        'siblings':         event.get_parent().get_immediate_children().exclude(id=event.id)
                                if event.get_parent() else None,
        'path':             event.get_ancestors(id=True),
        'children':         event.get_immediate_children(),
    })
    # }}}

    # {{{ Make forms
    if base['adm']:
        def check_form(formname, cl, check):
            if request.method == 'POST' and check in request.POST:
                f = cl(request=request, event=event)
                base['messages'] += f.update_event(event)
            else:
                f = cl(event=event)
            base[formname] = f

        check_form('form', EventModForm, 'modevent')
        check_form('addform', AddForm, 'addevent')
        if event.has_children():
            check_form('reorderform', ReorderForm, 'reorder')
        if event.type == TYPE_EVENT:
            check_form('ppform', PrizepoolModForm, 'modpp')
        if not event.has_children() and event.get_immediate_matchset().exists():
            check_form('stform', StoryModForm, 'modstories')
    # }}}

    # {{{ Prizepool information for the public
    total_earnings = Earnings.objects.filter(event__uplink__parent=event)
    currencies = list({r['currency'] for r in total_earnings.values('currency').distinct()})
    base.update({
        'prizepool':     total_earnings.aggregate(Sum('earnings'))['earnings__sum'],
        'nousdpp':       len(currencies) > 1 or len(currencies) == 1 and currencies[0] != 'USD',
        'prizepoolorig': [{
            'pp':  total_earnings.filter(currency=k).aggregate(Sum('origearnings'))['origearnings__sum'],
            'cur': k,
        } for k in currencies],
    })
    # }}}

    # {{{ Other easy statistics
    base.update({
        'game':      etn(lambda: dict(Match.GAMES)[matches.values('game').distinct()[0]['game']]),
        'offline':   etn(lambda: matches.values('offline').distinct()[0]['offline']),
        'nmatches':  matches.count(),
        'ngames':    sum(count_winloss_games(matches)),
        'pvp_games': count_mirror_games(matches, 'P'),
        'tvt_games': count_mirror_games(matches, 'T'),
        'zvz_games': count_mirror_games(matches, 'Z'),
        'matches':   display_matches(
            matches.prefetch_related('message_set')
                .prefetch_related('pla', 'plb', 'eventobj')
                .annotate(Count('eventobj__match'))
                .order_by('-eventobj__latest', '-eventobj__idx', '-date', '-id')[0:200],
            eventcount=True,
        ),
        'nplayers':  Player.objects.filter(
            Q(id__in=matches.values('pla')) | Q(id__in=matches.values('plb'))
        ).count(),
    })

    base['pvt_wins'], base['pvt_loss'] = count_matchup_games(matches, 'P', 'T')
    base['pvz_wins'], base['pvz_loss'] = count_matchup_games(matches, 'P', 'Z')
    base['tvz_wins'], base['tvz_loss'] = count_matchup_games(matches, 'T', 'Z')
    base['tot_mirror'] = base['pvp_games'] + base['tvt_games'] + base['zvz_games']
    # }}}

    base.update({"title": event})

    return render_to_response('eventres.html', base)
示例#7
0
def events(request, event_id=None):
    # {{{ Get base context, redirect if necessary
    if 'goto' in request.GET:
        return redirect('/results/events/' + request.GET['goto'])

    base = base_ctx('Results', 'By Event', request)
    # }}}

    # {{{ Display the main table if event ID is not given
    if event_id is None:
        root_events = (Event.objects.annotate(
            num_uplinks=Count("uplink")).filter(
                num_uplinks=1).order_by('name').only('id', 'name', 'big',
                                                     'category', 'fullname'))
        base.update({
            'bigs':
            (list(root_events.filter(big=True, category=CAT_INDIVIDUAL)) +
             list(root_events.filter(big=True, category=CAT_TEAM)) +
             list(root_events.filter(big=True, category=CAT_FREQUENT))),
            'smalls':
            (list(
                root_events.filter(big=False,
                                   category=CAT_INDIVIDUAL).order_by('name')) +
             list(
                 root_events.filter(big=False,
                                    category=CAT_TEAM).order_by('name')) +
             list(
                 root_events.filter(big=False,
                                    category=CAT_FREQUENT).order_by('name')))
        })

        base['messages'].append(
            Message(_(
                'The events are organized in a hierarchical fashion. Thus, all GSL tournaments '
                'are filed under GSL, all Code S under their respective seasons, all groups under '
                'their respective Code S event, and so on.'),
                    type=Message.INFO))

        return render_to_response('events.djhtml', base)
    # }}}

    # {{{ Get object, generate messages, and ensure big is set. Find familial relationships.
    event = get_object_or_404(Event, id=event_id)
    base['messages'] += generate_messages(event)

    matches = event.get_matchset()
    if matches.count() > 200 and not event.big:
        event.set_big(True)

    base.update({
        'event':
        event,
        'siblings':
        event.get_parent().get_immediate_children().exclude(
            id=event.id) if event.get_parent() else None,
        'path':
        event.get_ancestors(id=True),
        'children':
        event.get_immediate_children(),
    })
    # }}}

    # {{{ Make forms
    if base['adm']:

        def check_form(formname, cl, check):
            if request.method == 'POST' and check in request.POST:
                f = cl(request=request, event=event)
                base['messages'] += f.update_event(event)
            else:
                f = cl(event=event)
            base[formname] = f

        check_form('form', EventModForm, 'modevent')
        check_form('addform', AddForm, 'addevent')
        if event.has_children():
            check_form('reorderform', ReorderForm, 'reorder')
        if event.type == TYPE_EVENT:
            check_form('ppform', PrizepoolModForm, 'modpp')
        if not event.has_children() and event.get_immediate_matchset().exists(
        ):
            check_form('stform', StoriesForm, 'modstory')
    # }}}

    # {{{ Prizepool information for the public
    total_earnings = Earnings.objects.filter(event__uplink__parent=event)

    local_earnings = Earnings.objects.filter(event=event)

    ranked_prize = local_earnings.exclude(placement=0)\
                                 .order_by('-earnings', 'placement')
    unranked_prize = list(
        local_earnings.filter(placement=0).order_by('-earnings'))

    placements = get_placements(event)
    prize_pool_table = list()
    for k, g in groupby(ranked_prize, key=lambda x: x.earnings):
        gl = list(g)
        prize_pool_table.append((k, placements[k], gl, len(gl)))

    if len(prize_pool_table) > 0:
        base['ranked_prize'] = prize_pool_table
    if len(unranked_prize) > 0:
        base['unranked_prize'] = unranked_prize

    currencies = list(
        {r['currency']
         for r in total_earnings.values('currency').distinct()})
    base.update({
        'prizepool':
        total_earnings.aggregate(Sum('earnings'))['earnings__sum'],
        'nousdpp':
        len(currencies) > 1 or len(currencies) == 1 and currencies[0] != 'USD',
        'prizepoolorig': [{
            'pp':
            total_earnings.filter(currency=k).aggregate(
                Sum('origearnings'))['origearnings__sum'],
            'cur':
            k,
        } for k in currencies],
    })
    # }}}

    # {{{ Other easy statistics

    add_links = request.user.is_authenticated() and request.user.is_staff

    base.update({
        'game':
        etn(lambda: dict(GAMES)[matches.values('game').distinct()[0]['game']]),
        'nmatches':
        matches.count(),
        'ngames':
        sum(count_winloss_games(matches)),
        'pvp_games':
        count_mirror_games(matches, 'P'),
        'tvt_games':
        count_mirror_games(matches, 'T'),
        'zvz_games':
        count_mirror_games(matches, 'Z'),
        'matches':
        display_matches(
            matches.prefetch_related('message_set').prefetch_related(
                'pla', 'plb',
                'eventobj').annotate(Count('eventobj__match')).order_by(
                    '-eventobj__latest', '-eventobj__idx', '-date',
                    '-id')[0:200],
            eventcount=True,
            add_links=add_links),
        'nplayers':
        Player.objects.filter(
            Q(id__in=matches.values('pla'))
            | Q(id__in=matches.values('plb'))).count(),
    })

    offlines = list(matches.values('offline').distinct())
    if len(offlines) > 1:
        base['offline'] = _('Both')
    elif len(offlines) == 1:
        base['offline'] = _('Offline') if offlines[0]['offline'] else _(
            'Online')

    base['pvt_wins'], base['pvt_loss'] = count_matchup_games(matches, 'P', 'T')
    base['pvz_wins'], base['pvz_loss'] = count_matchup_games(matches, 'P', 'Z')
    base['tvz_wins'], base['tvz_loss'] = count_matchup_games(matches, 'T', 'Z')
    base['tot_mirror'] = base['pvp_games'] + base['tvt_games'] + base[
        'zvz_games']
    # }}}

    return render_to_response('eventres.djhtml', base)
示例#8
0
def match(request):
    base = base_ctx('Inference', 'Predict', request=request)

    # {{{ Get data, set up and simulate
    form = SetupForm(request.GET)
    if not form.is_valid():
        return redirect('/inference/')

    result = MatchPredictionResult(
        dbpl=form.cleaned_data['ps'],
        bos=form.cleaned_data['bo'],
        s1=get_param(request, 's1', 0),
        s2=get_param(request, 's2', 0),
    )
    # }}}

    # {{{ Postprocessing
    base.update({
        'form': form,
        'dbpl': result.dbpl,
        'rta': result.rta,
        'rtb': result.rtb,
        'proba': result.proba,
        'probb': result.probb,
        'match': result.obj,
    })

    base.update({
        'max':
        max(base['proba'], base['probb']),
        'fav':
        result.dbpl[0] if base['proba'] > base['probb'] else result.dbpl[1],
    })

    resa = [oc for oc in result.outcomes if oc['sca'] > oc['scb']]
    resb = [oc for oc in result.outcomes if oc['scb'] > oc['sca']]
    if len(resa) < len(resb):
        resa = [None] * (len(resb) - len(resa)) + resa
    else:
        resb = [None] * (len(resa) - len(resb)) + resb
    base['res'] = list(zip(resa, resb))
    # }}}

    # {{{ Scores and other data
    dbpl = result.dbpl
    thr = date.today() - relativedelta(months=2)
    pla_matches = dbpl[0].get_matchset()
    plb_matches = dbpl[1].get_matchset()
    base['tot_w_a'], base['tot_l_a'] = count_winloss_player(
        pla_matches, dbpl[0])
    base['frm_w_a'], base['frm_l_a'] = count_winloss_player(
        pla_matches.filter(date__gte=thr), dbpl[0])
    base['tot_w_b'], base['tot_l_b'] = count_winloss_player(
        plb_matches, dbpl[1])
    base['frm_w_b'], base['frm_l_b'] = count_winloss_player(
        plb_matches.filter(date__gte=thr), dbpl[1])
    if dbpl[1].race in 'PTZ':
        base['mu_w_a'], base['mu_l_a'] = count_matchup_player(
            pla_matches, dbpl[0], dbpl[1].race)
        base['fmu_w_a'], base['fmu_l_a'] = count_matchup_player(
            pla_matches.filter(date__gte=thr), dbpl[0], dbpl[1].race)
    if dbpl[0].race in 'PTZ':
        base['mu_w_b'], base['mu_l_b'] = count_matchup_player(
            plb_matches, dbpl[1], dbpl[0].race)
        base['fmu_w_b'], base['fmu_l_b'] = count_matchup_player(
            plb_matches.filter(date__gte=thr), dbpl[1], dbpl[0].race)
    wa_a, wb_a = count_winloss_games(
        Match.objects.filter(pla=dbpl[0], plb=dbpl[1]))
    wb_b, wa_b = count_winloss_games(
        Match.objects.filter(pla=dbpl[1], plb=dbpl[0]))
    base['vs_a'] = wa_a + wa_b
    base['vs_b'] = wb_a + wb_b

    base['matches'] = display_matches(
        Match.objects.filter(
            Q(pla=dbpl[0], plb=dbpl[1])
            | Q(plb=dbpl[0], pla=dbpl[1])).select_related(
                'period', 'pla', 'plb').order_by('-date', 'id'),
        fix_left=dbpl[0],
    )
    # }}}

    postable_match(base, request)

    return render_to_response('pred_match.djhtml', base)
示例#9
0
def match(request):
    base = base_ctx('Inference', 'Predict', request=request)

    # {{{ Get data, set up and simulate
    form = SetupForm(request.GET)
    if not form.is_valid():
        return redirect('/inference/')

    num = form.cleaned_data['bo'][0]
    dbpl = form.cleaned_data['ps']
    sipl = [make_player(p) for p in dbpl]

    match = MatchSim(num)
    match.set_players(sipl)
    match.modify(
        get_param_range(request, 's1', (0, num), 0),
        get_param_range(request, 's2', (0, num), 0),
    )
    match.compute()
    # }}}

    # {{{ Postprocessing
    base.update({
        'form': form,
        'dbpl': dbpl,
        'rta': sipl[0].elo_vs_opponent(sipl[1]),
        'rtb': sipl[1].elo_vs_opponent(sipl[0]),
        'proba': match.get_tally()[sipl[0]][1],
        'probb': match.get_tally()[sipl[1]][1],
        'match': match,
    })

    base.update({
        'max': max(base['proba'], base['probb']),
        'fav': dbpl[0] if base['proba'] > base['probb'] else dbpl[1],
    })

    resa, resb = [], []
    outcomes = [
        {'sca': outcome[1], 'scb': outcome[2], 'prob': outcome[0]} 
        for outcome in match.instances_detail()
    ]
    resa = [oc for oc in outcomes if oc['sca'] > oc['scb']]
    resb = [oc for oc in outcomes if oc['scb'] > oc['sca']]
    if len(resa) < len(resb):
        resa = [None] * (len(resb) - len(resa)) + resa
    else:
        resb = [None] * (len(resa) - len(resb)) + resb
    base['res'] = list(zip(resa, resb))
    # }}}

    # {{{ Scores and other data
    thr = date.today() - relativedelta(months=2)
    pla_matches = dbpl[0].get_matchset()
    plb_matches = dbpl[1].get_matchset()
    base['tot_w_a'], base['tot_l_a'] = count_winloss_player(pla_matches, dbpl[0])
    base['frm_w_a'], base['frm_l_a'] = count_winloss_player(pla_matches.filter(date__gte=thr), dbpl[0])
    base['tot_w_b'], base['tot_l_b'] = count_winloss_player(plb_matches, dbpl[1])
    base['frm_w_b'], base['frm_l_b'] = count_winloss_player(plb_matches.filter(date__gte=thr), dbpl[1])
    if dbpl[1].race in 'PTZ':
        base['mu_w_a'], base['mu_l_a'] = count_matchup_player(pla_matches, dbpl[0], dbpl[1].race)
        base['fmu_w_a'], base['fmu_l_a'] = count_matchup_player(
            pla_matches.filter(date__gte=thr), dbpl[0], dbpl[1].race
        )
    if dbpl[0].race in 'PTZ':
        base['mu_w_b'], base['mu_l_b'] = count_matchup_player(plb_matches, dbpl[1], dbpl[0].race)
        base['fmu_w_b'], base['fmu_l_b'] = count_matchup_player(
            plb_matches.filter(date__gte=thr), dbpl[1], dbpl[0].race
        )
    wa_a, wb_a = count_winloss_games(Match.objects.filter(pla=dbpl[0], plb=dbpl[1]))
    wb_b, wa_b = count_winloss_games(Match.objects.filter(pla=dbpl[1], plb=dbpl[0]))
    base['vs_a'] = wa_a + wa_b
    base['vs_b'] = wb_a + wb_b

    base['matches'] = display_matches(
        Match.objects.filter(Q(pla=dbpl[0], plb=dbpl[1]) | Q(plb=dbpl[0], pla=dbpl[1]))
            .select_related('period', 'pla', 'plb')
            .order_by('-date', 'id'),
        fix_left=dbpl[0],
    )
    # }}}

    postable_match(base, request)

    base.update({"title": "{} vs. {}".format(dbpl[0].tag, dbpl[1].tag)})

    return render_to_response('pred_match.html', base)