def __fetch_to_object(self, fetchresult, return_one=False): """ fetch[0]: id_championnat fetch[1]: id_equipe fetch[2]: id_equipe_exterieur fetch[3]: id_match fetch[4]: date_match fetch[5]: commentaire_match fetch[6]: isplayed_match :param fetchresult: :param return_one: :return: """ liste = [] try: if len(fetchresult) > 0: for fetch in fetchresult: obj = Match(fetch[1], fetch[2], fetch[4], fetch[5], fetch[6]) obj.id = fetch[3] liste.append(obj) return liste if not return_one else liste[0] else: return None except Exception as ex: DAOException(self, ex)
def register_player(contest_id, user_id): contest = Contest.objects(id = contest_id)[0] player_list = PlayerList.objects(contestId = contest_id)[0] user_id_to_substitute = player_list.userIds[contest.currentPlayers] player_list.userIds[contest.currentPlayers] = user_id player_list.save() match_list = get_match_list_by_contest_id(contest_id) contest.currentPlayers += 1 contest.save() for i in Match.objects(player1Id = user_id_to_substitute): if not i.id in match_list.matches: print "OK!" continue print "YEAH" i.player1Id = user_id i.save() print "HAHA" for i in Match.objects(player2Id = user_id_to_substitute): if not i.id in match_list.matches: print "OK!" continue print "YEAH" i.player2Id = user_id i.save() if contest.format == "Single Round-Robin": graph1 = get_graph_by_contest_id(contest_id) for i in graph1.items: if i.playerId == user_id_to_substitute: i.playerId = user_id break graph1.save()
def push_loop_preventing_drop_rules(self, sw, table_number): for h_id in self.network_graph.host_ids: # Get concerned only with hosts that are directly connected to this sw h_obj = self.network_graph.get_node_object(h_id) if h_obj.sw.node_id != sw: continue # Get a vanilla flow flow = self.create_base_flow(sw, table_number, 100) action_list = [] # Compile match with in_port and destination mac address if self.network_graph.controller == "ryu": flow["match"]["in_port"] = h_obj.switch_port.port_number flow["match"]["eth_dst"] = h_obj.mac_addr elif self.network_graph.controller == "onos": flow_match = Match(is_wildcard=True) flow_match["ethernet_type"] = 0x0800 mac_int = int(h_obj.mac_addr.replace(":", ""), 16) flow_match["ethernet_destination"] = int(mac_int) flow_match["in_port"] = int(h_obj.switch_port.port_number) flow["selector"]["criteria"] = flow_match.generate_match_raw( self.network_graph.controller, flow["selector"]["criteria"]) # Make and push the flow self.populate_flow_action_instruction(flow, action_list, True) self.push_flow(sw, flow)
def push_host_vlan_tagged_packets_drop_rules(self, sw, host_vlan_tagged_drop_table): for h_id in self.network_graph.host_ids: # Get concerned only with hosts that are directly connected to this sw h_obj = self.network_graph.get_node_object(h_id) if h_obj.sw.node_id != sw: continue # Get a vanilla flow flow = self.create_base_flow(sw, host_vlan_tagged_drop_table, 100) action_list = [] if self.network_graph.controller == "ryu": flow["match"]["in_port"] = h_obj.switch_port.port_number flow["match"]["vlan_vid"] = self.network_graph.graph.node[sw][ "sw"].synthesis_tag elif self.network_graph.controller == "onos": flow_match = Match(is_wildcard=True) flow_match["ethernet_type"] = 0x0800 flow_match["in_port"] = int(h_obj.switch_port.port_number) flow_match["vlan_id"] = self.network_graph.graph.node[sw][ "sw"].synthesis_tag flow["selector"]["criteria"] = flow_match.generate_match_raw( self.network_graph.controller, flow["selector"]["criteria"]) # Make and push the flow self.populate_flow_action_instruction(flow, action_list, True) self.push_flow(sw, flow)
def create_match(message): app.logger.info("TRYING TO CREATE A NEW MATCH") match = Match(server_config, message['whites'], message['blacks'], message['wt'], message['bt'], message['wi'], message['bi']) manager.add(match) emit('receive-new-match', match.get_reduced_status(), room=accountant.get_cpanel())
def new(): if request.method == 'GET': return make_response(render_template('Theme/form_component.html')) elif request.method == 'POST': app.logger.info("CREATING MATCH FOR W:" + request.json['white_name'] + " B:" + request.json['black_name']) match = Match(server_config, request.json['white_name'], request.json['black_name']) manager.add(match) return json.dumps(match.get_reduced_status())
def validate_game_collection(): """ To perform AFTER the method model.service.set_player_codes() is called Assert the game setup complies with the following constraints: - a team cannot play against itself - a team cannot play against another team more one than once - a team cannot play a game more than once - a team cannot play two matches at the same time - a game cannot have the same hash as another game """ duel_set_list = list() for time in range(1, len(Match.objects().distinct('time')) + 1): player_list = list() for m in Match.objects(time=time): players = m.players_number players_set = {players[0], players[1]} assert (players[0] not in player_list ), "Team {} plays two games at time {}".format( players[0], time) assert (players[1] not in player_list ), "Team {} plays two games at time {}".format( players[1], time) assert ( players[0] != players[1] ), "Player {} plays against itself in game {} at time {}".format( players[0], m.game_number, time) assert (players_set not in duel_set_list ), "Team {} already played against team {}".format( players[0], players[1]) player_list.append(players[0]) player_list.append(players[1]) duel_set_list.append(players_set) hash_list = list() for g in Game.objects(): game_hash = g.hash assert game_hash not in hash_list, "Hash {} is used twice".format( game_hash) hash_list.append(game_hash) player_list = list() matches = Match.objects(game_number=g.number) for m in matches: players = m.players_number assert ( players[0] not in player_list), "Team {} plays twice the game {}".format( players[0], g.number) assert ( players[1] not in player_list), "Team {} plays twice the game {}".format( players[1], g.number) player_list.append(players[0]) player_list.append(players[1])
def get_score(team_code): """ Get the score of a given team :param team_code: a team code :return: a tuple (score, victories, evens, defeats) """ evens = Match.objects(players_code=team_code, even=True).count() victories = Match.objects(winner=team_code).count() defeats = Match.objects(loser=team_code).count() score = victories * 2 + evens return score, victories, evens, defeats
def round_deserializer(reloaded_round): reload_round = Round(reloaded_round["round_number"], reloaded_round["start_time"], reloaded_round["end_time"]) for match in reloaded_round["matches"]: player1 = player_deserializer(match["player1"]) player2 = player_deserializer(match["player2"]) reload_match = Match(player1, player2) reload_match.score_player1 = match["score_player1"] reload_match.score_player2 = match["score_player2"] reload_round.add_reload_match(reload_match) return reload_round
def update_scores(self, match): """ Update score of both Match and Player table Args: match: match to update """ while True: response = self.select.write_score_menu(match) if input_validators.is_valid_write_score_menu_response(response): break Match.update_score_match(self, match, response, self.match_table) Player.update_score_player(self, match, response, self.player_table)
def search(self, password=None, **kwargs): login_page = request_login("match", password, 2) if login_page: return login_page page = get_html("search.html") warning = "" len_kwargs = len([k for k, v in kwargs.items() if v != ""]) if kwargs: if len_kwargs > 1: try: time = None game_number = None if kwargs["time"]: time = int(kwargs["time"]) if kwargs["game_number"]: game_number = int(kwargs["game_number"]) if kwargs["team1_code"] and kwargs["team2_code"]: match = Match.objects(players_code__all=[ kwargs["team1_code"], kwargs["team2_code"] ]).get() else: team_code = kwargs.get("team1_code") or kwargs.get( "team2_code") or None if team_code: if time: match = Match.objects( time=time, players_code=team_code).get() else: match = Match.objects( game_number=game_number, players_code=team_code).get() else: match = Match.objects( time=time, game_number=game_number).get() except ValueError: warning = "Le numéro doit être un nombre" log.error( "{} tried to search a match with an non-integer value)" .format(str(cherrypy.request.remote.ip))) except (DoesNotExist, Exception): warning = "Aucun match ne correspond à la recherche" log.error( "{} tried to search a match but it was not found (time={}, game_number={}, team1_code={}, team2_code={})" .format(str(cherrypy.request.remote.ip), kwargs.get("time", ""), kwargs.get("game_number", ""), kwargs.get("team1_code", ""), kwargs.get("team2_code", ""))) else: return self.match(mid=match.id) else: warning = "Minimum 2 champs sont nécessaires pour trouver un match" return page.replace("{warning}", warning)
def get_all_schedules(): schedules = list() highest_time_game_number = Match.objects( time=model.match.get_match_quantity()).first().game_number for match in Game.objects(number=highest_time_game_number).get().matches: schedules.append(match.schedule) return schedules
def get_new(id_team_home, id_team_outside, datetime=None, comment=None, isplayed=False): obj = Match(id_team_home, id_team_outside, datetime, comment, isplayed) return obj
def get_matches(team_code): """ Get list of matches for a given team :param team_code: team code :return: Match QuerySet ordered in time """ return Match.objects(players_code=team_code).order_by('time')
def prepare_flow_specifications(measurement_rates=None, tests_duration=None): flow_specs = [] flow_match = Match(is_wildcard=True) flow_match["ethernet_type"] = 0x0800 switch_hosts = ["7e", "e5", "66", "38"] configured_rate = 50 # for src_host, dst_host in permutations(switch_hosts, 2): # for src_host, dst_host in [("7e", "38"), # ("38", "7e"), # ("66", "e5"), # ("e5", "66")]: # for src_host, dst_host in [("e5", "7e"), ("7e", "e5")]: if src_host == dst_host: continue # measurement_rates = [] fs = FlowSpecification(src_host_id=src_host, dst_host_id=dst_host, configured_rate=configured_rate, flow_match=flow_match, measurement_rates=measurement_rates, tests_duration=tests_duration, delay_budget=None) flow_specs.append(fs) return flow_specs
def create_first_round(self): new_round = Round.create_round() serialized_round = vars(new_round) new_matchs_id = [] self.round_table.insert(serialized_round) list_of_players_by_ranking = self.list_of_players_by_ranking() Play = Query() for i in range(4): new_match = Match.create_match( self.player_table.get( Play.ranking == list_of_players_by_ranking[0][i]["ranking"] ).doc_id, self.player_table.get( Play.ranking == list_of_players_by_ranking[1][i]["ranking"] ).doc_id, ) serialized_match = vars(new_match) self.match_table.insert(serialized_match) new_matchs_id.append(self.match_table.all()[-1].doc_id) list_of_rounds = self.tournament_table.all()[-1]["rounds"] list_of_rounds.append(self.round_table.all()[-1].doc_id) self.round_table.update( {"list_of_match": new_matchs_id}, doc_ids=[self.round_table.all()[-1].doc_id], ) self.tournament_table.update( {"rounds": list_of_rounds}, doc_ids=[self.tournament_table.all()[-1].doc_id], ) self.warning.round_create(str(self.round_table.all()[-1]["current_round"])) self.table.matchs() return self.manage_tournament()
def set_player_codes(): """ Set players codes in all the Match objects """ for match in Match.objects(): for number in match.players_number: match.players_code.append(Team.objects(number=number).get().code) match.save()
def set_matches(): modified_teams = list() for t in Team.objects(): for m in Match.objects(players_code=t.code).order_by('time'): t.matches.append(m) modified_teams.append(t) for t in modified_teams: t.save()
def get_opponent_code(game_number, team_code): """ Get the opponent of a given player at a given game :param game_number: the game number :param team_code: the player code :return: the opponent code """ match = Match.objects(game_number=game_number, players_code=team_code).get() for p in match.players_code: if p != team_code: return p
def deserializer(name): db = TinyDB("db_tournament.json", indent=4) tournaments = db.table("Tournaments") tournament = Query() tournament = tournaments.search(tournament.name == name)[0] reload_tournament = Tournament( tournament["name"], tournament["time control"], tournament["place"], tournament["date"], tournament["description"], ) for player in tournament["players"]: reload_player = Player( player["first name"], player["last name"], player["elo"], player["date of birth"], player["player's gender"], player["score"], player["opponent list"], ) reload_tournament.add_player(reload_player) for round in tournament["rounds"]: reload_round = Round(round["number"]) for match in round["matchs"]: player1 = Player( match["player1"]["first name"], match["player1"]["last name"], match["player1"]["elo"], match["player1"]["date of birth"], match["player1"]["player's gender"], match["player1"]["score"], match["player1"]["opponent list"], ) player2 = Player( match["player2"]["first name"], match["player2"]["last name"], match["player2"]["elo"], match["player2"]["date of birth"], match["player2"]["player's gender"], match["player2"]["score"], match["player2"]["opponent list"], ) reload_match = Match(player1, player2, match["score player 1"], match["Score player 2"]) reload_round.add_reload_match(reload_match) reload_tournament.add_round(reload_round) return reload_tournament
def instanciation_matchs(self, i): """ Fonction qui instancie les matchs du tournoi à partir du .json """ round_table = self.tournament_progress.serialized_rounds[i] round_matchs = round_table["Round Matchs"] for s_match in round_matchs: print(s_match) m = Match( player1=s_match["Player1"], player2=s_match["Player2"], score1=s_match["Score1"], score2=s_match["Score2"], ) self.tournament_progress.rounds[i].add_match(m.player1, m.player2)
def reset_match(game_number, team1_code, team2_code): """ Reset the score of a match Assert the match exists. :param game_number: a game number :param team1_code: a team code :param team2_code: another team code """ match = Match.objects(game_number=game_number, players_code__all=[team1_code, team2_code]).get() match.winner = "" match.loser = "" match.even = False match.recorded = False match.save() log.info("Match id {} score has been reset".format(match.id))
def prepare_flow_specifications(measurement_rates, tests_duration, number_of_switches, hps, number_of_RT_flows, number_of_BE_flows, delay_budget, cap_rate): flow_specs = [] flow_match = Match(is_wildcard=True) flow_match["ethernet_type"] = 0x0800 flowlist = list(itertools.product(range(1, number_of_switches+1), range(1, hps+1))) # for real-time flows # if unique number (e.g. unique flow-per host) required # index_list = random.sample(range(len(flowlist)), number_of_RT_flows + 1) # for real-time flows # generate random indices (#of_RT_flows) index_list = [random.randint(0, len(flowlist) - 1) for i in range(number_of_RT_flows)] for i in range(number_of_RT_flows): indx = flowlist[index_list[i]] rnd = range(1, indx[0]) + range(indx[0]+1, number_of_switches+1) nxtindx = (random.choice(rnd), random.randint(1, hps)) #nxtindx = flowlist[index_list[i+1]] forward_flow, reverse_flow = get_forward_reverse_flow(measurement_rates, cap_rate, indx, nxtindx, flow_match, delay_budget, tests_duration, "real-time") flow_specs.append(forward_flow) flow_specs.append(reverse_flow) # for best-effort flows index_list = random.sample(range(len(flowlist)), number_of_BE_flows + 1) # for best-effort flows for i in range(number_of_BE_flows): indx = flowlist[index_list[i]] rnd = range(1, indx[0]) + range(indx[0] + 1, number_of_switches + 1) nxtindx = (random.choice(rnd), random.randint(1, hps)) #nxtindx = flowlist[index_list[i + 1]] forward_flow, reverse_flow = get_forward_reverse_flow(measurement_rates, cap_rate, indx, nxtindx, flow_match, delay_budget, tests_duration, "best-effort") flow_specs.append(forward_flow) flow_specs.append(reverse_flow) return flow_specs
def prepare_flow_specifications(measurement_rates, tests_duration, delay_budget): flow_specs = [] flow_match = Match(is_wildcard=True) flow_match["ethernet_type"] = 0x0800 h1s2_to_h1s1 = FlowSpecification(src_host_id="h1s2", dst_host_id="h1s1", configured_rate=50, flow_match=flow_match, measurement_rates=measurement_rates, tests_duration=tests_duration, delay_budget=delay_budget) h2s2_to_h2s1 = FlowSpecification(src_host_id="h2s2", dst_host_id="h2s1", configured_rate=50, flow_match=flow_match, measurement_rates=measurement_rates, tests_duration=tests_duration, delay_budget=delay_budget) h1s1_to_h1s2 = FlowSpecification(src_host_id="h1s1", dst_host_id="h1s2", configured_rate=50, flow_match=flow_match, measurement_rates=[], tests_duration=tests_duration, delay_budget=delay_budget) h2s1_to_h2s2 = FlowSpecification(src_host_id="h2s1", dst_host_id="h2s2", configured_rate=50, flow_match=flow_match, measurement_rates=[], tests_duration=tests_duration, delay_budget=delay_budget) flow_specs.append(h1s2_to_h1s1) flow_specs.append(h2s2_to_h2s1) flow_specs.append(h1s1_to_h1s2) flow_specs.append(h2s1_to_h2s2) return flow_specs
def matching(list_sort, turn, tournament): """ Cette fonction fait correspondre le joueur 1 avec le jouer 2 le joueur 3 avec le joueur 4, et ainsi de suite. Si le joueur 1 a déjà joué contre le joueur 2, elle l'associe plutôt au joueur 3. """ matches = 0 while matches < 4: player = list_sort[0] for opponent in list_sort[1:]: current_match = Match(player, opponent) if current_match in tournament.matches_list: continue tournament.add_matches(current_match) turn.matches_list.append(current_match) list_sort.remove(opponent) list_sort.remove(player) break matches += 1
def set_even(game_number, team1_code, team2_code): """ Set a match as equally won. Assert the match exists. :param game_number: a game number :param team1_code: a team code :param team2_code: another team code """ match = Match.objects(game_number=game_number, players_code__all=[team1_code, team2_code]).get() match.winner = "" match.loser = "" match.even = True match.recorded = True match.save() log.info("Team {} and team {} are equally placed at the game {}".format( team1_code, team2_code, game_number))
def create_match_players(user_id_from, user_id_to): user_from = User.query.get(user_id_from) user_to = User.query.get(user_id_to) if not user_from or not user_to: response_object = { 'status': 'fail', 'message': 'Usuario no encontrado' } return response_object, 404 match = Match(user_from_id=user_id_from, user_to_id=user_id_to) save_changes(match) response_object = { 'status': 'success', 'message': 'Match enviado correctamente.' } return response_object, 200
def set_winner(game_number, winner_team_code, loser_team_code): """ Set a team as the winner of a match. Assert the match exists. :param game_number: a game number :param winner_team_code: the winner team code :param loser_team_code: the loser team code :return: True if the match was updated, False if the match was not found """ if winner_team_code == loser_team_code: raise BadenException("Winner and loser team code are identical") match = Match.objects( game_number=game_number, players_code__all=[winner_team_code, loser_team_code]).get() match.winner = winner_team_code match.loser = loser_team_code match.even = False match.recorded = True match.save() log.info("Team {} won the game {} against {}".format( winner_team_code, game_number, loser_team_code))
def get_game_number(self, team1_code, team2_code): if not service.is_team(team1_code): log.error( "{} unsuccessfully tried to get the game number of team code {} but the opponent team code {} was wrong" .format(str(cherrypy.request.remote.ip), team2_code, team1_code)) return "" if not service.is_team(team2_code): log.error( "{} unsuccessfully tried to get the game number of team code {} but the opponent team code {} was wrong" .format(str(cherrypy.request.remote.ip), team1_code, team2_code)) return "" try: return str( Match.objects(players_code__all=[team1_code, team2_code ]).get().game_number) except DoesNotExist: msg = "Les équipes {} et {} ne sont pas censées jouer ensemble".format( team1_code, team2_code) log.info(msg) return "Error: " + msg
def synthesize_node_pairs(self, src_hosts, dst_hosts, dst_port=None): print "Synthesizing backup paths between host pairs..." for i in xrange(len(src_hosts)): src_h_obj = self.network_graph.get_node_object(src_hosts[i]) dst_h_obj = self.network_graph.get_node_object(dst_hosts[i]) # Ignore installation of paths between switches on the same switch if src_h_obj.sw.node_id == dst_h_obj.sw.node_id: continue print "-----------------------------------------------------------------------------------------------" print 'Synthesizing primary and backup paths from', src_hosts[ i], 'to', dst_hosts[i] print "-----------------------------------------------------------------------------------------------" flow_match = Match(is_wildcard=True) flow_match["ethernet_type"] = 0x0800 if dst_port: flow_match["ip_protocol"] = 6 flow_match["tcp_destination_port"] = dst_port self.synthesize_flow(src_h_obj, dst_h_obj, flow_match) print "-----------------------------------------------------------------------------------------------" self._identify_reverse_and_balking_intents() self.push_switch_changes() if "mac_acl" in self.params: if self.params["mac_acl"]: self.push_mac_acls() self.synthesis_lib.save_synthesized_paths( self.network_configuration.conf_path)
def matches(): if request.method == 'POST': teams = get_teams_db() match = Match(request.form['team_home'], request.form['team_away']) match_id = insert_match_db(match) stadiums = get_stadiums_db() stadium_id = get_stad_id_with_stad_name(request.form['stadium_name']) appointment = Appointment(request.form['appointment_name'], match_id, stadium_id, request.form['start_time'], request.form['end_time'], request.form['match_date']) if not request.form['appointment_name']: matchs = get_appointments_db() return render_template("matches.html", matchs=matchs, teams=teams, stadiums=stadiums, error="Appointment name can not be empty!") try: insert_appointments_db(appointment) flash("Appointment successfully created!") matchs = get_appointments_db() except psycopg2.errors.UniqueViolation: matchs = get_appointments_db() return render_template("matches.html", matchs=matchs, teams=teams, stadiums=stadiums, error="Appointment name already exists!") return render_template("matches.html", matchs=matchs, teams=teams, stadiums=stadiums) if request.method == 'GET': teams = get_teams_db() matchs = get_appointments_db() stadiums = get_stadiums_db() return render_template("matches.html", matchs=matchs, teams=teams, stadiums=stadiums)
def generate_match_list(contest_id): contest = get_contest_by_id(contest_id) player_list = get_player_list_by_contest_id(contest_id) print player_list.userIds if contest.format == "Single Round-Robin": n = contest.totalPlayers if n % 2 == 0: matches = [] for i in range(0, n - 1): for j in range(i, n - 1): t = (i + j) % (n - 1) + 1 if i == j: player1_id = player_list.userIds[i] player2_id = player_list.userIds[n - 1] else: player1_id = player_list.userIds[i] player2_id = player_list.userIds[j] match = Match(player1Id = player1_id, player2Id = player2_id, score1 = -1, score2 = -1, day = t) match.save() matches.append(match) else: matches = [] for i in range(0, n): for j in range(i, n): t = (i + j) % n + 1 if i == j: player1_id = player_list.userIds[i] player2_id = usermanage.get_user_by_name("", "BYE").id else: player1_id = player_list.userIds[i] player2_id = player_list.userIds[j] match = Match(player1Id = player1_id, player2Id = player2_id, score1 = -1, score2 = -1, day = t) match.save() matches.append(match) matches.sort(key = lambda Match: Match.day) match_list = MatchList(contestId = contest_id, matches = []) for i in matches: match_list.matches.append(i.id) match_list.save()
def get_match_by_id(match_id): return Match.objects(id = match_id)[0]