示例#1
0
	def put(self, request):
		"""
		Adds a team.
		"""
		try:
			post_fields = read_json(request.body)
		except ValueError:
			return HttpResponse(_("JSON, please!"), status=400)
		
		try:
			assert type(post_fields['name']) is str
			assert type(post_fields['players']) is list
			for item in post_fields['players']:
				assert type(item) is str
		except (AssertionError, KeyError):
			return HttpResponse(_("Hack attempt detected."), status=400)
		
		team = Team()
		team.race = self.token.race
		team.name = post_fields['name']
		team.save()
		
		for player_name in post_fields['players']:
			player = Player()
			player.team = team
			player.name = player_name
			player.save()
		
		response = {
			'id': team.pk
		}
		return HttpResponse(make_json(response), status=200)
示例#2
0
def port_csv_to_db():
    csv_path = "/home/ubuntu/test-bigdata/new_bd_resp.csv"
    df = pd.read_csv(csv_path)
    for index, row in df.iterrows():
        try:
            team_obj = Team(team_name=row["Enter team name"],
                            member_1=row["Team member 1 email"],
                            member_2=row["Team member 2 email"],
                            member_3=row["Team member 3 email"],
                            member_4=row["Team member 4 email"])
            team_obj.save()
        except Exception as e:
            print(e)
            print("Invalid row")
示例#3
0
def create_team(data):
    print(data)
    token = Token.objects.get(token=data['auth_token'])
    for member in data['member']:
        team = Team(boat_id=Team.objects.get(member_id=token.user_id).boat_id,
                    member_id=member)
        try:
            team.save()
            Member.objects.filter(id=member).update(take_part_flag=False)
        except db.DataError as e:
            return HttpResponse(renderers.JSONRenderer().render({
                'status': '0',
                'error': e
            }))
    return HttpResponse(renderers.JSONRenderer().render("lol"))
示例#4
0
def register_boat(data):
    boat = Boat(name=data['name'],
                boat_class_id=data['boat_class'],
                boat_number=data['boat_number'],
                tech_inspection=data['tech_inspection'])
    try:
        boat.save()
        team = Team(boat_id=boat.id, member_id=data['member'])
        team.save()
        return HttpResponse(renderers.JSONRenderer().render({'status': '1'}))
    except db.DataError as e:
        return HttpResponse(renderers.JSONRenderer().render({
            'status': '0',
            'error': e
        }))
示例#5
0
def enter_team_list(url, tournament, dryrun=True):
  team_list = get_team_list(url)
  tourny = Tournament.objects.get(tournament_name = tournament)
  for (code, names) in team_list:
    code = tp.team_code(code)
    try:
      team = Team.objects.get(team_code = code)
      if team.team_name != names:
        team = Team(team_code = code, team_name = name)
      print "got team %s" % code
      team.tournaments.add(tourny)
    except:
      team = Team(team_code = code, team_name = names)
      if not dryrun:
        team.save()
        team.tournaments.add(tourny)
      print "made team %s" % code
示例#6
0
def initial_comp_setup():
    round_setup()
    for round in range(1, ROUNDS + 1):
        logger.info("Fetching round %s/%s...", round, ROUNDS)
        start = datetime.now()
        r = requests.get(
            "http://api.stats.foxsports.com.au/3.0/api/sports/league/series/1/seasons/116/rounds/"
            + str(round) +
            "/fixturesandresultswithbyes.json?userkey=A00239D3-45F6-4A0A-810C-54A347F144C2"
        )

        if round == 1:
            # Setup teams if they don't already exist
            team_ids = list(Team.objects.values_list('fox_id', flat=True))

            for game in json.loads(r.text):
                team = {}
                team['name'] = game["team_A"]["name"] + ' ' + game["team_A"][
                    "short_name"]
                team['fox_id'] = game["team_A"]["id"]
                if team['fox_id'] not in team_ids:
                    team_ids.append(team['fox_id'])
                    logger.info("Adding team %s to teams", team['name'])
                    new_team = Team(name=team['name'], fox_id=team['fox_id'])
                    new_team.save()

                team = {}
                team['name'] = game["team_B"]["name"] + ' ' + game["team_B"][
                    "short_name"]
                team['fox_id'] = game["team_B"]["id"]
                if team['fox_id'] not in team_ids:
                    team_ids.append(team['fox_id'])
                    logger.info("Adding team %s to teams", team['name'])
                    new_team = Team(name=team['name'], fox_id=team['fox_id'])
                    new_team.save()

        for game in json.loads(r.text):
            fixture_id = game["fixture_id"]
            round_object = Round.objects.get(round=round)
            game_time = parse_datetime(game["match_start_date"])
            home_team = Team.objects.get(fox_id=game["team_A"]["id"])
            away_team = Team.objects.get(fox_id=game["team_B"]["id"])
            stadium = game["venue"]["name"]
            new_game = Game(fixture_id=fixture_id,
                            start_time=game_time,
                            round=round_object,
                            home_team=home_team,
                            away_team=away_team,
                            stadium=stadium)
            new_game.save()
        end = datetime.now()
        elapsed_time = end - start
        if elapsed_time.total_seconds() < 5:
            time.sleep(5 - elapsed_time.total_seconds())
def mock_data():

    db.drop_all()
    db.create_all()

    # insert teams
    cubs = Team("Chicago Cubs")
    yankees = Team('New York Yankees')
    tigers = Team("Detroit Tigers")
    db.session.add_all([cubs, yankees, tigers])

    db.session.flush()

    # insert players
    arizzo = Player("Anthony Rizzo", "1B", cubs.id)
    kbryant = Player("Kris Bryant", "3B", cubs.id)
    kschwarber = Player("Kyle Schwarber", "LF", cubs.id)
    jbaez = Player("Javier Baez", "2B", cubs.id)
    db.session.add_all([arizzo, kbryant, kschwarber, jbaez])

    db.session.flush()

    # insert stats
    ba = Statistic("Batting Average", "Batting", "%", True)
    obp = Statistic("On Base Percentage", "Batting", "%", True)
    slg = Statistic("Slugging Percentage", "Batting", "%", True)

    db.session.add_all([ba, obp, slg])

    db.session.flush()

    # insert player stat records
    db.session.add(PlayerStat(ba.id, arizzo.id, .273, .268))
    db.session.add(PlayerStat(obp.id, arizzo.id, .366, .219))
    db.session.add(PlayerStat(slg.id, arizzo.id, .214, .485))

    db.session.add(PlayerStat(ba.id, kbryant.id, .289, .348))
    db.session.add(PlayerStat(obp.id, kbryant.id, .390, .464))
    db.session.add(PlayerStat(slg.id, kbryant.id, .530, .630))

    db.session.commit()
示例#8
0
def check_team_existence_or_create(name, tourny, team_name="enter_names", dryrun=True):
  try:
    teams = Team.objects.filter(team_code = name)
    # check to make sure that the team is actually entered
    # this is to solve when a team is in rounds but wasnt on the entries page
    if len(teams) > 1:
      team = None
      for the_team in teams:
        if team_name != "enter_names" and the_team.team_name == team_name:
          team = the_team
          break
      if not team:
        return teams[0]
      if not team:
        team = Team(team_code = name, team_name= team_name)
        if not dryrun:
          team.save()
          team.tournaments.add(tourny)
    else:
      team = teams[0]
    if tourny not in Tournament.objects.filter(entries__id=team.id):
      team.tournaments.add(tourny)
    return team
  except:
    print "making team: " + name
    team = Team(team_code = name, team_name= team_name)
    if not dryrun:
      team.save()
      team.tournaments.add(tourny)
    return team
示例#9
0
 def handle(self, *args, **options):
     print("""
     ===================================================
     Total users: {}
     Total teams: {}
     Users/team: {}
     Eligible teams: {}
     
     Total problems: {}
     Total submissions: {}
     Scoring teams: {}
     
     Countries: {}
     States: {}
     ===================================================
     """.format(
         User.objects.count(),
         Team.current().count(),
         Team.current().annotate(count=Count("members")).aggregate(
             Avg("count"))['count__avg'],
         Team.current().filter(eligible=True).count(),
         Problem.current().count(),
         Problem.current().annotate(count=Count("solves")).aggregate(
             Sum("count"))['count__sum'],
         Team.current().filter(score__gt=0).count(),
         Team.current().filter(score__gt=0).values(
             "members__profile__country").distinct().count(),
         Team.current().filter(score__gt=0).values(
             "members__profile__state").distinct().count()))
示例#10
0
文件: views.py 项目: kincl/oncall
def teams():
    if request.method == 'GET':
        return jsonify({'teams': [t.to_json() for t in Team.query.all()]})

    if request.method == 'POST':
        if not request.json or not 'team' in request.json:
            # flash('Malformed request, "team" not found in JSON', 'danger')
            # abort(400)
            return _api_error('Malformed request, "team" not found in JSON', 'danger')
        db.session.add(Team(request.json.get('team')))

    db.session.commit()
    return Response(status=200)
示例#11
0
文件: tests.py 项目: kincl/oncall
    def setUp(self):
        db.create_all()
        db.session.commit()

        team1 = Team('Team 1')
        team2 = Team('Team 2')
        db.session.add(team1)
        db.session.add(team2)

        # so primary key gets populated
        db.session.flush()

        user1 = User('user1', 'Test User', [team1.id])
        user2 = User('user2', 'Another User', [team1.id])
        user3 = User('user3', 'Byzantine Candor', [team1.id, team2.id])
        user4 = (User('user4', 'Cottonmouth', [team1.id, team2.id]))
        db.session.add(user1)
        db.session.add(user2)
        db.session.add(user3)
        db.session.add(user4)

        db.session.flush()

        db.session.add(Schedule(team1.id, user1.id, "Primary", 0))
        db.session.add(Schedule(team1.id, user2.id, "Secondary", 0))
        db.session.add(Schedule(team1.id, user3.id, "Primary", 1))
        db.session.add(Schedule(team1.id, user1.id, "Secondary", 1))
        db.session.add(Schedule(team1.id, user2.id, "Primary", 2))
        db.session.add(Schedule(team1.id, user3.id, "Secondary", 2))

        db.session.add(Schedule(team2.id, user3.id, "Primary", 0))
        db.session.add(Schedule(team2.id, user4.id, "Secondary", 0))
        db.session.add(Schedule(team2.id, user4.id, "Primary", 1))
        db.session.add(Schedule(team2.id, user3.id, "Secondary", 1))

        db.session.commit()
示例#12
0
 def restore_object(self, attrs, instance=None):
     org = attrs.get('organization', None)
     projects = attrs.get('projects', [])
     if instance:
         instance.organization = org if org else instance.organization
         instance.name = attrs.get('team_name', instance.name)
         instance.projects.clear()
         for project in projects:
             instance.projects.add(project)
         return instance
     team_name = attrs.get('team_name', None)
     if not team_name:
         self.errors['name'] = u'A team name is required'
         return attrs
     return Team(organization=org, name=team_name)
示例#13
0
    def handle(self, *args, **options):

        for i, team in enumerate(Team.current().all()):
            score = 0

            team.solved.clear()

            for submission in Submission.objects.all().filter(team=team).order_by('time'):
                score += submission.problem.value
                submission.new_score = score
                submission.save()
                team.solved.add(submission.problem)

            team.score = score
            team.save()

            print("Fixed score for team {%d}/{%d}" % (i, Team.objects.count()))
示例#14
0
文件: helpers.py 项目: MMX13/tipping
def initial_comp_setup():
    round_setup()
    for round in range(1, ROUNDS+1):
        logger.info("Fetching round %s/%s...", round, ROUNDS)
        start = datetime.now()
        r = requests.get("http://api.stats.foxsports.com.au/3.0/api/sports/league/series/1/seasons/114/rounds/"+str(round)+"/fixturesandresultswithbyes.json?userkey=A00239D3-45F6-4A0A-810C-54A347F144C2")

        if round==1:
            teams = []
            for game in json.loads(r.text):
                team = {}
                team['name']=game["team_A"]["name"]+' '+game["team_A"]["short_name"]
                team['fox_id']=game["team_A"]["id"]
                if team not in teams:
                    teams.append(team)
                    logger.info("Adding team %s to teams", team['name'])
                    new_team=Team(name=team['name'], fox_id=team['fox_id'])
                    new_team.save()

                team = {}
                team['name']=game["team_B"]["name"]+' '+game["team_B"]["short_name"]
                team['fox_id']=game["team_B"]["id"]
                if team not in teams:
                    teams.append(team)
                    logger.info("Adding team %s to teams", team['name'])
                    new_team=Team(name=team['name'], fox_id=team['fox_id'])
                    new_team.save()



        for game in json.loads(r.text):
            fixture_id = game["fixture_id"]
            round_object = Round.objects.get(round=round)
            game_time = parse_datetime(game["match_start_date"])
            home_team = Team.objects.get(fox_id=game["team_A"]["id"])
            away_team = Team.objects.get(fox_id=game["team_B"]["id"])
            stadium = game["venue"]["name"]
            new_game = Game(fixture_id=fixture_id,
                            start_time = game_time,
                            round=round_object,
                            home_team=home_team,
                            away_team=away_team,
                            stadium=stadium)
            new_game.save()
        end = datetime.now()
        elapsed_time = end-start
        if elapsed_time.total_seconds()<5:
            time.sleep(5 - elapsed_time.total_seconds())
示例#15
0
def test_passing():
    model = Team(
        id=1,
        team_name="test_team",
    )
    assert model.team_name == "test_team"
示例#16
0
def create_users():
    user_1 = User.objects.create_user("testuser1", "*****@*****.**",
                                      "test123")
    user_2 = User.objects.create_user("testuser2", "*****@*****.**",
                                      "test123")
    user_3 = User.objects.create_user("testuser3", "*****@*****.**",
                                      "test123")
    user_4 = User.objects.create_user("testuser4", "*****@*****.**",
                                      "test123")
    user_5 = User.objects.create_user("testuser5", "*****@*****.**",
                                      "test123")
    user_6 = User.objects.create_user("testuser6", "*****@*****.**",
                                      "test123")

    team_1 = Team(name="Team 1", description="Team 1")
    team_1.save()
    team_2 = Team(name="Team 2", description="Team 2")
    team_2.save()
    team_3 = Team(name="Team 3", description="Team 3")
    team_3.save()

    emp_1 = Employee(user=user_1, team=team_1, name="Test 1")
    emp_1.save()
    emp_2 = Employee(user=user_2, team=team_1, name="Test 2")
    emp_2.save()
    emp_3 = Employee(user=user_3, team=team_2, name="Test 3")
    emp_3.save()
    emp_4 = Employee(user=user_4, team=team_2, name="Test 4")
    emp_4.save()
    emp_5 = Employee(user=user_5, team=team_3, name="Test 5")
    emp_5.save()
    emp_6 = Employee(user=user_6, team=team_3, name="Test 6")
    emp_6.save()
                 modified=timezone.now(),
                 uid=uuid4(),
                 name=row['name'],
                 state=State.states.get(name__iexact=row['name_state']),
                 slug=slugify(row['name']+'_'+row['name_state']),)
        p.save()

with open('./populate/teams.csv') as c:
    r = DictReader(c)
    for row in r:
        city      = City.cities.get(name__iexact=row['name_city'])
        authority = Authority.authorities.get(name__iexact=row['name_authority'])
        p = Team(created=timezone.now(),
                 modified=timezone.now(),
                 uid=uuid4(),
                 name=row['name'],
                 city=city,
                 authority=authority,
                 kind=row['kind'],
                 slug=slugify(row['name']),)
        p.save()

with open('./populate/finishes.csv') as c:
    r = DictReader(c)
    for row in r:
        tourney = Tournament.tournaments.get(name__iexact=row['name_tournament'])
        team       = Team.teams.get(name__iexact=row['name_team'])
        p = Finish(created=timezone.now(),
                   modified=timezone.now(),
                   uid=uuid4(),
                   tournament=tourney,
                   team=team,
示例#18
0
def get_teams_by_summoner_id(summoner_id, region):
    """
    Get team data, given a summoner ID and region, and stores it in the DB.

    Each summoner can have 0 or more teams. This checks for matching teams in the DB
    and updates them if they are present, otherwise it creates a new team.
    Matches are made by comparing region and full_id.

    Team queries to the Riot API return the following data, per team:
    -timestamps for roster invites
    -timestamps for roster joins
    -summoner IDs for team roster
    -summoner ID for team owner
    -match summary for each game played
    -summary for overall performance in 5v5 and 3v3
    -team basic data (e.g. tag, name, etc)
    -timestamps for most recent game, team modified, team created
    """
    # Riot API returns HTTP 404 if summoner is not on any teams.
    try:
        teams_dto = riot_api.get_teams_for_summoner(summoner_id, region)
        got_teams = True
    except LoLException as e:
        got_teams = False
        if e == error_404:
            print('Summoner ID', summoner_id, 'is not on any teams (error_404).')
        else:
            got_teams = False
            print('ERROR getting teams:', e)

    if got_teams:
        # teams_dto is a list that will contain an entry for each team the summoner is on.

        for team in teams_dto:
            # Can we match this data to a Team in the DB?
            try:
                matching_team = Team.objects.filter(region=region).get(full_id=team['fullId'])
                # We found a match, so set the working Team to that.
                print('Found matching Team {} {}'.format(matching_team.region, matching_team.name))
                matched = True
                new_team = matching_team
            except ObjectDoesNotExist:
                # No match found, so create a new Team.
                matched = False
                print('No matching team found. Creating a new Team...')
                new_team = Team()

            # We get all the Team data from Riot API call,
            # so we can delete everything and just create new models below.
            if matched:
                new_team.roster.delete()
                new_team.delete()

            # Set everything in the Team model that isn't a related field.
            new_team.create_date = team['createDate']
            new_team.full_id = team['fullId']

            # If team hasn't played a game (this season?)
            if 'lastGameDate' in team:
                new_team.last_game_date = team['lastGameDate']
            new_team.last_joined_ranked_team_queue_date = team['lastJoinedRankedTeamQueueDate']
            new_team.modify_date = team['modifyDate']
            new_team.name = team['name']
            new_team.last_join_date = team['lastJoinDate']
            new_team.second_last_join_date = team['secondLastJoinDate']
            new_team.third_last_join_date = team['thirdLastJoinDate']
            new_team.status = team['status']
            new_team.tag = team['tag']
            new_team.region = region

            # This leaves: roster, teamStatDetails, matchHistory.
            roster_dto = team['roster']
            team_stat_details_dto = team['teamStatDetails']

            # If team hasn't played a game (extends past this season, so no games played ever!)
            if 'matchHistory' in team:
                match_history_dto = team['matchHistory']

            # Setup and save the Roster model.
            new_roster = Roster(owner_id=roster_dto['ownerId'])
            new_roster.save()

            # We can set the roster relation on the Team model now, and save it.
            new_team.roster = new_roster
            new_team.save()

            # Setup and save the TeamMemberInfo models for this Roster.
            for member in roster_dto['memberList']:
                new_member = TeamMemberInfo(invite_date=member['inviteDate'],
                                            join_date=member['joinDate'],
                                            player_id=member['playerId'],
                                            status=member['status'],
                                            roster=new_roster)
                new_member.save()

            # Setup and save the TeamStatDetail models for the Team.
            for stats in team_stat_details_dto:
                new_stats = TeamStatDetail(team_stat_type=stats['teamStatType'],
                                           average_games_played=stats['averageGamesPlayed'],
                                           wins=stats['wins'],
                                           losses=stats['losses'],
                                           team=new_team)
                new_stats.save()

            # Setup and save the MatchHistorySummary models for the Team, if it has a history.

            if match_history_dto:
                for match in match_history_dto:
                    new_match = MatchHistorySummary(assists=match['assists'],
                                                    date=match['date'],
                                                    deaths=match['deaths'],
                                                    game_id=match['gameId'],
                                                    game_mode=match['gameMode'],
                                                    invalid=match['invalid'],
                                                    kills=match['kills'],
                                                    map_id=match['mapId'],
                                                    opposing_team_kills=match['opposingTeamKills'],
                                                    opposing_team_name=match['opposingTeamName'],
                                                    win=match['win'],
                                                    team=new_team)
                    new_match.save()
示例#19
0
def get_teams_by_summoner_id(summoner_id, region):
    """
    Get team data, given a summoner ID and region, and stores it in the DB.

    Each summoner can have 0 or more teams. This checks for matching teams in the DB
    and updates them if they are present, otherwise it creates a new team.
    Matches are made by comparing region and full_id.

    Team queries to the Riot API return the following data, per team:
    -timestamps for roster invites
    -timestamps for roster joins
    -summoner IDs for team roster
    -summoner ID for team owner
    -match summary for each game played
    -summary for overall performance in 5v5 and 3v3
    -team basic data (e.g. tag, name, etc)
    -timestamps for most recent game, team modified, team created
    """
    # Riot API returns HTTP 404 if summoner is not on any teams.
    try:
        teams_dto = riot_api.get_teams_for_summoner(summoner_id, region)
        got_teams = True
    except LoLException as e:
        got_teams = False
        if e == error_404:
            print('Summoner ID', summoner_id,
                  'is not on any teams (error_404).')
        else:
            got_teams = False
            print('ERROR getting teams:', e)

    if got_teams:
        # teams_dto is a list that will contain an entry for each team the summoner is on.

        for team in teams_dto:
            # Can we match this data to a Team in the DB?
            try:
                matching_team = Team.objects.filter(region=region).get(
                    full_id=team['fullId'])
                # We found a match, so set the working Team to that.
                print('Found matching Team {} {}'.format(
                    matching_team.region, matching_team.name))
                matched = True
                new_team = matching_team
            except ObjectDoesNotExist:
                # No match found, so create a new Team.
                matched = False
                print('No matching team found. Creating a new Team...')
                new_team = Team()

            # We get all the Team data from Riot API call,
            # so we can delete everything and just create new models below.
            if matched:
                new_team.roster.delete()
                new_team.delete()

            # Set everything in the Team model that isn't a related field.
            new_team.create_date = team['createDate']
            new_team.full_id = team['fullId']

            # If team hasn't played a game (this season?)
            if 'lastGameDate' in team:
                new_team.last_game_date = team['lastGameDate']
            new_team.last_joined_ranked_team_queue_date = team[
                'lastJoinedRankedTeamQueueDate']
            new_team.modify_date = team['modifyDate']
            new_team.name = team['name']
            new_team.last_join_date = team['lastJoinDate']
            new_team.second_last_join_date = team['secondLastJoinDate']
            new_team.third_last_join_date = team['thirdLastJoinDate']
            new_team.status = team['status']
            new_team.tag = team['tag']
            new_team.region = region

            # This leaves: roster, teamStatDetails, matchHistory.
            roster_dto = team['roster']
            team_stat_details_dto = team['teamStatDetails']

            # If team hasn't played a game (extends past this season, so no games played ever!)
            if 'matchHistory' in team:
                match_history_dto = team['matchHistory']

            # Setup and save the Roster model.
            new_roster = Roster(owner_id=roster_dto['ownerId'])
            new_roster.save()

            # We can set the roster relation on the Team model now, and save it.
            new_team.roster = new_roster
            new_team.save()

            # Setup and save the TeamMemberInfo models for this Roster.
            for member in roster_dto['memberList']:
                new_member = TeamMemberInfo(invite_date=member['inviteDate'],
                                            join_date=member['joinDate'],
                                            player_id=member['playerId'],
                                            status=member['status'],
                                            roster=new_roster)
                new_member.save()

            # Setup and save the TeamStatDetail models for the Team.
            for stats in team_stat_details_dto:
                new_stats = TeamStatDetail(
                    team_stat_type=stats['teamStatType'],
                    average_games_played=stats['averageGamesPlayed'],
                    wins=stats['wins'],
                    losses=stats['losses'],
                    team=new_team)
                new_stats.save()

            # Setup and save the MatchHistorySummary models for the Team, if it has a history.

            if match_history_dto:
                for match in match_history_dto:
                    new_match = MatchHistorySummary(
                        assists=match['assists'],
                        date=match['date'],
                        deaths=match['deaths'],
                        game_id=match['gameId'],
                        game_mode=match['gameMode'],
                        invalid=match['invalid'],
                        kills=match['kills'],
                        map_id=match['mapId'],
                        opposing_team_kills=match['opposingTeamKills'],
                        opposing_team_name=match['opposingTeamName'],
                        win=match['win'],
                        team=new_team)
                    new_match.save()