def post(self, base_url, extra): """The user is saving their availability for the year, so save it to the datastore and invalidate the affected pages' HTML""" try: delete_years = set() if self.request.POST.has_key('updated'): player = Player.get_by_key_name(self.request.get('updated')) for year_round_key in self.request.POST.keys(): try: split_key = year_round_key.split('-') year = split_key[0] delete_years.add(year) round = split_key[1] if len(round) == 0: # Might have been a negative round, so an extra split! round = '-' + split_key[2] round_key = Round.get_key(round, year) round = Round.get_by_key_name(round_key) # Writes the current round's date each time, just in case it has changed. Would have preferred to have # multiple records for the player, linked by date and not time, but django made it difficult (unless I # wanted to have a Model that just contains a date, and everything links back to that...) if round: args = { 'key_name': Availability.get_key(player.db_key, round.num, round.year), 'year': round.year, 'round': round, 'player': player, 'playing': self.request.POST.get(year_round_key) == "0", 'given_date': round.date, } Availability(**args).put() except IndexError: pass # Pages that have been affected by this update: for y in delete_years: # - Draw page, via the number available memcache.delete(PlayerPage.get_draw_mem_key(y)) # - Player summary, because their checkboxes have changed memcache.delete( PlayerPage.get_player_mem_key(player.db_key, y)) memcache.delete(PlayerPage.get_draw_mem_key(ALL_YEARS)) memcache.delete( PlayerPage.get_player_mem_key(player.db_key, ALL_YEARS)) self.get(base_url, extra) except Exception, e: self.get(base_url, extra, error=e)
def do_body(self, args): """Render the HTML for all the results, and provide enough information to edit an game""" data = { 'url_args': args, } year = self.get_year(args) if year == ALL_YEARS: data['rounds'] = Round.gql('ORDER BY date ASC') else: data['rounds'] = Round.gql('WHERE year = :1 ORDER BY date ASC', year) tpath = os.path.join(DeeWhyPage.TEMPLATE_DIR, 'rounds.html') self.response.out.write(template.render(tpath, data)) data = { 'url_args': args, } # Get the full data for the given round so they can edit it if args.has_key('round'): round_num = args['round'] round_key = Round.get_key(round_num, year) result_key = Result.get_key(round_num, year) if round_key != '': curr_round = Round.get_by_key_name(round_key) if curr_round: data['players'] = [ p.player for p in TeamList.gql('WHERE year = :1', curr_round.date.year) ] data['players'].sort(self.sort_players) data['round'] = curr_round curr_result = Result.get_by_key_name(result_key) if curr_result: data['result'] = curr_result if curr_result.other_goals == 0: curr_result.other_goals = None if curr_result.own_goals == 0: curr_result.own_goals = None #if curr_result.deewhy_forfeit: # curr_result.deewhy_goals = 0 # curr_result.opponent_goals = 5 #elif curr_result.opponent_forfeit: # curr_result.deewhy_goals = 5 # curr_result.opponent_goals = 0 tpath = os.path.join(DeeWhyPage.TEMPLATE_DIR, 'manage_results.html') self.response.out.write(template.render(tpath, data))
def score_input(): this_Rounds_Players = [] this_Rounds_Players += Player.query.filter_by( name=session['player_1_Name']) this_Rounds_Players += Player.query.filter_by( name=session['player_2_Name']) this_Rounds_Players += Player.query.filter_by( name=session['player_3_Name']) this_Rounds_Players += Player.query.filter_by( name=session['player_4_Name']) if 'hole_num' not in session: session['hole_num'] = 1 if 'round_num' not in session: session['round_num'] = 1 db.session.add(Round(session['round_num'], 1)) db.session.add( Round_Player_Table(round_id=session['round_num'], player_id=1)) db.session.add( Round_Player_Table(round_id=session['round_num'], player_id=2)) db.session.add( Round_Player_Table(round_id=session['round_num'], player_id=3)) db.session.add( Round_Player_Table(round_id=session['round_num'], player_id=4)) db.session.commit() #get the hole from the db for the par property hole = Hole.query.filter_by(id=session['hole_num']).first() return render_template('score_input.html', players=this_Rounds_Players, hole_num=session['hole_num'], round_num=session['round_num'], par_num=hole.par)
def score_input():#this fills in a blank template with player,round,and par information for use in score inputs. if 'error' not in session: session['error'] = "" if 'error1' not in session: session['error1'] = "" if 'error2' not in session: session['error2'] = "" if 'error3' not in session: session['error3'] = "" if 'error4' not in session: session['error4'] = "" this_Rounds_Players = []#create an empty list then add player names from session into the list this_Rounds_Players += Player.query.filter_by(id = session['player_1_Id']) this_Rounds_Players += Player.query.filter_by(id = session['player_2_Id']) this_Rounds_Players += Player.query.filter_by(id = session['player_3_Id']) this_Rounds_Players += Player.query.filter_by(id = session['player_4_Id']) if 'hole_num' not in session:#This tracks the current hole number being scored session['hole_num'] = 1 if 'round_num' not in session:#This tracks the current round number being scored session['round_num'] = 1 db.session.add(Round(session['round_num'],session['tournament_Id']))#Instantiate a round with the given round number. db.session.add(Round_Player_Table(round_id=session['round_num'],player_id=1))#Connect each player to this new round db.session.add(Round_Player_Table(round_id=session['round_num'],player_id=2)) db.session.add(Round_Player_Table(round_id=session['round_num'],player_id=3)) db.session.add(Round_Player_Table(round_id=session['round_num'],player_id=4)) db.session.commit() #get the hole from the db for the par property hole = Hole.query.filter_by(id = session['hole_num']).first() return render_template('score_input.html', players=this_Rounds_Players, hole_num=session['hole_num'], round_num=session['round_num'],par_num=hole.par, errors=session['error'], error1=session['error1'], error2=session['error2'], error3=session['error3'], error4=session['error4'])
def count_score(round_cont): #lost_score = Round.query(Round.defenseteamid,counta(Round.defenseteamid)).filter(Round.rounds==round_cont,Round.attackteamid!=0).group_by(Round.defenseteamid).all() lost_score = db.session.query(Round.defenseteamid, func.count(Round.defenseteamid)).filter( Round.rounds == round_cont, Round.attackteamid != 0).group_by( Round.defenseteamid).all() print(lost_score) #lost_score = db.session.query(Round.defenseteamid,func.count(Round.defenseteamid)).group_by(Round.defenseteamid).all() for i in lost_score: scroe_avg = score_unit // i[1] #print(scroe_avg) print('lost team id', i[0], 'lost times', i[1], 'avg_score', scroe_avg) db.session.query(Round).filter( Round.defenseteamid == i[0], Round.rounds == round_cont, Round.attackteamid != 0).update({"score": scroe_avg}) db.session.commit() #print(lost_score) #print(1) check_score = db.session.query(Round.defenseteamid).filter( Round.rounds == round_cont, Round.attackteamid == 0).group_by(Round.defenseteamid).all() print('=== start count service score ===') print(check_score) teams = Teams.query.all() print(teams) scroe_avg = (service_down) // (len(teams) - len(check_score)) service_down_team_list = [] for i in check_score: service_down_team_list.append(i[0]) print(service_down_team_list) service_down_team = [] service_up_team = [] teamname = {} for eteam in teams: if eteam.id in service_down_team_list: service_down_team.append(eteam.id) else: service_up_team.append(eteam.id) teamname[eteam.id] = eteam.name for i in service_down_team: for j in service_up_team: db.session.add( Round(j, i, round_cont, u"%s 躺赢获取 %s 的故障分" % (teamname[j], teamname[i]), scroe_avg)) db.session.commit() print('count of service down teams', len(check_score), service_down_team) print('count of service ok teams', len(teams) - len(check_score), service_up_team) print('=== end count service score ===')
def resolve_matchups(parent, info): matchups = SQLRound.get_matchups_for_round(parent.tournament_id, parent.round_num) return [ Matchup( id=matchup["id"], pl=Team(num=matchup["pl"]), defense=Team(num=matchup["def"]), ) for matchup in matchups ]
def post(self, base_url, extra): """Save the data posted about the all the items from the HTML form""" try: delete_years = set() # Only refresh the cache for affected years # All the rounds are saved at once for year_round_key in self.request.POST.keys(): try: split_key = year_round_key.split('-') year = split_key[0] delete_years.add(year) round = split_key[1] if len(round) == 0: # Might have been a negative round, so an extra split! round = '-' + split_key[2] round_key = Round.get_key(round, year) round = Round.get_by_key_name(round_key) if round: args = { 'year': round.year, 'key_name': self.data_class.get_key(round.num, round.year), 'round': round } player_key = self.request.POST.get(year_round_key) args[self.name_property] = player_key if not player_key in self.data_class.OTHERS: args['player_ref'] = Player.get_by_key_name( player_key) new_entry = self.data_class(**args) new_entry.put() except IndexError: pass # Flush the cache for the affected years for y in delete_years: memcache.delete(CommonItemPage.get_mem_key(self.type, y)) memcache.delete(CommonItemPage.get_mem_key(self.type, ALL_YEARS)) self.get(base_url, extra) except Exception, e: self.get(base_url, extra, error=e)
def init_team_flag(mathobj, themath): #themath = models.math.query.first() #global round_cont #round_cont+=1 #获取当前最大的轮数 round_cont = db.session.query(func.max( Flags.rounds)).scalar() #Round.query.fields(Round.rounds).first() if round_cont: round_cont = round_cont + 1 else: round_cont = 1 #flag_list=[] for i in mathobj: text = '%s %s check False' % (i.teamname, i.db_containers.typename) #记录 check_rezult 状态 if i.db_containers.check_stat == 1: # Round(attackteamid,rounds,containerid,text,score=0) db.session.add( Round(0, round_cont - 1, i.id, text, -themath.checkscore)) # db.session.commit() #初始化新的一轮 check_rezult i.db_containers.check_stat = 0 i.db_containers.attack_stat = 0 i.update_checkstat() i.update_attackstat() #i.session.commit() flag = Flags(i.id, make_flag_str(i.container_name), round_cont) #flag_list.append(flag) db.session.add(flag) db.session.commit() try: i.freshflag(flag.flag) #logger.info('%s Flag fresed : %s'%(i.teamname,flag.flag)) except: i.db_containers.check_stat = 1 i.update_checkstat() #i.session.commit() logger.warning('Round %d flag fresh %s error' % (round_cont, i.teamname)) t = threading.Thread(target=errorfresh, args=( i, flag.flag, )) t.setDaemon(True) t.start() #db.session.add_all(flag_list) #db.session.commit() countscore(round_cont - 1, mathobj, themath.checkscore, themath.atacckscore) return round_cont
def do_body(self, args): """Render the HTML for all the items, and provide enough information to edit one of them.""" updated_args = dict(args) year = self.get_year(args) updated_args['year'] = year data = { 'url_args': updated_args, } if year == ALL_YEARS: data['rounds'] = Round.gql('ORDER BY date ASC') data['players'] = Player.gql( 'ORDER BY last_name ASC, first_name ASC') else: data['rounds'] = Round.gql('WHERE year = :1 ORDER BY date ASC', int(year)) data['players'] = [ p.player for p in TeamList.gql('WHERE year = :1', int(year)) ] data['players'].sort(self.sort_players) tpath = os.path.join(DeeWhyPage.TEMPLATE_DIR, self.template_file) self.response.out.write(template.render(tpath, data))
def init_db(): Base.metadata.drop_all(bind=engine) Base.metadata.create_all(bind=engine) wall_question = Question(text='What was on your wall as a kid?') db_session.add(wall_question) pet_question = Question(text='What was your favorite pet?') db_session.add(pet_question) matt = Comrade(name='Matt', email='*****@*****.**') db_session.add(matt) julian = Comrade(name='Julian', email='*****@*****.**') db_session.add(julian) wall_1 = Round(name='wall_round_one', date=date.today(), question=wall_question) wall_2 = Round(name='wall_round_two', date=date.today() + one_week, question=wall_question) pet_1 = Round(name='pet_round_one', date=date.today() + 2 * one_week, question=pet_question) pet_2 = Round(name='pet_round_two', date=date.today() + 3 * one_week, question=pet_question) db_session.add_all([wall_1, wall_2, pet_1, pet_2]) db_session.commit() db_session.execute(comrade_to_round.insert().values([ (matt.uuid, wall_1.uuid), (julian.uuid, wall_2.uuid), (julian.uuid, pet_1.uuid), (matt.uuid, pet_2.uuid) ])) db_session.commit()
def do_body(self, args): """Render the HTML for the front page""" self.do_player_list(args) year = self.get_year(args) # Different key for the different modes if args.has_key('player'): mem_key = PlayerPage.get_player_mem_key(args['player'], year) else: mem_key = PlayerPage.get_draw_mem_key(year) player_page = memcache.get(mem_key) if player_page is None: data = { 'url_args': args, } # Switches mode depending on the input: if args.has_key('player'): # Present the player with the dialogues to set the availability page = 'individual.html' data = { 'rounds': Round.gql('WHERE year = :1 ORDER BY date ASC', year), 'player': Player.get_by_key_name(args['player']), } else: # Present the full season summary of upcoming games page = 'summary.html' if year == ALL_YEARS: data['rounds'] = Round.gql('ORDER BY date ASC') else: data['rounds'] = Round.gql( 'WHERE year = :1 ORDER BY date ASC', year) tpath = os.path.join(DeeWhyPage.TEMPLATE_DIR, page) player_page = template.render(tpath, data) memcache.set(mem_key, player_page) self.response.out.write(player_page)
def game(self): """ Run chess game""" tournoi = self.load_tt() if len(tournoi.players_list) < 8: self.menu.add_player() self.add_players_in_tt(tournoi) else: p_score = [] round_list = [] rcount = 0 while rcount < tournoi.rounds_number: if rcount < 1: sttime = time.strftime('%H:%M:%S') r1_order, r2_order = self.first_round_by_rank(tournoi) scores, round1 = self.scoring_first_round( r1_order, r2_order) endtime = time.strftime('%H:%M:%S') round_list.append( Round(rcount + 1, sttime, endtime, round1)) for score in scores: p_score.append(score) else: sttime = time.strftime('%H:%M:%S') other_round, round = self.next_round_by_score(p_score) endtime = time.strftime('%H:%M:%S') round_list.append(Round(rcount + 1, sttime, endtime, round)) for score in other_round: p_score.append(score) rcount += 1 rlist = self.add_round_bdd(round_list, tournoi) for round in rlist: tournoi.add_round(round) p_score.sort(key=lambda x: (x["Score"], x["Rank"]), reverse=True) self.menu.end_tournament(p_score) self.start_menu()
def do_body(self, args): """Render the HTML for all the rounds, and provide enough information to edit an existing round or create a new one""" data = { 'url_args': args, 'new_round': True, 'grounds': Ground.gql('ORDER BY name ASC') } year = self.get_year(args) if year == ALL_YEARS: data['rounds'] = Round.gql('ORDER BY date ASC') else: data['rounds'] = Round.gql('WHERE year = :1 ORDER BY date ASC', year) # Retrieve the full information for the given round so we can edit it if args.has_key('round'): round_key = Round.get_key( urllib.unquote(urllib.unquote(args['round'])), year) curr_round = Round.get_by_key_name(round_key) if curr_round: data['current'] = curr_round data['new_round'] = False tpath = os.path.join(DeeWhyPage.TEMPLATE_DIR, 'manage_draw.html') self.response.out.write(template.render(tpath, data))
async def start_round(self, message, stripped): if message.author.guild_permissions.manage_guild: data = session.query(RootData).first() if data.prizes == []: await message.channel.send('You need to set your prizes before you continue. To do so please type `{}prizes`'.format(data.prefix)) return round_ = session.query(Round).filter(Round.completed == False).first() if round_ is not None: await message.channel.send('There is already a round in progress. Please use `lotto end` to end the round.') else: r = Round(completed=False) session.add(r) session.commit() await message.channel.send('A round has been started! The Draw ID is **{}**'.format(r.id))
def round_2_5sec(exchange_5sec): new_round = Round( round_date=date(2000, 1, 1), round_number=28, exchange_id=exchange_5sec.id, start_time=datetime(2000, 1, 1, 0, 5, 15), lock_in_bets_time=datetime(2000, 1, 1, 0, 5, 17), spinning_start_time=datetime(2000, 1, 1, 0, 5, 20), end_time=datetime(2000, 1, 1, 0, 5, 25), round_status=RoundStatus.SPINNING, created_at=datetime(2000, 1, 1, 0, 5, 15), updated_at=datetime(2000, 1, 1, 0, 5, 15), ) db.session.add(new_round) db.session.commit() yield new_round
def index(): """Index page of the website.""" # TODO(Make the game) if request.method == 'POST': # print("This is the data.") # print(request.get_data()) # print(request.form) category = request.form['category'] players = [] current_game = Game(start=datetime.datetime.now()) for key in request.form.keys(): if key != 'category': print(key) current_player = User(name=request.form[key], points=0) current_game.players.append(current_player) players.append(current_player) db.session.add(current_player) db.session.add(current_game) # Rounds, current_round, and redirect r = requests.get(BING_IMAGE.format(query=category), headers={'Authorization': CREDENTIALS}) response = json.loads(r.text) results = response['d']['results'] # MediaUrl for result in results[:min(5, len(results))]: current_round = Round(impression=result['MediaUrl']) db.session.add(current_round) current_game.rounds.append(current_round) # print(current_game.rounds) db.session.add(current_game) db.session.commit() current_game.current_round = current_game.rounds[0].id db.session.commit() # print("Finished making a game.") return redirect(url_for('game', game_id=current_game.id)) # return redirect('/game/' + str(current_game.id)) return render_template('index.html')
def service_checker(teamid, rounds): port = 30080 + teamid * 100 url = 'http://127.0.0.1:%d/' % port check_rezult = True try: r = requests.get(url) if b'Home' not in r.content: check_rezult = False logger.info('team %d check index.php False' % teamid) url = 'http://127.0.0.1:%d/login.php' % port r = requests.get(url) if r.status_code != 200: check_rezult = False logger.info('team %d check login.php False' % teamid) except: check_rezult = False logger.info('team %d check webservice False' % teamid) if rounds == 0: return 'round 0 not check' ''' check_rezult = True if teamid == 3: check_rezult = False if rounds > 5 and teamid == 2: check_rezult = False ''' if check_rezult == False: if Round.query.filter(Round.attackteamid == 0, Round.defenseteamid == teamid, Round.rounds == rounds).first(): return 'team %d already checke false' % teamid else: team = Teams.query.filter(Teams.id == 1).first() db.session.add( Round(0, teamid, rounds, '{} 服务故障'.format(team.name), service_down)) #Round(j,i,round_cont,'%s 躺赢获取 %s 的故障分'%(teamname[j],teamname[i]),scroe_avg)) db.session.commit() #db.session.query(Round).filter(Round.defenseteamid ==i[0],Round.rounds==rounds).update({"score":scroe_avg}) return 'team %d check false' % teamid return 'team %d check ok' % teamid
def round_with_max_lots(exchange_with_max_lots): new_round = Round( round_date=date(2000, 1, 1), round_number=27, exchange_id=exchange_with_max_lots.id, max_rise_bets_amount=100000, max_fall_bets_amount=100000, start_time=datetime(2000, 1, 1, 0, 5, 10), lock_in_bets_time=datetime(2000, 1, 1, 0, 5, 12), spinning_start_time=datetime(2000, 1, 1, 0, 5, 15), end_time=datetime(2000, 1, 1, 0, 5, 20), round_status=RoundStatus.BETTING, created_at=datetime(2000, 1, 1, 0, 5, 10), updated_at=datetime(2000, 1, 1, 0, 5, 10), ) db.session.add(new_round) db.session.commit() yield new_round
def process_score(): tournament_id = 1 if session['hole_num'] >= 18: session['hole_num'] = 1 #session['round_num'] += 1 db.session.add(Round(session['round_num'], tournament_id)) db.session.add( Round_Player_Table(round_id=session['round_num'], player_id=1)) db.session.add( Round_Player_Table(round_id=session['round_num'], player_id=2)) db.session.add( Round_Player_Table(round_id=session['round_num'], player_id=3)) db.session.add( Round_Player_Table(round_id=session['round_num'], player_id=4)) db.session.commit() return redirect('/leaderboard') player_1_Score = int(request.form['player_1_score']) player_2_Score = int(request.form['player_2_score']) player_3_Score = int(request.form['player_3_score']) player_4_Score = int(request.form['player_4_score']) db.session.add( Score(round_id=session['round_num'], hole_id=session['hole_num'], player_id=1, score=player_1_Score)) db.session.add( Score(round_id=session['round_num'], hole_id=session['hole_num'], player_id=2, score=player_2_Score)) db.session.add( Score(round_id=session['round_num'], hole_id=session['hole_num'], player_id=3, score=player_3_Score)) db.session.add( Score(round_id=session['round_num'], hole_id=session['hole_num'], player_id=4, score=player_4_Score)) session['hole_num'] += 1 db.session.commit() return redirect('/score_input')
def create_game(self, player, access_token, opponent_fb_id): ordem_aleatoria = ['0', '1'] random.shuffle(ordem_aleatoria) game = Game(status=ordem_aleatoria[0]) game.save() player1 = Player(user=player, game=game, last_round=1) player1.save() op_user = User.objects.get(username=opponent_fb_id) player2 = Player(user=op_user, game=game, last_round=1) player2.save() f1 = self.__create_cards(player1, access_token) f2 = self.__create_cards(player2, access_token) Round(round_number=1, game=game).save() players = game.player_set.all() return game.id
def yield_round(self): round = self.rounds.next() winner = None for log in round: if "CTs_Win" in log.event: winner = "CT" elif "Terrorists_Win" in log.event: winner = "T" elif 'joined team "TERRORIST"' in log.event: self.change_team(log, self.te) elif 'joined team "CT"' in log.event: self.change_team(log, self.ct) elif 'joined team "SPECTATOR"' in log.event: self.change_team(log, self.sp) elif 'disconnected' in log.event: self.change_team(log, remove=True) return Round(winner, self.te, self.ct, self.sp, round)
def start_new_round(exchange, now): round_number = (now.hour * 60 * 60 + now.minute * 60 + now.second) // exchange.bet_and_lock_seconds new_round = Round( round_date=now.date(), round_number=round_number, exchange_id=exchange.id, start_time=now, lock_in_bets_time=now + timedelta( seconds=exchange.bet_and_lock_seconds - LOCK_IN_BETS_TIME_DELAY), spinning_start_time=now + timedelta(seconds=exchange.bet_and_lock_seconds), end_time=now + timedelta(seconds=exchange.bet_and_lock_seconds + exchange.max_spin_seconds), start_price=None, end_price=None, round_result=None, round_result_decided_time=None, round_status=RoundStatus.BETTING, ) db.session.add(new_round) db.session.flush() logger.info(f"Starting new round: {new_round}") return new_round
def do_body(self, args): """Generate the HTML email if there is an upcoming game""" day_skip = 2 if args.has_key('days'): try: day_skip = int(args['days']) except: pass admin_address = '*****@*****.**' curr_date = datetime.now() start_date = curr_date.replace(hour=0, minute=0, second=0) + timedelta(days=day_skip) end_date = curr_date.replace(hour=0, minute=0, second=0) + timedelta(days=day_skip + 1) # Find all the games that are within the given date range - really only expect one, behaviour # could end up a little strange if there's multiple... query = Round.gql('WHERE date >= :1 AND date <= :2', start_date, end_date) curr_round = query.get() logging.debug('WHERE date >= %s AND date <= %s' % (start_date, end_date)) logging.debug(curr_round) if curr_round: data = { 'current': curr_round, } tpath = os.path.join(DeeWhyPage.TEMPLATE_DIR, 'mailer.html') email_content = template.render(tpath, data) self.response.out.write( email_content) # Print the content as an added debug players = [ p.player for p in TeamList.gql('WHERE year = :1', curr_round.date.year) ] non_admins = [] admin = '' for p in players: details = '%s %s<%s>' % (p.first_name, p.last_name, p.email) if p.email == admin_address: admin = details else: non_admins.append(details) recipients = ','.join(non_admins) cc_recipients = admin # working around a server bug where cron emails fail when sent to me! #recipients = 'Test Guy<*****@*****.**>' % (curr_date.strftime('%A %d %B %I:%M')) # To make sure tests don't go out! logging.debug('Sending to ' + recipients) """ recipients = ','.join([ 'Adam1<*****@*****.**>', 'Adam2<*****@*****.**>', ]) logging.debug('Really sending to ' + recipients) """ caption = curr_round.caption if not caption: caption = 'Round ' + ` int(curr_round.num) ` kickoffStr = ` int(curr_round.time.strftime('%I')) ` if curr_round.time.minute > 0: kickoffStr += ':' + curr_round.time.strftime('%M') kickoffStr += curr_round.time.strftime('%p') subject = caption + ' - ' + curr_round.date.strftime( '%A %d %B') + ' at ' + kickoffStr message = mail.EmailMessage() message.subject = subject message.sender = 'Dee Why AL5 Team Page<*****@*****.**>' message.to = recipients message.cc = cc_recipients # Too lazy to add BCC recipients as a UI option so just add them here message.bcc = '*****@*****.**' message.html = email_content message.check_initialized() message.send()
def post(self, base_url, extra): """Save the data posted about the result from the HTML form""" try: curr_round = None round_num = int(self.request.get('round_num')) year = int(self.request.get('year')) round_key = Round.get_key(round_num, year) if round_key: curr_round = Round.get_by_key_name(round_key) if curr_round: # Quite a few cached pages depend upon this output, need to delete them all # - Removing this page from the summary memcache.delete(PlayerPage.get_draw_mem_key(year)) memcache.delete(PlayerPage.get_draw_mem_key(ALL_YEARS)) # - Disabling the options for this page for each player for t in TeamList.gql('WHERE year = :1', year): memcache.delete( PlayerPage.get_player_mem_key(t.player.db_key, year)) # - Changing the result and who scored memcache.delete(ResultsPage.get_mem_key(year)) memcache.delete(ResultsPage.get_mem_key(ALL_YEARS)) # - Changing the number of goals memcache.delete(ScorersPage.get_mem_key(year)) memcache.delete(ScorersPage.get_mem_key(ALL_YEARS)) # - Triggering previously suppressed rounds for the beer and shirts memcache.delete(BeerPage.get_mem_key('beer', year)) memcache.delete(BeerPage.get_mem_key('beer', ALL_YEARS)) memcache.delete(ShirtsPage.get_mem_key('shirts', year)) memcache.delete(ShirtsPage.get_mem_key('shirts', ALL_YEARS)) args = { 'year': year, 'key_name': Result.get_key(round_num, year), 'round': curr_round, } deewhy_forfeit = self.request.get('deewhy_forfeit') opponent_forfeit = self.request.get('opponent_forfeit') if not (deewhy_forfeit or opponent_forfeit): # Regular operation - read the goal counts args['deewhy_goals'] = self.get_goals('deewhy_goals') args['opponent_goals'] = self.get_goals('opponent_goals') args['other_goals'] = self.get_goals('other_goals') args['own_goals'] = self.get_goals('own_goals') elif deewhy_forfeit is not None and self.request.get( 'deewhy_forfeit') == 'on': # No goals in a forfeit args['deewhy_forfeit'] = True elif opponent_forfeit is not None and self.request.get( 'opponent_forfeit') == 'on': # No goals in a forfeit args['opponent_forfeit'] = True curr_result = Result(**args) curr_result.put() # Need to delete any existing scorers for this round - otherwise orphaned goals will stuff up the tallies for scorer in curr_result.scorer_set: scorer.delete() if not (deewhy_forfeit or opponent_forfeit): for post_key in self.request.POST.keys(): # Each goal scorer in the game needs a separate record if post_key.startswith('goals_'): player = Player.get_by_key_name( post_key[len('goals_'):]) goals = self.get_goals(post_key) if player is not None and goals > 0: GoalsScored( key_name=GoalsScored.get_key( player.db_key, round_num, year), year=int(year), player=player, result=curr_result, count=goals, ).put() self.get(base_url, extra) except Exception, e: self.get(base_url, extra, error=e)
def post(self, base_url, extra): """Save the details for the given round""" try: old_key = self.request.get('key_name') if self.request.POST.get('do_delete') == 'true': # Delete the selected round self.delete_round(old_key) year = old_key.split('-')[0] else: # Create/update the round num = int(self.request.get('num').strip()) caption = self.request.get('caption').strip() #if caption == '': # caption = 'Rd ' + `num` try: date = datetime.strptime( self.request.get('date').strip(), '%d/%m/%Y').date() except: date = datetime.strptime( self.request.get('date').strip(), '%d/%m/%y').date() time_value = self.request.get('time').strip() if time_value == '': time = None else: time = datetime.strptime(time_value, '%H:%M').time() opponent = self.request.get('opponent').strip() homeaway = self.request.get('homeaway').strip() location = Ground.get(self.request.get('location')) key = Round.get_key(num, date.year) if key != '' and num != '': new_round = Round( key_name=key, num=num, year=date.year, caption=caption, date=date, time=time, opponent=opponent, homeaway=homeaway, location=location, ) new_round.put() if old_key != key: # If changing the info changes the key, be sure to scrap the old entry too self.delete_round(old_key) year = date.year # Pages that are affected by this post: # - Draw, via a new item memcache.delete(PlayerPage.get_draw_mem_key(year)) memcache.delete(PlayerPage.get_draw_mem_key(ALL_YEARS)) # - All the individual player pages, via the items they can update for p in TeamList.gql('WHERE year = :1', year): memcache.delete( PlayerPage.get_player_mem_key(p.player.db_key, year)) memcache.delete( PlayerPage.get_player_mem_key(p.player.db_key, ALL_YEARS)) # NOT - results, beer or shirts (until results posted) self.get(base_url, extra) except Exception, e: self.get(base_url, extra, error=e)
def delete_round(self, key): """Scrap the entire round""" if key: r = Round.get_by_key_name(key) if r: r.delete()
def run(self, num_rounds=50, seed=None, deployment_rate=1.0): """Simulate the game. For reproducibility, you can specify the seed for the random number generator. """ random.seed(seed) rounds = list() for round_no in range(num_rounds): self.logger.debug("Starting round %d" % round_no) round_ = Round(round_no) # Decides which Challenge Sets to field for service_name, service in self.services.items(): if not service.is_active(round_no): deploy = random.random() self.logger.debug("Deployment %f with threshold %f" % (deploy, deployment_rate)) if deploy < deployment_rate: self.logger.debug("Activating service %s" % service_name) service.activate(round_no) for team in self.teams.values(): for team_service_name, team_service in team.services.items( ): if team_service_name == service_name: team_service.activate(round_no) # Run PoVs of each team for team in self.teams.values(): self.logger.debug("Executing the PoVs of team %s (%d)" % \ (team.name, len(team.povs))) # Execute the current team PoVs against the relevant binaries # of other teams (Evaluation points). for pov in team.povs: # Only attack teams who have same binary fielded; a team # might have fielded a patched version for which the PoV # does not work. targets = ( t for t in self.teams.values() if t != team and t.services[pov.service.name].binary == pov.binary and t.services[pov.service.name].is_active(round_no) and t.services[pov.service.name].is_fielded(round_no)) for target in targets: self.logger.debug("Throwing PoV of type %d against team %s, service %s, binary %s" % \ (pov.kind, target.name, pov.service.name, pov.service.binary.name)) if pov.successful(target): self.logger.debug("PoV succeeded!") round_.pov_successful(team, pov, target) else: self.logger.debug("PoV failed!") # Total score per Team for team in self.teams.values(): self.logger.debug("Evaluating scores for team %s" % team.name) for service in team.services.values(): self.logger.debug("Evaluating scores for service %s" % service.name) if not service.is_active(round_no): score = Score(service.name, 0, 0, 0, 0, 0, 0, len(self.teams.values())) round_.scores[team.name].append(score) self.logger.debug("Service is inactive, values is 0") continue attacks_performed = round_.successful_attacks_performed( service.name, team.name) attacks_received = round_.successful_attacks_received( service.name, team.name) self.logger.debug("Attacks performed: %d" % attacks_performed) self.logger.debug("Attacks received: %d" % attacks_received) #consensus = round_.successful[service.name].count(team.name) #povcount = PoVCount(consensus, # service.reference_povs_successful, # service.reference_povs_total) if service.is_fielded(round_no): functionality = service.binary.functionality else: functionality = 0 score = Score(service.name, functionality, service.binary.overhead_time, service.binary.overhead_memory, service.binary.overhead_size, attacks_performed, attacks_received, len(self.teams.values())) round_.scores[team.name].append(score) self.logger.debug("Score %f: Availability: %f min(performance %f, functionality %f), Security: %f, Evaluation: %f" % \ (score.total, score.availability, score.performance, score.functionality, score.security, score.evaluation)) #scores[team.name] = sum(s.total for s in # round_.scores[team.name]) rounds.append(round_) # Team actions for team in self.teams.values(): self.logger.debug("Determining behavior for team %s" % team.name) for service in team.services.values(): self.logger.debug("Determining behavior for service %s" % service.name) if not service.is_active(round_no): self.logger.debug("Service is inactive, skipping") continue team.generate_patch(service.name, round_no) team.generate_pov(service.name, round_no, self.teams) self.logger.debug(str(team)) return rounds
def init_team_flag(mathobj): global timespan themath = math.query.first() #匹配比赛信息,控制刷新时间在比赛进行时 if themath: timespan = themath.flagflash * 60 if (datetime.datetime.now() - themath.endtime).total_seconds() > 0 or ( datetime.datetime.now() - themath.starttime).total_seconds() < 0: print('=== Time up ===') print('[+]starttime', themath.starttime) print('[+]the time', datetime.datetime.now()) print('[+]endtime', themath.endtime) print((datetime.datetime.now() - themath.endtime).total_seconds()) print((datetime.datetime.now() - themath.starttime).total_seconds()) #return False else: print('=== No math infomation ===') #return False #global round_cont #round_cont+=1 #获取当前最大的轮数 round_cont = db.session.query(func.max( Flags.rounds)).scalar() #Round.query.fields(Round.rounds).first() if round_cont: round_cont = round_cont + 1 else: round_cont = 1 flag_list = [] for i in mathobj: text = '%s %s check False' % (i.teamname, i.db_containers.typename) #记录 check_rezult 状态 if i.db_containers.check_stat == 1: # Round(attackteamid,rounds,containerid,text,score=0) db.session.add( Round(0, round_cont - 1, i.id, text, themath.checkscore)) # db.session.commit() #初始化新的一轮 check_rezult i.db_containers.check_stat = 0 flag = Flags(i.id, make_flag_str(i.container_name), round_cont) flag_list.append(flag) try: i.freshflag(flag.flag) except: i.db_containers.check_stat = 1 print('Round %d flag fresh %s error' % (round_cont, i.teamname)) t = threading.Thread(target=errorfresh, args=( i, flag.flag, )) t.setDaemon(True) t.start() db.session.add_all(flag_list) db.session.commit() countscore(round_cont - 1, mathobj, themath.checkscore, themath.atacckscore) time.sleep(timespan) return round_cont
def process_score(): # if request.method=='POST': tournament_id = session['tournament_Id'] tournament_id_str = str(tournament_id) session['error'] = "" session['error1'] = "" session['error2'] = "" session['error3'] = "" session['error4'] = "" #grab scores from form POST request score1 = request.form['player_1_score'] if (score1 == None) or (score1 == "") or (score1 == False): session['error1'] = "You must input a score for every player" score2 = request.form['player_2_score'] if (score2 == None) or (score2 == "") or (score2 == False): session['error1'] = "You must input a score for every player" score3 = request.form['player_3_score'] if (score3 == None) or (score3 == "") or (score3 == False): session['error1'] = "You must input a score for every player" score4 = request.form['player_4_score'] if (score4 == None) or (score4 == "") or (score4 == False): session['error1'] = "You must input a score for every player" if session['error1'] != "": session['error'] += session['error1'] return redirect ('/score_input') else: player_1_Score_val = score1.strip() for c in player_1_Score_val: if not c in '0123456789': session['error2'] = "Input must be a number" # return redirect('/score_input') if session['error2'] == "": player_1_Score = int(player_1_Score_val) if player_1_Score <= 0: session['error3'] = "Score must be greater than 0" if player_1_Score > 99: session['error4'] = "Score must be no greater than 99" player_2_Score_val = score2.strip() for c in player_2_Score_val: if not c in '0123456789': session['error2'] = "Input must be a number" # return redirect('/score_input') if session['error2'] == "": player_2_Score = int(player_2_Score_val) if player_2_Score <= 0: session['error3'] = "Score must be greater than 0" if player_2_Score > 99: session['error4'] = "Score must be no greater than 99" player_3_Score_val = score3.strip() for c in player_3_Score_val: if not c in '0123456789': session['error2'] = "Input must be a number" # return redirect('/score_input') if session['error2'] == "": player_3_Score = int(player_3_Score_val) if player_3_Score <= 0: session['error3'] = "Score must be greater than 0" if player_3_Score > 99: session['error4'] = "Score must be no greater than 99" player_4_Score_val = score4.strip() for c in player_4_Score_val: if not c in '0123456789': session['error2'] = "Input must be a number" # return redirect('/score_input') if session['error2'] == "": player_4_Score = int(player_4_Score_val) if player_4_Score <= 0: session['error3'] = "Score must be greater than 0" if player_4_Score > 99: session['error4'] = "Score must be no greater than 99" session['error'] += session['error1'] + session['error2'] + session['error3'] + session['error4'] if session['error'] > "": return redirect('/score_input') #get the player ids using Session variable hole_id = Hole.query.filter_by(hole_num = session['hole_num'], owner_id = session['course_id']).first().id print(hole_id) #create new score object using player ID, Round ID, Hole ID, Course ID, Tournament ID all from session and Score from the POST request db.session.add(Score(round_id=session['round_num'], hole_id=hole_id, course_id=session['course_id'], player_id=session['player_1_Id'], tournament_id=session['tournament_Id'],score=player_1_Score)) db.session.add(Score(round_id=session['round_num'], hole_id=hole_id, course_id=session['course_id'], player_id=session['player_2_Id'], tournament_id=session['tournament_Id'],score=player_2_Score)) db.session.add(Score(round_id=session['round_num'], hole_id=hole_id, course_id=session['course_id'], player_id=session['player_3_Id'], tournament_id=session['tournament_Id'],score=player_3_Score)) db.session.add(Score(round_id=session['round_num'], hole_id=hole_id, course_id=session['course_id'], player_id=session['player_4_Id'], tournament_id=session['tournament_Id'],score=player_4_Score)) db.session.commit() #update the current hole number in the session variable session['hole_num'] += 1 if session['hole_num'] > 18:#this logic will determine if all 18 holes have been played. session['hole_num'] = 1#After 18 holes, hole is reset to 1 session['round_num'] += 1#Round is increased by 1 db.session.add(Round(session['round_num'],tournament_id))#New round is created in preparation for new scores db.session.add(Round_Player_Table(round_id=session['round_num'],player_id=1))#Player connected to new round db.session.add(Round_Player_Table(round_id=session['round_num'],player_id=2)) db.session.add(Round_Player_Table(round_id=session['round_num'],player_id=3)) db.session.add(Round_Player_Table(round_id=session['round_num'],player_id=4)) db.session.commit() return redirect('/leaderboard?tournament_id='+ tournament_id_str)#After last 18 holes, user sent to leaderboard return redirect('/score_input')#when there are more scores to report, user goes to next score_input template