Exemple #1
0
def confirm_match(request, req_id=None):
    if request.method == "POST":
        if req_id is not None:
            try:
                sr = ScoreRequest.objects.get(id=req_id)
            except:
                return HttpResponseRedirect('/welcome/')
            form = ConfirmRequestForm(request.POST, instance=sr)
            print form
            if form.is_valid() and sr.player2.user.username == request.user.username: #and needs to verify player2 is current player lol
                form.save()
                if int(request.POST['verified']) == 2:
                    #Save fields into a Match object now
                    match = Match()
                    match.player1 = sr.player1
                    match.player2 = sr.player2
                    match.wins = sr.wins
                    match.loss = sr.loss
                    match.ties = sr.ties
                    match.tournament = sr.tournament
                    match.save()
                return HttpResponseRedirect('/welcome/') 
            return HttpResponseRedirect('/welcome/')
    else:
        print "Only POST requests for now"
        return HttpResponseRedirect('/welcome/')
Exemple #2
0
def match_put(mid, pid):
    """ Insert match via Match ID and DotA2 ID """
    if not match_check(mid, pid):
        query = Match(match_id=mid, player=pid)
        query.save()
        return True
    return False
def score(update: Update, context: CallbackContext, args):
    if len(gamers) == 1:
        context.bot.send_message(chat_id=update.message.chat_id,
                                 text="Вы еще не сыграли игру.")
    s: int
    try:
        s = int(update.message.text.replace("/score", ""))
    except ValueError:
        context.bot.send_message(chat_id=update.message.chat_id,
                                 text="Неверный формат")
        return
    if s < 0:
        context.bot.send_message(
            chat_id=update.message.chat_id,
            text="Количество очков должно быть больше 0.",
        )
    if s > 10:
        context.bot.send_message(
            chat_id=update.message.chat_id,
            text="Количество очков должно быть меньше 10.",
        )

    if gamers[0].get("score") is not None and gamers[1].get(
            "score") is not None:
        match = Match(
            first_opponent_user_id=gamers[0]["user_id"],
            second_opponent_user_id=gamers[1]["user_id"],
            first_opponent_score=gamers[0]["score"],
            second_opponent_score=gamers[1]["score"],
        )
        match.save()
        gamers.clear()
Exemple #4
0
 def exists(cls,iid,table):
     if table == "match":
         try:
             Match.get(iid=iid)
         except Match.DoesNotExist:
             return False
     if table == "odd":
         try:
             Odd.get(iid=iid)
         except Odd.DoesNotExist:
             return False
     if table == "cat":
         try:
             OddCategory.get(idd=iid)
         except OddCategory.DoesNotExist:
             return False
     if table == "result":
         try:
             Result.get(iid=iid)
         except Result.DoesNotExist:
             return False
     if table == "user":
         try:
             User.get(iid=iid)
         except User.DoesNotExist:
             return False
     return True
Exemple #5
0
 def exists(cls, iid, table):
     if table == "match":
         try:
             Match.get(iid=iid)
         except Match.DoesNotExist:
             return False
     if table == "odd":
         try:
             Odd.get(iid=iid)
         except Odd.DoesNotExist:
             return False
     if table == "cat":
         try:
             OddCategory.get(idd=iid)
         except OddCategory.DoesNotExist:
             return False
     if table == "result":
         try:
             Result.get(iid=iid)
         except Result.DoesNotExist:
             return False
     if table == "user":
         try:
             User.get(iid=iid)
         except User.DoesNotExist:
             return False
     return True
    def _mk_match(cls, event_key, mname, result, red_a, blue_a):
        comp_level, mnum, set_number = cls.parse_match_code(mname)
        match = Match(event_key=event_key,
                      comp_level=comp_level,
                      match_number=mnum,
                      set_number=set_number)
        scores, winner = result.split()
        red_score, blue_score = scores.split('-')
        match.winner = cls.res_map[winner]
        match.gen_keys()

        red = MatchScore(key=match.red_key,
                         alliance_color="red",
                         event_key=event_key,
                         match_key=match.key,
                         dqed=[],
                         total=int(red_score),
                         teams=[f'ftc{s.strip("*")}' for s in red_a])
        red.surrogates = [
            f'ftc{s.strip("*")}' for s in red_a if s.endswith('*')
        ]

        blue = MatchScore(key=match.blue_key,
                          alliance_color="blue",
                          event_key=event_key,
                          match_key=match.key,
                          dqed=[],
                          total=int(blue_score),
                          teams=[f'ftc{s.strip("*")}' for s in blue_a])
        blue.surrogates = [
            f'ftc{s.strip("*")}' for s in blue_a if s.endswith('*')
        ]

        return (match, red, blue)
Exemple #7
0
def matching(request):
    print "m matching"
    if request.method != 'POST':
        return redirect('/')

    # Create a match
    print request.POST.get('player1'), "<=== player1"
    print request.POST.get('player2'), "<=== player2"
 
    # Validation for creating new object
    errors = Match.objects.create_validator(request.POST)
    if len(errors) > 0:
        for tag, error in errors.iteritems():
            # messages.error(request, error, extra_tags=tag)
            messages.error(request, error, extra_tags="creatematching")
        return redirect('/')
    player1 = Knight.objects.get(id = request.POST.get('player1'))
    player2 = Knight.objects.get(id = request.POST.get('player2'))

    if randint(1,2) == 1:
        winner = player1
        loser = player2
    else:
        winner = player2
        loser = player1

    match = Match(winner = winner, loser = loser)
    match.save()
    
    return redirect('/')
Exemple #8
0
def create_initial_matches(season: str, week: int) -> None:
    if not (1 <= week <= 7):
        return
    match: Match = Match.objects.filter_by(season=season, week=week).first()
    if match:
        return
    groups: List[Group] = Group.objects.filter_by(season=season, week=week).get()
    if len(groups) != 4 * 4 * 3:
        raise PlayerInGroupNot48(groups)
    matches_to_create: List[Match] = list()
    match_index = 1
    for region in Config.REGIONS:
        region_players = [player for player in groups if player.region == region]
        for group_index in range(0, 4):
            group_players = [player for player in region_players if player.group == Config.GROUPS[group_index]]
            for player_index in range(0, 3, 2):
                match = Match()
                match.season = season
                match.week = week
                match.region = region
                match.group = Config.GROUPS[group_index]
                match.type = Config.INITIAL_1 if player_index == 0 else Config.INITIAL_2
                match.player1 = group_players[player_index].player
                match.player2 = group_players[player_index + 1].player
                match.match_id = _generate_match_id(match_index)
                match_index += 1
                matches_to_create.append(match)
    Match.objects.create_all(Match.objects.to_dicts(matches_to_create))
Exemple #9
0
    def create_test_data(self):
        user = User.get_or_create(123)
        user.admin = True
        User.get_or_create(12345)
        db.session.commit()

        team1 = Team.create(user, 'EnvyUs', 'EnvyUs', 'fr', 'nv',
                            ['76561198053858673'])
        team2 = Team.create(user, 'Fnatic', 'Fnatic', 'se', 'fntc',
                            ['76561198053858673'])
        server = GameServer.create(user, 'myserver1', '127.0.0.1', '27015',
                                   'password', False)
        server.in_use = True

        GameServer.create(user, 'myserver2', '127.0.0.1', '27016', 'password',
                          True)
        db.session.commit()
        season = Season.create(
            user, 'Season One Test', datetime.datetime.utcnow(),
            datetime.datetime.utcnow() + datetime.timedelta(days=1))
        db.session.commit()

        Match.create(user, team1.id, team2.id, '', '', 1, False,
                     'Map {MAPNUMBER}', ['de_dust2', 'de_cache', 'de_mirage'],
                     season.id, 'always_knife', 'CT', server.id)
        db.session.commit()

        vetoBan = Veto.create(1, 'EnvyUs', 'de_dust2', 'ban')
        vetoPick = Veto.create(1, 'EnvyUs', 'de_overpass', 'pick')
        db.session.commit()
Exemple #10
0
def new_match():
    """
    async request from client to create a new match
    """
    if request.method == 'POST':
        player1_id = request.form['player1_id']
        player2_id = request.form['player2_id']

        # Checking to see if goals were provided
        try:
            player1_goals = int(request.form['player1_goals'])
            player2_goals = int(request.form['player2_goals'])
        except ValueError:
            return jsonify({
                "response": False,
                "error": "Provide goals for players."
            })

        if player1_id == player2_id:
            return jsonify({
                "response": False,
                "error": "Player 1 cannot be the same as Player2"
            })

        Match.create(player1_id=player1_id,
                     player2_id=player2_id,
                     player1_goals=player1_goals,
                     player2_goals=player2_goals)

        # ranks in memcache now are obselete so update the 'update_ranks' key
        MC.set("update_ranks", True)

        return jsonify({"response": True})
Exemple #11
0
def test_undo_match(g):
    p = Player("test player")
    p2 = Player("test player 2")
    player_dao.create(p)
    p.id = 1
    player_dao.create(p2)
    p2.id = 2
    t = Tournament(0,'','T1','type',0)
    tournament_dao.create(t)
    t.id = 1
    match_dao.create([p.id, p2.id], t.id)
    match_id = 1
    match = Match(player1=p,player2=p2,id=match_id)
    match.score1 = 19
    match.score2 = 21
    match_dao.update(match)

    match_dao.undo(match)
    retrieved_match = match_dao.find(match_id)
    matches = match_dao.find_by_tournament(t.id)

    assert retrieved_match.score1 == 0
    assert retrieved_match.score2 == 0
    assert retrieved_match.player1.fname == p.fname
    assert retrieved_match.player2.fname == p2.fname
    assert retrieved_match.player1.id == p.id
    assert retrieved_match.player2.id == p2.id
    assert not matches[0].entered_time
def migrate():
    old_matches = list(Match_2018_06_26.select().order_by(Match_2018_06_26.id))
    print('old matches: {}'.format(old_matches))

    def convert_match(old_match):
        return Match(winner_handle=old_match.winner.slack_id,
                     winner_score=old_match.winner_score,
                     loser_handle=old_match.loser.slack_id,
                     loser_score=old_match.loser_score,
                     pending=old_match.pending,
                     played=old_match.played)

    new_matches = [convert_match(old_match) for old_match in old_matches]
    print('new matches (not yet committed): {}'.format(new_matches))

    print('dropping old Match table')
    db.drop_tables([Match_2018_06_26])
    print('dropping old Player table')
    db.drop_tables([Player_2018_06_26])

    print('creating new Match table')
    Match.create_table()
    print('saving new matches')
    for new_match in new_matches:
        new_match.save()
Exemple #13
0
def match(request, user_id):
    user = get_object_or_404(Profile, pk=user_id)
    match = Match(date=timezone.now())
    match.save()
    match.users.add(user, request.user)
    match.save()

    return HttpResponseRedirect(reverse('meet:match_detail', args=(match.id,)))
Exemple #14
0
def entry():
    if not session.get('user'):
        return redirect(url_for('index'))

    user = session.get('user')
    u = User.select().where(User.username == user)[0]

    already_entered = Crush.select().where(Crush.user == u)

    if request.method == 'POST':
        entries = filter(None, request.form.getlist("entry"))

        if len(entries) > 5:
            return redirect('entry')

        captcha = request.form.get('g-recaptcha-response')

        captcha_r = requests.post('https://www.google.com/recaptcha/api/siteverify',
                                  data={'secret': '6Lcd-gcTAAAAANlxsT-ptOTxsgRiJKTGTut2VgLk',
                                        'response': captcha,
                                        'remoteip': request.remote_addr})

        if not captcha_r.json()['success']:
            return render_template('entry.html', user=user, entries=entries,
                                    already_entered=already_entered,
                                    already_entered_count=already_entered.count())

        if not any(entries):
            return redirect('entry')

        suggestions = map(lookup, entries)

        for i, entry in enumerate(entries):
            if entry not in suggestions[i]:
                return render_template('entry.html', user=user,
                                                     entries=entries,
                                                     suggestions=suggestions,
                                                     already_entered=already_entered,
                                                     already_entered_count=already_entered.count())

        for entry in entries:
            exists = Crush.select().where(Crush.user == u, Crush.crush == entry).count()
            if not exists:
                Crush.create(user=u, crush=entry)

                crush_user_exists = User.select().where(User.username == entry).count()
                if crush_user_exists:
                    crush_user = User.select().where(User.username == entry)[0]
                    crush_user_crushes = map(lambda m: m.crush, Crush.select().where(Crush.user == crush_user))
                    if crush_user and u.username in crush_user_crushes:
                        Match.create(user_1 = u, user_2 = crush_user)

        return redirect('/matches')

    return render_template('entry.html', user=user,
                            already_entered=already_entered,
                            already_entered_count=already_entered.count())
Exemple #15
0
def get_all_matches(account_id):
    """Try to retrieve and add all matches from a player to the database."""
    matches = api.get_match_history(account_id=account_id)["result"]
    while matches["results_remaining"] >= 0 and matches["num_results"] > 1:
        for match in matches["matches"]:
            try:
                Match.get(Match.match_id == match["match_id"])
            except DoesNotExist:
                new_match_task = add_match.delay(match["match_id"])
        matches = api.get_match_history(account_id=account_id, start_at_match_id=match["match_id"])["result"]
Exemple #16
0
def _create_tbd_match(season: str, week: int, region: str, match_type: str, index: int, group: str = None) -> Match:
    match = Match()
    match.season = season
    match.week = week
    match.region = region
    match.type = match_type
    match.match_id = _generate_match_id(index)
    match.group = group if group else str()
    match.player1 = Config.TBD
    match.player2 = Config.TBD
    return match
Exemple #17
0
 def _trigger_played_match(self, match_type):
     if MatchSoloQueue.query(MatchSoloQueue.type == match_type).count() >= 2:
         match_solo_queues = [match_queue for match_queue in MatchSoloQueue.query(MatchSoloQueue.type == match_type).fetch(10)]
         players = [match_queue.player.get() for match_queue in match_solo_queues]
         match = Match(type=match_type)
         match.setup_soloqueue_match(players)
         ndb.delete_multi([queue.key for queue in match_solo_queues])
         for player in players:
             player.doing = match.key
             player.put()
             websocket_notify_player("Player_MatchFound", player.key, None, match.get_data())
 def get(self):
     #500 is max delete at once limit.
     db.delete(Match.all().fetch(500))
     
     match_count = Match.all().count()
     
     template_values = {
         'match_count': match_count,
     }
     
     path = os.path.join(os.path.dirname(__file__), '../templates/matches/flush.html')
     self.response.out.write(template.render(path, template_values))
Exemple #19
0
 def query_by_owner(self, user, status='all'):
     logger.info('NdbMatchDao:: DBHIT: query_by_owner for %s ' % user.email)
     owner_query = Match.query()
     if not user_has_role(user, 'admin'):
         owner_query = Match.query(
             ndb.OR(Match.owners == user.key, Match.created_by == user.key,
                    Match.updated_by == user.key))
     if status != 'all':
         status_value = STATUS_DICT.get(status)
         owner_query = owner_query.filter(status == status_value)
     owner_query = owner_query.order(-Match.updated_on)
     return owner_query.fetch()
Exemple #20
0
    def init_database(self, numPlayers, numPairs, user):
        assert int(numPlayers) <= len(
            GameLogicTestLibrary.users), 'max numPlayers exceeded'
        assert user in GameLogicTestLibrary.users, 'must use a predefined user'

        self.game = Game(numPlayers=int(numPlayers),
                         numPairs=int(numPairs),
                         creator=user)
        Match.remove_all()
        for i in range(int(numPlayers)):
            Match.save(
                (i, self.game.gameId, GameLogicTestLibrary.users[i], i + 1))
Exemple #21
0
def create_new_match(data, type):
    match = Match(type, data['username'])
    match.save()
    emit('match_created', match.serialize())
    join_room(match.id)
    BOARDS[match.id] = {
        'board': chess.Board(),
        'white_player': request.sid,
        'n_moves_white': 0,
        'n_moves_black': 0,
        'n_points_white': 0,
        'n_points_black': 0
    }
Exemple #22
0
    def post(self):
        player = current_user_player()

        if player.doing:
            error_400(self.response, "ERROR_PLAYER_BUSY", "Player is busy.")
            return

        bot_match = Match(type="Bot")
        bot_match.setup_bot_match(player)

        player.doing = bot_match.key
        player.put()

        set_json_response(self.response, bot_match.get_data("full"))
Exemple #23
0
 def syncMatchTable(self):
     self.connection.request("GET", "/sync/match")
     response = self.connection.getresponse()
     data = response.read()
     data = json.loads(data)
     print response.read()
     print data
     if not data.has_key('up-to-date'):
         for match in data['name']:
             try:
                 Match.create(iid=match['iid'],homeTeam=match['homeTeam'], awayTeam=match["awayTeam"], startTime=match['startTime'],
                     league=match['league'])
             except Exception, e:
                 print str(e) + "- Match"
Exemple #24
0
def matches():
    if not session.get('user'):
        return redirect('/login')

    user = User.select().where(User.username == session.get('user'))[0]

    count = Crush.select().where(Crush.crush == session.get('user')).count()

    matches_1 = map(lambda m: m.user_2.username, Match.select().where(Match.user_1 == user))
    matches_2 = map(lambda m: m.user_1.username, Match.select().where(Match.user_2 == user))

    matches_1.extend(matches_2)

    return render_template('match.html', matches=matches_1, count=count, user=user.username)
    def get_upcoming_matches(self):
        matchdays = self.upcoming_soup.find_all("div", {"data-zonedgrouping-headline-classes": "standard-headline"}, limit=self.num_daysadvance)

        if not len(matchdays):
            raise exceptions.NoMatchesFound(1)
            return []

        matchdays = matchdays[0].find_all("div", {"class": "match-day"})

        if not len(matchdays):
            raise exceptions.NoMatchesFound(1)
            return []

        for s in matchdays:
            match_day = s.find("span", {"class": "standard-headline"})
            match_day = match_day.text

            for matchdata in s.find_all("a"):
                dictMatch = {}
                dictMatch["id"] = int(re.search(self.regex_matchid, matchdata["href"]).group(1))
                dictMatch["unix_ts"] = int(matchdata["data-zonedgrouping-entry-unix"])
                dictMatch["state"] = 1

                dictMatch["map"] = '?'

                table = matchdata.find("tr")
                teams = []
                for tag in table.find_all("div", class_="team map-text".split()):
                    if tag["class"][0] == "team":
                        teams.append(tag.text)
                    elif tag["class"][0] == "map-text":
                        dictMatch["map"] = tag.text

                dictMatch["teamname1"] = teams[0]
                dictMatch["teamname2"] = teams[1]

                if dictMatch["id"] in self.matches.keys():
                    self.matches[dictMatch['id']].set(**dictMatch)
                    self.matches[dictMatch['id']].ms_unix_to_unix()
                else:
                    match = Match(**dictMatch)
                    match.ms_unix_to_unix()
                    self.matches[dictMatch['id']] = match

                    self.session.add(match)

                log.debug(f"Finished upcoming match (id: {dictMatch['id']})")

            log.debug(f"Finished upcoming matchday (date: {match_day})")
def get_matches():
    """
    http://wiki.guildwars2.com/wiki/API:1/wvw/matches
    """
    for m in api.api_request('wvw/matches')['wvw_matches']:
        match = Match(
            match_id=m['wvw_match_id'],
            red=World.objects.get(world_id=m['red_world_id']),
            blue=World.objects.get(world_id=m['blue_world_id']),
            green=World.objects.get(world_id=m['green_world_id']),
            start_time=m['start_time'],
            end_time=m['end_time'])
        match.save()

    return Match.objects.all()
Exemple #27
0
def newgame():
    """Create new game from request. Commit new game to db, save to fold.

    Form Parameters:
        name: new game name
        player{1,2,..}: players to add (e.g. /newgame?player1=joe&player2=sally)
        add_gems: gems to add to default (e.g. rgbbb)

    If game exists, redirect to game with that name.
    """
    # PARSE FORM INPUTS
    args = request.form or request.args
    suggested_name = args.get('game') or 'default'  #TODO make default name
    name = Match.make_unique_gamename(suggested_name)
    players = [
        player for k, player in args.items() if 'player' in k and player
    ]
    add_gems = args.get('add_gems') or ""
    # MAKE SURE PLAYERS EXIST
    users = []
    for pname in players:
        u = User.query.filter_by(nickname=pname).first()
        if not u:
            return "invalid player name, %s" % pname  #TODO better error handling
        else:
            users.append(u)
    # Get ongoing match names
    active_matches = [m.name for m in Match.query.filter_by(is_active=True)]
    if name not in active_matches:
        print players
        print type(players)
        # create game
        args = pickle.load(open('game_args.pickle', 'rb'))
        G = MutableGame(*args)
        G.start(players, add_gems)
        # create db entry
        m = Match(name=name,
                  is_active=True,
                  creator=g.user.id,
                  game=G,
                  summary=str(G))
        m.players.extend(users)
        db.session.add(m)
        db.session.commit()
        # save initial copy of game and add to game dict
        #G.save(savedir + '/' + name)

    return redirect('/game/%s' % name)
Exemple #28
0
def add_match(p1_id, nd1, p2_id, nd2, score_p1, score_p2):
    if p1_id == p2_id or int(score_p1) == int(score_p2):
        raise InvalidMatchRegistration()

    p1_id += "(nd)" if nd1 else ""
    p1 = get_player(p1_id)
    p2_id += "(nd)" if nd2 else ""
    p2 = get_player(p2_id)

    if p1 and p2:
        match = Match(None, p1_id, p2_id, score_p1, score_p2, p1.get_rating(),
                      p2.get_rating())
        conn, cursor = db.connect()
        db.create_match(cursor, match)

        new_rating1, new_rating2 = calculate_new_elo_ratings(
            rating1=p1.get_rating(),
            rating2=p2.get_rating(),
            player1_win=int(match.player1_score) > int(match.player2_score))
        db.update_player(cursor, p1.id, new_rating=new_rating1)
        db.update_player(cursor, p2.id, new_rating=new_rating2)
        conn.commit()
        conn.close()

        new_p1 = get_player(p1.id)
        new_p2 = get_player(p2.id)

        updated_players = (new_p1, new_rating1 - p1.get_rating(), new_p2,
                           new_rating2 - p2.get_rating())
        return updated_players
    raise PlayerDoesNotExist()
Exemple #29
0
    def winner(self, message):
        # 0: space, 1: winning verb, 2: loser_id, 3: first score, 4: second score
        # then 0 or more of...
        # 5: 2nd game hyphenated score, 6: 2nd game first score, 7: 2nd game second score
        msg = message['text']
        values = re.split(WINNER_REGEX, msg)
        if not values or len(values) < 5:
            return

        loser_id = values[2]

        # csv game list starts after the end of the slack username
        games_csv = msg[(msg.index('>') + 1):]
        games = games_csv.replace(' ', '').split(',')

        for game in games:
            scores = game.split('-')
            if len(scores) != 2:
                continue

            first_score = int(scores[0])
            second_score = int(scores[1])

            try:
                match = Match.create(winner=message['user'], winner_score=first_score, loser=loser_id, loser_score=second_score)
                self.talk('<@' + loser_id + '>: Please type "Confirm ' + str(match.id) + '" to confirm the above match or ignore it if it is incorrect')
            except Exception as e:
                self.talk('Unable to save match. ' + str(e))
Exemple #30
0
 def get(self, name):
     c = Club.get_by_key_name(name)
     if c is None:
         self.response.set_status(404)
         t = JINJA2_ENV.get_template('404.html')
         self.response.out.write(t.render({}))
         return
     cal = CalendarWrap(c.display)
     q = Match.all().filter('home = ', c)
     for match in q:
         cal.add(match)
     q = Match.all().filter('away = ', c)
     for match in q:
         cal.add(match)
     self.response.headers["Content-Type"] = "text/calendar; charset=utf-8"
     self.response.out.write(cal.to_string())
Exemple #31
0
def addMatchesFromCsv(filename, tables):
    matches = []
    competition_tables = {}
    teams = {}

    # setup team and table dictionaries for quick access
    for team in Team.query.all():
        teams[team.number] = team.id

    for table in tables:
        competition_tables[table.name] = table.id

    with open(filename) as csvfile:
        reader = csv.DictReader(csvfile)

        j = 1
        for row in reader:
            # Create the overall match object
            match = Match(j, 'Q', row['Round'], row['Time'])

            j += 1
            for key, value in competition_tables.iteritems():
                # if there is a team number in the table column, then add a match-slot object
                if row[key]:
                    team_id = Team.query.filter_by(number=row[key]).first().id
                    table_id = value
                    match.slots.append(MatchSlot(table_id, team_id))

            matches.append(match)
            db.session.add(match)

        db.session.commit()

        return len(matches)
Exemple #32
0
 def check(self):
     try:
         match = Match.get(iid=self.matchCode.get_text())
         category = OddCategory.get(name=self.category.get_active_text())
         odd = Odd.get(match=match,category=category,oddCode=self.bet.get_text())
         self.addMatchButton.set_sensitive(False)
         self.reason.set_text("Match Started")
     except Match.DoesNotExist:
         self.addMatchButton.set_sensitive(False)
         self.odd.set_text("")
         self.reason.set_text("Invalid Match")
     except OddCategory.DoesNotExist:
         self.addMatchButton.set_sensitive(False)
         self.odd.set_text("")
         self.reason.set_text("Invalid Category")
     except Odd.DoesNotExist:
         self.addMatchButton.set_sensitive(False)
         self.odd.set_text("")
         self.reason.set_text("Invalid Bet")
     else:
         if match.is_valid():
             self.addMatchButton.set_sensitive(True)
             self.reason.set_text("Available")
             self.odd.set_text(str(odd.odd))
         else:
             self.addMatchButton.set_sensitive(False)
             self.reason.set_text("Match Started")
     if len(self.bets)>0 and self.amountstaked.get_text()!= "":
         self.stakebutton.set_sensitive(True)
     else:
         self.stakebutton.set_sensitive(False)
Exemple #33
0
def match_masscreate():
    if not g.user:
        return redirect('/login')
    if not g.user.admin:
        return redirect('/match/create')
    form = MatchMultiForm(request.form)

    if request.method == 'POST':
        if form.validate():
            match_list = form.data['matches'].split('\n')
            for item in match_list:
                split_parts = item.split(',')
                if not len(split_parts) == 3:
                    continue
                server = get_next_empty_server()
                t1_name, t2_name, bo_whatever = split_parts
                max_maps = int(form.series_type.data[2])
                team1 = Team.query.filter_by(name=t1_name).first()
                team2 = Team.query.filter_by(name=t2_name).first()
                default_mapchoices = config_setting('DEFAULT_MAPLIST')
                match = Match.create(g.user, team1.id, team2.id, team1.name,
                                     team2.name, max_maps, False, '',
                                     default_mapchoices, server.id)
                server.in_use = True
                match.plugin_version = 'unknown'
                db.session.commit()
                redirect('/matches')
    return render_template(
        'match_mass_create.html',
        form=form,
        user=g.user,
        teams=g.user.teams,
    )
Exemple #34
0
    def post(self):
        """
        POST method adds new match to collection
        """
        if not request.json:
            return create_error_response(415, "Unsupported media type",
                                         "Request must be JSON")

        try:
            validate(request.json, GameBuilder.match_schema())
        except ValidationError as e:
            return create_error_response(400, "Invalid JSON document", str(e))

        new_match = Match(
            #id=request.json["id"],
            team1=request.json["team1"],
            team2=request.json["team2"],
            date=request.json["date"],
            team1_points=request.json["team1_points"],
            team2_points=request.json["team2_points"])

        try:
            db.session.add(new_match)
            db.session.commit()
        except IntegrityError:
            return create_error_response(409, "Already exists",
                                         "Match already inserted")

        return Response(
            status=201,
            headers={"Location": api.url_for(MatchItem, id=new_match.id)})
Exemple #35
0
def check_and_add_to_db():
    while True:
        matches = matches_to_show()
        check_and_delete(matches)
        if matches:
            session = sessionmaker(engine)()
            for match in matches:
                url = match[5]
                hltv_match_time = match[2]
                exists = session.query(Match).filter_by(match_url=url).count()
                if exists:
                    db_match = session.query(Match).filter_by(match_url=url).all()[0]
                    db_match_time = db_match.match_time
                    if hltv_match_time != db_match_time:
                        session.query(Match).filter_by(match_url=url).update({'match_time': hltv_match_time})
                        logging.info('Match has changed its time.')
                    else:
                        break
                else:
                    m = Match(
                        team1=match[0],
                        team2=match[1],
                        match_time=match[2],
                        best_of=match[3],
                        event=match[4],
                        match_url=match[5],
                        twitch=get_russian_twitch_link(match[5])
                    )
                    session.add(m)
                    logging.info('New match added.')
            session.commit()
            session.close()
        time.sleep(CHECK_HLTV_TIMEOUT)  # Проверяем матчи раз в 10 минут и добавляем в базу, если появились новые
Exemple #36
0
 def query_by_alias(self, alias, event_id, sport):
     logger.info('NdbMatchDao:: DBHIT: query_by_alias for %s ' % alias)
     match_query = Match.query(Match.alias == alias,
                               Match.event_id == event_id,
                               Match.sport == sport)
     match = match_query.fetch(1)
     return match[0] if match is not None and len(match) > 0 else None
Exemple #37
0
def getCurrentMatchByUser(current_user_id):
    #Gets the match the user is currently participating in, or None if no match started.
    #TODO: Check & Confirm creation order
    hackathon = Match.all().filter("users =", current_user_id).order("-created").get()
    if not hackathon or (100 in hackathon.outcome): #Most recent is nonexistant or completed
        return None
    return hackathon
    def get(self):
        """Send a reminder email to each User with active Matches.
        Called every hour using a cron job"""
        app_id = app_identity.get_application_id()
        users = User.query(User.email != None)

        for user in users:
            matches = Match.query(ndb.AND(Match.is_active == True,
                                          ndb.OR(
                                              Match.player_1_name == user.name,
                                              Match.player_2_name == user.name)
                                          )).fetch()

            if matches:
                subject = 'Unfinished match reminder!'
                body = 'Hello {}, \n\nThe following matches are still in ' \
                       'progress:\n'.format(user.name)
                html = 'Hello {}, <br><br>The following matches are still in ' \
                       'progress:<br>'.format(user.name)
                for match in matches:
                    body += '{} vs {}\n'.format(match.player_1_name,
                                                match.player_2_name)
                    html += '{} vs {}<br>'.format(match.player_1_name,
                                                  match.player_2_name)
                body += 'https://{}.appspot.com">Continue playing'\
                    .format(app_id)
                html += '<a href="https://{}.appspot.com">Continue playing' \
                        '</a>'.format(app_id)
                mail.send_mail('noreply@{}.appspotmail.com'.format(app_id),
                               user.email, subject, body, html=html)
Exemple #39
0
    def get(self):
        """Send a reminder email to each User with active Matches.
        Called every hour using a cron job"""
        app_id = app_identity.get_application_id()
        users = User.query(User.email != None)

        for user in users:
            matches = Match.query(
                ndb.AND(
                    Match.is_active == True,
                    ndb.OR(Match.player_1_name == user.name,
                           Match.player_2_name == user.name))).fetch()

            if matches:
                subject = 'Unfinished match reminder!'
                body = 'Hello {}, \n\nThe following matches are still in ' \
                       'progress:\n'.format(user.name)
                html = 'Hello {}, <br><br>The following matches are still in ' \
                       'progress:<br>'.format(user.name)
                for match in matches:
                    body += '{} vs {}\n'.format(match.player_1_name,
                                                match.player_2_name)
                    html += '{} vs {}<br>'.format(match.player_1_name,
                                                  match.player_2_name)
                body += 'https://{}.appspot.com">Continue playing'\
                    .format(app_id)
                html += '<a href="https://{}.appspot.com">Continue playing' \
                        '</a>'.format(app_id)
                mail.send_mail('noreply@{}.appspotmail.com'.format(app_id),
                               user.email,
                               subject,
                               body,
                               html=html)
Exemple #40
0
    def get_matches_for_event(self, event_key, user_info=None, no_records=-1):
        logger.info(
            'NdbMatchDao:: DBHIT: get_matches_for_event for event_key, %s' %
            (event_key))
        match_query = Match.query(Match.event_id == event_key)
        if user_info is None or (not has_admin_access(
                user_info, self.eventDao.get_record(event_key.id()))):
            match_query = match_query.filter(Match.status == 2)
        match_query = match_query.order(-Match.start_datetime)

        if no_records > -1:
            matches = match_query.fetch(no_records)
        else:
            matches = match_query.fetch()

        match_dtos = []
        if matches is not None:
            for match in matches:
                match_dto = MatchDTO()
                match_dto.match = match
                if match.playground_id:
                    match_dto.playground = match.playground_id.get()
                else:
                    match_dto.playground = None
                if match.participants:
                    match_dto.teams = []
                    for participant in match.participants:
                        match_dto.teams.append(participant.get())
                match_dtos.append(match_dto)
        return match_dtos
Exemple #41
0
 def confirm_all(self, message):
     match_list = []
     for match in Match.select(Match).where(Match.loser == message['user'],
                                            Match.pending == True):
         match_list.append(match)
     for match in match_list:
         self.confirm(message['user'], 'Confirm ' + str(match.id))
Exemple #42
0
    def winner(self, message):
        # 0: space, 1: winning verb, 2: loser_id, 3: first score, 4: second score
        # then 0 or more of...
        # 5: 2nd game hyphenated score, 6: 2nd game first score, 7: 2nd game second score
        msg = message['text']
        values = re.split(WINNER_REGEX, msg)
        if not values or len(values) < 5:
            return

        loser_id = values[2]

        # csv game list starts after the end of the slack username
        games_csv = msg[(msg.index('>') + 1):]
        games = games_csv.replace(' ', '').split(',')

        for game in games:
            scores = game.split('-')
            if len(scores) != 2:
                continue

            first_score = int(scores[0])
            second_score = int(scores[1])

            try:
                match = Match.create(winner=message['user'], winner_score=first_score, loser=loser_id, loser_score=second_score)
                self.talk('<@' + loser_id + '>: Please type "Confirm ' + str(match.id) + '" to confirm the above match or ignore it if it is incorrect')
            except Exception as e:
                self.talk('Unable to save match. ' + str(e))
Exemple #43
0
def learn():
    while len(Chromosome.all()) < 30:
        Chromosome().create()
    test_set = Match.test_set()
    if not test_set:
        print('There are no matches to learn from')
        return
    agent_pool = [Agent(c) for c in Chromosome.all()]
    reserve = []
    n = 1
    with Pool(4) as pool:
        while True:
            try:
                print('Starting Generation {}'.format(n))
                start = datetime.now()
                for n2, agent in enumerate(agent_pool):
                    print('Running Agent {}'.format(n2))
                    guesses = pool.map(agent.guess, test_set)
                    agent.right = guesses.count(True)
                    agent.wrong = guesses.count(False)
                    agent.chromosome.agent_score = agent.accuracy
                    agent.chromosome.save()
                agent_pool.extend(reserve)
                agent_pool.sort(key=get_score, reverse=True)
                print('Generation took {}'.format(datetime.now() - start))
                print('Best Agent: {}% accurate'.format(agent_pool[0].accuracy * 100))
                Chromosome.delete_many(ids=[agent.chromosome.id for agent in agent_pool[15:]])
                agent_pool = [Agent(agent.chromosome.mutate()) for agent in agent_pool[:15]]  # mutate the top half
                reserve = agent_pool[:15]
                n += 1
            except KeyboardInterrupt:
                Chromosome.clean()  # keep best 15
                break
    print('Finished learning')
 def get(self, key_name):
     
     memcache_key = "match_detail_%s" % key_name
     html = memcache.get(memcache_key)
     
     if html is None:
         match = Match.get_by_key_name(key_name)
         if not match:
             # TODO: Add real "match not found" template
             self.response.out.write("404.")
             return None
         
         match.unpack_json()
         
         tbavideo = None
         if match.tbavideo_set.count() > 0:
             tbavideo = match.tbavideo_set[0]
         
         template_values = {
             "match": match,
             "tbavideo": tbavideo,
         }
         
         path = os.path.join(os.path.dirname(__file__), '../templates/matches/details.html')
         html = template.render(path, template_values)
         memcache.add(memcache_key, html, 600)
     
     self.response.out.write(html)
Exemple #45
0
def wager_result(wager_id=None):
    """
    Updates the database with the wager result
    :return: HttpResponse
    """
    if "username" not in request.cookies:
        return redirect("/")

    if request.method == 'POST':
        # Add the new match in the database and update the wager
        # With the new match id
        wager_match = Match.create(player1_id=request.form['player1_id'],
                                   player2_id=request.form['player2_id'],
                                   player1_goals=request.form['player1_goals'],
                                   player2_goals=request.form['player2_goals'])
        # Updating wager with the match
        wager = Wager.get(Wager.id == wager_id)
        wager.match = wager_match
        wager.save()

        # Update memcache key
        MC.set("update_ranks", True)
        return jsonify({"response": True})

    wager = Wager.get(Wager.id == wager_id)
    return render_template("wager_result.html",
                           name=request.cookies['username'],
                           player1=wager.initiator,
                           player2=wager.opponent)
Exemple #46
0
 def get(self):
     logging.info( "#1 admin, settings. " )
     
     matches = Match.all()
     
     self.render(u'admin',
                 matches = matches)
Exemple #47
0
    def get(self):
        """ Send a reminder to players who have unfinished matches """
        app_id = app_identity.get_application_id()

        matches = Match.query(Match.match_over == False)

        players = list()
        for match in matches:
            logger.debug(match)
            players.append(match.player)

        # Remove duplicates in list by list-set-list conversion
        players = list(set(players))

        # Get players from datastore
        players = ndb.get_multi(players)

        # Create message and send to each player
        for player in players:
            subject = 'This is a reminder'
            body = """Hello %s,
                      you have unfinished
                      quizzles business!""" % player.user_name
            mail.send_mail('noreply@{}.appspotmail.com'.format(app_id),
                           player.email_address,
                           subject,
                           body)
Exemple #48
0
 def insert_match(self, speech_id, sentence_number, text):
     match = Match(speech_id=speech_id,
                   sentence_number=sentence_number,
                   text=text)
     self.session.add(match)
     self.session.commit()
     return match
Exemple #49
0
    def create_test_data(self):
        user = User.get_or_create(123)
        User.get_or_create(12345)
        db.session.commit()

        team1 = Team.create(user, 'EnvyUs', 'fr', 'nv', ['76561198053858673'])
        team2 = Team.create(user, 'Fnatic', 'se', 'fntc',
                            ['76561198053858673'])
        server = GameServer.create(user, '127.0.0.1', '27015', 'password')
        server.in_use = True

        GameServer.create(user, '127.0.0.1', '27016', 'password')
        db.session.commit()

        Match.create(user, team1.id, team2.id, 1, False,
                     'Map {MAPNUMBER}', ['de_dust2', 'de_cache', 'de_mirage'], server.id)
        db.session.commit()
Exemple #50
0
    def get(self):
        logging.info( "#2 ADMIN Deleting Missing Picks;" )
        
        values = {
#           "users" : User.all(),
           "matches" : Match.all(),
#           "picks" : Pick.all().fetch(20),
        }
        self.render(u'admin', values=values)
Exemple #51
0
 def post(self):
     date = self.request.POST[u'date'].strip()
     time = self.request.POST[u'time'].strip()
     team1 = self.request.POST[u'team1'].strip()
     team2 = self.request.POST[u'team2'].strip()
     location = self.request.POST[u'location'].strip()
     timestamp = datetime.datetime(2011, 02, 16, 20, 30, 15)
     
     key_name = "%s_%s_%s" % (team1, team2, timestamp.strftime("%Y_%m_%d_%H_%M_%S"))
     
     match = Match(team1 = team1,
                   team2 = team2,
                   key_name = key_name,
                   timestamp = timestamp,
                   )
     match.put()
     
     self.redirect(u'/admin')
Exemple #52
0
def check_available(match_id,oddCode,category_name):
    try:
        match = Match.get(iid=match_id)
        category = OddCategory.get(name=category_name)
        odd = Odd.get(match=match,category=category,oddCode=oddCode)
    except peewee.DoesNotExist:
        return None
    else:
        return odd.odd
 def get(self):
     match_count = Match.all().count()
     
     template_values = {
         "match_count": match_count
     }
     
     path = os.path.join(os.path.dirname(__file__), '../../templates/admin/matches/dashboard.html')
     self.response.out.write(template.render(path, template_values))
 def get(self):
     matches = Match.all().order('event').fetch(100)
     
     template_values = {
         "matches": matches,
     }
     
     path = os.path.join(os.path.dirname(__file__), '../templates/matches/list.html')
     self.response.out.write(template.render(path, template_values))
    def get(self, match_key):
        match = Match.get_by_key_name(match_key)
        
        template_values = {
            "match": match
        }

        path = os.path.join(os.path.dirname(__file__), '../../templates/admin/matches/edit.html')
        self.response.out.write(template.render(path, template_values))
Exemple #56
0
 def get(self):
     for match in Match.query(Match.winning_faction == None, Match.date <= datetime.datetime.now()):
         match.play_match()
         for match_player in MatchPlayer.query(MatchPlayer.match == match.key):
             player = match_player.player.get()
             player.doing = None
             player.put()
             websocket_notify_player("Match_Finished", player.key, None, match.get_data("full"))
             websocket_notify_player("Player_StatsChanged", player.key, "player", {'stats': player.get_stats_data()})
Exemple #57
0
    def get_win_streak(self, player_slack_id):
        win_streak = 0
        matches = Match.select().where(Match.pending == False, (player_slack_id == Match.winner) | (player_slack_id == Match.loser)).order_by(Match.played.desc())
        for match in matches:
            if (player_slack_id == match.winner_id):
                win_streak = win_streak + 1
            else:
                break

        return win_streak