Inning Events.
        :param soup: Beautifulsoup object
        :param inning_number: Inning Number
        :param inning_id: Inning Id(0:home, 1:away)
        :param hit_location: Hitlocation data(dict)
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']
1159399
def parse_stats(self, soup):
    
    stats = {}
    for row in soup.children:
      try:
        key = row.name.replace(u'user_', u'')
        if key == u'id':
          stats[key] = int(row.text)
        elif key == u'name':
          stats[key] = row.text
        elif key == self.verb + u'ing':
          try:
            stats[key] = int(row.text)
          except ValueError:
            stats[key] = 0
        elif key == u'completed':
          try:
            stats[key] = int(row.text)
          except ValueError:
            stats[key] = 0
        elif key == u'onhold':
          try:
            stats['on_hold'] = int(row.text)
          except ValueError:
            stats[key] = 0
        elif key == u'dropped':
          try:
            stats[key] = int(row.text)
          except ValueError:
            stats[key] = 0
        elif key == u'planto' + self.verb:
          try:
            stats[u'plan_to_' + self.verb] = int(row.text)
          except ValueError:
            stats[key] = 0
        # for some reason, MAL doesn't substitute 'read' in for manga for the verb here
        elif key == u'days_spent_watching':
          try:
            stats[u'days_spent'] = decimal.Decimal(row.text)
          except decimal.InvalidOperation:
            stats[key] = decimal.Decimal(0)
      except:
        if not self.session.suppress_parse_exceptions:
          raise
    return stats
234035
def scrape(cls, start, end, output):
        
        # Logger setting
        logging.basicConfig(
            level=logging.INFO,
            format="time:%(asctime)s.%(msecs)03d" + "\tmessage:%(message)s",
            datefmt="%Y-%m-%d %H:%M:%S"
        )

        # validate
        for param_day in ({'name': 'Start Day', 'value': start}, {'name': 'End Day', 'value': end}):
            try:
                cls._validate_datetime(param_day['value'])
            except (validators.Invalid, MlbAmException) as e:
                raise MlbAmException('{msg} a {name}.'.format(name=param_day['name'], msg=e.msg))
        cls._validate_datetime_from_to(start, end)

        # Download
        logging.info('->- MLBAM dataset download start')
        mlb = MlbAm(os.path.dirname(os.path.abspath(__file__)), output, cls._days(start, end))
        mlb.download()
        logging.info('-<- MLBAM dataset download end')
935635
def get_atbats
      atbats = []
      innings = get_innings
      innings.each do |inning|
        inning.top_atbats.each do |atbat|
          atbats << atbat
        end
        inning.bottom_atbats.each do |atbat|
          atbats << atbat
        end
      end
      atbats
    end
700545
def init(element)
    	@xml_doc = element
      self.away_team_runs = element.attributes["away_team_runs"]
      self.away_team_hits = element.attributes["away_team_hits"]
      self.away_team_errors = element.attributes["away_team_errors"]
      
      self.home_team_runs = element.attributes["home_team_runs"]
      self.home_team_hits = element.attributes["home_team_hits"]
      self.home_team_errors = element.attributes["home_team_errors"]
    
      # Set score by innings
      set_innings 
    end
607459
def batting_stats_range(start_dt=None, end_dt=None):
    
    # make sure date inputs are valid
    start_dt, end_dt = sanitize_input(start_dt, end_dt)
    if datetime.datetime.strptime(start_dt, "%Y-%m-%d").year < 2008:
        raise ValueError("Year must be 2008 or later")
    if datetime.datetime.strptime(end_dt, "%Y-%m-%d").year < 2008:
        raise ValueError("Year must be 2008 or later")
    # retrieve html from baseball reference
    soup = get_soup(start_dt, end_dt)
    table = get_table(soup)
    table = table.dropna(how='all')  # drop if all columns are NA
    # scraped data is initially in string format.
    # convert the necessary columns to numeric.
    for column in ['Age', '#days', 'G', 'PA', 'AB', 'R', 'H', '2B', '3B',
                    'HR', 'RBI', 'BB', 'IBB', 'SO', 'HBP', 'SH', 'SF', 'GDP',
                    'SB', 'CS', 'BA', 'OBP', 'SLG', 'OPS']:
        #table[column] = table[column].astype('float')
        table[column] = pd.to_numeric(table[column])
        #table['column'] = table['column'].convert_objects(convert_numeric=True)
    table = table.drop('', 1)
    return table
971329
def start_active_players_path(page):
    
    soup = BeautifulSoup(page)
    try:
        return soup.find('a', href=True, text='Start Active Players')['href']
    except:
        return None
1300035
def standings(date=datetime.now()):
    
    data = mlbgame.info.standings(date)
    return mlbgame.info.Standings(data)
753967
def team_id(team, org)
      /^\d+$/.match(team.to_s) ? team : team_id_by_slug(team, org)
    end
1288281
def live_feed(game_id, timecode: nil)
      MLBStatsAPI::LiveFeed.new(
        self,
        get("/game/#{game_id}/feed/live", version: '1.1', timecode: timecode)
      )
    end
85823
def get_all_appearances(year)
      if !@appearances
        @appearances = []
        all_appearances = []
        games = get_games_for_season(year)    
        games.each do |game|
          @team_abbrev == game.home_team_abbrev ? status = 'home' : status = 'away'
          if @position == 'P'
            all_appearances.push *(game.get_pitchers(status))
          else
            all_appearances.push *(game.get_batters(status))
          end
        end
        # now go through all appearances to find those for this player
        all_appearances.each do |appearance|
          if appearance.pid == @pid
           @appearances << appearance
          end
        end
      end
      @appearances
    end
253463
def event_cd(cls, event_tx, ab_des):
        
        _event_tx = event_tx.lower()
        _ab_des = ab_des.lower()
        # Generic out(event_cd:2)
        if _event_tx in cls.EVENT_02_GENERIC_OUT_FLYBALL:
            return 2
        elif _event_tx in cls.EVENT_02_GENERIC_OUT_LINEDRIVE:
            return 2
        elif _event_tx in cls.EVENT_02_GENERIC_OUT_POPUP:
            return 2
        elif _event_tx in cls.EVENT_02_GENERIC_OUT_GROUNDBALL:
            return 2
        elif _event_tx in cls.EVENT_02_GENERIC_OUT_OTHER:
            return 2
        # Strike out(event_cd:3)
        elif _event_tx in cls.EVENT_03_STRIKE_OUT:
            return 3
        # Walk(event_cd:14)
        elif _event_tx in cls.EVENT_14_WALK:
            return 14
        # Intent Walk(event_cd:15)
        elif _event_tx in cls.EVENT_15_INTENT_WALK:
            return 15
        # Hit By Pitch(event_cd:16)
        elif _event_tx in cls.EVENT_16_HIT_BY_PITCH:
            return 16
        # Interference(event_cd:17)
        elif _event_tx.lower().count('interference') > 0:
            return 17
        # Error(event_cd:18)
        elif _event_tx[-5:] == 'error':
            return 18
        # Fielder's choice(event_cd:19)
        elif _event_tx in cls.EVENT_19_FIELDERS_CHOICE:
            return 19
        # Single(event_cd:20)
        elif _event_tx in cls.EVENT_20_SINGLE:
            return 20
        # 2B(event_cd:21)
        elif _event_tx in cls.EVENT_21_DOUBLE:
            return 21
        # 3B(event_cd:22)
        elif _event_tx in cls.EVENT_22_TRIPLE:
            return 22
        # HR(event_cd:22)
        elif _event_tx in cls.EVENT_23_HOME_RUN:
            return 23
        # Runner Out
        elif _event_tx == 'runner out':
            # Caught stealing(event_cd:6)
            if _ab_des.count("caught stealing") > 0:
                return 6
            # Picks off(event_cd:6)
            elif _ab_des.count("picks off") > 0:
                return 8
            # Unknown event(event_cd:0)
            else:
                return 0
        # Unknown event(event_cd:0)
        else:
            return 0
1079972
def ball_count(cls, ball_tally, strike_tally, pitch_res):
        
        b, s = ball_tally, strike_tally
        if pitch_res == "B":
            if ball_tally < 4:
                b += 1
        elif pitch_res == "S" or pitch_res == "C" or pitch_res == "X":
            if strike_tally < 3:
                s += 1
        elif pitch_res == "F":
            if strike_tally < 2:
                s += 1
        return b, s
1213633
def download_all_for_game(gid)
      download_xml_for_game(gid)
      download_batters_for_game(gid)
      download_inning_for_game(gid)
      download_media_for_game(gid)
      download_notification_for_game(gid)
      download_onbase_for_game(gid)
      download_pitchers_for_game(gid)
    end
1036759
def batting_stats_bref(season=None):
    
    if season is None:
        season = datetime.datetime.today().strftime("%Y")
    season = str(season)
    start_dt = season + '-03-01' #opening day is always late march or early april
    end_dt = season + '-11-01' #season is definitely over by November
    return(batting_stats_range(start_dt, end_dt))
1027405
def players(game_id):
    """"""
    # get data
    data = mlbgame.data.get_players(game_id)
    # parse data
    parsed = etree.parse(data)
    root = parsed.getroot()

    output = {}
    output['game_id'] = game_id

    # get player/coach data
    for team in root.findall('team'):
        type = team.attrib['type'] + "_team"
        # the type is either home_team or away_team
        output[type] = {}
        output[type]['players'] = []
        output[type]['coaches'] = []

        for p in team.findall('player'):
            player = {}
            for key in p.keys():
                player[key] = p.get(key)
            output[type]['players'].append(player)

        for c in team.findall('coach'):
            coach = {}
            for key in c.keys():
                coach[key] = c.get(key)
            output[type]['coaches'].append(coach)

    # get umpire data
    output['umpires'] = []
    for u in root.find('umpires').findall('umpire'):
        umpire = {}
        for key in u.keys():
            umpire[key] = u.get(key)
        output['umpires'].append(umpire)

    return output
808359
def init(element)
        self.pid = element.attributes['id']
        self.batter_name = element.attributes['name']
        self.pos = element.attributes['pos']
        self.bo = element.attributes['bo']
        self.ab = element.attributes['ab']
        self.po = element.attributes['po']
        self.r = element.attributes['r']
        self.bb = element.attributes['bb']
        self.a = element.attributes['a']
        self.t = element.attributes['t']
        self.sf = element.attributes['sf']
        self.h = element.attributes['h']
        self.e = element.attributes['e']
        self.d = element.attributes['d']
        self.hbp = element.attributes['hbp']
        self.so = element.attributes['so']
        self.hr = element.attributes['hr']
        self.rbi = element.attributes['rbi']
        self.lob = element.attributes['lob']
        self.sb = element.attributes['sb']
        self.avg = element.attributes['avg']  # season avg
        self.fldg = element.attributes['fldg']
        self.s_hr = element.attributes['s_hr']
        self.s_rbi = element.attributes['s_rbi']
      end