예제 #1
0
  def post(self):
    team = Team.get_by_key_name(self.request.get("team_name"))

    user = users.get_current_user()

    if team and user:
      coach = Coach.all().filter("user =", user).get()
      team.coach = coach  
      team.put()  
    
    coach_stats = CoachStats.all().ancestor(coach).get()
    if not coach_stats:    #Coach doesn't have stats yet.
      coach_stats = CoachStats(parent=coach)
    
    for record in team.teamrecord_set.order('created'):
      coach_stats.update(record)
    coach_stats.put()
  
    for leader in CoachLeader.all():
      CoachLeaderStanding(
        key_name = coach_stats.parent().key().name(),
        parent   = leader,
        coach_stats     = coach_stats,
        score    = leader.get_score(coach_stats)).put()

    views.CoachLeaders.clear()
    views.RecentMatches.clear()
    views.LeagueStandings.clear()
    views.TeamBox.clear(team.key())

    # OFL eligibility rule checks
    season, week = misc.get_ofl_season_and_week()
    if not team.check_eligibility(season=season):
      team.set_flag(TeamProfile.INELIGIBLE_FLAG)
      team.put()
예제 #2
0
    def post(self):
        team = Team.get_by_key_name(self.request.get("team_name"))

        user = users.get_current_user()

        if team and user:
            coach = Coach.all().filter("user =", user).get()
            team.coach = coach
            team.put()

        coach_stats = CoachStats.all().ancestor(coach).get()
        if not coach_stats:  #Coach doesn't have stats yet.
            coach_stats = CoachStats(parent=coach)

        for record in team.teamrecord_set.order('created'):
            coach_stats.update(record)
        coach_stats.put()

        for leader in CoachLeader.all():
            CoachLeaderStanding(key_name=coach_stats.parent().key().name(),
                                parent=leader,
                                coach_stats=coach_stats,
                                score=leader.get_score(coach_stats)).put()

        views.CoachLeaders.clear()
        views.RecentMatches.clear()
        views.LeagueStandings.clear()
        views.TeamBox.clear(team.key())

        # OFL eligibility rule checks
        season, week = misc.get_ofl_season_and_week()
        if not team.check_eligibility(season=season):
            team.set_flag(TeamProfile.INELIGIBLE_FLAG)
            team.put()
예제 #3
0
 def get(self):
   logging.debug("checking OFL match results...")
   # We have to parse OFL Schedule to get up to date results.
   season, week = misc.get_ofl_season_and_week()
   season += 3
   weekbegin = week - 1
   if weekbegin < 1:
     weekbegin = 1
   weekend = week + 1
   if weekend > 16:
     weekend = 16
   for week in range(weekbegin, weekend+1):
     parser = OFLScheduleParser()
     data = []
     data = parser.parse(season, week)
     parser.update_schedule_entries(data)
     #Now that entries are updated, let's look at predictions for all coaches
     put_list=[]
     predictions = OFL_Prediction.all().filter("season =", season).filter("week =", week)
     for prediction in predictions:
       keyname = prediction.key().name()
       match = OFL_Match.get_by_key_name(keyname)
       # match exists so compare - should not occur unless Thul changes team matchups
       if match:
         if match.gamePlayed:
           if prediction.Update(match.scoreA, match.scoreB):
             put_list.append(prediction)
             logging.debug("Updating prediction %s for %s" % (prediction.key().name(), prediction.parent().key().name())) 
     batch_put(put_list)
예제 #4
0
  def get(self):

    
    user = users.get_current_user()
    if user:
      log_out_url = users.create_logout_url("/")
      coach = Coach.all().filter("user ="******"<img src='http://www.oldworldfootball.com/%s'/>" % (match.teamAlogo)
          return html

        def logoB_getter(match):
          html = "<img src='http://www.oldworldfootball.com/%s'/>" % (match.teamBlogo)
          return html

        def nameA_getter(prediction):
          match = OFL_Match.get_by_key_name(prediction.key().name())
          html = "%s (%s - %s)" % (match.teamA, match.teamAcoach, match.teamArace)
          return html

        def nameB_getter(prediction):
          match = OFL_Match.get_by_key_name(prediction.key().name())
          html = "%s (%s - %s)" % (match.teamB, match.teamBcoach, match.teamBrace)
          return html

        def key_name_getter(prediction):
          return prediction.key().name()

        def choice_getter(prediction):
          match = OFL_Match.get_by_key_name(prediction.key().name())
          #html = "<img src='./get_wager_pic?keyname=%s&team=A'/>" % (prediction.key().name())
          html = "<img src='http://www.oldworldfootball.com/%s'/>" % (match.teamAlogo)
          if not match.gamePlayed:
            html += "<input type='radio' name='%schoice' value='-1' %s>" % (match.key().name(), prediction.isChecked(-1))
            html += "<input type='radio' name='%schoice' value='0' %s>" % (match.key().name(), prediction.isChecked(0))
            html += "<input type='radio' name='%schoice' value='1' %s>" % (match.key().name(), prediction.isChecked(1))
          else:
            html += "<input type='radio' name='%schoice' value='-1' disabled %s>" % (match.key().name(), prediction.isChecked(-1))
            html += "<input type='radio' name='%schoice' value='0' disabled %s>" % (match.key().name(), prediction.isChecked(0))
            html += "<input type='radio' name='%schoice' value='1' disabled %s>" % (match.key().name(), prediction.isChecked(1))
          html += "<img src='http://www.oldworldfootball.com/%s'/>" % (match.teamBlogo)
          #html += "<img src='./get_wager_pic?keyname=%s&team=B'/>" % (prediction.key().name())
          return html
  

        # Bypassing table.html Django template to create this table
        # Table requires Jquery code for sortable entires and wagers
        # Hidden input tags are also used with form.
        prediction_list = OFL_Prediction.all().filter("season =", season).filter("week =", week).ancestor(coach).filter("gameScored =", False).order("-wager")
        columns = ["Wager", "Away Team", "Prediction", "Home Team"]
        table_html = []
        table_html.append('''
        <table class="ofl_pickem schedule_table">
        <thead>
            <tr>''')
        for column in columns:
          table_html.append('<th style="text-align: center;"> %s </th>' % column)
        table_html.append('''
            </tr>
        </thead>
        <tbody id="sortable">''')
        k = 0        
        for prediction in prediction_list:
          table_html.append('<tr class="row_%s">' % k)
          table_html.append('<input type="hidden" name="row_%s" value="%s">' % (k, prediction.key().name()))
          table_html.append("<input type='hidden' class='row_%s' name='%svalue' value='%s'>" % (k, prediction.key().name(), prediction.wager))
          table_html.append('<td class="row_%s" style="text -align: center;">%s</td>' % (k, prediction.wager))
          table_html.append('<td style="text-align: center;">%s</td>' % nameA_getter(prediction))
          table_html.append('<td style="text-align: center;">%s</td>' % choice_getter(prediction))
          table_html.append('<td style="text-align: center;">%s</td>' % nameB_getter(prediction))
          k += 1
        table_html.append('</tbody>\n</table>')
        table_html = "\n".join(table_html)
        
        played_table = Table(
          columns = [
            # profile
            Column("Points",     "Points Earned",      attrgetter("points")),
            Column("Wager",      "Wager Placed",       attrgetter("wager")),
            Column("Away Team",  "Away Team",          nameA_getter, center=True),
            Column("Prediction", "Your Prediction",    choice_getter, center=True),
            Column("Home Team",  "Home Team",          nameB_getter, center=True),
            ],
          query = OFL_Prediction.all().filter("season =", season).filter("week =", week).ancestor(coach).filter("gameScored =", True).order("-points"),
          id = "played_table",
          cls = "tablesorter",
          )
          
      def logo_getter(standing):
        coach = Coach.get_by_key_name(standing.get_coach_name())
        img = "<img src='%s' />" % coach.get_logo_url() # FIXME: thumb is broken
        return "<div style='background-color: %(color)s'>%(img)s</div>" % {
          'color': coach.color, 'img': img}

      def name_getter(standing):
        coach = Coach.get_by_key_name(standing.get_coach_name())
        return "<a class='leader_link' rel='leader_coach' href='%s'>%s</a>" % (
          coach.get_box_href(),coach.key().name())
      
      leader_table = {}
      query = OFLPickemStats.all().order('-all_time').fetch(10)
      label = "alltime"
      leader_table[label] = Table(
          columns = [
            Column(" ",         "Logo",        logo_getter, center=True),
            Column("Coach Name", "Coach name", name_getter),
            Column("Score",     "Score",       attrgetter("all_time")),
            ],
          query = query,
          cls = "leader_table",
          )
          
      query = OFLPickemSeasonRecord.all().filter("season =", season).order("-points").fetch(10)
      label = "season"
      leader_table[label] = Table(
          columns = [
            Column(" ",         "Logo",        logo_getter, center=True),
            Column("Coach Name", "Coach name", name_getter),
            Column("Score",     "Score",       attrgetter("points")),
            ],
          query = query,
          cls = "leader_table",
          )
          
      query = OFLPickemWeekRecord.all().filter("week =", week).filter("season =", season).order("-points").fetch(10)
      label = "week"
      leader_table[label] = Table(
          columns = [
            Column(" ",         "Logo",        logo_getter, center=True),
            Column("Coach Name", "Coach name", name_getter),
            Column("Score",     "Score",       attrgetter("points")),
            ],
          query = query,
          cls = "leader_table",
          )
          
      query = OFLPickemStats.all().order('-matches').fetch(10)
      label = "alltime_matches"
      leader_table[label] = Table(
          columns = [
            Column(" ",         "Logo",        logo_getter, center=True),
            Column("Coach Name", "Coach name", name_getter),
            Column("Matches",     "Matches Predicted",       attrgetter("matches")),
            ],
          query = query,
          cls = "leader_table",
          )
          
      query = OFLPickemSeasonRecord.all().filter("season =", season).order("-matches").fetch(10)
      label = "season_matches"
      leader_table[label] = Table(
          columns = [
            Column(" ",         "Logo",        logo_getter, center=True),
            Column("Coach Name", "Coach name", name_getter),
            Column("Matches",     "Matches Predicted",       attrgetter("matches")),
            ],
          query = query,
          cls = "leader_table",
          )
          
      query = OFLPickemWeekRecord.all().filter("week =", week).filter("season =", season).order("-matches").fetch(10)
      label = "week_matches"
      leader_table[label] = Table(
          columns = [
            Column(" ",         "Logo",        logo_getter, center=True),
            Column("Coach Name", "Coach name", name_getter),
            Column("Matches",     "Matches Predicted",       attrgetter("matches")),
            ],
          query = query,
          cls = "leader_table",
          )    
          
    else:
      log_in_url = users.create_login_url("/") 

    # render and update 
    #--------------------------------------------------------------------#

    ofl_pickem_page = misc.render('ofl_pickem_page.html', locals())
    self.update(ofl_pickem_page)

    self.response.out.write(ofl_pickem_page)
      
    
예제 #5
0
def process_update(match):
    match_lookup = match.parent()
    put_list = []

    logging.debug("preparing to update for %s" % match_lookup.get_string())

    assert_log = misc.AssertLog(match_lookup.get_string())
    season, week = misc.get_ofl_season_and_week()

    # Update team information
    #--------------------------------------------------------------------#

    team_records = list(match.get_team_records_query())
    teams = [record.team for record in team_records]
    coach_stats_list = []

    for team, team_record in zip(teams, team_records):

        # this check is to make sure we only do this once (for idempotence) in case
        # of a retry
        if team.teamrecord_set.count() > team.matches:
            team.update(team_record)
            coach = team.coach
            if coach:
                coach.last_active = datetime.date.today()
                coach_stats = CoachStats.all().ancestor(coach).get()
                coach_stats.update(team_record)
                coach_stats_list.append(coach_stats)

            # OFTL eligibility rule checks
            if not team.check_eligibility(season=season):
                team.set_flag(TeamProfile.INELIGIBLE_FLAG)

            # retirement (not by death)
            active_player_count = 0
            player_keys = [
                pr.player.key() for pr in team_record.playerrecord_set
            ]
            for player in team.player_set:
                if not player.key() in player_keys:
                    if player.retired == False:
                        player.retired = True
                        put_list.append(player)

                if not player.retired:
                    active_player_count += 1

            # boost TV for potential loners
            if active_player_count < 11:
                team.tv += (11 - active_player_count) * 50

    # Update player information
    #--------------------------------------------------------------------#

    player_records = list(match.get_player_records_query())
    players = [record.player for record in player_records]

    # Structure to map to the already-updated player team.
    #   We use this map because 'player.team' and the same team indexed in
    #   'teams' do not point to the same object. To avoid conflict we
    #   update the one in 'teams' through the map
    team_map = dict((t.key(), t) for t in teams)

    # Keep track of the number of players that violate the SPP check.  Allow one
    # violation for journeyman hire, which is impossible to track otherwise.
    violation_set = set()
    for player, player_record in zip(players, player_records):
        if not player.team:
            # journeyman / star player
            continue

        if player.matches == 0 and player_record.is_empty():
            # a journeyman/necro/nurgle hire that may have acquired SPP in-game
            continue

        if player.team.key() not in team_map:
            assert player_record.is_empty()
            # Unfortunately BB assigns a journeyman/necro/nurgle hire an arbitrary id
            # that may conflict with an existing OFTL player from a different team.
            # In this case, player.matches != 0. This code is a safety net.
            continue

        # this check is to make sure we only do this once (for idempotence) in case
        # of a retry
        if player.playerrecord_set.count() > player.matches:

            # OFTL rule checks
            if not assert_log.check(
                    player_record.spp, player.spp, "%s %s (%s) expected spp" %
                (player.team.key().name(), player.name, player.key().name())):

                # allow one violation for a journeyman hire before setting the
                # inconsistent flag
                if player.spp != 0 or (player.team.key() in violation_set):
                    team_map[player.team.key()].set_flag(
                        TeamProfile.INCONSISTENT_FLAG)

                violation_set.add(player.team.key())

            tv_delta = player.update(player_record)
            if tv_delta:
                team_map[player.team.key()].tv += tv_delta

    put_list.extend(coach_stats_list)
    put_list.extend(teams)
    put_list.extend(players)
    batch_put(put_list)

    # Update Race Statistics
    #--------------------------------------------------------------------#
    update_race_statistics(teams, team_records)

    # Update leader information
    #--------------------------------------------------------------------#

    update_coach_leaders(coach_stats_list)
    update_team_leaders(teams)
    update_player_leaders(players)

    # Update tournament details
    #--------------------------------------------------------------------#

    match_up = match_lookup.tournamentmatchup_set.get()

    # disqualify team if played match outside of tournament
    for team in teams:
        active_membership = team.get_active_tournament_membership()
        if active_membership and (not match_up or match_up.parent().key() !=
                                  active_membership.parent().key()):

            active_tournament = active_membership.parent()
            if active_tournament.started:
                mail.send_mail(
                    sender="*****@*****.**",
                    to="*****@*****.**",
                    subject="OFTL rules violation",
                    body="%s played outside of %s\n" %
                    (team.key().name(), active_tournament.key().name()))
            else:
                # force withdraw
                active_membership.delete()

    # there can only be one tournament for this match
    if match_up:
        tournament = match_up.parent()

        # determine the winner
        if team_records[0].result == 0:
            # decide the winner by a 'coin flip'.  Seed the random number generator by
            # the match key to make it deterministic in case we need to retry
            random.seed(str(match.key()))
            winner_index = random.choice([0, 1])
        else:
            winner_index = 0 if team_records[0].result == 1 else 1

        winner = teams[winner_index]
        winner = winner.tournamentmembership_set.ancestor(tournament).get()

        loser = teams[winner_index ^ 1]
        loser = loser.tournamentmembership_set.ancestor(tournament).get()

        if match_up.advance(winner, loser, match):
            update_team_leaders([winner.team])

        views.TournamentBox.clear(tournament.key())
        views.Tournaments.clear()

    # Evict relevant pages from memcache so they are regenerated
    #--------------------------------------------------------------------#

    for team in teams:
        views.TeamBox.clear(team.key())

    for player in players:
        views.PlayerBox.clear(player.key())

    views.RecentMatches.clear()
    views.LeagueStandings.clear()
    views.TeamLeaders.clear()
    views.PlayerLeaders.clear()
    views.CoachLeaders.clear()
    views.GeneralStatistics.clear()

    assert_log.mail()
    logging.debug("update successful for %s" % match_lookup.get_string())
예제 #6
0
파일: submit.py 프로젝트: midnjerry/bb-oftl
def process_update(match):
  match_lookup = match.parent()
  put_list = []

  logging.debug("preparing to update for %s" % match_lookup.get_string())

  assert_log = misc.AssertLog(match_lookup.get_string())
  season, week = misc.get_ofl_season_and_week()

  # Update team information
  #--------------------------------------------------------------------#

  team_records = list(match.get_team_records_query())
  teams = [record.team for record in team_records]
  coach_stats_list = []
  
  for team, team_record in zip(teams, team_records):

    # this check is to make sure we only do this once (for idempotence) in case
    # of a retry
    if team.teamrecord_set.count() > team.matches:
      team.update(team_record)
      coach = team.coach
      if coach:
        coach_stats = CoachStats.all().ancestor(coach).get()
        coach_stats.update(team_record)
        coach_stats_list.append(coach_stats)

      # OFTL eligibility rule checks
      if not team.check_eligibility(season=season):
        team.set_flag(TeamProfile.INELIGIBLE_FLAG)

      # retirement (not by death)
      active_player_count = 0
      player_keys = [pr.player.key() for pr in team_record.playerrecord_set]
      for player in team.player_set:
        if not player.key() in player_keys:
          if player.retired == False:
            player.retired = True
            put_list.append(player)

        if not player.retired:
          active_player_count += 1

      # boost TV for potential loners
      if active_player_count < 11:
        team.tv += (11 - active_player_count) * 50

  # Update player information
  #--------------------------------------------------------------------#

  player_records = list(match.get_player_records_query())
  players = [record.player for record in player_records]

  # Structure to map to the already-updated player team.
  #   We use this map because 'player.team' and the same team indexed in
  #   'teams' do not point to the same object. To avoid conflict we
  #   update the one in 'teams' through the map
  team_map = dict((t.key(), t) for t in teams)

  # Keep track of the number of players that violate the SPP check.  Allow one
  # violation for journeyman hire, which is impossible to track otherwise.
  violation_set = set()
  for player, player_record in zip(players, player_records):
    if not player.team:
      # journeyman / star player
      continue

    if player.matches == 0 and player_record.is_empty():
      # a journeyman/necro/nurgle hire that may have acquired SPP in-game
      continue

    if player.team.key() not in team_map:
      assert player_record.is_empty()
      # Unfortunately BB assigns a journeyman/necro/nurgle hire an arbitrary id
      # that may conflict with an existing OFTL player from a different team.
      # In this case, player.matches != 0. This code is a safety net.
      continue

    # this check is to make sure we only do this once (for idempotence) in case
    # of a retry
    if player.playerrecord_set.count() > player.matches:

      # OFTL rule checks
      if not assert_log.check(player_record.spp, player.spp,
          "%s %s (%s) expected spp" % (
            player.team.key().name(), player.name, player.key().name())):

        # allow one violation for a journeyman hire before setting the
        # inconsistent flag
        if player.spp != 0 or (player.team.key() in violation_set):
          team_map[player.team.key()].set_flag(TeamProfile.INCONSISTENT_FLAG)

        violation_set.add(player.team.key())

      tv_delta = player.update(player_record)
      if tv_delta:
        team_map[player.team.key()].tv += tv_delta

  put_list.extend(coach_stats_list)
  put_list.extend(teams)
  put_list.extend(players)
  batch_put(put_list)

  # Update leader information
  #--------------------------------------------------------------------#

  update_coach_leaders(coach_stats_list)
  update_team_leaders(teams)
  update_player_leaders(players)

  # Update tournament details
  #--------------------------------------------------------------------#

  match_up = match_lookup.tournamentmatchup_set.get() 

  # disqualify team if played match outside of tournament
  for team in teams:
    active_membership = team.get_active_tournament_membership()
    if active_membership and (not match_up or
        match_up.parent().key() != active_membership.parent().key()):

      active_tournament = active_membership.parent()
      if active_tournament.started:
        mail.send_mail(
            sender="*****@*****.**",
            to="*****@*****.**",
            subject="OFTL rules violation",
            body="%s played outside of %s\n" % (
              team.key().name(), active_tournament.key().name()))
      else:
        # force withdraw
        active_membership.delete()

  # there can only be one tournament for this match
  if match_up:
    tournament = match_up.parent()

    # determine the winner
    if team_records[0].result == 0:
      # decide the winner by a 'coin flip'.  Seed the random number generator by
      # the match key to make it deterministic in case we need to retry
      random.seed(str(match.key()))
      winner_index = random.choice([0, 1])
    else:
      winner_index = 0 if team_records[0].result == 1 else 1

    winner = teams[winner_index]
    winner = winner.tournamentmembership_set.ancestor(tournament).get()

    loser = teams[winner_index ^ 1]
    loser = loser.tournamentmembership_set.ancestor(tournament).get()

    if match_up.advance(winner, loser, match):
      update_team_leaders([winner.team])

    views.TournamentBox.clear(tournament.key())
    views.Tournaments.clear()
    
  # Evict relevant pages from memcache so they are regenerated
  #--------------------------------------------------------------------#

  for team in teams:
    views.TeamBox.clear(team.key())

  for player in players:
    views.PlayerBox.clear(player.key())

  views.RecentMatches.clear()
  views.LeagueStandings.clear()
  views.TeamLeaders.clear()
  views.PlayerLeaders.clear()
  views.CoachLeaders.clear()

  assert_log.mail()
  logging.debug("update successful for %s" % match_lookup.get_string())
예제 #7
0
  def get(self):

    # check for a cached version
    #--------------------------------------------------------------------#

    if self.emit(self.response.out):
      return

    # not cached or evicted from cache; regenerate
    #--------------------------------------------------------------------#

    season, week = misc.get_ofl_season_and_week()
    ofl_week = (season - 1) * 16 + week

    def name_getter(team):
      return "<a rel='team' href='%s'>%s</a>" % (
          team.get_box_href(), team.key().name())

    def race_getter(team):
      return "<img title='%s' src='%s' />" % (
          team.race.key().name(), team.race.get_image_src(thumb=True))

    def coach_getter(team):
      if team.coach:
        return "<a rel='coach' href='%s'>%s</a>" % (
          team.coach.get_box_href(),team.coach.key().name())
      else:
        return "<i>Unknown</i>"

    def awp_getter(team):
      return "%0.3f" % team.awp

    def glicko_getter(team):
      return "%4.0f" % team.glicko_r

    def status_getter(team):
      html = []

      matches = team.matches
      if team.pre_wins != None:
        matches += team.pre_wins + team.pre_draws + team.pre_losses

      #if (team.status or matches > ofl_week or not team.coach):
      #  html.append("<span class='red_text'>OFL Ineligible</span>")

      if not team.coach:
          html.append("<span class='orange_text'>(Unclaimed!)</span>")

      elif team.test_flag(models.TeamProfile.INCONSISTENT_FLAG):
          html.append("<span class='red_text'>(Inconsistent Data!)</span>")

      #  elif team.test_flag(models.TeamProfile.INELIGIBLE_FLAG):
      #    html.append("<span class='orange_text'>(Exceeds Quota)</b>")

      elif team.test_flag(models.TeamProfile.PRE_LE_FLAG):
          html.append("<span class='yellow_text'>(Incomplete History)</span>")

       # else:
       #  html.append("<span class='orange_text'>(Ahead of OFL Schedule)</b>")

      else:
          html.append("<span class='green_text'>Consistent Data</span>")

      if team.pre_wins != None:
          html.append(
              "<span class='yellow_text'>(Pre-LE history validated: %sW-%sD-%sL)</span>"
              % (team.pre_wins, team.pre_draws, team.pre_losses))

      return " ".join(html)


    #def get_ave_getter(attr):
    #  def ave_getter(team):
    #    return "%.1f" % (float(getattr(team, attr)) / team.matches)
    #  return ave_getter

    tables = {}
    #Getting rid of retired table
    #for label in ("active", "retired"):
    #Taking for loop out, and removing an indent from tables line
    label = "active"
    tables[label] = Table(
          columns = [
            # profile
            Column(" ",         "Race",               race_getter, center=True),
            Column("Team Name", "Team name",          name_getter),
            Column("Coach",     "Coach",              coach_getter),
            Column("TV",        "Team value (approximate)",
              attrgetter("tv"), divider=True),

            # record
            Column("Pl",        "Matches played",     attrgetter("matches")),
            Column("W",         "Matches won",        attrgetter("wins")),
            Column("D",         "Matches drawn",      attrgetter("draws")),
            Column("L",         "Matches lost",       attrgetter("losses"),
              divider=True),

            # rankings
            Column("AWP",       "Adjusted win percentage", awp_getter),
            Column("TPts",      "Tournament Points",       attrgetter("tpts")),
            Column("Rating",    "Glicko Rating",           glicko_getter,
              divider=True),

            Column("Status & Eligibility",
              "OFTL/OFL Status and/or Eligibility",    status_getter),
            ## touchdowns
            #Column("TD+",       "Touchdowns for",     attrgetter("tds_for")),
            #Column("TD-",       "Touchdowns against", attrgetter("tds_against")),
            #Column("<span class='over'>TD+</span>",  "Average touchdowns for",
            #  get_ave_getter("tds_for")),
            #Column("<span class='over'>TD-</span>",  "Average touchdowns against",
            #  get_ave_getter("tds_against")),

            ## casualties
            #Column("C+",        "Casualties for",     attrgetter("cas_for")),
            #Column("C-",        "Casualties against", attrgetter("cas_against")),
            #Column("<span class='over'>C+</span>",  "Average casualties for",
            #  get_ave_getter("cas_for")),
            #Column("<span class='over'>C-</span>",  "Average casualties against",
            #  get_ave_getter("cas_against")),
            ],
          query = models.Team.all().filter("retired =", label == "retired").filter(
            "matches >", 0).order("-matches"),
          id = "team-standings-table",
          cls = "tablesorter",
          )

    # render and update
    #--------------------------------------------------------------------#

    league_standings = misc.render('league_standings.html', locals())
    self.update(league_standings)

    self.response.out.write(league_standings)
예제 #8
0
    def get(self):

        user = users.get_current_user()
        if user:
            log_out_url = users.create_logout_url("/")
            coach = Coach.all().filter("user ="******"<img src='http://www.oldworldfootball.com/%s'/>" % (
                        match.teamAlogo)
                    return html

                def logoB_getter(match):
                    html = "<img src='http://www.oldworldfootball.com/%s'/>" % (
                        match.teamBlogo)
                    return html

                def nameA_getter(prediction):
                    match = OFL_Match.get_by_key_name(prediction.key().name())
                    html = "%s (%s - %s)" % (match.teamA, match.teamAcoach,
                                             match.teamArace)
                    return html

                def nameB_getter(prediction):
                    match = OFL_Match.get_by_key_name(prediction.key().name())
                    html = "%s (%s - %s)" % (match.teamB, match.teamBcoach,
                                             match.teamBrace)
                    return html

                def key_name_getter(prediction):
                    return prediction.key().name()

                def choice_getter(prediction):
                    match = OFL_Match.get_by_key_name(prediction.key().name())
                    #html = "<img src='./get_wager_pic?keyname=%s&team=A'/>" % (prediction.key().name())
                    html = "<img src='http://www.oldworldfootball.com/%s'/>" % (
                        match.teamAlogo)
                    if not match.gamePlayed:
                        html += "<input type='radio' name='%schoice' value='-1' %s>" % (
                            match.key().name(), prediction.isChecked(-1))
                        html += "<input type='radio' name='%schoice' value='0' %s>" % (
                            match.key().name(), prediction.isChecked(0))
                        html += "<input type='radio' name='%schoice' value='1' %s>" % (
                            match.key().name(), prediction.isChecked(1))
                    else:
                        html += "<input type='radio' name='%schoice' value='-1' disabled %s>" % (
                            match.key().name(), prediction.isChecked(-1))
                        html += "<input type='radio' name='%schoice' value='0' disabled %s>" % (
                            match.key().name(), prediction.isChecked(0))
                        html += "<input type='radio' name='%schoice' value='1' disabled %s>" % (
                            match.key().name(), prediction.isChecked(1))
                    html += "<img src='http://www.oldworldfootball.com/%s'/>" % (
                        match.teamBlogo)
                    #html += "<img src='./get_wager_pic?keyname=%s&team=B'/>" % (prediction.key().name())
                    return html

                # Bypassing table.html Django template to create this table
                # Table requires Jquery code for sortable entires and wagers
                # Hidden input tags are also used with form.
                prediction_list = OFL_Prediction.all().filter(
                    "season =",
                    season).filter("week =", week).ancestor(coach).filter(
                        "gameScored =", False).order("-wager")
                columns = ["Wager", "Away Team", "Prediction", "Home Team"]
                table_html = []
                table_html.append('''
        <table class="ofl_pickem schedule_table">
        <thead>
            <tr>''')
                for column in columns:
                    table_html.append(
                        '<th style="text-align: center;"> %s </th>' % column)
                table_html.append('''
            </tr>
        </thead>
        <tbody id="sortable">''')
                k = 0
                for prediction in prediction_list:
                    table_html.append('<tr class="row_%s">' % k)
                    table_html.append(
                        '<input type="hidden" name="row_%s" value="%s">' %
                        (k, prediction.key().name()))
                    table_html.append(
                        "<input type='hidden' class='row_%s' name='%svalue' value='%s'>"
                        % (k, prediction.key().name(), prediction.wager))
                    table_html.append(
                        '<td class="row_%s" style="text -align: center;">%s</td>'
                        % (k, prediction.wager))
                    table_html.append(
                        '<td style="text-align: center;">%s</td>' %
                        nameA_getter(prediction))
                    table_html.append(
                        '<td style="text-align: center;">%s</td>' %
                        choice_getter(prediction))
                    table_html.append(
                        '<td style="text-align: center;">%s</td>' %
                        nameB_getter(prediction))
                    k += 1
                table_html.append('</tbody>\n</table>')
                table_html = "\n".join(table_html)

                played_table = Table(
                    columns=[
                        # profile
                        Column("Points", "Points Earned",
                               attrgetter("points")),
                        Column("Wager", "Wager Placed", attrgetter("wager")),
                        Column("Away Team",
                               "Away Team",
                               nameA_getter,
                               center=True),
                        Column("Prediction",
                               "Your Prediction",
                               choice_getter,
                               center=True),
                        Column("Home Team",
                               "Home Team",
                               nameB_getter,
                               center=True),
                    ],
                    query=OFL_Prediction.all().filter(
                        "season =",
                        season).filter("week =", week).ancestor(coach).filter(
                            "gameScored =", True).order("-points"),
                    id="played_table",
                    cls="tablesorter",
                )

            def logo_getter(standing):
                coach = Coach.get_by_key_name(standing.get_coach_name())
                img = "<img src='%s' />" % coach.get_logo_url(
                )  # FIXME: thumb is broken
                return "<div style='background-color: %(color)s'>%(img)s</div>" % {
                    'color': coach.color,
                    'img': img
                }

            def name_getter(standing):
                coach = Coach.get_by_key_name(standing.get_coach_name())
                return "<a class='leader_link' rel='leader_coach' href='%s'>%s</a>" % (
                    coach.get_box_href(), coach.key().name())

            leader_table = {}
            query = OFLPickemStats.all().order('-all_time').fetch(10)
            label = "alltime"
            leader_table[label] = Table(
                columns=[
                    Column(" ", "Logo", logo_getter, center=True),
                    Column("Coach Name", "Coach name", name_getter),
                    Column("Score", "Score", attrgetter("all_time")),
                ],
                query=query,
                cls="leader_table",
            )

            query = OFLPickemSeasonRecord.all().filter(
                "season =", season).order("-points").fetch(10)
            label = "season"
            leader_table[label] = Table(
                columns=[
                    Column(" ", "Logo", logo_getter, center=True),
                    Column("Coach Name", "Coach name", name_getter),
                    Column("Score", "Score", attrgetter("points")),
                ],
                query=query,
                cls="leader_table",
            )

            query = OFLPickemWeekRecord.all().filter("week =", week).filter(
                "season =", season).order("-points").fetch(10)
            label = "week"
            leader_table[label] = Table(
                columns=[
                    Column(" ", "Logo", logo_getter, center=True),
                    Column("Coach Name", "Coach name", name_getter),
                    Column("Score", "Score", attrgetter("points")),
                ],
                query=query,
                cls="leader_table",
            )

            query = OFLPickemStats.all().order('-matches').fetch(10)
            label = "alltime_matches"
            leader_table[label] = Table(
                columns=[
                    Column(" ", "Logo", logo_getter, center=True),
                    Column("Coach Name", "Coach name", name_getter),
                    Column("Matches", "Matches Predicted",
                           attrgetter("matches")),
                ],
                query=query,
                cls="leader_table",
            )

            query = OFLPickemSeasonRecord.all().filter(
                "season =", season).order("-matches").fetch(10)
            label = "season_matches"
            leader_table[label] = Table(
                columns=[
                    Column(" ", "Logo", logo_getter, center=True),
                    Column("Coach Name", "Coach name", name_getter),
                    Column("Matches", "Matches Predicted",
                           attrgetter("matches")),
                ],
                query=query,
                cls="leader_table",
            )

            query = OFLPickemWeekRecord.all().filter("week =", week).filter(
                "season =", season).order("-matches").fetch(10)
            label = "week_matches"
            leader_table[label] = Table(
                columns=[
                    Column(" ", "Logo", logo_getter, center=True),
                    Column("Coach Name", "Coach name", name_getter),
                    Column("Matches", "Matches Predicted",
                           attrgetter("matches")),
                ],
                query=query,
                cls="leader_table",
            )

        else:
            log_in_url = users.create_login_url("/")

        # render and update
        #--------------------------------------------------------------------#

        ofl_pickem_page = misc.render('ofl_pickem_page.html', locals())
        self.update(ofl_pickem_page)

        self.response.out.write(ofl_pickem_page)
예제 #9
0
    def get(self):

        # check for a cached version
        #--------------------------------------------------------------------#

        if self.emit(self.response.out):
            return

        # not cached or evicted from cache; regenerate
        #--------------------------------------------------------------------#

        season, week = misc.get_ofl_season_and_week()
        ofl_week = (season - 1) * 16 + week

        def name_getter(team):
            return "<a rel='team' href='%s'>%s</a>" % (team.get_box_href(),
                                                       team.key().name())

        def race_getter(team):
            return "<img title='%s' src='%s' />" % (
                team.race.key().name(), team.race.get_image_src(thumb=True))

        def coach_getter(team):
            if team.coach:
                return "<a rel='coach' href='%s'>%s</a>" % (
                    team.coach.get_box_href(), team.coach.key().name())
            else:
                return "<i>Unknown</i>"

        def awp_getter(team):
            return "%0.3f" % team.awp

        def glicko_getter(team):
            return "%4.0f" % team.glicko_r

        def status_getter(team):
            html = []

            matches = team.matches
            if team.pre_wins != None:
                matches += team.pre_wins + team.pre_draws + team.pre_losses

            #if (team.status or matches > ofl_week or not team.coach):
            #  html.append("<span class='red_text'>OFL Ineligible</span>")

            if not team.coach:
                html.append("<span class='orange_text'>(Unclaimed!)</span>")

            elif team.test_flag(models.TeamProfile.INCONSISTENT_FLAG):
                html.append(
                    "<span class='red_text'>(Inconsistent Data!)</span>")

            #  elif team.test_flag(models.TeamProfile.INELIGIBLE_FLAG):
            #    html.append("<span class='orange_text'>(Exceeds Quota)</b>")

            elif team.test_flag(models.TeamProfile.PRE_LE_FLAG):
                html.append(
                    "<span class='yellow_text'>(Incomplete History)</span>")

            # else:
            #  html.append("<span class='orange_text'>(Ahead of OFL Schedule)</b>")

            else:
                html.append("<span class='green_text'>Consistent Data</span>")

            if team.pre_wins != None:
                html.append(
                    "<span class='yellow_text'>(Pre-LE history validated: %sW-%sD-%sL)</span>"
                    % (team.pre_wins, team.pre_draws, team.pre_losses))

            return " ".join(html)

        #def get_ave_getter(attr):
        #  def ave_getter(team):
        #    return "%.1f" % (float(getattr(team, attr)) / team.matches)
        #  return ave_getter

        tables = {}
        #Getting rid of retired table
        #for label in ("active", "retired"):
        #Taking for loop out, and removing an indent from tables line
        label = "active"
        tables[label] = Table(
            columns=[
                # profile
                Column(" ", "Race", race_getter, center=True),
                Column("Team Name", "Team name", name_getter),
                Column("Coach", "Coach", coach_getter),
                Column("TV",
                       "Team value (approximate)",
                       attrgetter("tv"),
                       divider=True),

                # record
                Column("Pl", "Matches played", attrgetter("matches")),
                Column("W", "Matches won", attrgetter("wins")),
                Column("D", "Matches drawn", attrgetter("draws")),
                Column("L", "Matches lost", attrgetter("losses"),
                       divider=True),

                # rankings
                Column("AWP", "Adjusted win percentage", awp_getter),
                Column("TPts", "Tournament Points", attrgetter("tpts")),
                Column("Rating", "Glicko Rating", glicko_getter, divider=True),
                Column("Status & Eligibility",
                       "OFTL/OFL Status and/or Eligibility", status_getter),
                ## touchdowns
                #Column("TD+",       "Touchdowns for",     attrgetter("tds_for")),
                #Column("TD-",       "Touchdowns against", attrgetter("tds_against")),
                #Column("<span class='over'>TD+</span>",  "Average touchdowns for",
                #  get_ave_getter("tds_for")),
                #Column("<span class='over'>TD-</span>",  "Average touchdowns against",
                #  get_ave_getter("tds_against")),

                ## casualties
                #Column("C+",        "Casualties for",     attrgetter("cas_for")),
                #Column("C-",        "Casualties against", attrgetter("cas_against")),
                #Column("<span class='over'>C+</span>",  "Average casualties for",
                #  get_ave_getter("cas_for")),
                #Column("<span class='over'>C-</span>",  "Average casualties against",
                #  get_ave_getter("cas_against")),
            ],
            #query = models.Team.all().filter("retired =", label == "retired").filter(
            #  "matches >", 0).order("-matches"),
            query=models.Team.all().filter("matches >",
                                           0).order("-matches").fetch(50),
            id="team-standings-table",
            cls="tablesorter",
        )

        # render and update
        #--------------------------------------------------------------------#

        league_standings = misc.render('league_standings.html', locals())
        self.update(league_standings)

        self.response.out.write(league_standings)
예제 #10
0
    def get(self):

        user = users.get_current_user()
        if user:
            log_out_url = users.create_logout_url("/")
            coach = Coach.all().filter("user ="******"schedule").split("-")

                if not season or not week:
                    season, week = misc.get_ofl_season_and_week()
                    season += 3
                else:
                    season = int(season)
                    week = int(week)

                parser = OFLScheduleParser()
                ofl_info = urlfetch.fetch(
                    "http://www.shalkith.com/bloodbowl/processSchedule.php?s=%s&w=%s"
                    % (season, week))
                parser.feed(ofl_info.content)
                update_schedule_entries(coach, season, week, parser.data)
                sort_wagers(coach, season, week)

                def logoA_getter(match):
                    html = "<img src='http://www.shalkith.com/bloodbowl/%s'/>" % (
                        match.teamAlogo)
                    return html

                def logoB_getter(match):
                    html = "<img src='http://www.shalkith.com/bloodbowl/%s'/>" % (
                        match.teamBlogo)
                    return html

                def nameA_getter(prediction):
                    match = OFL_Match.get_by_key_name(prediction.key().name())
                    html = "%s (%s)" % (match.teamA, match.teamAcoach)
                    return html

                def nameB_getter(prediction):
                    match = OFL_Match.get_by_key_name(prediction.key().name())
                    html = "%s (%s)" % (match.teamB, match.teamBcoach)
                    return html

                def key_name_getter(prediction):
                    return prediction.key().name()

                def choice_getter(prediction):
                    match = OFL_Match.get_by_key_name(prediction.key().name())
                    html = "<img src='http://www.shalkith.com/bloodbowl/%s'/>" % (
                        match.teamAlogo)
                    if not match.gamePlayed:
                        html += "<input type='radio' name='%schoice' value='-1' %s>" % (
                            match.key().name(), prediction.isChecked(-1))
                        html += "<input type='radio' name='%schoice' value='0' %s>" % (
                            match.key().name(), prediction.isChecked(0))
                        html += "<input type='radio' name='%schoice' value='1' %s>" % (
                            match.key().name(), prediction.isChecked(1))
                    else:
                        html += "<input type='radio' name='%schoice' value='-1' disabled %s>" % (
                            match.key().name(), prediction.isChecked(-1))
                        html += "<input type='radio' name='%schoice' value='0' disabled %s>" % (
                            match.key().name(), prediction.isChecked(0))
                        html += "<input type='radio' name='%schoice' value='1' disabled %s>" % (
                            match.key().name(), prediction.isChecked(1))
                    html += "<img src='http://www.shalkith.com/bloodbowl/%s'/>" % (
                        match.teamBlogo)
                    return html

                # Bypassing table.html Django template to create this table
                # Table requires Jquery code for sortable entires and wagers
                # Hidden input tags are also used with form.
                prediction_list = OFL_Prediction.all().filter(
                    "season =",
                    season).filter("week =", week).ancestor(coach).filter(
                        "gameScored =", False).order("-wager")
                columns = ["Wager", "Away Team", "Prediction", "Home Team"]
                table_html = []
                table_html.append('''
        <table class="ofl_pickem schedule_table">
        <thead>
            <tr>''')
                for column in columns:
                    table_html.append(
                        '<th style="text-align: center;"> %s </th>' % column)
                table_html.append('''
            </tr>
        </thead>
        <tbody id="sortable">''')
                k = 0
                for prediction in prediction_list:
                    table_html.append('<tr class="row_%s">' % k)
                    table_html.append(
                        '<input type="hidden" name="row_%s" value="%s">' %
                        (k, prediction.key().name()))
                    table_html.append(
                        "<input type='hidden' class='row_%s' name='%svalue' value='%s'>"
                        % (k, prediction.key().name(), prediction.wager))
                    table_html.append(
                        '<td class="row_%s" style="text -align: center;">%s</td>'
                        % (k, prediction.wager))
                    table_html.append(
                        '<td style="text-align: center;">%s</td>' %
                        nameA_getter(prediction))
                    table_html.append(
                        '<td style="text-align: center;">%s</td>' %
                        choice_getter(prediction))
                    table_html.append(
                        '<td style="text-align: center;">%s</td>' %
                        nameB_getter(prediction))
                    k += 1
                table_html.append('</tbody>\n</table>')
                table_html = "\n".join(table_html)

                played_table = Table(
                    columns=[
                        # profile
                        Column("Points", "Points Earned",
                               attrgetter("points")),
                        Column("Wager", "Wager Placed", attrgetter("wager")),
                        Column("Away Team",
                               "Away Team",
                               nameA_getter,
                               center=True),
                        Column("Prediction",
                               "Your Prediction",
                               choice_getter,
                               center=True),
                        Column("Home Team",
                               "Home Team",
                               nameB_getter,
                               center=True),
                    ],
                    query=OFL_Prediction.all().filter(
                        "season =",
                        season).filter("week =", week).ancestor(coach).filter(
                            "gameScored =", True).order("-points"),
                    id="played_table",
                    cls="tablesorter",
                )

        else:
            log_in_url = users.create_login_url("/")

        # render and update
        #--------------------------------------------------------------------#

        ofl_pickem_page = misc.render('ofl_pickem_box.html', locals())
        self.update(ofl_pickem_page)

        self.response.out.write(ofl_pickem_page)
예제 #11
0
  def get(self):

    user = users.get_current_user()
    if user:
      log_out_url = users.create_logout_url("/")
      coach = Coach.all().filter("user ="******"schedule").split("-")

        if not season or not week:
          season, week = misc.get_ofl_season_and_week()
          season += 3
        else:
          season = int(season)
          week = int(week)

        parser = OFLScheduleParser()
        ofl_info = urlfetch.fetch("http://www.shalkith.com/bloodbowl/processSchedule.php?s=%s&w=%s" % (season, week))
        parser.feed(ofl_info.content)
        update_schedule_entries(coach, season, week, parser.data)
        sort_wagers(coach, season, week)

        def logoA_getter(match):
          html = "<img src='http://www.shalkith.com/bloodbowl/%s'/>" % (match.teamAlogo)
          return html

        def logoB_getter(match):
          html = "<img src='http://www.shalkith.com/bloodbowl/%s'/>" % (match.teamBlogo)
          return html

        def nameA_getter(prediction):
          match = OFL_Match.get_by_key_name(prediction.key().name())
          html = "%s (%s)" % (match.teamA, match.teamAcoach)
          return html

        def nameB_getter(prediction):
          match = OFL_Match.get_by_key_name(prediction.key().name())
          html = "%s (%s)" % (match.teamB, match.teamBcoach)
          return html

        def key_name_getter(prediction):
          return prediction.key().name()

        def choice_getter(prediction):
          match = OFL_Match.get_by_key_name(prediction.key().name())
          html = "<img src='http://www.shalkith.com/bloodbowl/%s'/>" % (match.teamAlogo)
          if not match.gamePlayed:
            html += "<input type='radio' name='%schoice' value='-1' %s>" % (match.key().name(), prediction.isChecked(-1))
            html += "<input type='radio' name='%schoice' value='0' %s>" % (match.key().name(), prediction.isChecked(0))
            html += "<input type='radio' name='%schoice' value='1' %s>" % (match.key().name(), prediction.isChecked(1))
          else:
            html += "<input type='radio' name='%schoice' value='-1' disabled %s>" % (match.key().name(), prediction.isChecked(-1))
            html += "<input type='radio' name='%schoice' value='0' disabled %s>" % (match.key().name(), prediction.isChecked(0))
            html += "<input type='radio' name='%schoice' value='1' disabled %s>" % (match.key().name(), prediction.isChecked(1))
          html += "<img src='http://www.shalkith.com/bloodbowl/%s'/>" % (match.teamBlogo)
          return html
  

        # Bypassing table.html Django template to create this table
        # Table requires Jquery code for sortable entires and wagers
        # Hidden input tags are also used with form.
        prediction_list = OFL_Prediction.all().filter("season =", season).filter("week =", week).ancestor(coach).filter("gameScored =", False).order("-wager")
        columns = ["Wager", "Away Team", "Prediction", "Home Team"]
        table_html = []
        table_html.append('''
        <table class="ofl_pickem schedule_table">
        <thead>
            <tr>''')
        for column in columns:
          table_html.append('<th style="text-align: center;"> %s </th>' % column)
        table_html.append('''
            </tr>
        </thead>
        <tbody id="sortable">''')
        k = 0        
        for prediction in prediction_list:
          table_html.append('<tr class="row_%s">' % k)
          table_html.append('<input type="hidden" name="row_%s" value="%s">' % (k, prediction.key().name()))
          table_html.append("<input type='hidden' class='row_%s' name='%svalue' value='%s'>" % (k, prediction.key().name(), prediction.wager))
          table_html.append('<td class="row_%s" style="text -align: center;">%s</td>' % (k, prediction.wager))
          table_html.append('<td style="text-align: center;">%s</td>' % nameA_getter(prediction))
          table_html.append('<td style="text-align: center;">%s</td>' % choice_getter(prediction))
          table_html.append('<td style="text-align: center;">%s</td>' % nameB_getter(prediction))
          k += 1
        table_html.append('</tbody>\n</table>')
        table_html = "\n".join(table_html)
        
        played_table = Table(
          columns = [
            # profile
            Column("Points",     "Points Earned",      attrgetter("points")),
            Column("Wager",      "Wager Placed",       attrgetter("wager")),
            Column("Away Team",  "Away Team",          nameA_getter, center=True),
            Column("Prediction", "Your Prediction",    choice_getter, center=True),
            Column("Home Team",  "Home Team",          nameB_getter, center=True),
            ],
          query = OFL_Prediction.all().filter("season =", season).filter("week =", week).ancestor(coach).filter("gameScored =", True).order("-points"),
          id = "played_table",
          cls = "tablesorter",
          )
        
        
        
    else:
      log_in_url = users.create_login_url("/") 

    # render and update 
    #--------------------------------------------------------------------#

    ofl_pickem_page = misc.render('ofl_pickem_box.html', locals())
    self.update(ofl_pickem_page)

    self.response.out.write(ofl_pickem_page)