Example #1
0
    def mutate(parent, info, tournament_id, matchups):
        existing_rounds = SQLTournament.get_all_rounds(tournament_id)
        current_round = len(existing_rounds) + 1

        for matchup in matchups:
            SQLMatchup.add_matchup(
                tournament_id,
                round_num=current_round,
                pl=matchup["pl"],
                defense=matchup["defense"],
            )
        return Round(round_num=current_round, tournament_id=tournament_id)
Example #2
0
	def parse_row(self, a, row):
		safea = a.string.encode('ascii', 'replace')
		score = re.search("[0-9]\-[0-9]", safea)
		source = self.url
		if score is not None:
			current_score = score.group()
			teams = safea.partition(' %s ' % current_score)
		else:
			teams = safea.partition(' vs ')

		team_a = teams[0]
		team_b = teams[2]

		match_date = row.td.a
		if match_date is None:
			match_date = row.td.div

		match_date = match_date['title']

		# empty rows:
		team_a_raw_odds = row.find('td', {'class' : 'odds'})
		if team_a_raw_odds == None:
			raise UnparsableException("Odds not found found for first team")
			return 0
		team_b_raw_odds = row.find('td', {'class' : 'odds noBorder '})
		if team_b_raw_odds == None:
			return 0
		draw_raw_odds = row.find('td', {'class' : 'odds noBorder'})
		if draw_raw_odds == None:
			return 0


		team_a_odds = self.calc_odds(team_a_raw_odds.a.string.strip().encode('ascii', 'replace'))
		team_b_odds = self.calc_odds(team_b_raw_odds.a.string.strip().encode('ascii', 'replace'))
		draw_odds = self.calc_odds(draw_raw_odds.a.string.strip().encode('ascii', 'replace'))
		matchup = Matchup.all().filter('team_a_name = ', team_a).filter('team_b_name', team_b)
		result = matchup.fetch(1);

		date_match_formatted = parse_date(match_date.split())

		if len(result) == 0:
			matchup = Matchup(team_a_name = team_a, team_b_name = team_b, 
				source = source, date_match = match_date, date_match_formatted = date_match_formatted
				)
			matchup.put()
		else:
			matchup = result[0]
		bet = Bet(team_a_odds = team_a_odds, team_b_odds = team_b_odds, 
				draw_odds = draw_odds,
				match = matchup
			)
		bet.put()
Example #3
0
	def get(self):
		w = self.response.out
		team_a = self.request.get('team_a')
		team_b = self.request.get('team_b')
		if team_a == "":
			w.write('illegal request, need name for team a')
			return
		if team_b == "":
			w.write('illegal request, need name for team b')
			return
			
		matches = Matchup.all().filter('team_a_name = ', team_a).filter('team_b_name = ', team_b).fetch(1)
		if len(matches) == 0:
			w.write('no matches found')
			return
		
		match = matches[0]
		w.write("<h1>%s vs %s</h1>" % (match.team_a_name, match.team_b_name))
		w.write("<div>Match date: %s </div>" % match.date_match_formatted)
		bets = Bet.all().filter('match = ', match).fetch(1000)
		w.write("<table>")
		w.write("<tr><td>%s</td><td>Draw</td><td>%s</td><td>Recorded on</td><td>Current score</td></tr>" % (match.team_a_name, match.team_b_name))
		for b in bets:
			w.write("<tr>")
			w.write("<td>%s</td>" % b.team_a_odds)
			w.write("<td>%s</td>" % b.draw_odds)
			w.write("<td>%s</td>" % b.team_b_odds)
			w.write("<td>%s</td>" % b.date_recorded)
			w.write("<td>%s</td>" % b.current_score)
			w.write("</tr>")
		w.write("</table>")
		w.write('found %s bets' % len(bets))
Example #4
0
 def get_team_roster(self,
                     team,
                     week,
                     matchup=None,
                     league=None,
                     is_postseason=False):
     if is_postseason:
         matchup = league.matchups.where((Matchup.week == week) & (
             (Matchup.team_a == team.id) | (Matchup.team_b == team.id)))
         if matchup.exists():
             print("Using existing for postseason")
             matchup = matchup[0]
         else:
             print("Creating new for postseason")
             key = "%s.%s.%s.unmatched" % (league.key, week, team.key)
             matchup = Matchup.create(
                 key=key,
                 team_a=team,
                 team_a_points=0,
                 week=week,
                 league=league,
                 is_playoffs=False,
                 is_consolation=False,
             )
     logger.info("Getting roster info for %s for week %s...", team.key,
                 week)
     tree = self.get_team_resource(team.key,
                                   'roster;week=%s;/players/stats' % (week))
     return self.process_roster(tree, team, matchup)
Example #5
0
File: csv.py Project: Achiel/hedgy
	def get(self):
			w = self.response.out
			offset = self.request.get('offset')
			limit = self.request.get('limit')
			
			if limit is "":
			    limit = 100
			if offset is "":
			    offset = 0
			
			limit = int(limit)
			offset = int(offset)
			matches = Matchup.all()[offset:limit+offset]
			for m in matches:
				bets = Bet.all().filter("match = ", m)
				for b in bets:
					template = "%s;%s;%s;%s;%s;%s;%s" % (m.team_a_name, m.team_b_name, b.team_a_odds, b.team_b_odds,b.draw_odds,m.date_match_formatted, b.date_recorded)
					w.write(template)
					w.write("<br/>")
Example #6
0
File: home.py Project: Achiel/hedgy
    def get(self):
        w = self.response.out
        w.write("<a href='?till=24'>matches for the next 24h</a> ")
        w.write("<a href='?till=3'>matches for the next 3h</a> ")
        w.write("<a href='?till=3'>matches for the next hour</a> ")
        w.write("<a href='?till=all'>all matches</a>")
        w.write("<h1>matches:</h1>")

        matches = Matchup.all().order("date_match_formatted")

        span = self.request.get("till")
        if not span == "all":
            matches.filter("date_match_formatted > ", datetime.now() - timedelta(hours=2))

        if not span == "" and not span == "all":
            span = int(span)
            matches.filter("date_match_formatted < ", datetime.now() + timedelta(hours=span))

        for m in matches:
            match_name = "%s vs %s" % (m.team_a_name, m.team_b_name)
            fluctuations = self.calc_fluctuation(m)
            if fluctuations == 2:
                style = "color: orange"
            elif fluctuations > 2:
                style = "color: red"
            else:
                style = ""
            link = "<a style='%s' href='/match?team_a=%s&team_b=%s'>%s</a> at %s" % (
                style,
                m.team_a_name,
                m.team_b_name,
                match_name,
                m.date_match_formatted,
            )
            w.write(link)
            two_hours = timedelta(hours=2)
            diff = datetime.now() - m.date_match_formatted
            if diff < two_hours and diff > timedelta():
                w.write(" <a style='color: red' href='%s'>live</a>" % m.source)
            w.write("<br/>")
Example #7
0
 def process_matchup(self, tree, league):
     week = tree.find('./yh:week', self._ns).text
     teams = [
         self.process_team(team, league, add_to_roster=False, week=week)
         for team in tree.findall('.//yh:team', self._ns)
     ]
     teams = sorted(teams, key=lambda team: team[0].name)
     key = '%s.%s.%s' % (league.key, week, '.'.join(
         sorted([teams[0][0].key, teams[1][0].key])))
     try:
         winner_team_key = tree.find('./yh:winner_team_key', self._ns).text
     except AttributeError:
         winner_team_key = None
     matchup, created = Matchup.update_or_create(
         key=key,
         defaults={
             'team_a':
             teams[0][0],
             'team_a_projected_points':
             teams[0][1],
             'team_a_points':
             teams[0][2],
             'team_b':
             teams[1][0],
             'team_b_projected_points':
             teams[1][1],
             'team_b_points':
             teams[1][2],
             'week':
             week,
             'is_playoffs':
             tree.find('./yh:is_playoffs', self._ns).text == '1',
             'is_consolation':
             tree.find('./yh:is_consolation', self._ns).text == '1',
             'winner_team_key':
             winner_team_key,
             'league':
             league
         })
     return matchup
Example #8
0
def getMatchups(soup, _cshTeam, url):
    """
    Gets every team's data given the CSH team's name and url. Gathers the
    scores, dates for upcoming games, and opposing teams stats. Stores the
    information into the database after making the appropriate objects.
    """
    x = soup.find_all(text=re.compile(_cshTeam))
    _csh_wins = 0
    _csh_losses = 0
    _csh_ties = 0
    # sportContent = soup.find_all("div", { "class" : "popover-content" })[0]
    # li = sportContent.find_all("li")[2]
    # _sport = li.find_next("a").get_text()
    title = soup.title.string
    _sport = title.split("/")[1]
    # header = soup.find(id="ctl00_ucSiteHeader_divHeaderBox")
    header = soup.find("a", {"class": "school-logo"})
    csh_picture = header.find_next("img").get("src")
    try:
        cshTeam = Team.objects.get(link=url)
    except:
        cshTeam = None
    if cshTeam:
        cshTeam.picture = csh_picture
        cshTeam.save()
    else:
        cshTeam = Team(
            link=url,
            sport=_sport,
            name=_cshTeam,
            wins=_csh_wins,
            losses=_csh_losses,
            ties=_csh_ties,
            picture=csh_picture,
            rank=0,
            iscsh=True,
            season=Season.objects.all()[0].season,
        )
        cshTeam.save()
    matchList = list(cshTeam.CSH.all())
    overall = soup.find(id="ctl00_ContentPlaceHolder2_ucTeamRelated_pnlTeamSchedule")
    teamSchedule = overall.find_next("tbody")
    if teamSchedule == None:
        print("No team schedule found.")
    else:
        counter = 0
        teams = teamSchedule.find_all("tr")
        year = overall.get_text()[1:5]
        endofyear = False
        for i in range(len(teams) // 2):
            match = teams[counter].find_all("td")
            _clean_date = match[0].get_text() + " " + year
            if _clean_date.split(" ")[1] == "Dec":
                endofyear = True
            if endofyear == True and _clean_date.split(" ")[1] != "Dec":
                newyear = str(int(_clean_date.split(" ")[3]) + 1)
                _clean_date = match[0].get_text() + " " + newyear
            opponent = match[1].get_text().split("  ")
            _enemyTeam = opponent[1]
            loc = opponent[0]  # gets whether it is VS or @
            result = match[2].get_text().split()
            print(result)
            _outcome = result[0]  # gets whether it was a W or L or T
            if (_outcome != "W") and (_outcome != "L") and (_outcome != "T"):  # if matchup hasn't happened yet
                _outcome = None
                _upcoming = match[2].get_text()
            elif len(result) < 4:
                _outcome = None
                _upcoming = "Awaiting Scores..."
            else:
                if loc == "VS":
                    _cshScore = result[1]
                    _enemyScore = result[3]
                else:
                    _cshScore = result[3]
                    _enemyScore = result[1]
            record = match[4].get_text().split("-")
            _wins = record[0]
            _losses = record[1]
            _ties = record[2]
            enemyUrl = match[1].find_next("a").get("href")
            pictureLink = match[1].find_next("img").get("src")
            if "DefaultLogo" in pictureLink:
                _picture = pictureLink
            else:
                _picture = getPicture(pictureLink)
            if _outcome == "W":
                _csh_wins += 1
            elif _outcome == "L":
                _csh_losses += 1
            elif _outcome == "T":
                _csh_ties += 1
            _date = datetime.strptime(_clean_date, "%a, %b %d %Y")
            print(_date)
            counter += 2
            try:
                enemyTeam = Team.objects.get(link=enemyUrl)
            except:
                enemyTeam = None
            if enemyTeam:
                enemyTeam.wins = _wins
                enemyTeam.losses = _losses
                enemyTeam.ties = _ties
                enemyTeam.picture = _picture
                enemyTeam.rank = getRank(soup, enemyTeam.name, _wins, _losses, _ties)
                enemyTeam.save()
            else:
                enemyTeam = Team(
                    link=enemyUrl,
                    sport=_sport,
                    name=_enemyTeam,
                    wins=_wins,
                    losses=_losses,
                    ties=_ties,
                    picture=_picture,
                    rank=getRank(soup, _enemyTeam, _wins, _losses, _ties),
                    iscsh=False,
                    season=Season.objects.all()[0].season,
                )
                enemyTeam.save()
            try:
                happened = cshTeam.CSH.filter(enemy=enemyTeam).filter(date=_date)[0]
            except:
                happened = None
            if happened:  # if matchup made
                if _outcome:  # if game happened
                    happened.cshScore = _cshScore
                    happened.enemyScore = _enemyScore
                    happened.outcome = _outcome
                    happened.save()
                else:
                    happened.upcoming = _upcoming
                    happened.clean_date = _clean_date
                    happened.date = _date
                    happened.save()
                if happened in matchList:
                    matchList.remove(happened)
            else:
                if _outcome:
                    matchup = Matchup(
                        csh=cshTeam,
                        enemy=enemyTeam,
                        cshScore=_cshScore,
                        enemyScore=_enemyScore,
                        outcome=_outcome,
                        clean_date=_clean_date,
                        date=_date,
                    )
                    matchup.save()
                else:
                    matchup = Matchup(
                        csh=cshTeam,
                        enemy=enemyTeam,
                        cshScore=None,
                        enemyScore=None,
                        upcoming=_upcoming,
                        clean_date=_clean_date,
                        date=_date,
                    )
                    matchup.save()
                if matchup in matchList:
                    matchList.remove(matchup)
    for match in matchList:
        match.enemy.delete()
    cshTeam.wins = _csh_wins
    cshTeam.losses = _csh_losses
    cshTeam.ties = _csh_ties
    cshTeam.rank = getRank(soup, cshTeam.name, _csh_wins, _csh_losses, _csh_ties)
    cshTeam.save()
Example #9
0
def load_matchups(is_mid, opponent_champion_id):
    matchups=[]
    filename = 'solo_mid_matchups.csv' if is_mid else 'solo_top_matchups.csv'
    csv_filepathname = os.path.join(os.path.dirname(os.path.realpath(__file__)), filename)
    dataReader = csv.reader(open(csv_filepathname), delimiter=',', quotechar='"')
    for row in dataReader:
        if row[16] == str(opponent_champion_id):
            matchup = Matchup()
            matchup.champion_level=int(row[0])
            matchup.champion_points=int(row[1])
            matchup.chest_granted=row[2]
            matchup.highest_grade=row[3]
            matchup.champion_id=int(row[4])
            matchup.summoner_table_id=row[5]
            matchup.region=row[6]
            matchup.role=row[7]
            matchup.lane=row[8]
            matchup.queue=row[9]
            matchup.match_id=row[10]
            matchup.won=int(row[11])
            matchup.grade=row[12]
            matchup.chest=int(row[13])
            matchup.champion_level_avg=row[14]
            matchup.champion_level_diff=row[15]
            matchup.opponent_champion_id=int(row[16])
            matchup.matchup=row[17]
            matchups.append(matchup)
    return matchups