INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Command handler for the metrics command.
def handle(self, *args, **kwargs): """ Command handler for the "metrics" command. """ frequency = kwargs['frequency'] frequencies = settings.STATISTIC_FREQUENCY_ALL if frequency == 'a' else (frequency.split(',') if ',' in frequency else [frequency]) if kwargs['list']: ...
Returns the GET array s contents for the specified variable.
def get_GET_array(request, var_name, fail_silently=True): """ Returns the GET array's contents for the specified variable. """ vals = request.GET.getlist(var_name) if not vals: if fail_silently: return [] else: raise Exception, _("No array called '%(varname)s...
Tries to extract a boolean variable from the specified request.
def get_GET_bool(request, var_name, default=True): """ Tries to extract a boolean variable from the specified request. """ val = request.GET.get(var_name, default) if isinstance(val, str) or isinstance(val, unicode): val = True if val[0] == 't' else False return val
Gets the next colour in the Geckoboard colour list.
def get_next_colour(): """ Gets the next colour in the Geckoboard colour list. """ colour = settings.GECKOBOARD_COLOURS[get_next_colour.cur_colour] get_next_colour.cur_colour += 1 if get_next_colour.cur_colour >= len(settings.GECKOBOARD_COLOURS): get_next_colour.cur_colour = 0 ret...
Returns the default GET parameters for a particular Geckoboard view request.
def get_gecko_params(request, uid=None, days_back=0, cumulative=True, frequency=settings.STATISTIC_FREQUENCY_DAILY, min_val=0, max_val=100, chart_type='standard', percentage='show', sort=False): """ Returns the default GET parameters for a particular Geckoboard view request. """ return { ...
Returns a number widget for the specified metric s cumulative total.
def geckoboard_number_widget(request): """ Returns a number widget for the specified metric's cumulative total. """ params = get_gecko_params(request, days_back=7) metric = Metric.objects.get(uid=params['uid']) try: latest_stat = metric.statistics.filter(frequency=params['frequency']).o...
Searches the GET variables for metric UIDs and displays them in a RAG widget.
def geckoboard_rag_widget(request): """ Searches the GET variables for metric UIDs, and displays them in a RAG widget. """ params = get_gecko_params(request) print params['uids'] max_date = datetime.now()-timedelta(days=params['days_back']) metrics = Metric.objects.filter(uid__in=param...
Shows a pie chart of the metrics in the uids [] GET variable array.
def geckoboard_pie_chart(request): """ Shows a pie chart of the metrics in the uids[] GET variable array. """ params = get_gecko_params(request, cumulative=True) from_date = datetime.now()-timedelta(days=params['days_back']) metrics = Metric.objects.filter(uid__in=params['uids']) results =...
Returns the data for a line chart for the specified metric.
def geckoboard_line_chart(request): """ Returns the data for a line chart for the specified metric. """ params = get_gecko_params(request, cumulative=False, days_back=7) metric = Metric.objects.get(uid=params['uid']) start_date = datetime.now()-timedelta(days=params['days_back']) stats = [...
Returns a Geck - o - Meter control for the specified metric.
def geckoboard_geckometer(request): """ Returns a Geck-o-Meter control for the specified metric. """ params = get_gecko_params(request, cumulative=True) metric = Metric.objects.get(uid=params['uid']) return (metric.latest_count(frequency=params['frequency'], count=not params['cumulative'], ...
Returns a funnel chart for the metrics specified in the GET variables.
def geckoboard_funnel(request, frequency=settings.STATISTIC_FREQUENCY_DAILY): """ Returns a funnel chart for the metrics specified in the GET variables. """ # get all the parameters for this function params = get_gecko_params(request, cumulative=True) metrics = Metric.objects.filter(uid__in=par...
Returns all of the active statistics for the gadgets currently registered.
def get_active_stats(self): """ Returns all of the active statistics for the gadgets currently registered. """ stats = [] for gadget in self._registry.values(): for s in gadget.stats: if s not in stats: stats.append(s) retur...
Registers a gadget object. If a gadget is already registered this will raise AlreadyRegistered.
def register(self, gadget): """ Registers a gadget object. If a gadget is already registered, this will raise AlreadyRegistered. """ if gadget in self._registry: raise AlreadyRegistered else: self._registry.append(gadget)
Unregisters the specified gadget ( s ) if it/ they has/ have already been registered. gadgets can be a single class or a tuple/ list of classes to unregister.
def unregister(self, gadgets): """ Unregisters the specified gadget(s) if it/they has/have already been registered. "gadgets" can be a single class or a tuple/list of classes to unregister. """ gadgets = maintenance.ensure_list(gadgets) for gadget in gadgets: ...
Get the context for this view.
def get_context_data(self, **kwargs): """ Get the context for this view. """ #max_columns, max_rows = self.get_max_dimension() context = { 'gadgets': self._registry, 'columns': self.columns, 'rows': self.rows, 'column_ratio': 100 - ...
Print error and stop command
def error(self, message, code=1): """ Print error and stop command """ print >>sys.stderr, message sys.exit(code)
TODO: Need to validate model name has 2x. chars
def get_model(self, model_name): """ TODO: Need to validate model name has 2x '.' chars """ klass = None try: module_name, class_name = model_name.rsplit('.', 1) mod = __import__(module_name, fromlist=[class_name]) klass = getattr(mod, class_na...
Specific server side errors use: - 32000 to - 32099 reserved for implementation - defined server - errors
def custom(self, code, message): """ Specific server side errors use: -32000 to -32099 reserved for implementation-defined server-errors """ if -32000 < code or -32099 > code: code = -32603 message = 'Internal error' return JResponse(jsonrpc={ ...
Get/ decode/ validate json from request
def decode(request): """ Get/decode/validate json from request """ try: data = yield from request.json(loader=json.loads) except Exception as err: raise ParseError(err) try: validate(data, REQ_JSONRPC20) except ValidationError as err: raise InvalidRequest(err) ex...
Validation data by specific validictory configuration
def valid(schema=None): """ Validation data by specific validictory configuration """ def dec(fun): @wraps(fun) def d_func(self, ctx, data, *a, **kw): try: validate(data['params'], schema) except ValidationError as err: ...
Run service
def __run(self, ctx): """ Run service """ try: data = yield from decode(ctx) except ParseError: return JError().parse() except InvalidRequest: return JError().request() except InternalError: return JError().internal() try: ...
Python 3 input ()/ Python 2 raw_input ()
def string_input(prompt=''): """Python 3 input()/Python 2 raw_input()""" v = sys.version[0] if v == '3': return input(prompt) else: return raw_input(prompt)
Get input from a list of choices ( q to quit )
def choice_input(options=[], prompt='Press ENTER to continue.', showopts=True, qopt=False): """Get input from a list of choices (q to quit)""" choice = None if showopts: prompt = prompt + ' ' + str(options) if qopt: prompt = prompt + ' (q to quit)' while not choice: ...
Get a multi - line string as input
def long_input(prompt='Multi-line input\n' + \ 'Enter EOF on a blank line to end ' + \ '(ctrl-D in *nix, ctrl-Z in windows)', maxlines = None, maxlength = None): """Get a multi-line string as input""" lines = [] print(prompt) lnum = 1 try: while True: ...
Get a list of strings as input
def list_input(prompt='List input - enter each item on a seperate line\n' + \ 'Enter EOF on a blank line to end ' + \ '(ctrl-D in *nix, ctrl-Z in windows)', maxitems=None, maxlength=None): """Get a list of strings as input""" lines = [] print(prompt) inum = 1 try: ...
Get an output file name as input
def outfile_input(extension=None): """Get an output file name as input""" fileok = False while not fileok: filename = string_input('File name? ') if extension: if not filename.endswith(extension): if extension.startswith('.'): filenam...
Returns the roster table for the given year.
def roster(self, year): """Returns the roster table for the given year. :year: The year for which we want the roster; defaults to current year. :returns: A DataFrame containing roster information for that year. """ doc = self.get_year_doc(year) table = doc('table#roster'...
Gets schedule information for a team - season.
def schedule(self, year): """Gets schedule information for a team-season. :year: The year for which we want the schedule. :returns: DataFrame of schedule information. """ doc = self.get_year_doc('{}_games'.format(year)) table = doc('table#games') df = sportsref.u...
Returns the date of the game. See Python datetime. date documentation for more.: returns: A datetime. date object with year month and day attributes.
def date(self): """Returns the date of the game. See Python datetime.date documentation for more. :returns: A datetime.date object with year, month, and day attributes. """ match = re.match(r'(\d{4})(\d{2})(\d{2})', self.boxscore_id) year, month, day = map(int, match.grou...
Returns the day of the week on which the game occurred.: returns: String representation of the day of the week for the game.
def weekday(self): """Returns the day of the week on which the game occurred. :returns: String representation of the day of the week for the game. """ days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] date = self.date() ...
Returns home team ID.: returns: 3 - character string representing home team s ID.
def home(self): """Returns home team ID. :returns: 3-character string representing home team's ID. """ doc = self.get_doc() table = doc('table.linescore') relURL = table('tr').eq(2)('a').eq(2).attr['href'] home = sportsref.utils.rel_url_to_id(relURL) retur...
Returns score of the home team.: returns: int of the home score.
def home_score(self): """Returns score of the home team. :returns: int of the home score. """ doc = self.get_doc() table = doc('table.linescore') home_score = table('tr').eq(2)('td')[-1].text_content() return int(home_score)
Returns score of the away team.: returns: int of the away score.
def away_score(self): """Returns score of the away team. :returns: int of the away score. """ doc = self.get_doc() table = doc('table.linescore') away_score = table('tr').eq(1)('td')[-1].text_content() return int(away_score)
Returns the team ID of the winning team. Returns NaN if a tie.
def winner(self): """Returns the team ID of the winning team. Returns NaN if a tie.""" hmScore = self.home_score() awScore = self.away_score() if hmScore > awScore: return self.home() elif hmScore < awScore: return self.away() else: ret...
Returns the week in which this game took place. 18 is WC round 19 is Div round 20 is CC round 21 is SB.: returns: Integer from 1 to 21.
def week(self): """Returns the week in which this game took place. 18 is WC round, 19 is Div round, 20 is CC round, 21 is SB. :returns: Integer from 1 to 21. """ doc = self.get_doc() raw = doc('div#div_other_scores h2 a').attr['href'] match = re.match( ...
Returns the year ID of the season in which this game took place. Useful for week 17 January games.
def season(self): """ Returns the year ID of the season in which this game took place. Useful for week 17 January games. :returns: An int representing the year of the season. """ date = self.date() return date.year - 1 if date.month <= 3 else date.year
Returns a DataFrame where each row is an entry in the starters table from PFR.
def starters(self): """Returns a DataFrame where each row is an entry in the starters table from PFR. The columns are: * player_id - the PFR player ID for the player (note that this column is not necessarily all unique; that is, one player can be a starter in multiple po...
The playing surface on which the game was played.
def surface(self): """The playing surface on which the game was played. :returns: string representing the type of surface. Returns np.nan if not avaiable. """ doc = self.get_doc() table = doc('table#game_info') giTable = sportsref.utils.parse_info_table(table) ...
Returns the over/ under for the game as a float or np. nan if not available.
def over_under(self): """ Returns the over/under for the game as a float, or np.nan if not available. """ doc = self.get_doc() table = doc('table#game_info') giTable = sportsref.utils.parse_info_table(table) if 'over_under' in giTable: ou = giT...
Gets information relating to the opening coin toss.
def coin_toss(self): """Gets information relating to the opening coin toss. Keys are: * wonToss - contains the ID of the team that won the toss * deferred - bool whether the team that won the toss deferred it :returns: Dictionary of coin toss-related info. """ d...
Returns a dictionary of weather - related info.
def weather(self): """Returns a dictionary of weather-related info. Keys of the returned dict: * temp * windChill * relHumidity * windMPH :returns: Dict of weather data. """ doc = self.get_doc() table = doc('table#game_info') giTa...
Returns a dataframe of the play - by - play data from the game.
def pbp(self): """Returns a dataframe of the play-by-play data from the game. Order of function calls: 1. parse_table on the play-by-play table 2. expand_details - calls parse_play_details & _clean_features 3. _add_team_columns 4. various ...
Gets a dictionary of ref positions and the ref IDs of the refs for that game.
def ref_info(self): """Gets a dictionary of ref positions and the ref IDs of the refs for that game. :returns: A dictionary of ref positions and IDs. """ doc = self.get_doc() table = doc('table#officials') return sportsref.utils.parse_info_table(table)
Gets the stats for offense defense returning and kicking of individual players in the game.: returns: A DataFrame containing individual player stats.
def player_stats(self): """Gets the stats for offense, defense, returning, and kicking of individual players in the game. :returns: A DataFrame containing individual player stats. """ doc = self.get_doc() tableIDs = ('player_offense', 'player_defense', 'returns', 'kicking...
Gets the snap counts for both teams players and returns them in a DataFrame. Note: only goes back to 2012.
def snap_counts(self): """Gets the snap counts for both teams' players and returns them in a DataFrame. Note: only goes back to 2012. :returns: DataFrame of snap count data """ # TODO: combine duplicate players, see 201312150mia - ThomDa03 doc = self.get_doc() ta...
Returns PyQuery object for the main season URL.: returns: PyQuery object.
def get_main_doc(self): """Returns PyQuery object for the main season URL. :returns: PyQuery object. """ url = (sportsref.nba.BASE_URL + '/leagues/NBA_{}.html'.format(self.yr)) return pq(sportsref.utils.get_html(url))
Returns PyQuery object for a given subpage URL.: subpage: The subpage of the season e. g. per_game.: returns: PyQuery object.
def get_sub_doc(self, subpage): """Returns PyQuery object for a given subpage URL. :subpage: The subpage of the season, e.g. 'per_game'. :returns: PyQuery object. """ html = sportsref.utils.get_html(self._subpage_url(subpage)) return pq(html)
Returns a list of the team IDs for the given year.: returns: List of team IDs.
def get_team_ids(self): """Returns a list of the team IDs for the given year. :returns: List of team IDs. """ df = self.team_stats_per_game() if not df.empty: return df.index.tolist() else: print('ERROR: no teams found') return []
Mapping from 3 - letter team IDs to full team names.: returns: Dictionary with team IDs as keys and full team strings as values.
def team_ids_to_names(self): """Mapping from 3-letter team IDs to full team names. :returns: Dictionary with team IDs as keys and full team strings as values. """ doc = self.get_main_doc() table = doc('table#team-stats-per_game') flattened = sportsref.utils.parse_...
Mapping from full team names to 3 - letter team IDs.: returns: Dictionary with tean names as keys and team IDs as values.
def team_names_to_ids(self): """Mapping from full team names to 3-letter team IDs. :returns: Dictionary with tean names as keys and team IDs as values. """ d = self.team_ids_to_names() return {v: k for k, v in d.items()}
Returns a list of BoxScore IDs for every game in the season. Only needs to handle R or P options because decorator handles B.
def schedule(self, kind='R'): """Returns a list of BoxScore IDs for every game in the season. Only needs to handle 'R' or 'P' options because decorator handles 'B'. :param kind: 'R' for regular season, 'P' for playoffs, 'B' for both. Defaults to 'R'. :returns: DataFrame of s...
Returns a DataFrame containing standings information.
def standings(self): """Returns a DataFrame containing standings information.""" doc = self.get_sub_doc('standings') east_table = doc('table#divs_standings_E') east_df = pd.DataFrame(sportsref.utils.parse_table(east_table)) east_df.sort_values('wins', ascending=False, inplace=Tr...
Helper function for stats tables on season pages. Returns a DataFrame.
def _get_team_stats_table(self, selector): """Helper function for stats tables on season pages. Returns a DataFrame.""" doc = self.get_main_doc() table = doc(selector) df = sportsref.utils.parse_table(table) df.set_index('team_id', inplace=True) return df
Helper function for player season stats.
def _get_player_stats_table(self, identifier): """Helper function for player season stats. :identifier: string identifying the type of stat, e.g. 'per_game'. :returns: A DataFrame of stats. """ doc = self.get_sub_doc(identifier) table = doc('table#{}_stats'.format(identi...
Returns a DataFrame containing information about ROY voting.
def roy_voting(self): """Returns a DataFrame containing information about ROY voting.""" url = '{}/awards/awards_{}.html'.format(sportsref.nba.BASE_URL, self.yr) doc = pq(sportsref.utils.get_html(url)) table = doc('table#roy') df = sportsref.utils.parse_table(table) retur...
Returns the linescore for the game as a DataFrame.
def linescore(self): """Returns the linescore for the game as a DataFrame.""" doc = self.get_main_doc() table = doc('table#line_score') columns = [th.text() for th in table('tr.thead').items('th')] columns[0] = 'team_id' data = [ [sportsref.utils.flatten_lin...
Returns the year ID of the season in which this game took place.
def season(self): """ Returns the year ID of the season in which this game took place. :returns: An int representing the year of the season. """ d = self.date() if d.month >= 9: return d.year + 1 else: return d.year
Returns a DataFrame of player stats from the game ( either basic or advanced depending on the argument.
def _get_player_stats(self, table_id_fmt): """Returns a DataFrame of player stats from the game (either basic or advanced, depending on the argument. :param table_id_fmt: Format string for str.format with a placeholder for the team ID (e.g. 'box_{}_basic') :returns: DataFram...
Returns a dataframe of the play - by - play data from the game.
def pbp(self, dense_lineups=False, sparse_lineups=False): """Returns a dataframe of the play-by-play data from the game. :param dense_lineups: If True, adds 10 columns containing the names of the players on the court. Defaults to False. :param sparse_lineups: If True, adds binary co...
Decorator that switches to given directory before executing function and then returning to orignal directory.
def switch_to_dir(dirPath): """ Decorator that switches to given directory before executing function, and then returning to orignal directory. """ def decorator(func): @funcutils.wraps(func) def wrapper(*args, **kwargs): orig_cwd = os.getcwd() os.chdir(dirPat...
Caches the HTML returned by the specified function func. Caches it in the user cache determined by the appdirs package.
def cache(func): """Caches the HTML returned by the specified function `func`. Caches it in the user cache determined by the appdirs package. """ CACHE_DIR = appdirs.user_cache_dir('sportsref', getpass.getuser()) if not os.path.isdir(CACHE_DIR): os.makedirs(CACHE_DIR) @funcutils.wraps(...
Returns a unique identifier for a class instantiation.
def get_class_instance_key(cls, args, kwargs): """ Returns a unique identifier for a class instantiation. """ l = [id(cls)] for arg in args: l.append(id(arg)) l.extend((k, id(v)) for k, v in kwargs.items()) return tuple(sorted(l))
A decorator for memoizing functions.
def memoize(fun): """A decorator for memoizing functions. Only works on functions that take simple arguments - arguments that take list-like or dict-like arguments will not be memoized, and this function will raise a TypeError. """ @funcutils.wraps(fun) def wrapper(*args, **kwargs): ...
Returns the age of the player on a given date.
def age(self, year, month=2, day=1): """Returns the age of the player on a given date. :year: int representing the year. :month: int representing the month (1-12). :day: int representing the day within the month (1-31). :returns: Age in years as a float. """ doc ...
Returns the player s height ( in inches ).: returns: An int representing a player s height in inches.
def height(self): """Returns the player's height (in inches). :returns: An int representing a player's height in inches. """ doc = self.get_main_doc() raw = doc('span[itemprop="height"]').text() try: feet, inches = map(int, raw.split('-')) return f...
Returns the player s weight ( in pounds ).: returns: An int representing a player s weight in pounds.
def weight(self): """Returns the player's weight (in pounds). :returns: An int representing a player's weight in pounds. """ doc = self.get_main_doc() raw = doc('span[itemprop="weight"]').text() try: weight = re.match(r'(\d+)lb', raw).group(1) retu...
Returns the player s handedness.: returns: L for left - handed R for right - handed.
def hand(self): """Returns the player's handedness. :returns: 'L' for left-handed, 'R' for right-handed. """ doc = self.get_main_doc() hand = re.search(r'Shoots:\s*(L|R)', doc.text()).group(1) return hand
Returns when in the draft the player was picked.: returns: TODO
def draft_pick(self): """Returns when in the draft the player was picked. :returns: TODO """ doc = self.get_main_doc() try: p_tags = doc('div#meta p') draft_p_tag = next(p for p in p_tags.items() if p.text().lower().startswith('draft')) draft_p...
Gets a stats table from the player page ; helper function that does the work for per - game per - 100 - poss etc. stats.
def _get_stats_table(self, table_id, kind='R', summary=False): """Gets a stats table from the player page; helper function that does the work for per-game, per-100-poss, etc. stats. :table_id: the ID of the HTML table. :kind: specifies regular season, playoffs, or both. One of 'R', 'P',...
Returns a DataFrame of per - game box score stats.
def stats_per_game(self, kind='R', summary=False): """Returns a DataFrame of per-game box score stats.""" return self._get_stats_table('per_game', kind=kind, summary=summary)
Returns a DataFrame of total box score statistics by season.
def stats_totals(self, kind='R', summary=False): """Returns a DataFrame of total box score statistics by season.""" return self._get_stats_table('totals', kind=kind, summary=summary)
Returns a DataFrame of per - 36 - minutes stats.
def stats_per36(self, kind='R', summary=False): """Returns a DataFrame of per-36-minutes stats.""" return self._get_stats_table('per_minute', kind=kind, summary=summary)
Returns a DataFrame of per - 100 - possession stats.
def stats_per100(self, kind='R', summary=False): """Returns a DataFrame of per-100-possession stats.""" return self._get_stats_table('per_poss', kind=kind, summary=summary)
Returns a DataFrame of advanced stats.
def stats_advanced(self, kind='R', summary=False): """Returns a DataFrame of advanced stats.""" return self._get_stats_table('advanced', kind=kind, summary=summary)
Returns a DataFrame of shooting stats.
def stats_shooting(self, kind='R', summary=False): """Returns a DataFrame of shooting stats.""" return self._get_stats_table('shooting', kind=kind, summary=summary)
Returns a DataFrame of play - by - play stats.
def stats_pbp(self, kind='R', summary=False): """Returns a DataFrame of play-by-play stats.""" return self._get_stats_table('advanced_pbp', kind=kind, summary=summary)
Returns a table of a player s basic game - by - game stats for a season.
def gamelog_basic(self, year, kind='R'): """Returns a table of a player's basic game-by-game stats for a season. :param year: The year representing the desired season. :param kind: specifies regular season, playoffs, or both. One of 'R', 'P', 'B'. Defaults to 'R'. :returns: ...
Parse play details from a play - by - play string describing a play.
def parse_play(boxscore_id, details, is_hm): """Parse play details from a play-by-play string describing a play. Assuming valid input, this function returns structured data in a dictionary describing the play. If the play detail string was invalid, this function returns None. :param boxscore_id: t...
Fixes up columns of the passed DataFrame such as casting T/ F columns to boolean and filling in NaNs for team and opp.
def clean_features(df): """Fixes up columns of the passed DataFrame, such as casting T/F columns to boolean and filling in NaNs for team and opp. :param df: DataFrame of play-by-play data. :returns: Dataframe with cleaned columns. """ df = pd.DataFrame(df) bool_vals = set([True, False, Non...
TODO: Docstring for clean_multigame_features.
def clean_multigame_features(df): """TODO: Docstring for clean_multigame_features. :df: TODO :returns: TODO """ df = pd.DataFrame(df) if df.index.value_counts().max() > 1: df.reset_index(drop=True, inplace=True) df = clean_features(df) # if it's many games in one DataFrame, ma...
TODO
def get_period_starters(df): """TODO """ def players_from_play(play): """Figures out what players are in the game based on the players mentioned in a play. Returns away and home players as two sets. :param play: A dictionary representing a parsed play. :returns: (aw_players...
TODO: Docstring for get_sparse_lineups.
def get_sparse_lineups(df): """TODO: Docstring for get_sparse_lineups. :param df: TODO :returns: TODO """ # get the lineup data using get_dense_lineups if necessary if (set(ALL_LINEUP_COLS) - set(df.columns)): lineup_df = get_dense_lineups(df) else: lineup_df = df[ALL_LINEU...
Returns a new DataFrame based on the one it is passed. Specifically it adds five columns for each team ( ten total ) where each column has the ID of a player on the court during the play.
def get_dense_lineups(df): """Returns a new DataFrame based on the one it is passed. Specifically, it adds five columns for each team (ten total), where each column has the ID of a player on the court during the play. This information is figured out sequentially from the game's substitution data in...
Docstring will be filled in by __init__. py
def GamePlayFinder(**kwargs): """ Docstring will be filled in by __init__.py """ querystring = _kwargs_to_qs(**kwargs) url = '{}?{}'.format(GPF_URL, querystring) # if verbose, print url if kwargs.get('verbose', False): print(url) html = utils.get_html(url) doc = pq(html) # pars...
Converts kwargs given to GPF to a querystring.
def _kwargs_to_qs(**kwargs): """Converts kwargs given to GPF to a querystring. :returns: the querystring. """ # start with defaults inpOptDef = inputs_options_defaults() opts = { name: dct['value'] for name, dct in inpOptDef.items() } # clean up keys and values for ...
Handles scraping options for play finder form.
def inputs_options_defaults(): """Handles scraping options for play finder form. :returns: {'name1': {'value': val, 'options': [opt1, ...] }, ... } """ # set time variables if os.path.isfile(GPF_CONSTANTS_FILENAME): modtime = int(os.path.getmtime(GPF_CONSTANTS_FILENAME)) curtime = ...
Please don t do this in production environments.
def get(self): ''' Please don't do this in production environments. ''' self.write("Memory Session Object Demo:") if "sv" in self.session: current_value = self.session["sv"] self.write("current sv value is %s, and system will delete this value.<br/>" % sel...
Expands the details column of the given dataframe and returns the resulting DataFrame.
def expand_details(df, detailCol='detail'): """Expands the details column of the given dataframe and returns the resulting DataFrame. :df: The input DataFrame. :detailCol: The detail column name. :returns: Returns DataFrame with new columns from pbp parsing. """ df = copy.deepcopy(df) d...
Parses play details from play - by - play string and returns structured data.
def parse_play_details(details): """Parses play details from play-by-play string and returns structured data. :details: detail string for play :returns: dictionary of play attributes """ # if input isn't a string, return None if not isinstance(details, basestring): return None ...
Cleans up the features collected in parse_play_details.
def _clean_features(struct): """Cleans up the features collected in parse_play_details. :struct: Pandas Series of features parsed from details string. :returns: the same dict, but with cleaner features (e.g., convert bools, ints, etc.) """ struct = dict(struct) # First, clean up play type b...
Converts a location string { Half } { YardLine } into a tuple of those values the second being an int.
def _loc_to_features(loc): """Converts a location string "{Half}, {YardLine}" into a tuple of those values, the second being an int. :l: The string from the play by play table representing location. :returns: A tuple that separates out the values, making them missing (np.nan) when necessary. "...
Function that adds team and opp columns to the features by iterating through the rows in order. A precondition is that the features dicts are in order in a continuous game sense and that all rows are from the same game.
def _add_team_columns(features): """Function that adds 'team' and 'opp' columns to the features by iterating through the rows in order. A precondition is that the features dicts are in order in a continuous game sense and that all rows are from the same game. :features: A DataFrame with each row repres...
Given a dict representing a play and the current team with the ball returns ( team opp ) where team is the team with the ball and opp is the team without the ball at the end of the play.
def _team_and_opp(struct, curTm=None, curOpp=None): """Given a dict representing a play and the current team with the ball, returns (team, opp) where team is the team with the ball and opp is the team without the ball at the end of the play. :struct: A Series/dict representing the play. :curTm: The...
Adds extra convenience features based on teams with and without possession with the precondition that the there are team and opp specified in row.
def _add_team_features(df): """Adds extra convenience features based on teams with and without possession, with the precondition that the there are 'team' and 'opp' specified in row. :df: A DataFrame representing a game's play-by-play data after _clean_features has been called and 'team' and 'o...
Helper function for player season stats.
def _get_player_stats_table(self, subpage, table_id): """Helper function for player season stats. :identifier: string identifying the type of stat, e.g. 'passing'. :returns: A DataFrame of stats. """ doc = self.get_sub_doc(subpage) table = doc('table#{}'.format(table_id)...
Gets the initial win probability of a game given its Vegas line.
def initialWinProb(line): """Gets the initial win probability of a game given its Vegas line. :line: The Vegas line from the home team's perspective (negative means home team is favored). :returns: A float in [0., 100.] that represents the win probability. """ line = float(line) probWin = 1...
Gets the career gamelog of the given player.: kind: One of R P or B ( for regular season playoffs or both ). Case - insensitive ; defaults to R.: year: The year for which the gamelog should be returned ; if None return entire career gamelog. Defaults to None.: returns: A DataFrame with the player s career gamelog.
def gamelog(self, year=None, kind='R'): """Gets the career gamelog of the given player. :kind: One of 'R', 'P', or 'B' (for regular season, playoffs, or both). Case-insensitive; defaults to 'R'. :year: The year for which the gamelog should be returned; if None, return entire care...
Gets yearly passing stats for the player.
def passing(self, kind='R'): """Gets yearly passing stats for the player. :kind: One of 'R', 'P', or 'B'. Case-insensitive; defaults to 'R'. :returns: Pandas DataFrame with passing stats. """ doc = self.get_doc() table = (doc('table#passing') if kind == 'R' else ...
Gets yearly rushing/ receiving stats for the player.
def rushing_and_receiving(self, kind='R'): """Gets yearly rushing/receiving stats for the player. :kind: One of 'R', 'P', or 'B'. Case-insensitive; defaults to 'R'. :returns: Pandas DataFrame with rushing/receiving stats. """ doc = self.get_doc() table = (doc('table#rush...
Returns a DataFrame of plays for a given year for a given play type ( like rushing receiving or passing ).
def _plays(self, year, play_type, expand_details): """Returns a DataFrame of plays for a given year for a given play type (like rushing, receiving, or passing). :year: The year for the season. :play_type: A type of play for which there are plays (as of this writing, either "pass...