INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Uses the given build config to find an existing matching build config. Build configs are a match if: - metadata. labels. git - repo - name AND metadata. labels. git - branch AND metadata. labels. git - full - repo are equal OR - metadata. labels. git - repo - name AND metadata. labels. git - branch are equal AND metada...
def _get_existing_build_config(self, build_config): """ Uses the given build config to find an existing matching build config. Build configs are a match if: - metadata.labels.git-repo-name AND metadata.labels.git-branch AND metadata.labels.git-full-repo are equal OR ...
Return ImageStream and ImageStreamTag name for base_image of build_request
def _get_image_stream_info_for_build_request(self, build_request): """Return ImageStream, and ImageStreamTag name for base_image of build_request If build_request is not auto instantiated, objects are not fetched and None, None is returned. """ image_stream = None image_...
Create a production build
def create_prod_build(self, *args, **kwargs): """ Create a production build :param git_uri: str, URI of git repository :param git_ref: str, reference to commit :param git_branch: str, branch name :param user: str, user name :param component: str, not used anymore...
Create a worker build
def create_worker_build(self, **kwargs): """ Create a worker build Pass through method to create_prod_build with the following modifications: - platform param is required - release param is required - arrangement_version param is required, which is us...
Create an orchestrator build
def create_orchestrator_build(self, **kwargs): """ Create an orchestrator build Pass through method to create_prod_build with the following modifications: - platforms param is required - arrangement_version param may be used to select which orchestr...
provide logs from build
def get_build_logs(self, build_id, follow=False, build_json=None, wait_if_missing=False, decode=False): """ provide logs from build NOTE: Since atomic-reactor 1.6.25, logs are always in UTF-8, so if asked to decode, we assume that is the encoding in use. Otherwise...
provide logs from orchestrator build
def get_orchestrator_build_logs(self, build_id, follow=False, wait_if_missing=False): """ provide logs from orchestrator build :param build_id: str :param follow: bool, fetch logs as they come? :param wait_if_missing: bool, if build doesn't exist, wait :return: generator...
Import image tags from a Docker registry into an ImageStream
def import_image(self, name, tags=None): """ Import image tags from a Docker registry into an ImageStream :return: bool, whether tags were imported """ stream_import_file = os.path.join(self.os_conf.get_build_json_store(), 'image_stream_...
Import image tags from specified container repository.
def import_image_tags(self, name, tags, repository, insecure=False): """Import image tags from specified container repository. :param name: str, name of ImageStream object :param tags: iterable, tags to be imported :param repository: str, remote location of container image ...
Ensures the tag is monitored in ImageStream
def ensure_image_stream_tag(self, stream, tag_name, scheduled=False, source_registry=None, organization=None, base_image=None): """Ensures the tag is monitored in ImageStream :param stream: dict, ImageStream object :param tag_name: str, name of tag to check, with...
Create an ImageStream object
def create_image_stream(self, name, docker_image_repository, insecure_registry=False): """ Create an ImageStream object Raises exception on error :param name: str, name of ImageStream :param docker_image_repository: str, pull spec for docker image ...
Find the filename extension for the docker save output which may or may not be compressed.
def get_compression_extension(self): """ Find the filename extension for the 'docker save' output, which may or may not be compressed. Raises OsbsValidationException if the extension cannot be determined due to a configuration error. :returns: str including leading dot,...
Create an ConfigMap object on the server
def create_config_map(self, name, data): """ Create an ConfigMap object on the server Raises exception on error :param name: str, name of configMap :param data: dict, dictionary of data to be stored :returns: ConfigMapResponse containing the ConfigMap with name and data...
Get a ConfigMap object from the server
def get_config_map(self, name): """ Get a ConfigMap object from the server Raises exception on error :param name: str, name of configMap to get from the server :returns: ConfigMapResponse containing the ConfigMap with the requested name """ response = self.os.ge...
Context manager to disable retries on requests: returns: OSBS object
def retries_disabled(self): """ Context manager to disable retries on requests :returns: OSBS object """ self.os.retries_enabled = False yield self.os.retries_enabled = True
Wipe the bolt database.
def wipe(self): """ Wipe the bolt database. Calling this after HoverPy has been instantiated is potentially dangerous. This function is mostly used internally for unit tests. """ try: if os.isfile(self._dbpath): os.remove(self._dbpath)...
Gets/ Sets the simulation data.
def simulation(self, data=None): """ Gets / Sets the simulation data. If no data is passed in, then this method acts as a getter. if data is passed in, then this method acts as a setter. Keyword arguments: data -- the simulation data you wish to set (default None) ...
Gets/ Sets the destination data.
def destination(self, name=""): """ Gets / Sets the destination data. """ if name: return self._session.put( self.__v2() + "/hoverfly/destination", data={"destination": name}).json() else: return self._session.get( ...
Gets/ Sets the mode.
def mode(self, mode=None): """ Gets / Sets the mode. If no mode is provided, then this method acts as a getter. Keyword arguments: mode -- this should either be 'capture' or 'simulate' (default None) """ if mode: logging.debug("SWITCHING TO %s" % mod...
Gets the metadata.
def metadata(self, delete=False): """ Gets the metadata. """ if delete: return self._session.delete(self.__v1() + "/metadata").json() else: return self._session.get(self.__v1() + "/metadata").json()
Gets/ Sets records.
def records(self, data=None): """ Gets / Sets records. """ if data: return self._session.post( self.__v1() + "/records", data=data).json() else: return self._session.get(self.__v1() + "/records").json()
Gets/ Sets the delays.
def delays(self, delays=[]): """ Gets / Sets the delays. """ if delays: return self._session.put( self.__v1() + "/delays", data=json.dumps(delays)).json() else: return self._session.get(self.__v1() + "/delays").json()
Adds delays.
def addDelay(self, urlPattern="", delay=0, httpMethod=None): """ Adds delays. """ print("addDelay is deprecated please use delays instead") delay = {"urlPattern": urlPattern, "delay": delay} if httpMethod: delay["httpMethod"] = httpMethod return self....
Set the required environment variables to enable the use of hoverfly as a proxy.
def __enableProxy(self): """ Set the required environment variables to enable the use of hoverfly as a proxy. """ os.environ[ "HTTP_PROXY"] = self.httpProxy() os.environ[ "HTTPS_PROXY"] = self.httpsProxy() os.environ["REQUESTS_CA_BUNDLE"] = os.pat...
HoverFly fails to launch if it s already running on the same ports. So we have to keep track of them using temp files with the proxy port and admin port containing the processe s PID.
def __writepid(self, pid): """ HoverFly fails to launch if it's already running on the same ports. So we have to keep track of them using temp files with the proxy port and admin port, containing the processe's PID. """ import tempfile d = tempfile.gettem...
Remove the PID file on shutdown unfortunately this may not get called if not given the time to shut down.
def __rmpid(self): """ Remove the PID file on shutdown, unfortunately this may not get called if not given the time to shut down. """ import tempfile d = tempfile.gettempdir() name = os.path.join(d, "hoverpy.%i.%i"%(self._proxyPort, self._adminPort)) ...
If the HoverFly process on these given ports did not shut down correctly then kill the pid before launching a new instance. todo: this will kill existing HoverFly processes on those ports indiscriminately
def __kill_if_not_shut_properly(self): """ If the HoverFly process on these given ports did not shut down correctly, then kill the pid before launching a new instance. todo: this will kill existing HoverFly processes on those ports indiscriminately """ imp...
Start the hoverfly process.
def __start(self): """ Start the hoverfly process. This function waits until it can make contact with the hoverfly API before returning. """ logging.debug("starting %i" % id(self)) self.__kill_if_not_shut_properly() self.FNULL = open(os.devnull, 'w') ...
Stop the hoverfly process.
def __stop(self): """ Stop the hoverfly process. """ if logging: logging.debug("stopping") self._process.terminate() # communicate means we wait until the process # was actually terminated, this removes some # warnings in python3 self._...
Internal method. Turns arguments into flags.
def __flags(self): """ Internal method. Turns arguments into flags. """ flags = [] if self._capture: flags.append("-capture") if self._spy: flags.append("-spy") if self._dbpath: flags += ["-db-path", self._dbpath] fl...
Extract tabular data as |TableData| instances from a JSON file. |load_source_desc_file|
def load(self): """ Extract tabular data as |TableData| instances from a JSON file. |load_source_desc_file| This method can be loading four types of JSON formats: **(1)** Single table data in a file: .. code-block:: json :caption: Acceptable JSON Sc...
Extract tabular data as |TableData| instances from a MediaWiki file. |load_source_desc_file|
def load(self): """ Extract tabular data as |TableData| instances from a MediaWiki file. |load_source_desc_file| :return: Loaded table data iterator. |load_table_name_desc| =================== ============================================== ...
Extract tabular data as |TableData| instances from a MediaWiki text object. |load_source_desc_text|
def load(self): """ Extract tabular data as |TableData| instances from a MediaWiki text object. |load_source_desc_text| :return: Loaded table data iterator. |load_table_name_desc| =================== =========================================...
return dock json from existing build json
def get_dock_json(self): """ return dock json from existing build json """ env_json = self.build_json['spec']['strategy']['customStrategy']['env'] try: p = [env for env in env_json if env["name"] == "ATOMIC_REACTOR_PLUGINS"] except TypeError: raise RuntimeError("\...
Return the configuration for a plugin.
def dock_json_get_plugin_conf(self, plugin_type, plugin_name): """ Return the configuration for a plugin. Raises KeyError if there are no plugins of that type. Raises IndexError if the named plugin is not listed. """ match = [x for x in self.dock_json[plugin_type] if x.g...
if config contains plugin remove it
def remove_plugin(self, plugin_type, plugin_name): """ if config contains plugin, remove it """ for p in self.dock_json[plugin_type]: if p.get('name') == plugin_name: self.dock_json[plugin_type].remove(p) break
if config has plugin override it else add it
def add_plugin(self, plugin_type, plugin_name, args_dict): """ if config has plugin, override it, else add it """ plugin_modified = False for plugin in self.dock_json[plugin_type]: if plugin['name'] == plugin_name: plugin['args'] = args_dict ...
Check whether a plugin is configured.
def dock_json_has_plugin_conf(self, plugin_type, plugin_name): """ Check whether a plugin is configured. """ try: self.dock_json_get_plugin_conf(plugin_type, plugin_name) return True except (KeyError, IndexError): return False
Create a file loader from the file extension to loading file. Supported file extensions are as follows:
def create_from_path(self): """ Create a file loader from the file extension to loading file. Supported file extensions are as follows: ========================================= ===================================== Extension Loader ...
Create a file loader from a format name. Supported file formats are as follows:
def create_from_format_name(self, format_name): """ Create a file loader from a format name. Supported file formats are as follows: ========================== ====================================== Format name Loader =========================...
: return: Mappings of format - extension and loader class.: rtype: dict
def _get_extension_loader_mapping(self): """ :return: Mappings of format-extension and loader class. :rtype: dict """ loader_table = self._get_common_loader_mapping() loader_table.update( { "asp": HtmlTableTextLoader, "aspx": H...
: return: Mappings of format - name and loader class.: rtype: dict
def _get_format_name_loader_mapping(self): """ :return: Mappings of format-name and loader class. :rtype: dict """ loader_table = self._get_common_loader_mapping() loader_table.update( { "excel": ExcelTableFileLoader, "json_lin...
Find the image IDs the containers use.
def get_container_image_ids(self): """ Find the image IDs the containers use. :return: dict, image tag to docker ID """ statuses = graceful_chain_get(self.json, "status", "containerStatuses") if statuses is None: return {} def remove_prefix(image_id...
Find the reason a pod failed
def get_failure_reason(self): """ Find the reason a pod failed :return: dict, which will always have key 'reason': reason: brief reason for state containerID (if known): ID of container exitCode (if known): numeric exit code """ ...
Return an error message based on atomic - reactor s metadata
def get_error_message(self): """ Return an error message based on atomic-reactor's metadata """ error_reason = self.get_error_reason() if error_reason: error_message = error_reason.get('pod') or None if error_message: return "Error in pod: ...
Create a file loader from the file extension to loading file. Supported file extensions are as follows:
def create_from_path(self): """ Create a file loader from the file extension to loading file. Supported file extensions are as follows: ========================== ======================================= Extension Loader ====================...
Create a file loader from a format name. Supported file formats are as follows:
def create_from_format_name(self, format_name): """ Create a file loader from a format name. Supported file formats are as follows: ================ ====================================== Format name Loader ================ ===================...
: return: Mappings of format extension and loader class.: rtype: dict
def _get_extension_loader_mapping(self): """ :return: Mappings of format extension and loader class. :rtype: dict """ loader_table = self._get_common_loader_mapping() loader_table.update( { "htm": HtmlTableFileLoader, "md": Mar...
: return: Mappings of format name and loader class.: rtype: dict
def _get_format_name_loader_mapping(self): """ :return: Mappings of format name and loader class. :rtype: dict """ loader_table = self._get_common_loader_mapping() loader_table.update( { "excel": ExcelTableFileLoader, "json_lin...
Extract tabular data as |TableData| instances from an Excel file. |spreadsheet_load_desc|
def load(self): """ Extract tabular data as |TableData| instances from an Excel file. |spreadsheet_load_desc| :return: Loaded |TableData| iterator. |TableData| created for each sheet in the workbook. |load_table_name_desc| ===============...
Extract tabular data as |TableData| instances from a LTSV file. |load_source_desc_file|
def load(self): """ Extract tabular data as |TableData| instances from a LTSV file. |load_source_desc_file| :return: Loaded table data. |load_table_name_desc| =================== ======================================== Format specifier ...
Extract tabular data as |TableData| instances from a LTSV text object. |load_source_desc_text|
def load(self): """ Extract tabular data as |TableData| instances from a LTSV text object. |load_source_desc_text| :return: Loaded table data. |load_table_name_desc| =================== ======================================== Format spe...
Computes and returns dictionary containing home/ away by player shots and face - off totals: returns: dict of the form { home/ away: { all_keys: w_numeric_data } }
def totals(self): """ Computes and returns dictionary containing home/away by player, shots and face-off totals :returns: dict of the form ``{ 'home/away': { 'all_keys': w_numeric_data } }`` """ def agg(d): keys = ['g','a','p','pm','pn','pim','s','ab','ms','h...
Return the subset home and away players that satisfy the provided filter function.: param pl_filter: function that takes a by player dictionary and returns bool: returns: dict of the form { home/ away: { by_player_dict } }. See: py: func: home_players and: py: func: away_players
def filter_players(self, pl_filter): """ Return the subset home and away players that satisfy the provided filter function. :param pl_filter: function that takes a by player dictionary and returns bool :returns: dict of the form ``{ 'home/away': { by_player_dict } }``. See :py:f...
Return all home and away by player info sorted by either the provided key or function. Must provide at least one of the two parameters. Can sort either ascending or descending.: param sort_key: ( def None ) dict key to sort on: param sort_func: ( def None ) sorting function: param reverse: ( optional def False ) if Tru...
def sort_players(self, sort_key=None, sort_func=None, reverse=False): """ Return all home and away by player info sorted by either the provided key or function. Must provide at least one of the two parameters. Can sort either ascending or descending. :param sort_key: (def None) ...
Return home/ away by player info for the players on each team that are first in the provided category.: param sort_key: str the dictionary key to be sorted on: returns: dict of the form { home/ away: { by_player_dict } }. See: py: func: home_players and: py: func: away_players
def top_by_key(self, sort_key): """ Return home/away by player info for the players on each team that are first in the provided category. :param sort_key: str, the dictionary key to be sorted on :returns: dict of the form ``{ 'home/away': { by_player_dict } }``. See :py:func:`ho...
Return home/ away by player info for the players on each team who come in first according to the provided sorting function. Will perform ascending sort.: param sort_func: function that yields the sorting quantity: returns: dict of the form { home/ away: { by_player_dict } }. See: py: func: home_players and: py: func: a...
def top_by_func(self, sort_func): """ Return home/away by player info for the players on each team who come in first according to the provided sorting function. Will perform ascending sort. :param sort_func: function that yields the sorting quantity :returns: dict of the...
Encode one argument/ object to json
def encode(obj): """ Encode one argument/object to json """ if hasattr(obj, 'json'): return obj.json if hasattr(obj, '__json__'): return obj.__json__() return dumps(obj)
Encode a list of arguments
def encode_args(args, extra=False): """ Encode a list of arguments """ if not args: return '' methodargs = ', '.join([encode(a) for a in args]) if extra: methodargs += ', ' return methodargs
Establishes a socket connection to the zombie. js server and sends Javascript instructions.
def _send(self, javascript): """ Establishes a socket connection to the zombie.js server and sends Javascript instructions. :param js: the Javascript string to execute """ # Prepend JS to switch to the proper client context. message = """ var _ctx = ...
Call a method on the zombie. js Browser instance and wait on a callback.
def wait(self, method, *args): """ Call a method on the zombie.js Browser instance and wait on a callback. :param method: the method to call, e.g., html() :param args: one of more arguments for the method """ methodargs = encode_args(args, extra=True) js = """ ...
Evaluate a browser method and CSS selector against the document ( or an optional context DOMNode ) and return a single: class: zombie. dom. DOMNode object e. g.
def create_element(self, method, args=None): """ Evaluate a browser method and CSS selector against the document (or an optional context DOMNode) and return a single :class:`zombie.dom.DOMNode` object, e.g., browser._node('query', 'body > div') ...roughly translates to ...
Execute a browser method that will return a list of elements.
def create_elements(self, method, args=[]): """ Execute a browser method that will return a list of elements. Returns a list of the element indexes """ args = encode_args(args) js = """ create_elements(ELEMENTS, %(method)s(%(args)s)) """ % { ...
Fill a specified form field in the current document.
def fill(self, field, value): """ Fill a specified form field in the current document. :param field: an instance of :class:`zombie.dom.DOMNode` :param value: any string value :return: self to allow function chaining. """ self.client.nowait('browser.fill', (field,...
Evaluate a CSS selector against the document ( or an optional context: class: zombie. dom. DOMNode ) and return a single: class: zombie. dom. DOMNode object.
def query(self, selector, context=None): """ Evaluate a CSS selector against the document (or an optional context :class:`zombie.dom.DOMNode`) and return a single :class:`zombie.dom.DOMNode` object. :param selector: a string CSS selector (http://zombie.la...
Evaluate a CSS selector against the document ( or an optional context: class: zombie. dom. DOMNode ) and return a list of: class: zombie. dom. DOMNode objects.
def queryAll(self, selector, context=None): """ Evaluate a CSS selector against the document (or an optional context :class:`zombie.dom.DOMNode`) and return a list of :class:`zombie.dom.DOMNode` objects. :param selector: a string CSS selector (http://zomb...
Finds and returns a link <a > element (: class: zombie. dom. DOMNode ). You can use a CSS selector or find a link by its text contents ( case sensitive but ignores leading/ trailing spaces ).
def link(self, selector): """ Finds and returns a link ``<a>`` element (:class:`zombie.dom.DOMNode`). You can use a CSS selector or find a link by its text contents (case sensitive, but ignores leading/trailing spaces). :param selector: an optional string CSS selector ...
Used to set the value of form elements.
def value(self, value): """ Used to set the ``value`` of form elements. """ self.client.nowait( 'set_field', (Literal('browser'), self.element, value))
Fires a specified DOM event on the current node.
def fire(self, event): """ Fires a specified DOM event on the current node. :param event: the name of the event to fire (e.g., 'click'). Returns the :class:`zombie.dom.DOMNode` to allow function chaining. """ self.browser.fire(self.element, event) return self
Force all reports to be loaded and parsed instead of lazy loading on demand.: returns: self or None if load fails
def load_all(self): """ Force all reports to be loaded and parsed instead of lazy loading on demand. :returns: ``self`` or ``None`` if load fails """ try: self.toi.load_all() self.rosters.load_all() #self.summary.load_all() ...
Return the game meta information displayed in report banners including team names final score game date location and attendance. Data format is.. code:: python { home: home away: away final: final attendance: att date: date location: loc }: returns: matchup banner info: rtype: dict
def matchup(self): """ Return the game meta information displayed in report banners including team names, final score, game date, location, and attendance. Data format is .. code:: python { 'home': home, 'away': away, ...
Ensures all values are encoded in UTF - 8 and converts them to lowercase
def _utf8_encode(self, d): """ Ensures all values are encoded in UTF-8 and converts them to lowercase """ for k, v in d.items(): if isinstance(v, str): d[k] = v.encode('utf8').lower() if isinstance(v, list): for index,item ...
Converts bool values to lowercase strings
def _bool_encode(self, d): """ Converts bool values to lowercase strings """ for k, v in d.items(): if isinstance(v, bool): d[k] = str(v).lower() return d
Formats search parameters/ values for use with API: param \ * \ * kwargs: search parameters/ values
def _options(self, **kwargs): """ Formats search parameters/values for use with API :param \*\*kwargs: search parameters/values """ def _format_fq(d): for k,v in d.items(): if isinstance(v, list): d[k] = ' '.join(m...
Calls the API and returns a dictionary of the search results: param response_format: the format that the API uses for its response includes JSON (. json ) and JSONP (. jsonp ). Defaults to. json.: param key: a developer key. Defaults to key given when the articleAPI class was initialized.
def search(self, response_format = None, key = None, **kwargs): """ Calls the API and returns a dictionary of the search results :param response_format: the format that the API uses for its response, inc...
Fully parses game summary report.: returns: boolean success indicator: rtype: bool
def parse(self): """Fully parses game summary report. :returns: boolean success indicator :rtype: bool """ r = super(GameSummRep, self).parse() try: self.parse_scoring_summary() return r and False except: return False
Factory method creates objects derived from: py: class. Event with class name matching the: py: class. EventType.: param event_type: number for type of event: returns: constructed event corresponding to event_type: rtype:: py: class:. Event
def Create(event_type): """ Factory method creates objects derived from :py:class`.Event` with class name matching the :py:class`.EventType`. :param event_type: number for type of event :returns: constructed event corresponding to ``event_type`` :rtype: :py:class:`.Event...
: returns:: py: class:. ShiftSummary by player for the home team: rtype: dict { player_num: shift_summary_obj }
def home_shift_summ(self): """ :returns: :py:class:`.ShiftSummary` by player for the home team :rtype: dict ``{ player_num: shift_summary_obj }`` """ if not self.__wrapped_home: self.__wrapped_home = self.__wrap(self._home.by_player) return self.__wra...
: returns:: py: class:. ShiftSummary by player for the away team: rtype: dict { player_num: shift_summary_obj }
def away_shift_summ(self): """ :returns: :py:class:`.ShiftSummary` by player for the away team :rtype: dict ``{ player_num: shift_summary_obj }`` """ if not self.__wrapped_away: self.__wrapped_away = self.__wrap(self._away.by_player) return self.__wra...
Retreive and parse Play by Play data for the given: py: class: nhlscrapi. games. game. GameKey
def parse(self): """ Retreive and parse Play by Play data for the given :py:class:`nhlscrapi.games.game.GameKey`` :returns: ``self`` on success, ``None`` otherwise """ try: return super(RosterRep, self).parse() \ .parse_rosters() \ .p...
Parse the home and away game rosters
def parse_rosters(self): """ Parse the home and away game rosters :returns: ``self`` on success, ``None`` otherwise """ lx_doc = self.html_doc() if not self.__blocks: self.__pl_blocks(lx_doc) for t in ['home', 'away']: self.rosters[t] = ...
Parse the home and away healthy scratches
def parse_scratches(self): """ Parse the home and away healthy scratches :returns: ``self`` on success, ``None`` otherwise """ lx_doc = self.html_doc() if not self.__blocks: self.__pl_blocks(lx_doc) for t in ['aw_scr', 'h_scr']: ix = 'awa...
Parse the home and away coaches
def parse_coaches(self): """ Parse the home and away coaches :returns: ``self`` on success, ``None`` otherwise """ lx_doc = self.html_doc() tr = lx_doc.xpath('//tr[@id="HeadCoaches"]')[0] for i, td in enumerate(tr): txt = td.xpath('.//text()') ...
Parse the officials
def parse_officials(self): """ Parse the officials :returns: ``self`` on success, ``None`` otherwise """ # begin proper body of method lx_doc = self.html_doc() off_parser = opm(self.game_key.season) self.officials = off_parser(lx_doc) return self...
Validate an email address.
def is_email(address, check_dns=False, diagnose=False): """Validate an email address. Keyword arguments: address --- the email address as a string check_dns --- flag for whether to check the DNS status of the domain diagnose --- flag for whether to return True/False or a Diagnosis """ ...
Decorator that enforces one time loading for scrapers. The one time loading is applied to partial loaders e. g. only parse and load the home team roster once. This is not meant to be used directly.: param scraper: property name ( string ) containing an object of type: py: class: scrapr. ReportLoader: param loader_name:...
def dispatch_loader(scraper, loader_name): """ Decorator that enforces one time loading for scrapers. The one time loading is applied to partial loaders, e.g. only parse and load the home team roster once. This is not meant to be used directly. :param scraper: property name (string) containing ...
Parse shifts from TOI report: returns: self if successfule else None
def parse_shifts(self): """ Parse shifts from TOI report :returns: self if successfule else None """ lx_doc = self.html_doc() pl_heads = lx_doc.xpath('//td[contains(@class, "playerHeading")]') for pl in pl_heads: sh_sum = { } ...
Check whether a domain has a valid MX or A record.
def is_valid(self, domain, diagnose=False): """Check whether a domain has a valid MX or A record. Keyword arguments: domain --- the domain to check diagnose --- flag to report a diagnosis or a boolean (default False) """ return_status = [ValidDiagnosis()] dn...
: returns: the lxml processed html document: rtype: lxml. html. document_fromstring output
def html_doc(self): """ :returns: the lxml processed html document :rtype: ``lxml.html.document_fromstring`` output """ if self.__lx_doc is None: cn = NHLCn() if hasattr(cn, self.report_type): html = getattr(cn, self.rep...
Parse the banner matchup meta info for the game.: returns: self on success or None
def parse_matchup(self): """ Parse the banner matchup meta info for the game. :returns: ``self`` on success or ``None`` """ lx_doc = self.html_doc() try: if not self.matchup: self.matchup = self._fill_meta(lx_doc) return se...
Generate and yield a stream of parsed plays. Useful for per play processing.
def parse_plays_stream(self): """Generate and yield a stream of parsed plays. Useful for per play processing.""" lx_doc = self.html_doc() if lx_doc is not None: parser = PlayParser(self.game_key.season, self.game_key.game_type) plays = lx_doc.xpath('//tr[@class =...
Returns a dictionary mapping the type of information in the RTSS play row to the appropriate column number. The column locations pre/ post 2008 are different.: param season: int for the season number: returns: mapping of RTSS column to info type: rtype: dict keys are play_num per str time event desc vis home
def ColMap(season): """ Returns a dictionary mapping the type of information in the RTSS play row to the appropriate column number. The column locations pre/post 2008 are different. :param season: int for the season number :returns: mapping of RTSS column to info type ...
Parses table row from RTSS. These are the rows tagged with <tr class = evenColor... >. Result set contains: py: class: nhlscrapi. games. playbyplay. Strength and: py: class: nhlscrapi. games. events. EventType objects. Returned play data is in the form.. code:: python { play_num: num_of_play period: curr_period strengt...
def build_play(self, pbp_row): """ Parses table row from RTSS. These are the rows tagged with ``<tr class='evenColor' ... >``. Result set contains :py:class:`nhlscrapi.games.playbyplay.Strength` and :py:class:`nhlscrapi.games.events.EventType` objects. Returned play data is in the form ...
Constructs dictionary of players on the ice in the provided table at time of play.: param tab: RTSS table of the skaters and goalie on at the time of the play: rtype: dictionary key = player number value = [ position name ]
def __skaters(self, tab): """ Constructs dictionary of players on the ice in the provided table at time of play. :param tab: RTSS table of the skaters and goalie on at the time of the play :rtype: dictionary, key = player number, value = [position, name] """ res ...
Exclude elements in list l containing any elements from list ex. Example: >>> l = [ bob r rob \ r \ r \ nrobert ] >>> containing = [ \ n \ r ] >>> equal_to = [ r ] >>> exclude_from ( l containing equal_to ) [ bob ]
def exclude_from(l, containing = [], equal_to = []): """Exclude elements in list l containing any elements from list ex. Example: >>> l = ['bob', 'r', 'rob\r', '\r\nrobert'] >>> containing = ['\n', '\r'] >>> equal_to = ['r'] >>> exclude_from(l, containing, equal_to) ['bob...
inputs: surface - surface file ( e. g. lh. pial with full path ) labels - label file ( e. g. lh. cortex. label with full path ) annot - annot file ( e. g. lh. aparc. a2009s. annot with full path ) reg - registration file ( lh. sphere. reg ) origin - the label from which we calculate distances target - target surface ( ...
def calc_surfdist(surface, labels, annot, reg, origin, target): import nibabel as nib import numpy as np import os from surfdist import load, utils, surfdist import csv """ inputs: surface - surface file (e.g. lh.pial, with full path) labels - label file (e.g. lh.cortex.label, with full path) annot -...
This function takes a list of files as input and vstacks them
def stack_files(files, hemi, source, target): """ This function takes a list of files as input and vstacks them """ import csv import os import numpy as np fname = "sdist_%s_%s_%s.csv" % (hemi, source, target) filename = os.path.join(os.getcwd(),fname) alldist = [] for dfile in files: alldist...
Get short URL of blog post like/ blog/ <slug >/ using get_absolute_url if available. Removes dependency on reverse URLs of Mezzanine views when deploying Mezzanine only as an API backend.
def get_short_url(self, obj): """ Get short URL of blog post like '/blog/<slug>/' using ``get_absolute_url`` if available. Removes dependency on reverse URLs of Mezzanine views when deploying Mezzanine only as an API backend. """ try: url = obj.get_absolute_url() ...
Return the head - to - head face - off outcomes between two players. If the matchup didn t happen { } is returned.: param home_num: the number of the home team player: param away_num: the number of the away team player: returns: dict either { } or the following.. code:: python { home/ away: { off/ def/ neut/ all: { won...
def head_to_head(self, home_num, away_num): """ Return the head-to-head face-off outcomes between two players. If the matchup didn't happen, ``{ }`` is returned. :param home_num: the number of the home team player :param away_num: the number of the away team player ...
Returns the overall faceoff win/ total breakdown for home and away as: returns: dict { home/ away: { won: won total: total } }
def team_totals(self): """ Returns the overall faceoff win/total breakdown for home and away as :returns: dict, ``{ 'home/away': { 'won': won, 'total': total } }`` """ if self.__team_tots is None: self.__team_tots = self.__comp_tot() return {...