get box_score data
        :param soup: Beautifulsoup object
        :param game: MLBAM Game object
        :param players: MLBAM Players object
        :return: pitchpx.box_score.box_score.BoxScore object
427394
def _generate_object(cls, soup, game, players):
        

        def get_batter(soup, team_flag):
            batting = soup.find('batting', attrs={'team_flag': team_flag})
            if batting:
                return batting.find_all('batter')
            return []

        def get_pitcher(soup, team_flag):
            pitching = soup.find('pitching', attrs={'team_flag': team_flag})
            if pitching:
                return pitching.find_all('pitcher')
            return []

        box_score = BoxScore(game, players)

        box_score.retro_game_id = game.retro_game_id
        box_score.home_team_id = game.home_team_id
        box_score.away_team_id = game.away_team_id
        box_score.home_batting = [box_score._get_batter(b) for b in get_batter(soup, 'home')]
        box_score.away_batting = [box_score._get_batter(b) for b in get_batter(soup, 'away')]
        box_score.home_pitching = [box_score._get_pitcher(p) for p in get_pitcher(soup, 'home')]
        box_score.away_pitching = [box_score._get_pitcher(p) for p in get_pitcher(soup, 'away')]

        return box_score
1116078
def _get_pitch(self, soup, pa):
        
        pitches = []
        ball_tally, strike_tally = 0, 0
        for pitch in soup.find_all('pitch'):
            # pitching result
            pitch = Pitch.row(pitch, pa, pitches, ball_tally, strike_tally)
            pitches.append(pitch)
            # ball count
            ball_tally, strike_tally = RetroSheet.ball_count(ball_tally, strike_tally, pitch['pitch_res'])
        return pitches
198565
def _inning_events(self, soup, inning_number, inning_id, hit_location):
        
        # at bat(batter box data) & pitching data
        out_ct = 0
        for ab in soup.find_all('atbat'):
            # plate appearance data(pa)
            at_bat = AtBat.pa(ab, self.game, self.players.rosters, inning_number, inning_id, out_ct, hit_location)
            # pitching data
            pitching_stats = self._get_pitch(ab, at_bat)
            # at bat(pa result)
            pa_result = AtBat.result(ab, at_bat, pitching_stats)
            at_bat.update(pa_result)
            self.atbats.append(at_bat)
            self.pitches.extend(pitching_stats)
            # out count
            out_ct = at_bat['event_outs_ct']
715408
def filter_results(self, boxlist, num_classes):
        
        # unwrap the boxlist to avoid additional overhead.
        # if we had multi-class NMS, we could perform this directly on the boxlist
        boxes = boxlist.bbox.reshape(-1, num_classes * 4)
        scores = boxlist.get_field("scores").reshape(-1, num_classes)

        device = scores.device
        result = []
        # Apply threshold on detection probabilities and apply NMS
        # Skip j = 0, because it's the background class
        inds_all = scores > self.score_thresh
        for j in range(1, num_classes):
            inds = inds_all[:, j].nonzero().squeeze(1)
            scores_j = scores[inds, j]
            boxes_j = boxes[inds, j * 4 : (j + 1) * 4]
            boxlist_for_class = BoxList(boxes_j, boxlist.size, mode="xyxy")
            boxlist_for_class.add_field("scores", scores_j)
            boxlist_for_class = boxlist_nms(
                boxlist_for_class, self.nms
            )
            num_labels = len(boxlist_for_class)
            boxlist_for_class.add_field(
                "labels", torch.full((num_labels,), j, dtype=torch.int64, device=device)
            )
            result.append(boxlist_for_class)

        result = cat_boxlist(result)
        number_of_detections = len(result)

        # Limit to max_per_image detections **over all classes**
        if number_of_detections > self.detections_per_img > 0:
            cls_scores = result.get_field("scores")
            image_thresh, _ = torch.kthvalue(
                cls_scores.cpu(), number_of_detections - self.detections_per_img + 1
            )
            keep = cls_scores >= image_thresh.item()
            keep = torch.nonzero(keep).squeeze(1)
            result = result[keep]
        return result
840494
def get_fantasy_points(self, match_key):
        

        fantasy_points_url = self.api_path_v3 + "fantasy-match-points/" + match_key + "/"
        response = self.get_response(fantasy_points_url)
        return response
769211
def load_from_scoreboard(element)
        @away_innings = []
        @home_innings = []
        @scoreboard_game_id = element.attributes['id']
        @ampm = element.attributes['ampm']
        @venue = element.attributes['venue']
        @game_pk = element.attributes['game_pk']
        @time = element.attributes['time']
        @time_zone = element.attributes['time_zone']
        @game_type = element.attributes['game_type']
        @away_name_abbrev = element.attributes['away_name_abbrev']
        @home_name_abbrev = element.attributes['home_name_abbrev']
        @away_code = element.attributes['away_code']
        @away_file_code = element.attributes['away_file_code']
        @away_team_id = element.attributes['away_team_id']
        @away_team_city = element.attributes['away_team_city']
        @away_team_name = element.attributes['away_team_name']
        @away_division = element.attributes['away_division']
        @home_code = element.attributes['home_code']
        @home_file_code = element.attributes['home_file_code']
        @home_team_id = element.attributes['home_team_id']
        @home_team_city = element.attributes['home_team_city']
        @home_team_name = element.attributes['home_team_name']
        @home_division = element.attributes['home_division']
        @day = element.attributes['day']
        @gameday_sw = element.attributes['gameday_sw']
        @away_games_back = element.attributes['away_games_back']
        @home_games_back = element.attributes['home_games_back']
        @away_games_back_wildcard = element.attributes['away_games_back_wildcard']
        @home_games_back_wildcard = element.attributes['home_games_back_wildcard']
        @venue_w_chan_loc = element.attributes['venue_w_chan_loc']
        @gameday = element.attributes['gameday']
        @away_win = element.attributes['away_win']
        @away_loss = element.attributes['away_loss']
        @home_win = element.attributes['home_win']
        @home_loss = element.attributes['home_loss']
        @league = element.attributes['league']
      
        set_status(element)
        set_innings(element)
        set_totals(element)
        set_pitchers(element)
        set_homeruns(element)
      end
652264
def dataframe(self):
        
        if self._away_runs is None and self._home_runs is None:
            return None
        fields_to_include = {
            'date': self.date,
            'time': self.time,
            'venue': self.venue,
            'attendance': self.attendance,
            'duration': self.duration,
            'time_of_day': self.time_of_day,
            'winner': self.winner,
            'winning_name': self.winning_name,
            'winning_abbr': self.winning_abbr,
            'losing_name': self.losing_name,
            'losing_abbr': self.losing_abbr,
            'away_at_bats': self.away_at_bats,
            'away_runs': self.away_runs,
            'away_hits': self.away_hits,
            'away_rbi': self.away_rbi,
            'away_earned_runs': self.away_earned_runs,
            'away_bases_on_balls': self.away_bases_on_balls,
            'away_strikeouts': self.away_strikeouts,
            'away_plate_appearances': self.away_plate_appearances,
            'away_batting_average': self.away_batting_average,
            'away_on_base_percentage': self.away_on_base_percentage,
            'away_slugging_percentage': self.away_slugging_percentage,
            'away_on_base_plus': self.away_on_base_plus,
            'away_pitches': self.away_pitches,
            'away_strikes': self.away_strikes,
            'away_win_probability_for_offensive_player':
            self.away_win_probability_for_offensive_player,
            'away_average_leverage_index': self.away_average_leverage_index,
            'away_win_probability_added': self.away_win_probability_added,
            'away_win_probability_subtracted':
            self.away_win_probability_subtracted,
            'away_base_out_runs_added': self.away_base_out_runs_added,
            'away_putouts': self.away_putouts,
            'away_assists': self.away_assists,
            'away_innings_pitched': self.away_innings_pitched,
            'away_home_runs': self.away_home_runs,
            'away_strikes_by_contact': self.away_strikes_by_contact,
            'away_strikes_swinging': self.away_strikes_swinging,
            'away_strikes_looking': self.away_strikes_looking,
            'away_grounded_balls': self.away_grounded_balls,
            'away_fly_balls': self.away_fly_balls,
            'away_line_drives': self.away_line_drives,
            'away_unknown_bat_type': self.away_unknown_bat_type,
            'away_game_score': self.away_game_score,
            'away_inherited_runners': self.away_inherited_runners,
            'away_inherited_score': self.away_inherited_score,
            'away_win_probability_by_pitcher':
            self.away_win_probability_by_pitcher,
            'away_base_out_runs_saved': self.away_base_out_runs_saved,
            'home_at_bats': self.home_at_bats,
            'home_runs': self.home_runs,
            'home_hits': self.home_hits,
            'home_rbi': self.home_rbi,
            'home_earned_runs': self.home_earned_runs,
            'home_bases_on_balls': self.home_bases_on_balls,
            'home_strikeouts': self.home_strikeouts,
            'home_plate_appearances': self.home_plate_appearances,
            'home_batting_average': self.home_batting_average,
            'home_on_base_percentage': self.home_on_base_percentage,
            'home_slugging_percentage': self.home_slugging_percentage,
            'home_on_base_plus': self.home_on_base_plus,
            'home_pitches': self.home_pitches,
            'home_strikes': self.home_strikes,
            'home_win_probability_for_offensive_player':
            self.home_win_probability_for_offensive_player,
            'home_average_leverage_index': self.home_average_leverage_index,
            'home_win_probability_added': self.home_win_probability_added,
            'home_win_probability_subtracted':
            self.home_win_probability_subtracted,
            'home_base_out_runs_added': self.home_base_out_runs_added,
            'home_putouts': self.home_putouts,
            'home_assists': self.home_assists,
            'home_innings_pitched': self.home_innings_pitched,
            'home_home_runs': self.home_home_runs,
            'home_strikes_by_contact': self.home_strikes_by_contact,
            'home_strikes_swinging': self.home_strikes_swinging,
            'home_strikes_looking': self.home_strikes_looking,
            'home_grounded_balls': self.home_grounded_balls,
            'home_fly_balls': self.home_fly_balls,
            'home_line_drives': self.home_line_drives,
            'home_unknown_bat_type': self.home_unknown_bat_type,
            'home_game_score': self.home_game_score,
            'home_inherited_runners': self.home_inherited_runners,
            'home_inherited_score': self.home_inherited_score,
            'home_win_probability_by_pitcher':
            self.home_win_probability_by_pitcher,
            'home_base_out_runs_saved': self.home_base_out_runs_saved
        }
        return pd.DataFrame([fields_to_include], index=[self._uri])
13065
def read_xml(cls, url, markup, game):
        
        return Players._read_objects(MlbamUtil.find_xml("".join([url, cls.FILENAME]), markup) ,game)
665557
def statcast_single_game(game_pk, team=None):
    
    data = single_game_request(game_pk)
    data = postprocessing(data, team)
    return data
339137
def get_live_scores(self, use_12_hour_format):
        """"""
        req = requests.get(RequestHandler.LIVE_URL)
        if req.status_code == requests.codes.ok:
            scores_data = []
            scores = req.json()
            if len(scores["games"]) == 0:
                click.secho("No live action currently", fg="red", bold=True)
                return

            for score in scores['games']:
                # match football-data api structure
                d = {}
                d['homeTeam'] = {'name': score['homeTeamName']}
                d['awayTeam'] = {'name': score['awayTeamName']}
                d['score'] = {'fullTime': {'homeTeam': score['goalsHomeTeam'],
                                           'awayTeam': score['goalsAwayTeam']}}
                d['league'] = score['league']
                d['time'] = score['time']
                scores_data.append(d)
            self.writer.live_scores(scores_data)
        else:
            click.secho("There was problem getting live scores", fg="red", bold=True)
650026
def _get_pitcher(self, pitcher):
        
        values = OrderedDict()
        player = self.players.rosters.get(pitcher.get('id'))
        values['pos'] = pitcher.get('pos', MlbamConst.UNKNOWN_SHORT)
        values['id'] = pitcher.get('id', MlbamConst.UNKNOWN_SHORT)
        values['first'] = player.first
        values['last'] = player.last
        values['box_name'] = player.box_name
        values['rl'] = player.rl
        values['bats'] = player.bats
        values['out'] = pitcher.get('out', MlbamConst.UNKNOWN_SHORT)
        values['bf'] = pitcher.get('bf', MlbamConst.UNKNOWN_SHORT)
        return values
1111772
def _download(self, timestamp):
        
        games, atbats, pitches = [], [], []
        rosters, coaches, umpires = [], [], []
        boxscores, actions = [], []
        timestamp_params = {
            'year': str(timestamp.year),
            'month': str(timestamp.month).zfill(2),
            'day': str(timestamp.day).zfill(2)
        }

        logging.info('->- Game data download start({year}/{month}/{day})'.format(**timestamp_params))

        base_url = self.DELIMITER.join([self.url, self.PAGE_URL_GAME_DAY.format(**timestamp_params)])
        html = MlbamUtil.find_xml(base_url, self.parser)

        href = self.PAGE_URL_GAME_PREFIX.format(**timestamp_params)
        for gid in html.find_all('a', href=re.compile(href)):
            gid_path = gid.get_text().strip()
            gid_url = self.DELIMITER.join([base_url, gid_path])
            # Read XML & create dataset
            try:
                game = Game.read_xml(gid_url, self.parser, timestamp, MlbAm._get_game_number(gid_path))
                players = Players.read_xml(gid_url, self.parser, game)
                innings = Inning.read_xml(gid_url, self.parser, game, players)
                boxscore = BoxScore.read_xml(gid_url, self.parser, game, players)
            except MlbAmHttpNotFound as e:
                logging.warning(e.msg)
                continue

            # append a dataset
            games.append(game.row())
            rosters.extend([roseter.row() for roseter in players.rosters.values()])
            coaches.extend([coach.row() for coach in players.coaches.values()])
            umpires.extend([umpire.row() for umpire in players.umpires.values()])
            atbats.extend(innings.atbats)
            pitches.extend(innings.pitches)
            actions.extend(innings.actions)
            boxscores.append(boxscore.row())

        # writing csv
        day = "".join([timestamp_params['year'], timestamp_params['month'], timestamp_params['day']])
        for params in (
                {'datasets': games, 'filename': Game.DOWNLOAD_FILE_NAME},
                {'datasets': rosters, 'filename': Players.Player.DOWNLOAD_FILE_NAME},
                {'datasets': coaches, 'filename': Players.Coach.DOWNLOAD_FILE_NAME},
                {'datasets': umpires, 'filename': Players.Umpire.DOWNLOAD_FILE_NAME},
                {'datasets': atbats, 'filename': AtBat.DOWNLOAD_FILE_NAME},
                {'datasets': pitches, 'filename': Pitch.DOWNLOAD_FILE_NAME},
                {'datasets': boxscores, 'filename': BoxScore.DOWNLOAD_FILE_NAME},
                {'datasets': actions, 'filename': InningAction.DOWNLOAD_FILE_NAME},
        ):
            self._write_csv(params['datasets'], params['filename'].format(day=day, extension=self.extension))
        time.sleep(2)

        logging.info('-<- Game data download end({year}/{month}/{day})'.format(**timestamp_params))
1119205
def scoreboard(year, month, day, home=None, away=None):
    
    # get data
    data = mlbgame.data.get_scoreboard(year, month, day)
    # parse data
    parsed = etree.parse(data)
    root = parsed.getroot()
    games = {}
    output = {}
    # loop through games
    for game in root:
        if game.tag == 'data':
            return []
        # get team names
        teams = game.findall('team')
        home_name = teams[0].attrib['name']
        away_name = teams[1].attrib['name']
        # check if teams match parameters
        if (home_name == home and home is not None) \
                or (away_name == away and away is not None) \
                or (away is None and home is None):
            # throw all the data into a complicated dictionary
            game_tag = game.tag
            game_data = game.find('game')
            game_id = game_data.attrib['id']
            game_league = game_data.attrib['league']
            game_status = game_data.attrib['status']
            game_start_time = game_data.attrib['start_time']
            home_team_data = teams[0].find('gameteam')
            home_team = home_name
            home_team_runs = int(home_team_data.attrib['R'])
            home_team_hits = int(home_team_data.attrib['H'])
            home_team_errors = int(home_team_data.attrib['E'])
            away_team_data = teams[1].find('gameteam')
            away_team = away_name
            away_team_runs = int(away_team_data.attrib['R'])
            away_team_hits = int(away_team_data.attrib['H'])
            away_team_errors = int(away_team_data.attrib['E'])
            # check type of game
            if game_tag == 'go_game' or game_tag == 'ig_game':
                try:
                    w_pitcher_data = game.find('w_pitcher')
                    w_pitcher = w_pitcher_data.find('pitcher').attrib['name']
                    w_pitcher_wins = int(w_pitcher_data.attrib['wins'])
                    w_pitcher_losses = int(w_pitcher_data.attrib['losses'])
                except Exception:
                    w_pitcher = ""
                    w_pitcher_wins = 0
                    w_pitcher_losses = 0
                try:
                    l_pitcher_data = game.find('l_pitcher')
                    l_pitcher = l_pitcher_data.find('pitcher').attrib['name']
                    l_pitcher_wins = int(l_pitcher_data.attrib['wins'])
                    l_pitcher_losses = int(l_pitcher_data.attrib['losses'])
                except Exception:
                    l_pitcher = ""
                    l_pitcher_wins = 0
                    l_pitcher_losses = 0
                try:
                    sv_pitcher_data = game.find('sv_pitcher')
                    sv_pitcher = sv_pitcher_data.find('pitcher').attrib['name']
                    sv_pitcher_saves = int(sv_pitcher_data.attrib['saves'])
                except Exception:
                    sv_pitcher = ""
                    sv_pitcher_saves = 0
                output = {
                    'game_id': game_id,
                    'game_tag': game_tag,
                    'game_league': game_league,
                    'game_status': game_status,
                    'game_start_time': game_start_time,
                    'home_team': home_team,
                    'home_team_runs': home_team_runs,
                    'home_team_hits': home_team_hits,
                    'home_team_errors': home_team_errors,
                    'away_team': away_team,
                    'away_team_runs': away_team_runs,
                    'away_team_hits': away_team_hits,
                    'away_team_errors': away_team_errors,
                    'w_pitcher': w_pitcher,
                    'w_pitcher_wins': w_pitcher_wins,
                    'w_pitcher_losses': w_pitcher_losses,
                    'l_pitcher': l_pitcher,
                    'l_pitcher_wins': l_pitcher_wins,
                    'l_pitcher_losses': l_pitcher_losses,
                    'sv_pitcher': sv_pitcher,
                    'sv_pitcher_saves': sv_pitcher_saves
                }
            # games that were not played
            elif game_tag == 'sg_game':
                try:
                    p_pitcher_data = game.findall('p_pitcher')
                    p_pitcher_home_data = p_pitcher_data[0]
                    p_pitcher_home = p_pitcher_home_data.find(
                        'pitcher').attrib['name']
                    p_pitcher_home_wins = int(p_pitcher_home_data.
                                              attrib['wins'])
                    p_pitcher_home_losses = int(p_pitcher_home_data.
                                                attrib['losses'])
                    p_pitcher_away_data = p_pitcher_data[1]
                    p_pitcher_away = p_pitcher_away_data.find(
                        'pitcher').attrib['name']
                    p_pitcher_away_wins = int(p_pitcher_away_data.
                                              attrib['wins'])
                    p_pitcher_away_losses = int(p_pitcher_away_data.
                                                attrib['losses'])
                except Exception:
                    p_pitcher_home = ''
                    p_pitcher_home_wins = 0
                    p_pitcher_home_losses = 0
                    p_pitcher_away = ''
                    p_pitcher_away_wins = 0
                    p_pitcher_away_losses = 0
                output = {
                    'game_id': game_id,
                    'game_tag': game_tag,
                    'game_league': game_league,
                    'game_status': game_status,
                    'game_start_time': game_start_time,
                    'home_team': home_team,
                    'home_team_runs': home_team_runs,
                    'home_team_hits': home_team_hits,
                    'home_team_errors': home_team_errors,
                    'away_team': away_team,
                    'away_team_runs': away_team_runs,
                    'away_team_hits': away_team_hits,
                    'away_team_errors': away_team_errors,
                    'p_pitcher_home': p_pitcher_home,
                    'p_pitcher_home_wins': p_pitcher_home_wins,
                    'p_pitcher_home_losses': p_pitcher_home_losses,
                    'p_pitcher_away': p_pitcher_away,
                    'p_pitcher_away_wins': p_pitcher_away_wins,
                    'p_pitcher_away_losses': p_pitcher_away_losses
                }
            # put this dictionary into the larger dictionary
            games[game_id] = output
    return games
1359632
def get_players(self, team):
        
        team_id = self.__get_team_id(team)
        self.logger.debug(f'Getting players of team {team_id}.')
        return self._request('teams', team_id, 'players')
338811
def get_match_history(start_at_match_id=None, player_name=None, hero_id=None,
                      skill=0, date_min=None, date_max=None, account_id=None,
                      league_id=None, matches_requested=None, game_mode=None,
                      min_players=None, tournament_games_only=None,
                      **kwargs):
    

    params = {
        "start_at_match_id": start_at_match_id,
        "player_name": player_name,
        "hero_id": hero_id,
        "skill": skill,
        "date_min": date_min,
        "date_max": date_max,
        "account_id": account_id,
        "league_id": league_id,
        "matches_requested": matches_requested,
        "game_mode": game_mode,
        "min_players": min_players,
        "tournament_games_only": tournament_games_only
    }

    return make_request("GetMatchHistory", params, **kwargs)
605065
def get_sport(sport):
    
    sport = sport.lower()
    data = _request_xml(sport)

    matches = []
    for match in data:
        if sport == constants.SOCCER:
            desc = match.find('description').text
            match_info = _parse_match_info(desc, soccer=True)
        else:
            desc = match.find('title').text
            match_info = _parse_match_info(desc)
            match_info['match_time'] = match.find('description').text

        match_info['match_date'] = match.find('pubDate').text
        match_info['match_link'] = match.find('guid').text

        matches.append(Match(sport, match_info))

    return matches
1118130
def dataframe(self):
        
        if self._points_scored is None and self._points_allowed is None:
            return None
        fields_to_include = {
            'boxscore_index': self.boxscore_index,
            'date': self.date,
            'datetime': self.datetime,
            'day': self.day,
            'extra_points_attempted': self.extra_points_attempted,
            'extra_points_made': self.extra_points_made,
            'field_goals_attempted': self.field_goals_attempted,
            'field_goals_made': self.field_goals_made,
            'fourth_down_attempts': self.fourth_down_attempts,
            'fourth_down_conversions': self.fourth_down_conversions,
            'interceptions': self.interceptions,
            'location': self.location,
            'opponent_abbr': self.opponent_abbr,
            'opponent_name': self.opponent_name,
            'overtime': self.overtime,
            'pass_attempts': self.pass_attempts,
            'pass_completion_rate': self.pass_completion_rate,
            'pass_completions': self.pass_completions,
            'pass_touchdowns': self.pass_touchdowns,
            'pass_yards': self.pass_yards,
            'pass_yards_per_attempt': self.pass_yards_per_attempt,
            'points_allowed': self.points_allowed,
            'points_scored': self.points_scored,
            'punt_yards': self.punt_yards,
            'punts': self.punts,
            'quarterback_rating': self.quarterback_rating,
            'result': self.result,
            'rush_attempts': self.rush_attempts,
            'rush_touchdowns': self.rush_touchdowns,
            'rush_yards': self.rush_yards,
            'rush_yards_per_attempt': self.rush_yards_per_attempt,
            'third_down_attempts': self.third_down_attempts,
            'third_down_conversions': self.third_down_conversions,
            'time_of_possession': self.time_of_possession,
            'times_sacked': self.times_sacked,
            'type': self.type,
            'week': self.week,
            'yards_lost_from_sacks': self.yards_lost_from_sacks
        }
        return pd.DataFrame([fields_to_include], index=[self._boxscore])