repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
thombashi/pytablereader
pytablereader/spreadsheet/gsloader.py
GoogleSheetsTableLoader.load
def load(self): """ Load table data from a Google Spreadsheet. This method consider :py:attr:`.source` as a path to the credential JSON file to access Google Sheets API. The method automatically search the header row start from :py:attr:`.start_row`. The condition of the header row is that all of the columns have value (except empty columns). :return: Loaded table data. Return one |TableData| for each sheet in the workbook. The table name for data will be determined by :py:meth:`~.GoogleSheetsTableLoader.make_table_name`. :rtype: iterator of |TableData| :raises pytablereader.DataError: If the header row is not found. :raises pytablereader.OpenError: If the spread sheet not found. """ import gspread from oauth2client.service_account import ServiceAccountCredentials self._validate_table_name() self._validate_title() scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"] credentials = ServiceAccountCredentials.from_json_keyfile_name(self.source, scope) gc = gspread.authorize(credentials) try: for worksheet in gc.open(self.title).worksheets(): self._worksheet = worksheet self.__all_values = [row for row in worksheet.get_all_values()] if self._is_empty_sheet(): continue try: self.__strip_empty_col() except ValueError: continue value_matrix = self.__all_values[self._get_start_row_idx() :] try: headers = value_matrix[0] rows = value_matrix[1:] except IndexError: continue self.inc_table_count() yield TableData( self.make_table_name(), headers, rows, dp_extractor=self.dp_extractor, type_hints=self._extract_type_hints(headers), ) except gspread.exceptions.SpreadsheetNotFound: raise OpenError("spreadsheet '{}' not found".format(self.title)) except gspread.exceptions.APIError as e: raise APIError(e)
python
def load(self): """ Load table data from a Google Spreadsheet. This method consider :py:attr:`.source` as a path to the credential JSON file to access Google Sheets API. The method automatically search the header row start from :py:attr:`.start_row`. The condition of the header row is that all of the columns have value (except empty columns). :return: Loaded table data. Return one |TableData| for each sheet in the workbook. The table name for data will be determined by :py:meth:`~.GoogleSheetsTableLoader.make_table_name`. :rtype: iterator of |TableData| :raises pytablereader.DataError: If the header row is not found. :raises pytablereader.OpenError: If the spread sheet not found. """ import gspread from oauth2client.service_account import ServiceAccountCredentials self._validate_table_name() self._validate_title() scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"] credentials = ServiceAccountCredentials.from_json_keyfile_name(self.source, scope) gc = gspread.authorize(credentials) try: for worksheet in gc.open(self.title).worksheets(): self._worksheet = worksheet self.__all_values = [row for row in worksheet.get_all_values()] if self._is_empty_sheet(): continue try: self.__strip_empty_col() except ValueError: continue value_matrix = self.__all_values[self._get_start_row_idx() :] try: headers = value_matrix[0] rows = value_matrix[1:] except IndexError: continue self.inc_table_count() yield TableData( self.make_table_name(), headers, rows, dp_extractor=self.dp_extractor, type_hints=self._extract_type_hints(headers), ) except gspread.exceptions.SpreadsheetNotFound: raise OpenError("spreadsheet '{}' not found".format(self.title)) except gspread.exceptions.APIError as e: raise APIError(e)
[ "def", "load", "(", "self", ")", ":", "import", "gspread", "from", "oauth2client", ".", "service_account", "import", "ServiceAccountCredentials", "self", ".", "_validate_table_name", "(", ")", "self", ".", "_validate_title", "(", ")", "scope", "=", "[", "\"https://spreadsheets.google.com/feeds\"", ",", "\"https://www.googleapis.com/auth/drive\"", "]", "credentials", "=", "ServiceAccountCredentials", ".", "from_json_keyfile_name", "(", "self", ".", "source", ",", "scope", ")", "gc", "=", "gspread", ".", "authorize", "(", "credentials", ")", "try", ":", "for", "worksheet", "in", "gc", ".", "open", "(", "self", ".", "title", ")", ".", "worksheets", "(", ")", ":", "self", ".", "_worksheet", "=", "worksheet", "self", ".", "__all_values", "=", "[", "row", "for", "row", "in", "worksheet", ".", "get_all_values", "(", ")", "]", "if", "self", ".", "_is_empty_sheet", "(", ")", ":", "continue", "try", ":", "self", ".", "__strip_empty_col", "(", ")", "except", "ValueError", ":", "continue", "value_matrix", "=", "self", ".", "__all_values", "[", "self", ".", "_get_start_row_idx", "(", ")", ":", "]", "try", ":", "headers", "=", "value_matrix", "[", "0", "]", "rows", "=", "value_matrix", "[", "1", ":", "]", "except", "IndexError", ":", "continue", "self", ".", "inc_table_count", "(", ")", "yield", "TableData", "(", "self", ".", "make_table_name", "(", ")", ",", "headers", ",", "rows", ",", "dp_extractor", "=", "self", ".", "dp_extractor", ",", "type_hints", "=", "self", ".", "_extract_type_hints", "(", "headers", ")", ",", ")", "except", "gspread", ".", "exceptions", ".", "SpreadsheetNotFound", ":", "raise", "OpenError", "(", "\"spreadsheet '{}' not found\"", ".", "format", "(", "self", ".", "title", ")", ")", "except", "gspread", ".", "exceptions", ".", "APIError", "as", "e", ":", "raise", "APIError", "(", "e", ")" ]
Load table data from a Google Spreadsheet. This method consider :py:attr:`.source` as a path to the credential JSON file to access Google Sheets API. The method automatically search the header row start from :py:attr:`.start_row`. The condition of the header row is that all of the columns have value (except empty columns). :return: Loaded table data. Return one |TableData| for each sheet in the workbook. The table name for data will be determined by :py:meth:`~.GoogleSheetsTableLoader.make_table_name`. :rtype: iterator of |TableData| :raises pytablereader.DataError: If the header row is not found. :raises pytablereader.OpenError: If the spread sheet not found.
[ "Load", "table", "data", "from", "a", "Google", "Spreadsheet", "." ]
bc3c057a2cc775bcce690e0e9019c2907b638101
https://github.com/thombashi/pytablereader/blob/bc3c057a2cc775bcce690e0e9019c2907b638101/pytablereader/spreadsheet/gsloader.py#L62-L126
train
thombashi/pytablereader
pytablereader/_logger/_logger.py
set_log_level
def set_log_level(log_level): """ Set logging level of this module. Using `logbook <https://logbook.readthedocs.io/en/stable/>`__ module for logging. :param int log_level: One of the log level of `logbook <https://logbook.readthedocs.io/en/stable/api/base.html>`__. Disabled logging if ``log_level`` is ``logbook.NOTSET``. :raises LookupError: If ``log_level`` is an invalid value. """ if not LOGBOOK_INSTALLED: return # validate log level logbook.get_level_name(log_level) if log_level == logger.level: return if log_level == logbook.NOTSET: set_logger(is_enable=False) else: set_logger(is_enable=True) logger.level = log_level dataproperty.set_log_level(log_level) try: import simplesqlite simplesqlite.set_log_level(log_level) except ImportError: pass
python
def set_log_level(log_level): """ Set logging level of this module. Using `logbook <https://logbook.readthedocs.io/en/stable/>`__ module for logging. :param int log_level: One of the log level of `logbook <https://logbook.readthedocs.io/en/stable/api/base.html>`__. Disabled logging if ``log_level`` is ``logbook.NOTSET``. :raises LookupError: If ``log_level`` is an invalid value. """ if not LOGBOOK_INSTALLED: return # validate log level logbook.get_level_name(log_level) if log_level == logger.level: return if log_level == logbook.NOTSET: set_logger(is_enable=False) else: set_logger(is_enable=True) logger.level = log_level dataproperty.set_log_level(log_level) try: import simplesqlite simplesqlite.set_log_level(log_level) except ImportError: pass
[ "def", "set_log_level", "(", "log_level", ")", ":", "if", "not", "LOGBOOK_INSTALLED", ":", "return", "# validate log level", "logbook", ".", "get_level_name", "(", "log_level", ")", "if", "log_level", "==", "logger", ".", "level", ":", "return", "if", "log_level", "==", "logbook", ".", "NOTSET", ":", "set_logger", "(", "is_enable", "=", "False", ")", "else", ":", "set_logger", "(", "is_enable", "=", "True", ")", "logger", ".", "level", "=", "log_level", "dataproperty", ".", "set_log_level", "(", "log_level", ")", "try", ":", "import", "simplesqlite", "simplesqlite", ".", "set_log_level", "(", "log_level", ")", "except", "ImportError", ":", "pass" ]
Set logging level of this module. Using `logbook <https://logbook.readthedocs.io/en/stable/>`__ module for logging. :param int log_level: One of the log level of `logbook <https://logbook.readthedocs.io/en/stable/api/base.html>`__. Disabled logging if ``log_level`` is ``logbook.NOTSET``. :raises LookupError: If ``log_level`` is an invalid value.
[ "Set", "logging", "level", "of", "this", "module", ".", "Using", "logbook", "<https", ":", "//", "logbook", ".", "readthedocs", ".", "io", "/", "en", "/", "stable", "/", ">", "__", "module", "for", "logging", "." ]
bc3c057a2cc775bcce690e0e9019c2907b638101
https://github.com/thombashi/pytablereader/blob/bc3c057a2cc775bcce690e0e9019c2907b638101/pytablereader/_logger/_logger.py#L51-L85
train
projectatomic/osbs-client
osbs/utils.py
buildconfig_update
def buildconfig_update(orig, new, remove_nonexistent_keys=False): """Performs update of given `orig` BuildConfig with values from `new` BuildConfig. Both BuildConfigs have to be represented as `dict`s. This function: - adds all key/value pairs to `orig` from `new` that are missing - replaces values in `orig` for keys that are in both - removes key/value pairs from `orig` for keys that are not in `new`, but only in dicts nested inside `strategy` key (see https://github.com/projectatomic/osbs-client/pull/273#issuecomment-148038314) """ if isinstance(orig, dict) and isinstance(new, dict): clean_triggers(orig, new) if remove_nonexistent_keys: missing = set(orig.keys()) - set(new.keys()) for k in missing: orig.pop(k) for k, v in new.items(): if k == 'strategy': remove_nonexistent_keys = True if isinstance(orig.get(k), dict) and isinstance(v, dict): buildconfig_update(orig[k], v, remove_nonexistent_keys) else: orig[k] = v
python
def buildconfig_update(orig, new, remove_nonexistent_keys=False): """Performs update of given `orig` BuildConfig with values from `new` BuildConfig. Both BuildConfigs have to be represented as `dict`s. This function: - adds all key/value pairs to `orig` from `new` that are missing - replaces values in `orig` for keys that are in both - removes key/value pairs from `orig` for keys that are not in `new`, but only in dicts nested inside `strategy` key (see https://github.com/projectatomic/osbs-client/pull/273#issuecomment-148038314) """ if isinstance(orig, dict) and isinstance(new, dict): clean_triggers(orig, new) if remove_nonexistent_keys: missing = set(orig.keys()) - set(new.keys()) for k in missing: orig.pop(k) for k, v in new.items(): if k == 'strategy': remove_nonexistent_keys = True if isinstance(orig.get(k), dict) and isinstance(v, dict): buildconfig_update(orig[k], v, remove_nonexistent_keys) else: orig[k] = v
[ "def", "buildconfig_update", "(", "orig", ",", "new", ",", "remove_nonexistent_keys", "=", "False", ")", ":", "if", "isinstance", "(", "orig", ",", "dict", ")", "and", "isinstance", "(", "new", ",", "dict", ")", ":", "clean_triggers", "(", "orig", ",", "new", ")", "if", "remove_nonexistent_keys", ":", "missing", "=", "set", "(", "orig", ".", "keys", "(", ")", ")", "-", "set", "(", "new", ".", "keys", "(", ")", ")", "for", "k", "in", "missing", ":", "orig", ".", "pop", "(", "k", ")", "for", "k", ",", "v", "in", "new", ".", "items", "(", ")", ":", "if", "k", "==", "'strategy'", ":", "remove_nonexistent_keys", "=", "True", "if", "isinstance", "(", "orig", ".", "get", "(", "k", ")", ",", "dict", ")", "and", "isinstance", "(", "v", ",", "dict", ")", ":", "buildconfig_update", "(", "orig", "[", "k", "]", ",", "v", ",", "remove_nonexistent_keys", ")", "else", ":", "orig", "[", "k", "]", "=", "v" ]
Performs update of given `orig` BuildConfig with values from `new` BuildConfig. Both BuildConfigs have to be represented as `dict`s. This function: - adds all key/value pairs to `orig` from `new` that are missing - replaces values in `orig` for keys that are in both - removes key/value pairs from `orig` for keys that are not in `new`, but only in dicts nested inside `strategy` key (see https://github.com/projectatomic/osbs-client/pull/273#issuecomment-148038314)
[ "Performs", "update", "of", "given", "orig", "BuildConfig", "with", "values", "from", "new", "BuildConfig", ".", "Both", "BuildConfigs", "have", "to", "be", "represented", "as", "dict", "s", "." ]
571fe035dab3a7c02e1dccd5d65ffd75be750458
https://github.com/projectatomic/osbs-client/blob/571fe035dab3a7c02e1dccd5d65ffd75be750458/osbs/utils.py#L168-L191
train
projectatomic/osbs-client
osbs/utils.py
checkout_git_repo
def checkout_git_repo(git_url, target_dir=None, commit=None, retry_times=GIT_MAX_RETRIES, branch=None, depth=None): """ clone provided git repo to target_dir, optionally checkout provided commit yield the ClonedRepoData and delete the repo when finished :param git_url: str, git repo to clone :param target_dir: str, filesystem path where the repo should be cloned :param commit: str, commit to checkout, SHA-1 or ref :param retry_times: int, number of retries for git clone :param branch: str, optional branch of the commit, required if depth is provided :param depth: int, optional expected depth :return: str, int, commit ID of HEAD """ tmpdir = tempfile.mkdtemp() target_dir = target_dir or os.path.join(tmpdir, "repo") try: yield clone_git_repo(git_url, target_dir, commit, retry_times, branch, depth) finally: shutil.rmtree(tmpdir)
python
def checkout_git_repo(git_url, target_dir=None, commit=None, retry_times=GIT_MAX_RETRIES, branch=None, depth=None): """ clone provided git repo to target_dir, optionally checkout provided commit yield the ClonedRepoData and delete the repo when finished :param git_url: str, git repo to clone :param target_dir: str, filesystem path where the repo should be cloned :param commit: str, commit to checkout, SHA-1 or ref :param retry_times: int, number of retries for git clone :param branch: str, optional branch of the commit, required if depth is provided :param depth: int, optional expected depth :return: str, int, commit ID of HEAD """ tmpdir = tempfile.mkdtemp() target_dir = target_dir or os.path.join(tmpdir, "repo") try: yield clone_git_repo(git_url, target_dir, commit, retry_times, branch, depth) finally: shutil.rmtree(tmpdir)
[ "def", "checkout_git_repo", "(", "git_url", ",", "target_dir", "=", "None", ",", "commit", "=", "None", ",", "retry_times", "=", "GIT_MAX_RETRIES", ",", "branch", "=", "None", ",", "depth", "=", "None", ")", ":", "tmpdir", "=", "tempfile", ".", "mkdtemp", "(", ")", "target_dir", "=", "target_dir", "or", "os", ".", "path", ".", "join", "(", "tmpdir", ",", "\"repo\"", ")", "try", ":", "yield", "clone_git_repo", "(", "git_url", ",", "target_dir", ",", "commit", ",", "retry_times", ",", "branch", ",", "depth", ")", "finally", ":", "shutil", ".", "rmtree", "(", "tmpdir", ")" ]
clone provided git repo to target_dir, optionally checkout provided commit yield the ClonedRepoData and delete the repo when finished :param git_url: str, git repo to clone :param target_dir: str, filesystem path where the repo should be cloned :param commit: str, commit to checkout, SHA-1 or ref :param retry_times: int, number of retries for git clone :param branch: str, optional branch of the commit, required if depth is provided :param depth: int, optional expected depth :return: str, int, commit ID of HEAD
[ "clone", "provided", "git", "repo", "to", "target_dir", "optionally", "checkout", "provided", "commit", "yield", "the", "ClonedRepoData", "and", "delete", "the", "repo", "when", "finished" ]
571fe035dab3a7c02e1dccd5d65ffd75be750458
https://github.com/projectatomic/osbs-client/blob/571fe035dab3a7c02e1dccd5d65ffd75be750458/osbs/utils.py#L195-L214
train
projectatomic/osbs-client
osbs/utils.py
clone_git_repo
def clone_git_repo(git_url, target_dir=None, commit=None, retry_times=GIT_MAX_RETRIES, branch=None, depth=None): """ clone provided git repo to target_dir, optionally checkout provided commit :param git_url: str, git repo to clone :param target_dir: str, filesystem path where the repo should be cloned :param commit: str, commit to checkout, SHA-1 or ref :param retry_times: int, number of retries for git clone :param branch: str, optional branch of the commit, required if depth is provided :param depth: int, optional expected depth :return: str, int, commit ID of HEAD """ retry_delay = GIT_BACKOFF_FACTOR target_dir = target_dir or os.path.join(tempfile.mkdtemp(), "repo") commit = commit or "master" logger.info("cloning git repo '%s'", git_url) logger.debug("url = '%s', dir = '%s', commit = '%s'", git_url, target_dir, commit) cmd = ["git", "clone"] if branch: cmd += ["-b", branch, "--single-branch"] if depth: cmd += ["--depth", str(depth)] elif depth: logger.warning("branch not provided for %s, depth setting ignored", git_url) depth = None cmd += [git_url, target_dir] logger.debug("cloning '%s'", cmd) repo_commit = '' repo_depth = None for counter in range(retry_times + 1): try: # we are using check_output, even though we aren't using # the return value, but we will get 'output' in exception subprocess.check_output(cmd, stderr=subprocess.STDOUT) repo_commit, repo_depth = reset_git_repo(target_dir, commit, depth) break except subprocess.CalledProcessError as exc: if counter != retry_times: logger.info("retrying command '%s':\n '%s'", cmd, exc.output) time.sleep(retry_delay * (2 ** counter)) else: raise OsbsException("Unable to clone git repo '%s' " "branch '%s'" % (git_url, branch), cause=exc, traceback=sys.exc_info()[2]) return ClonedRepoData(target_dir, repo_commit, repo_depth)
python
def clone_git_repo(git_url, target_dir=None, commit=None, retry_times=GIT_MAX_RETRIES, branch=None, depth=None): """ clone provided git repo to target_dir, optionally checkout provided commit :param git_url: str, git repo to clone :param target_dir: str, filesystem path where the repo should be cloned :param commit: str, commit to checkout, SHA-1 or ref :param retry_times: int, number of retries for git clone :param branch: str, optional branch of the commit, required if depth is provided :param depth: int, optional expected depth :return: str, int, commit ID of HEAD """ retry_delay = GIT_BACKOFF_FACTOR target_dir = target_dir or os.path.join(tempfile.mkdtemp(), "repo") commit = commit or "master" logger.info("cloning git repo '%s'", git_url) logger.debug("url = '%s', dir = '%s', commit = '%s'", git_url, target_dir, commit) cmd = ["git", "clone"] if branch: cmd += ["-b", branch, "--single-branch"] if depth: cmd += ["--depth", str(depth)] elif depth: logger.warning("branch not provided for %s, depth setting ignored", git_url) depth = None cmd += [git_url, target_dir] logger.debug("cloning '%s'", cmd) repo_commit = '' repo_depth = None for counter in range(retry_times + 1): try: # we are using check_output, even though we aren't using # the return value, but we will get 'output' in exception subprocess.check_output(cmd, stderr=subprocess.STDOUT) repo_commit, repo_depth = reset_git_repo(target_dir, commit, depth) break except subprocess.CalledProcessError as exc: if counter != retry_times: logger.info("retrying command '%s':\n '%s'", cmd, exc.output) time.sleep(retry_delay * (2 ** counter)) else: raise OsbsException("Unable to clone git repo '%s' " "branch '%s'" % (git_url, branch), cause=exc, traceback=sys.exc_info()[2]) return ClonedRepoData(target_dir, repo_commit, repo_depth)
[ "def", "clone_git_repo", "(", "git_url", ",", "target_dir", "=", "None", ",", "commit", "=", "None", ",", "retry_times", "=", "GIT_MAX_RETRIES", ",", "branch", "=", "None", ",", "depth", "=", "None", ")", ":", "retry_delay", "=", "GIT_BACKOFF_FACTOR", "target_dir", "=", "target_dir", "or", "os", ".", "path", ".", "join", "(", "tempfile", ".", "mkdtemp", "(", ")", ",", "\"repo\"", ")", "commit", "=", "commit", "or", "\"master\"", "logger", ".", "info", "(", "\"cloning git repo '%s'\"", ",", "git_url", ")", "logger", ".", "debug", "(", "\"url = '%s', dir = '%s', commit = '%s'\"", ",", "git_url", ",", "target_dir", ",", "commit", ")", "cmd", "=", "[", "\"git\"", ",", "\"clone\"", "]", "if", "branch", ":", "cmd", "+=", "[", "\"-b\"", ",", "branch", ",", "\"--single-branch\"", "]", "if", "depth", ":", "cmd", "+=", "[", "\"--depth\"", ",", "str", "(", "depth", ")", "]", "elif", "depth", ":", "logger", ".", "warning", "(", "\"branch not provided for %s, depth setting ignored\"", ",", "git_url", ")", "depth", "=", "None", "cmd", "+=", "[", "git_url", ",", "target_dir", "]", "logger", ".", "debug", "(", "\"cloning '%s'\"", ",", "cmd", ")", "repo_commit", "=", "''", "repo_depth", "=", "None", "for", "counter", "in", "range", "(", "retry_times", "+", "1", ")", ":", "try", ":", "# we are using check_output, even though we aren't using", "# the return value, but we will get 'output' in exception", "subprocess", ".", "check_output", "(", "cmd", ",", "stderr", "=", "subprocess", ".", "STDOUT", ")", "repo_commit", ",", "repo_depth", "=", "reset_git_repo", "(", "target_dir", ",", "commit", ",", "depth", ")", "break", "except", "subprocess", ".", "CalledProcessError", "as", "exc", ":", "if", "counter", "!=", "retry_times", ":", "logger", ".", "info", "(", "\"retrying command '%s':\\n '%s'\"", ",", "cmd", ",", "exc", ".", "output", ")", "time", ".", "sleep", "(", "retry_delay", "*", "(", "2", "**", "counter", ")", ")", "else", ":", "raise", "OsbsException", "(", "\"Unable to clone git repo '%s' \"", "\"branch '%s'\"", "%", "(", "git_url", ",", "branch", ")", ",", "cause", "=", "exc", ",", "traceback", "=", "sys", ".", "exc_info", "(", ")", "[", "2", "]", ")", "return", "ClonedRepoData", "(", "target_dir", ",", "repo_commit", ",", "repo_depth", ")" ]
clone provided git repo to target_dir, optionally checkout provided commit :param git_url: str, git repo to clone :param target_dir: str, filesystem path where the repo should be cloned :param commit: str, commit to checkout, SHA-1 or ref :param retry_times: int, number of retries for git clone :param branch: str, optional branch of the commit, required if depth is provided :param depth: int, optional expected depth :return: str, int, commit ID of HEAD
[ "clone", "provided", "git", "repo", "to", "target_dir", "optionally", "checkout", "provided", "commit" ]
571fe035dab3a7c02e1dccd5d65ffd75be750458
https://github.com/projectatomic/osbs-client/blob/571fe035dab3a7c02e1dccd5d65ffd75be750458/osbs/utils.py#L217-L267
train
projectatomic/osbs-client
osbs/utils.py
reset_git_repo
def reset_git_repo(target_dir, git_reference, retry_depth=None): """ hard reset git clone in target_dir to given git_reference :param target_dir: str, filesystem path where the repo is cloned :param git_reference: str, any valid git reference :param retry_depth: int, if the repo was cloned with --shallow, this is the expected depth of the commit :return: str and int, commit ID of HEAD and commit depth of git_reference """ deepen = retry_depth or 0 base_commit_depth = 0 for _ in range(GIT_FETCH_RETRY): try: if not deepen: cmd = ['git', 'rev-list', '--count', git_reference] base_commit_depth = int(subprocess.check_output(cmd, cwd=target_dir)) - 1 cmd = ["git", "reset", "--hard", git_reference] logger.debug("Resetting current HEAD: '%s'", cmd) subprocess.check_call(cmd, cwd=target_dir) break except subprocess.CalledProcessError: if not deepen: raise OsbsException('cannot find commit %s in repo %s' % (git_reference, target_dir)) deepen *= 2 cmd = ["git", "fetch", "--depth", str(deepen)] subprocess.check_call(cmd, cwd=target_dir) logger.debug("Couldn't find commit %s, increasing depth with '%s'", git_reference, cmd) else: raise OsbsException('cannot find commit %s in repo %s' % (git_reference, target_dir)) cmd = ["git", "rev-parse", "HEAD"] logger.debug("getting SHA-1 of provided ref '%s'", git_reference) commit_id = subprocess.check_output(cmd, cwd=target_dir, universal_newlines=True) commit_id = commit_id.strip() logger.info("commit ID = %s", commit_id) final_commit_depth = None if not deepen: cmd = ['git', 'rev-list', '--count', 'HEAD'] final_commit_depth = int(subprocess.check_output(cmd, cwd=target_dir)) - base_commit_depth return commit_id, final_commit_depth
python
def reset_git_repo(target_dir, git_reference, retry_depth=None): """ hard reset git clone in target_dir to given git_reference :param target_dir: str, filesystem path where the repo is cloned :param git_reference: str, any valid git reference :param retry_depth: int, if the repo was cloned with --shallow, this is the expected depth of the commit :return: str and int, commit ID of HEAD and commit depth of git_reference """ deepen = retry_depth or 0 base_commit_depth = 0 for _ in range(GIT_FETCH_RETRY): try: if not deepen: cmd = ['git', 'rev-list', '--count', git_reference] base_commit_depth = int(subprocess.check_output(cmd, cwd=target_dir)) - 1 cmd = ["git", "reset", "--hard", git_reference] logger.debug("Resetting current HEAD: '%s'", cmd) subprocess.check_call(cmd, cwd=target_dir) break except subprocess.CalledProcessError: if not deepen: raise OsbsException('cannot find commit %s in repo %s' % (git_reference, target_dir)) deepen *= 2 cmd = ["git", "fetch", "--depth", str(deepen)] subprocess.check_call(cmd, cwd=target_dir) logger.debug("Couldn't find commit %s, increasing depth with '%s'", git_reference, cmd) else: raise OsbsException('cannot find commit %s in repo %s' % (git_reference, target_dir)) cmd = ["git", "rev-parse", "HEAD"] logger.debug("getting SHA-1 of provided ref '%s'", git_reference) commit_id = subprocess.check_output(cmd, cwd=target_dir, universal_newlines=True) commit_id = commit_id.strip() logger.info("commit ID = %s", commit_id) final_commit_depth = None if not deepen: cmd = ['git', 'rev-list', '--count', 'HEAD'] final_commit_depth = int(subprocess.check_output(cmd, cwd=target_dir)) - base_commit_depth return commit_id, final_commit_depth
[ "def", "reset_git_repo", "(", "target_dir", ",", "git_reference", ",", "retry_depth", "=", "None", ")", ":", "deepen", "=", "retry_depth", "or", "0", "base_commit_depth", "=", "0", "for", "_", "in", "range", "(", "GIT_FETCH_RETRY", ")", ":", "try", ":", "if", "not", "deepen", ":", "cmd", "=", "[", "'git'", ",", "'rev-list'", ",", "'--count'", ",", "git_reference", "]", "base_commit_depth", "=", "int", "(", "subprocess", ".", "check_output", "(", "cmd", ",", "cwd", "=", "target_dir", ")", ")", "-", "1", "cmd", "=", "[", "\"git\"", ",", "\"reset\"", ",", "\"--hard\"", ",", "git_reference", "]", "logger", ".", "debug", "(", "\"Resetting current HEAD: '%s'\"", ",", "cmd", ")", "subprocess", ".", "check_call", "(", "cmd", ",", "cwd", "=", "target_dir", ")", "break", "except", "subprocess", ".", "CalledProcessError", ":", "if", "not", "deepen", ":", "raise", "OsbsException", "(", "'cannot find commit %s in repo %s'", "%", "(", "git_reference", ",", "target_dir", ")", ")", "deepen", "*=", "2", "cmd", "=", "[", "\"git\"", ",", "\"fetch\"", ",", "\"--depth\"", ",", "str", "(", "deepen", ")", "]", "subprocess", ".", "check_call", "(", "cmd", ",", "cwd", "=", "target_dir", ")", "logger", ".", "debug", "(", "\"Couldn't find commit %s, increasing depth with '%s'\"", ",", "git_reference", ",", "cmd", ")", "else", ":", "raise", "OsbsException", "(", "'cannot find commit %s in repo %s'", "%", "(", "git_reference", ",", "target_dir", ")", ")", "cmd", "=", "[", "\"git\"", ",", "\"rev-parse\"", ",", "\"HEAD\"", "]", "logger", ".", "debug", "(", "\"getting SHA-1 of provided ref '%s'\"", ",", "git_reference", ")", "commit_id", "=", "subprocess", ".", "check_output", "(", "cmd", ",", "cwd", "=", "target_dir", ",", "universal_newlines", "=", "True", ")", "commit_id", "=", "commit_id", ".", "strip", "(", ")", "logger", ".", "info", "(", "\"commit ID = %s\"", ",", "commit_id", ")", "final_commit_depth", "=", "None", "if", "not", "deepen", ":", "cmd", "=", "[", "'git'", ",", "'rev-list'", ",", "'--count'", ",", "'HEAD'", "]", "final_commit_depth", "=", "int", "(", "subprocess", ".", "check_output", "(", "cmd", ",", "cwd", "=", "target_dir", ")", ")", "-", "base_commit_depth", "return", "commit_id", ",", "final_commit_depth" ]
hard reset git clone in target_dir to given git_reference :param target_dir: str, filesystem path where the repo is cloned :param git_reference: str, any valid git reference :param retry_depth: int, if the repo was cloned with --shallow, this is the expected depth of the commit :return: str and int, commit ID of HEAD and commit depth of git_reference
[ "hard", "reset", "git", "clone", "in", "target_dir", "to", "given", "git_reference" ]
571fe035dab3a7c02e1dccd5d65ffd75be750458
https://github.com/projectatomic/osbs-client/blob/571fe035dab3a7c02e1dccd5d65ffd75be750458/osbs/utils.py#L270-L314
train
projectatomic/osbs-client
osbs/utils.py
get_imagestreamtag_from_image
def get_imagestreamtag_from_image(image): """ return ImageStreamTag, give a FROM value :param image: str, the FROM value from the Dockerfile :return: str, ImageStreamTag """ ret = image # Remove the registry part ret = strip_registry_from_image(image) # ImageStream names cannot contain '/' ret = ret.replace('/', '-') # If there is no ':' suffix value, add one if ret.find(':') == -1: ret += ":latest" return ret
python
def get_imagestreamtag_from_image(image): """ return ImageStreamTag, give a FROM value :param image: str, the FROM value from the Dockerfile :return: str, ImageStreamTag """ ret = image # Remove the registry part ret = strip_registry_from_image(image) # ImageStream names cannot contain '/' ret = ret.replace('/', '-') # If there is no ':' suffix value, add one if ret.find(':') == -1: ret += ":latest" return ret
[ "def", "get_imagestreamtag_from_image", "(", "image", ")", ":", "ret", "=", "image", "# Remove the registry part", "ret", "=", "strip_registry_from_image", "(", "image", ")", "# ImageStream names cannot contain '/'", "ret", "=", "ret", ".", "replace", "(", "'/'", ",", "'-'", ")", "# If there is no ':' suffix value, add one", "if", "ret", ".", "find", "(", "':'", ")", "==", "-", "1", ":", "ret", "+=", "\":latest\"", "return", "ret" ]
return ImageStreamTag, give a FROM value :param image: str, the FROM value from the Dockerfile :return: str, ImageStreamTag
[ "return", "ImageStreamTag", "give", "a", "FROM", "value" ]
571fe035dab3a7c02e1dccd5d65ffd75be750458
https://github.com/projectatomic/osbs-client/blob/571fe035dab3a7c02e1dccd5d65ffd75be750458/osbs/utils.py#L385-L404
train
projectatomic/osbs-client
osbs/utils.py
get_time_from_rfc3339
def get_time_from_rfc3339(rfc3339): """ return time tuple from an RFC 3339-formatted time string :param rfc3339: str, time in RFC 3339 format :return: float, seconds since the Epoch """ try: # py 3 dt = dateutil.parser.parse(rfc3339, ignoretz=False) return dt.timestamp() except NameError: # py 2 # Decode the RFC 3339 date with no fractional seconds (the # format Origin provides). Note that this will fail to parse # valid ISO8601 timestamps not in this exact format. time_tuple = strptime(rfc3339, '%Y-%m-%dT%H:%M:%SZ') return timegm(time_tuple)
python
def get_time_from_rfc3339(rfc3339): """ return time tuple from an RFC 3339-formatted time string :param rfc3339: str, time in RFC 3339 format :return: float, seconds since the Epoch """ try: # py 3 dt = dateutil.parser.parse(rfc3339, ignoretz=False) return dt.timestamp() except NameError: # py 2 # Decode the RFC 3339 date with no fractional seconds (the # format Origin provides). Note that this will fail to parse # valid ISO8601 timestamps not in this exact format. time_tuple = strptime(rfc3339, '%Y-%m-%dT%H:%M:%SZ') return timegm(time_tuple)
[ "def", "get_time_from_rfc3339", "(", "rfc3339", ")", ":", "try", ":", "# py 3", "dt", "=", "dateutil", ".", "parser", ".", "parse", "(", "rfc3339", ",", "ignoretz", "=", "False", ")", "return", "dt", ".", "timestamp", "(", ")", "except", "NameError", ":", "# py 2", "# Decode the RFC 3339 date with no fractional seconds (the", "# format Origin provides). Note that this will fail to parse", "# valid ISO8601 timestamps not in this exact format.", "time_tuple", "=", "strptime", "(", "rfc3339", ",", "'%Y-%m-%dT%H:%M:%SZ'", ")", "return", "timegm", "(", "time_tuple", ")" ]
return time tuple from an RFC 3339-formatted time string :param rfc3339: str, time in RFC 3339 format :return: float, seconds since the Epoch
[ "return", "time", "tuple", "from", "an", "RFC", "3339", "-", "formatted", "time", "string" ]
571fe035dab3a7c02e1dccd5d65ffd75be750458
https://github.com/projectatomic/osbs-client/blob/571fe035dab3a7c02e1dccd5d65ffd75be750458/osbs/utils.py#L407-L427
train
projectatomic/osbs-client
osbs/utils.py
sanitize_strings_for_openshift
def sanitize_strings_for_openshift(str1, str2='', limit=LABEL_MAX_CHARS, separator='-', label=True): """ OpenShift requires labels to be no more than 64 characters and forbids any characters other than alphanumerics, ., and -. BuildConfig names are similar, but cannot contain /. Sanitize and concatanate one or two strings to meet OpenShift's requirements. include an equal number of characters from both strings if the combined length is more than the limit. """ filter_chars = VALID_LABEL_CHARS if label else VALID_BUILD_CONFIG_NAME_CHARS str1_san = ''.join(filter(filter_chars.match, list(str1))) str2_san = ''.join(filter(filter_chars.match, list(str2))) str1_chars = [] str2_chars = [] groups = ((str1_san, str1_chars), (str2_san, str2_chars)) size = len(separator) limit = min(limit, LABEL_MAX_CHARS) for i in range(max(len(str1_san), len(str2_san))): for group, group_chars in groups: if i < len(group): group_chars.append(group[i]) size += 1 if size >= limit: break else: continue break final_str1 = ''.join(str1_chars).strip(separator) final_str2 = ''.join(str2_chars).strip(separator) return separator.join(filter(None, (final_str1, final_str2)))
python
def sanitize_strings_for_openshift(str1, str2='', limit=LABEL_MAX_CHARS, separator='-', label=True): """ OpenShift requires labels to be no more than 64 characters and forbids any characters other than alphanumerics, ., and -. BuildConfig names are similar, but cannot contain /. Sanitize and concatanate one or two strings to meet OpenShift's requirements. include an equal number of characters from both strings if the combined length is more than the limit. """ filter_chars = VALID_LABEL_CHARS if label else VALID_BUILD_CONFIG_NAME_CHARS str1_san = ''.join(filter(filter_chars.match, list(str1))) str2_san = ''.join(filter(filter_chars.match, list(str2))) str1_chars = [] str2_chars = [] groups = ((str1_san, str1_chars), (str2_san, str2_chars)) size = len(separator) limit = min(limit, LABEL_MAX_CHARS) for i in range(max(len(str1_san), len(str2_san))): for group, group_chars in groups: if i < len(group): group_chars.append(group[i]) size += 1 if size >= limit: break else: continue break final_str1 = ''.join(str1_chars).strip(separator) final_str2 = ''.join(str2_chars).strip(separator) return separator.join(filter(None, (final_str1, final_str2)))
[ "def", "sanitize_strings_for_openshift", "(", "str1", ",", "str2", "=", "''", ",", "limit", "=", "LABEL_MAX_CHARS", ",", "separator", "=", "'-'", ",", "label", "=", "True", ")", ":", "filter_chars", "=", "VALID_LABEL_CHARS", "if", "label", "else", "VALID_BUILD_CONFIG_NAME_CHARS", "str1_san", "=", "''", ".", "join", "(", "filter", "(", "filter_chars", ".", "match", ",", "list", "(", "str1", ")", ")", ")", "str2_san", "=", "''", ".", "join", "(", "filter", "(", "filter_chars", ".", "match", ",", "list", "(", "str2", ")", ")", ")", "str1_chars", "=", "[", "]", "str2_chars", "=", "[", "]", "groups", "=", "(", "(", "str1_san", ",", "str1_chars", ")", ",", "(", "str2_san", ",", "str2_chars", ")", ")", "size", "=", "len", "(", "separator", ")", "limit", "=", "min", "(", "limit", ",", "LABEL_MAX_CHARS", ")", "for", "i", "in", "range", "(", "max", "(", "len", "(", "str1_san", ")", ",", "len", "(", "str2_san", ")", ")", ")", ":", "for", "group", ",", "group_chars", "in", "groups", ":", "if", "i", "<", "len", "(", "group", ")", ":", "group_chars", ".", "append", "(", "group", "[", "i", "]", ")", "size", "+=", "1", "if", "size", ">=", "limit", ":", "break", "else", ":", "continue", "break", "final_str1", "=", "''", ".", "join", "(", "str1_chars", ")", ".", "strip", "(", "separator", ")", "final_str2", "=", "''", ".", "join", "(", "str2_chars", ")", ".", "strip", "(", "separator", ")", "return", "separator", ".", "join", "(", "filter", "(", "None", ",", "(", "final_str1", ",", "final_str2", ")", ")", ")" ]
OpenShift requires labels to be no more than 64 characters and forbids any characters other than alphanumerics, ., and -. BuildConfig names are similar, but cannot contain /. Sanitize and concatanate one or two strings to meet OpenShift's requirements. include an equal number of characters from both strings if the combined length is more than the limit.
[ "OpenShift", "requires", "labels", "to", "be", "no", "more", "than", "64", "characters", "and", "forbids", "any", "characters", "other", "than", "alphanumerics", ".", "and", "-", ".", "BuildConfig", "names", "are", "similar", "but", "cannot", "contain", "/", "." ]
571fe035dab3a7c02e1dccd5d65ffd75be750458
https://github.com/projectatomic/osbs-client/blob/571fe035dab3a7c02e1dccd5d65ffd75be750458/osbs/utils.py#L444-L477
train
projectatomic/osbs-client
osbs/utils.py
make_name_from_git
def make_name_from_git(repo, branch, limit=53, separator='-', hash_size=5): """ return name string representing the given git repo and branch to be used as a build name. NOTE: Build name will be used to generate pods which have a limit of 64 characters and is composed as: <buildname>-<buildnumber>-<podsuffix> rhel7-1-build Assuming '-XXXX' (5 chars) and '-build' (6 chars) as default suffixes, name should be limited to 53 chars (64 - 11). OpenShift is very peculiar in which BuildConfig names it allows. For this reason, only certain characters are allowed. Any disallowed characters will be removed from repo and branch names. :param repo: str, the git repository to be used :param branch: str, the git branch to be used :param limit: int, max name length :param separator: str, used to separate the repo and branch in name :return: str, name representing git repo and branch. """ branch = branch or 'unknown' full = urlparse(repo).path.lstrip('/') + branch repo = git_repo_humanish_part_from_uri(repo) shaval = sha256(full.encode('utf-8')).hexdigest() hash_str = shaval[:hash_size] limit = limit - len(hash_str) - 1 sanitized = sanitize_strings_for_openshift(repo, branch, limit, separator, False) return separator.join(filter(None, (sanitized, hash_str)))
python
def make_name_from_git(repo, branch, limit=53, separator='-', hash_size=5): """ return name string representing the given git repo and branch to be used as a build name. NOTE: Build name will be used to generate pods which have a limit of 64 characters and is composed as: <buildname>-<buildnumber>-<podsuffix> rhel7-1-build Assuming '-XXXX' (5 chars) and '-build' (6 chars) as default suffixes, name should be limited to 53 chars (64 - 11). OpenShift is very peculiar in which BuildConfig names it allows. For this reason, only certain characters are allowed. Any disallowed characters will be removed from repo and branch names. :param repo: str, the git repository to be used :param branch: str, the git branch to be used :param limit: int, max name length :param separator: str, used to separate the repo and branch in name :return: str, name representing git repo and branch. """ branch = branch or 'unknown' full = urlparse(repo).path.lstrip('/') + branch repo = git_repo_humanish_part_from_uri(repo) shaval = sha256(full.encode('utf-8')).hexdigest() hash_str = shaval[:hash_size] limit = limit - len(hash_str) - 1 sanitized = sanitize_strings_for_openshift(repo, branch, limit, separator, False) return separator.join(filter(None, (sanitized, hash_str)))
[ "def", "make_name_from_git", "(", "repo", ",", "branch", ",", "limit", "=", "53", ",", "separator", "=", "'-'", ",", "hash_size", "=", "5", ")", ":", "branch", "=", "branch", "or", "'unknown'", "full", "=", "urlparse", "(", "repo", ")", ".", "path", ".", "lstrip", "(", "'/'", ")", "+", "branch", "repo", "=", "git_repo_humanish_part_from_uri", "(", "repo", ")", "shaval", "=", "sha256", "(", "full", ".", "encode", "(", "'utf-8'", ")", ")", ".", "hexdigest", "(", ")", "hash_str", "=", "shaval", "[", ":", "hash_size", "]", "limit", "=", "limit", "-", "len", "(", "hash_str", ")", "-", "1", "sanitized", "=", "sanitize_strings_for_openshift", "(", "repo", ",", "branch", ",", "limit", ",", "separator", ",", "False", ")", "return", "separator", ".", "join", "(", "filter", "(", "None", ",", "(", "sanitized", ",", "hash_str", ")", ")", ")" ]
return name string representing the given git repo and branch to be used as a build name. NOTE: Build name will be used to generate pods which have a limit of 64 characters and is composed as: <buildname>-<buildnumber>-<podsuffix> rhel7-1-build Assuming '-XXXX' (5 chars) and '-build' (6 chars) as default suffixes, name should be limited to 53 chars (64 - 11). OpenShift is very peculiar in which BuildConfig names it allows. For this reason, only certain characters are allowed. Any disallowed characters will be removed from repo and branch names. :param repo: str, the git repository to be used :param branch: str, the git branch to be used :param limit: int, max name length :param separator: str, used to separate the repo and branch in name :return: str, name representing git repo and branch.
[ "return", "name", "string", "representing", "the", "given", "git", "repo", "and", "branch", "to", "be", "used", "as", "a", "build", "name", "." ]
571fe035dab3a7c02e1dccd5d65ffd75be750458
https://github.com/projectatomic/osbs-client/blob/571fe035dab3a7c02e1dccd5d65ffd75be750458/osbs/utils.py#L480-L515
train
projectatomic/osbs-client
osbs/utils.py
wrap_name_from_git
def wrap_name_from_git(prefix, suffix, *args, **kwargs): """ wraps the result of make_name_from_git in a suffix and postfix adding separators for each. see docstring for make_name_from_git for a full list of parameters """ # 64 is maximum length allowed by OpenShift # 2 is the number of dashes that will be added prefix = ''.join(filter(VALID_BUILD_CONFIG_NAME_CHARS.match, list(prefix))) suffix = ''.join(filter(VALID_BUILD_CONFIG_NAME_CHARS.match, list(suffix))) kwargs['limit'] = kwargs.get('limit', 64) - len(prefix) - len(suffix) - 2 name_from_git = make_name_from_git(*args, **kwargs) return '-'.join([prefix, name_from_git, suffix])
python
def wrap_name_from_git(prefix, suffix, *args, **kwargs): """ wraps the result of make_name_from_git in a suffix and postfix adding separators for each. see docstring for make_name_from_git for a full list of parameters """ # 64 is maximum length allowed by OpenShift # 2 is the number of dashes that will be added prefix = ''.join(filter(VALID_BUILD_CONFIG_NAME_CHARS.match, list(prefix))) suffix = ''.join(filter(VALID_BUILD_CONFIG_NAME_CHARS.match, list(suffix))) kwargs['limit'] = kwargs.get('limit', 64) - len(prefix) - len(suffix) - 2 name_from_git = make_name_from_git(*args, **kwargs) return '-'.join([prefix, name_from_git, suffix])
[ "def", "wrap_name_from_git", "(", "prefix", ",", "suffix", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# 64 is maximum length allowed by OpenShift", "# 2 is the number of dashes that will be added", "prefix", "=", "''", ".", "join", "(", "filter", "(", "VALID_BUILD_CONFIG_NAME_CHARS", ".", "match", ",", "list", "(", "prefix", ")", ")", ")", "suffix", "=", "''", ".", "join", "(", "filter", "(", "VALID_BUILD_CONFIG_NAME_CHARS", ".", "match", ",", "list", "(", "suffix", ")", ")", ")", "kwargs", "[", "'limit'", "]", "=", "kwargs", ".", "get", "(", "'limit'", ",", "64", ")", "-", "len", "(", "prefix", ")", "-", "len", "(", "suffix", ")", "-", "2", "name_from_git", "=", "make_name_from_git", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "'-'", ".", "join", "(", "[", "prefix", ",", "name_from_git", ",", "suffix", "]", ")" ]
wraps the result of make_name_from_git in a suffix and postfix adding separators for each. see docstring for make_name_from_git for a full list of parameters
[ "wraps", "the", "result", "of", "make_name_from_git", "in", "a", "suffix", "and", "postfix", "adding", "separators", "for", "each", "." ]
571fe035dab3a7c02e1dccd5d65ffd75be750458
https://github.com/projectatomic/osbs-client/blob/571fe035dab3a7c02e1dccd5d65ffd75be750458/osbs/utils.py#L518-L531
train
projectatomic/osbs-client
osbs/utils.py
sanitize_version
def sanitize_version(version): """ Take parse_version() output and standardize output from older setuptools' parse_version() to match current setuptools. """ if hasattr(version, 'base_version'): if version.base_version: parts = version.base_version.split('.') else: parts = [] else: parts = [] for part in version: if part.startswith('*'): break parts.append(part) parts = [int(p) for p in parts] if len(parts) < 3: parts += [0] * (3 - len(parts)) major, minor, micro = parts[:3] cleaned_version = '{}.{}.{}'.format(major, minor, micro) return cleaned_version
python
def sanitize_version(version): """ Take parse_version() output and standardize output from older setuptools' parse_version() to match current setuptools. """ if hasattr(version, 'base_version'): if version.base_version: parts = version.base_version.split('.') else: parts = [] else: parts = [] for part in version: if part.startswith('*'): break parts.append(part) parts = [int(p) for p in parts] if len(parts) < 3: parts += [0] * (3 - len(parts)) major, minor, micro = parts[:3] cleaned_version = '{}.{}.{}'.format(major, minor, micro) return cleaned_version
[ "def", "sanitize_version", "(", "version", ")", ":", "if", "hasattr", "(", "version", ",", "'base_version'", ")", ":", "if", "version", ".", "base_version", ":", "parts", "=", "version", ".", "base_version", ".", "split", "(", "'.'", ")", "else", ":", "parts", "=", "[", "]", "else", ":", "parts", "=", "[", "]", "for", "part", "in", "version", ":", "if", "part", ".", "startswith", "(", "'*'", ")", ":", "break", "parts", ".", "append", "(", "part", ")", "parts", "=", "[", "int", "(", "p", ")", "for", "p", "in", "parts", "]", "if", "len", "(", "parts", ")", "<", "3", ":", "parts", "+=", "[", "0", "]", "*", "(", "3", "-", "len", "(", "parts", ")", ")", "major", ",", "minor", ",", "micro", "=", "parts", "[", ":", "3", "]", "cleaned_version", "=", "'{}.{}.{}'", ".", "format", "(", "major", ",", "minor", ",", "micro", ")", "return", "cleaned_version" ]
Take parse_version() output and standardize output from older setuptools' parse_version() to match current setuptools.
[ "Take", "parse_version", "()", "output", "and", "standardize", "output", "from", "older", "setuptools", "parse_version", "()", "to", "match", "current", "setuptools", "." ]
571fe035dab3a7c02e1dccd5d65ffd75be750458
https://github.com/projectatomic/osbs-client/blob/571fe035dab3a7c02e1dccd5d65ffd75be750458/osbs/utils.py#L539-L562
train
projectatomic/osbs-client
osbs/utils.py
Labels.get_name
def get_name(self, label_type): """ returns the most preferred label name if there isn't any correct name in the list it will return newest label name """ if label_type in self._label_values: return self._label_values[label_type][0] else: return Labels.LABEL_NAMES[label_type][0]
python
def get_name(self, label_type): """ returns the most preferred label name if there isn't any correct name in the list it will return newest label name """ if label_type in self._label_values: return self._label_values[label_type][0] else: return Labels.LABEL_NAMES[label_type][0]
[ "def", "get_name", "(", "self", ",", "label_type", ")", ":", "if", "label_type", "in", "self", ".", "_label_values", ":", "return", "self", ".", "_label_values", "[", "label_type", "]", "[", "0", "]", "else", ":", "return", "Labels", ".", "LABEL_NAMES", "[", "label_type", "]", "[", "0", "]" ]
returns the most preferred label name if there isn't any correct name in the list it will return newest label name
[ "returns", "the", "most", "preferred", "label", "name", "if", "there", "isn", "t", "any", "correct", "name", "in", "the", "list", "it", "will", "return", "newest", "label", "name" ]
571fe035dab3a7c02e1dccd5d65ffd75be750458
https://github.com/projectatomic/osbs-client/blob/571fe035dab3a7c02e1dccd5d65ffd75be750458/osbs/utils.py#L627-L636
train
projectatomic/osbs-client
osbs/utils.py
Labels.get_new_names_by_old
def get_new_names_by_old(): """Return dictionary, new label name indexed by old label name.""" newdict = {} for label_type, label_names in Labels.LABEL_NAMES.items(): for oldname in label_names[1:]: newdict[oldname] = Labels.LABEL_NAMES[label_type][0] return newdict
python
def get_new_names_by_old(): """Return dictionary, new label name indexed by old label name.""" newdict = {} for label_type, label_names in Labels.LABEL_NAMES.items(): for oldname in label_names[1:]: newdict[oldname] = Labels.LABEL_NAMES[label_type][0] return newdict
[ "def", "get_new_names_by_old", "(", ")", ":", "newdict", "=", "{", "}", "for", "label_type", ",", "label_names", "in", "Labels", ".", "LABEL_NAMES", ".", "items", "(", ")", ":", "for", "oldname", "in", "label_names", "[", "1", ":", "]", ":", "newdict", "[", "oldname", "]", "=", "Labels", ".", "LABEL_NAMES", "[", "label_type", "]", "[", "0", "]", "return", "newdict" ]
Return dictionary, new label name indexed by old label name.
[ "Return", "dictionary", "new", "label", "name", "indexed", "by", "old", "label", "name", "." ]
571fe035dab3a7c02e1dccd5d65ffd75be750458
https://github.com/projectatomic/osbs-client/blob/571fe035dab3a7c02e1dccd5d65ffd75be750458/osbs/utils.py#L639-L646
train
projectatomic/osbs-client
osbs/utils.py
Labels.get_name_and_value
def get_name_and_value(self, label_type): """ Return tuple of (label name, label value) Raises KeyError if label doesn't exist """ if label_type in self._label_values: return self._label_values[label_type] else: return (label_type, self._df_labels[label_type])
python
def get_name_and_value(self, label_type): """ Return tuple of (label name, label value) Raises KeyError if label doesn't exist """ if label_type in self._label_values: return self._label_values[label_type] else: return (label_type, self._df_labels[label_type])
[ "def", "get_name_and_value", "(", "self", ",", "label_type", ")", ":", "if", "label_type", "in", "self", ".", "_label_values", ":", "return", "self", ".", "_label_values", "[", "label_type", "]", "else", ":", "return", "(", "label_type", ",", "self", ".", "_df_labels", "[", "label_type", "]", ")" ]
Return tuple of (label name, label value) Raises KeyError if label doesn't exist
[ "Return", "tuple", "of", "(", "label", "name", "label", "value", ")", "Raises", "KeyError", "if", "label", "doesn", "t", "exist" ]
571fe035dab3a7c02e1dccd5d65ffd75be750458
https://github.com/projectatomic/osbs-client/blob/571fe035dab3a7c02e1dccd5d65ffd75be750458/osbs/utils.py#L648-L656
train
projectatomic/osbs-client
osbs/kerberos_ccache.py
kerberos_ccache_init
def kerberos_ccache_init(principal, keytab_file, ccache_file=None): """ Checks whether kerberos credential cache has ticket-granting ticket that is valid for at least an hour. Default ccache is used unless ccache_file is provided. In that case, KRB5CCNAME environment variable is set to the value of ccache_file if we successfully obtain the ticket. """ tgt_valid = False env = {"LC_ALL": "C"} # klist uses locales to format date on RHEL7+ if ccache_file: env["KRB5CCNAME"] = ccache_file # check if we have tgt that is valid more than one hour rc, klist, _ = run(["klist"], extraenv=env) if rc == 0: for line in klist.splitlines(): m = re.match(KLIST_TGT_RE, line) if m: year = m.group("year") if len(year) == 2: year = "20" + year expires = datetime.datetime( int(year), int(m.group("month")), int(m.group("day")), int(m.group("hour")), int(m.group("minute")), int(m.group("second")) ) if expires - datetime.datetime.now() > datetime.timedelta(hours=1): logger.debug("Valid TGT found, not renewing") tgt_valid = True break if not tgt_valid: logger.debug("Retrieving kerberos TGT") rc, out, err = run(["kinit", "-k", "-t", keytab_file, principal], extraenv=env) if rc != 0: raise OsbsException("kinit returned %s:\nstdout: %s\nstderr: %s" % (rc, out, err)) if ccache_file: os.environ["KRB5CCNAME"] = ccache_file
python
def kerberos_ccache_init(principal, keytab_file, ccache_file=None): """ Checks whether kerberos credential cache has ticket-granting ticket that is valid for at least an hour. Default ccache is used unless ccache_file is provided. In that case, KRB5CCNAME environment variable is set to the value of ccache_file if we successfully obtain the ticket. """ tgt_valid = False env = {"LC_ALL": "C"} # klist uses locales to format date on RHEL7+ if ccache_file: env["KRB5CCNAME"] = ccache_file # check if we have tgt that is valid more than one hour rc, klist, _ = run(["klist"], extraenv=env) if rc == 0: for line in klist.splitlines(): m = re.match(KLIST_TGT_RE, line) if m: year = m.group("year") if len(year) == 2: year = "20" + year expires = datetime.datetime( int(year), int(m.group("month")), int(m.group("day")), int(m.group("hour")), int(m.group("minute")), int(m.group("second")) ) if expires - datetime.datetime.now() > datetime.timedelta(hours=1): logger.debug("Valid TGT found, not renewing") tgt_valid = True break if not tgt_valid: logger.debug("Retrieving kerberos TGT") rc, out, err = run(["kinit", "-k", "-t", keytab_file, principal], extraenv=env) if rc != 0: raise OsbsException("kinit returned %s:\nstdout: %s\nstderr: %s" % (rc, out, err)) if ccache_file: os.environ["KRB5CCNAME"] = ccache_file
[ "def", "kerberos_ccache_init", "(", "principal", ",", "keytab_file", ",", "ccache_file", "=", "None", ")", ":", "tgt_valid", "=", "False", "env", "=", "{", "\"LC_ALL\"", ":", "\"C\"", "}", "# klist uses locales to format date on RHEL7+", "if", "ccache_file", ":", "env", "[", "\"KRB5CCNAME\"", "]", "=", "ccache_file", "# check if we have tgt that is valid more than one hour", "rc", ",", "klist", ",", "_", "=", "run", "(", "[", "\"klist\"", "]", ",", "extraenv", "=", "env", ")", "if", "rc", "==", "0", ":", "for", "line", "in", "klist", ".", "splitlines", "(", ")", ":", "m", "=", "re", ".", "match", "(", "KLIST_TGT_RE", ",", "line", ")", "if", "m", ":", "year", "=", "m", ".", "group", "(", "\"year\"", ")", "if", "len", "(", "year", ")", "==", "2", ":", "year", "=", "\"20\"", "+", "year", "expires", "=", "datetime", ".", "datetime", "(", "int", "(", "year", ")", ",", "int", "(", "m", ".", "group", "(", "\"month\"", ")", ")", ",", "int", "(", "m", ".", "group", "(", "\"day\"", ")", ")", ",", "int", "(", "m", ".", "group", "(", "\"hour\"", ")", ")", ",", "int", "(", "m", ".", "group", "(", "\"minute\"", ")", ")", ",", "int", "(", "m", ".", "group", "(", "\"second\"", ")", ")", ")", "if", "expires", "-", "datetime", ".", "datetime", ".", "now", "(", ")", ">", "datetime", ".", "timedelta", "(", "hours", "=", "1", ")", ":", "logger", ".", "debug", "(", "\"Valid TGT found, not renewing\"", ")", "tgt_valid", "=", "True", "break", "if", "not", "tgt_valid", ":", "logger", ".", "debug", "(", "\"Retrieving kerberos TGT\"", ")", "rc", ",", "out", ",", "err", "=", "run", "(", "[", "\"kinit\"", ",", "\"-k\"", ",", "\"-t\"", ",", "keytab_file", ",", "principal", "]", ",", "extraenv", "=", "env", ")", "if", "rc", "!=", "0", ":", "raise", "OsbsException", "(", "\"kinit returned %s:\\nstdout: %s\\nstderr: %s\"", "%", "(", "rc", ",", "out", ",", "err", ")", ")", "if", "ccache_file", ":", "os", ".", "environ", "[", "\"KRB5CCNAME\"", "]", "=", "ccache_file" ]
Checks whether kerberos credential cache has ticket-granting ticket that is valid for at least an hour. Default ccache is used unless ccache_file is provided. In that case, KRB5CCNAME environment variable is set to the value of ccache_file if we successfully obtain the ticket.
[ "Checks", "whether", "kerberos", "credential", "cache", "has", "ticket", "-", "granting", "ticket", "that", "is", "valid", "for", "at", "least", "an", "hour", "." ]
571fe035dab3a7c02e1dccd5d65ffd75be750458
https://github.com/projectatomic/osbs-client/blob/571fe035dab3a7c02e1dccd5d65ffd75be750458/osbs/kerberos_ccache.py#L53-L93
train
thombashi/pytablereader
pytablereader/sqlite/core.py
SqliteFileLoader.load
def load(self): """ Extract tabular data as |TableData| instances from a SQLite database file. |load_source_desc_file| :return: Loaded table data iterator. |load_table_name_desc| =================== ============================================== Format specifier Value after the replacement =================== ============================================== ``%(filename)s`` |filename_desc| ``%(key)s`` ``%(format_name)s%(format_id)s`` ``%(format_name)s`` ``"sqlite"`` ``%(format_id)s`` |format_id_desc| ``%(global_id)s`` |global_id| =================== ============================================== :rtype: |TableData| iterator :raises pytablereader.DataError: If the SQLite database file data is invalid or empty. """ self._validate() formatter = SqliteTableFormatter(self.source) formatter.accept(self) return formatter.to_table_data()
python
def load(self): """ Extract tabular data as |TableData| instances from a SQLite database file. |load_source_desc_file| :return: Loaded table data iterator. |load_table_name_desc| =================== ============================================== Format specifier Value after the replacement =================== ============================================== ``%(filename)s`` |filename_desc| ``%(key)s`` ``%(format_name)s%(format_id)s`` ``%(format_name)s`` ``"sqlite"`` ``%(format_id)s`` |format_id_desc| ``%(global_id)s`` |global_id| =================== ============================================== :rtype: |TableData| iterator :raises pytablereader.DataError: If the SQLite database file data is invalid or empty. """ self._validate() formatter = SqliteTableFormatter(self.source) formatter.accept(self) return formatter.to_table_data()
[ "def", "load", "(", "self", ")", ":", "self", ".", "_validate", "(", ")", "formatter", "=", "SqliteTableFormatter", "(", "self", ".", "source", ")", "formatter", ".", "accept", "(", "self", ")", "return", "formatter", ".", "to_table_data", "(", ")" ]
Extract tabular data as |TableData| instances from a SQLite database file. |load_source_desc_file| :return: Loaded table data iterator. |load_table_name_desc| =================== ============================================== Format specifier Value after the replacement =================== ============================================== ``%(filename)s`` |filename_desc| ``%(key)s`` ``%(format_name)s%(format_id)s`` ``%(format_name)s`` ``"sqlite"`` ``%(format_id)s`` |format_id_desc| ``%(global_id)s`` |global_id| =================== ============================================== :rtype: |TableData| iterator :raises pytablereader.DataError: If the SQLite database file data is invalid or empty.
[ "Extract", "tabular", "data", "as", "|TableData|", "instances", "from", "a", "SQLite", "database", "file", ".", "|load_source_desc_file|" ]
bc3c057a2cc775bcce690e0e9019c2907b638101
https://github.com/thombashi/pytablereader/blob/bc3c057a2cc775bcce690e0e9019c2907b638101/pytablereader/sqlite/core.py#L40-L68
train
projectatomic/osbs-client
osbs/build/config_map_response.py
ConfigMapResponse.get_data
def get_data(self): """ Find the data stored in the config_map :return: dict, the json of the data data that was passed into the ConfigMap on creation """ data = graceful_chain_get(self.json, "data") if data is None: return {} data_dict = {} for key in data: if self.is_yaml(key): data_dict[key] = yaml.load(data[key]) else: data_dict[key] = json.loads(data[key]) return data_dict
python
def get_data(self): """ Find the data stored in the config_map :return: dict, the json of the data data that was passed into the ConfigMap on creation """ data = graceful_chain_get(self.json, "data") if data is None: return {} data_dict = {} for key in data: if self.is_yaml(key): data_dict[key] = yaml.load(data[key]) else: data_dict[key] = json.loads(data[key]) return data_dict
[ "def", "get_data", "(", "self", ")", ":", "data", "=", "graceful_chain_get", "(", "self", ".", "json", ",", "\"data\"", ")", "if", "data", "is", "None", ":", "return", "{", "}", "data_dict", "=", "{", "}", "for", "key", "in", "data", ":", "if", "self", ".", "is_yaml", "(", "key", ")", ":", "data_dict", "[", "key", "]", "=", "yaml", ".", "load", "(", "data", "[", "key", "]", ")", "else", ":", "data_dict", "[", "key", "]", "=", "json", ".", "loads", "(", "data", "[", "key", "]", ")", "return", "data_dict" ]
Find the data stored in the config_map :return: dict, the json of the data data that was passed into the ConfigMap on creation
[ "Find", "the", "data", "stored", "in", "the", "config_map" ]
571fe035dab3a7c02e1dccd5d65ffd75be750458
https://github.com/projectatomic/osbs-client/blob/571fe035dab3a7c02e1dccd5d65ffd75be750458/osbs/build/config_map_response.py#L40-L57
train
projectatomic/osbs-client
osbs/build/config_map_response.py
ConfigMapResponse.get_data_by_key
def get_data_by_key(self, name): """ Find the object stored by a JSON string at key 'name' :return: str or dict, the json of the str or dict stored in the ConfigMap at that location """ data = graceful_chain_get(self.json, "data") if data is None or name not in data: return {} if self.is_yaml(name): return yaml.load(data[name]) or {} return json.loads(data[name])
python
def get_data_by_key(self, name): """ Find the object stored by a JSON string at key 'name' :return: str or dict, the json of the str or dict stored in the ConfigMap at that location """ data = graceful_chain_get(self.json, "data") if data is None or name not in data: return {} if self.is_yaml(name): return yaml.load(data[name]) or {} return json.loads(data[name])
[ "def", "get_data_by_key", "(", "self", ",", "name", ")", ":", "data", "=", "graceful_chain_get", "(", "self", ".", "json", ",", "\"data\"", ")", "if", "data", "is", "None", "or", "name", "not", "in", "data", ":", "return", "{", "}", "if", "self", ".", "is_yaml", "(", "name", ")", ":", "return", "yaml", ".", "load", "(", "data", "[", "name", "]", ")", "or", "{", "}", "return", "json", ".", "loads", "(", "data", "[", "name", "]", ")" ]
Find the object stored by a JSON string at key 'name' :return: str or dict, the json of the str or dict stored in the ConfigMap at that location
[ "Find", "the", "object", "stored", "by", "a", "JSON", "string", "at", "key", "name" ]
571fe035dab3a7c02e1dccd5d65ffd75be750458
https://github.com/projectatomic/osbs-client/blob/571fe035dab3a7c02e1dccd5d65ffd75be750458/osbs/build/config_map_response.py#L59-L72
train
thombashi/pytablereader
pytablereader/jsonlines/formatter.py
FlatJsonTableConverter.to_table_data
def to_table_data(self): """ :raises ValueError: :raises pytablereader.error.ValidationError: """ self._validate_source_data() header_list = [] for json_record in self._buffer: for key in json_record: if key not in header_list: header_list.append(key) self._loader.inc_table_count() yield TableData( self._make_table_name(), header_list, self._buffer, dp_extractor=self._loader.dp_extractor, type_hints=self._extract_type_hints(header_list), )
python
def to_table_data(self): """ :raises ValueError: :raises pytablereader.error.ValidationError: """ self._validate_source_data() header_list = [] for json_record in self._buffer: for key in json_record: if key not in header_list: header_list.append(key) self._loader.inc_table_count() yield TableData( self._make_table_name(), header_list, self._buffer, dp_extractor=self._loader.dp_extractor, type_hints=self._extract_type_hints(header_list), )
[ "def", "to_table_data", "(", "self", ")", ":", "self", ".", "_validate_source_data", "(", ")", "header_list", "=", "[", "]", "for", "json_record", "in", "self", ".", "_buffer", ":", "for", "key", "in", "json_record", ":", "if", "key", "not", "in", "header_list", ":", "header_list", ".", "append", "(", "key", ")", "self", ".", "_loader", ".", "inc_table_count", "(", ")", "yield", "TableData", "(", "self", ".", "_make_table_name", "(", ")", ",", "header_list", ",", "self", ".", "_buffer", ",", "dp_extractor", "=", "self", ".", "_loader", ".", "dp_extractor", ",", "type_hints", "=", "self", ".", "_extract_type_hints", "(", "header_list", ")", ",", ")" ]
:raises ValueError: :raises pytablereader.error.ValidationError:
[ ":", "raises", "ValueError", ":", ":", "raises", "pytablereader", ".", "error", ".", "ValidationError", ":" ]
bc3c057a2cc775bcce690e0e9019c2907b638101
https://github.com/thombashi/pytablereader/blob/bc3c057a2cc775bcce690e0e9019c2907b638101/pytablereader/jsonlines/formatter.py#L33-L55
train
projectatomic/osbs-client
osbs/api.py
OSBS.list_builds
def list_builds(self, field_selector=None, koji_task_id=None, running=None, labels=None): """ List builds with matching fields :param field_selector: str, field selector for Builds :param koji_task_id: str, only list builds for Koji Task ID :return: BuildResponse list """ if running: running_fs = ",".join(["status!={status}".format(status=status.capitalize()) for status in BUILD_FINISHED_STATES]) if not field_selector: field_selector = running_fs else: field_selector = ','.join([field_selector, running_fs]) response = self.os.list_builds(field_selector=field_selector, koji_task_id=koji_task_id, labels=labels) serialized_response = response.json() build_list = [] for build in serialized_response["items"]: build_list.append(BuildResponse(build, self)) return build_list
python
def list_builds(self, field_selector=None, koji_task_id=None, running=None, labels=None): """ List builds with matching fields :param field_selector: str, field selector for Builds :param koji_task_id: str, only list builds for Koji Task ID :return: BuildResponse list """ if running: running_fs = ",".join(["status!={status}".format(status=status.capitalize()) for status in BUILD_FINISHED_STATES]) if not field_selector: field_selector = running_fs else: field_selector = ','.join([field_selector, running_fs]) response = self.os.list_builds(field_selector=field_selector, koji_task_id=koji_task_id, labels=labels) serialized_response = response.json() build_list = [] for build in serialized_response["items"]: build_list.append(BuildResponse(build, self)) return build_list
[ "def", "list_builds", "(", "self", ",", "field_selector", "=", "None", ",", "koji_task_id", "=", "None", ",", "running", "=", "None", ",", "labels", "=", "None", ")", ":", "if", "running", ":", "running_fs", "=", "\",\"", ".", "join", "(", "[", "\"status!={status}\"", ".", "format", "(", "status", "=", "status", ".", "capitalize", "(", ")", ")", "for", "status", "in", "BUILD_FINISHED_STATES", "]", ")", "if", "not", "field_selector", ":", "field_selector", "=", "running_fs", "else", ":", "field_selector", "=", "','", ".", "join", "(", "[", "field_selector", ",", "running_fs", "]", ")", "response", "=", "self", ".", "os", ".", "list_builds", "(", "field_selector", "=", "field_selector", ",", "koji_task_id", "=", "koji_task_id", ",", "labels", "=", "labels", ")", "serialized_response", "=", "response", ".", "json", "(", ")", "build_list", "=", "[", "]", "for", "build", "in", "serialized_response", "[", "\"items\"", "]", ":", "build_list", ".", "append", "(", "BuildResponse", "(", "build", ",", "self", ")", ")", "return", "build_list" ]
List builds with matching fields :param field_selector: str, field selector for Builds :param koji_task_id: str, only list builds for Koji Task ID :return: BuildResponse list
[ "List", "builds", "with", "matching", "fields" ]
571fe035dab3a7c02e1dccd5d65ffd75be750458
https://github.com/projectatomic/osbs-client/blob/571fe035dab3a7c02e1dccd5d65ffd75be750458/osbs/api.py#L135-L159
train
projectatomic/osbs-client
osbs/api.py
OSBS.get_pod_for_build
def get_pod_for_build(self, build_id): """ :return: PodResponse object for pod relating to the build """ pods = self.os.list_pods(label='openshift.io/build.name=%s' % build_id) serialized_response = pods.json() pod_list = [PodResponse(pod) for pod in serialized_response["items"]] if not pod_list: raise OsbsException("No pod for build") elif len(pod_list) != 1: raise OsbsException("Only one pod expected but %d returned", len(pod_list)) return pod_list[0]
python
def get_pod_for_build(self, build_id): """ :return: PodResponse object for pod relating to the build """ pods = self.os.list_pods(label='openshift.io/build.name=%s' % build_id) serialized_response = pods.json() pod_list = [PodResponse(pod) for pod in serialized_response["items"]] if not pod_list: raise OsbsException("No pod for build") elif len(pod_list) != 1: raise OsbsException("Only one pod expected but %d returned", len(pod_list)) return pod_list[0]
[ "def", "get_pod_for_build", "(", "self", ",", "build_id", ")", ":", "pods", "=", "self", ".", "os", ".", "list_pods", "(", "label", "=", "'openshift.io/build.name=%s'", "%", "build_id", ")", "serialized_response", "=", "pods", ".", "json", "(", ")", "pod_list", "=", "[", "PodResponse", "(", "pod", ")", "for", "pod", "in", "serialized_response", "[", "\"items\"", "]", "]", "if", "not", "pod_list", ":", "raise", "OsbsException", "(", "\"No pod for build\"", ")", "elif", "len", "(", "pod_list", ")", "!=", "1", ":", "raise", "OsbsException", "(", "\"Only one pod expected but %d returned\"", ",", "len", "(", "pod_list", ")", ")", "return", "pod_list", "[", "0", "]" ]
:return: PodResponse object for pod relating to the build
[ ":", "return", ":", "PodResponse", "object", "for", "pod", "relating", "to", "the", "build" ]
571fe035dab3a7c02e1dccd5d65ffd75be750458
https://github.com/projectatomic/osbs-client/blob/571fe035dab3a7c02e1dccd5d65ffd75be750458/osbs/api.py#L182-L194
train
projectatomic/osbs-client
osbs/api.py
OSBS.get_build_request
def get_build_request(self, build_type=None, inner_template=None, outer_template=None, customize_conf=None, arrangement_version=DEFAULT_ARRANGEMENT_VERSION): """ return instance of BuildRequest or BuildRequestV2 :param build_type: str, unused :param inner_template: str, name of inner template for BuildRequest :param outer_template: str, name of outer template for BuildRequest :param customize_conf: str, name of customization config for BuildRequest :param arrangement_version: int, value of the arrangement version :return: instance of BuildRequest or BuildRequestV2 """ if build_type is not None: warnings.warn("build types are deprecated, do not use the build_type argument") validate_arrangement_version(arrangement_version) if not arrangement_version or arrangement_version < REACTOR_CONFIG_ARRANGEMENT_VERSION: build_request = BuildRequest( build_json_store=self.os_conf.get_build_json_store(), inner_template=inner_template, outer_template=outer_template, customize_conf=customize_conf) else: build_request = BuildRequestV2( build_json_store=self.os_conf.get_build_json_store(), outer_template=outer_template, customize_conf=customize_conf) # Apply configured resource limits. cpu_limit = self.build_conf.get_cpu_limit() memory_limit = self.build_conf.get_memory_limit() storage_limit = self.build_conf.get_storage_limit() if (cpu_limit is not None or memory_limit is not None or storage_limit is not None): build_request.set_resource_limits(cpu=cpu_limit, memory=memory_limit, storage=storage_limit) return build_request
python
def get_build_request(self, build_type=None, inner_template=None, outer_template=None, customize_conf=None, arrangement_version=DEFAULT_ARRANGEMENT_VERSION): """ return instance of BuildRequest or BuildRequestV2 :param build_type: str, unused :param inner_template: str, name of inner template for BuildRequest :param outer_template: str, name of outer template for BuildRequest :param customize_conf: str, name of customization config for BuildRequest :param arrangement_version: int, value of the arrangement version :return: instance of BuildRequest or BuildRequestV2 """ if build_type is not None: warnings.warn("build types are deprecated, do not use the build_type argument") validate_arrangement_version(arrangement_version) if not arrangement_version or arrangement_version < REACTOR_CONFIG_ARRANGEMENT_VERSION: build_request = BuildRequest( build_json_store=self.os_conf.get_build_json_store(), inner_template=inner_template, outer_template=outer_template, customize_conf=customize_conf) else: build_request = BuildRequestV2( build_json_store=self.os_conf.get_build_json_store(), outer_template=outer_template, customize_conf=customize_conf) # Apply configured resource limits. cpu_limit = self.build_conf.get_cpu_limit() memory_limit = self.build_conf.get_memory_limit() storage_limit = self.build_conf.get_storage_limit() if (cpu_limit is not None or memory_limit is not None or storage_limit is not None): build_request.set_resource_limits(cpu=cpu_limit, memory=memory_limit, storage=storage_limit) return build_request
[ "def", "get_build_request", "(", "self", ",", "build_type", "=", "None", ",", "inner_template", "=", "None", ",", "outer_template", "=", "None", ",", "customize_conf", "=", "None", ",", "arrangement_version", "=", "DEFAULT_ARRANGEMENT_VERSION", ")", ":", "if", "build_type", "is", "not", "None", ":", "warnings", ".", "warn", "(", "\"build types are deprecated, do not use the build_type argument\"", ")", "validate_arrangement_version", "(", "arrangement_version", ")", "if", "not", "arrangement_version", "or", "arrangement_version", "<", "REACTOR_CONFIG_ARRANGEMENT_VERSION", ":", "build_request", "=", "BuildRequest", "(", "build_json_store", "=", "self", ".", "os_conf", ".", "get_build_json_store", "(", ")", ",", "inner_template", "=", "inner_template", ",", "outer_template", "=", "outer_template", ",", "customize_conf", "=", "customize_conf", ")", "else", ":", "build_request", "=", "BuildRequestV2", "(", "build_json_store", "=", "self", ".", "os_conf", ".", "get_build_json_store", "(", ")", ",", "outer_template", "=", "outer_template", ",", "customize_conf", "=", "customize_conf", ")", "# Apply configured resource limits.", "cpu_limit", "=", "self", ".", "build_conf", ".", "get_cpu_limit", "(", ")", "memory_limit", "=", "self", ".", "build_conf", ".", "get_memory_limit", "(", ")", "storage_limit", "=", "self", ".", "build_conf", ".", "get_storage_limit", "(", ")", "if", "(", "cpu_limit", "is", "not", "None", "or", "memory_limit", "is", "not", "None", "or", "storage_limit", "is", "not", "None", ")", ":", "build_request", ".", "set_resource_limits", "(", "cpu", "=", "cpu_limit", ",", "memory", "=", "memory_limit", ",", "storage", "=", "storage_limit", ")", "return", "build_request" ]
return instance of BuildRequest or BuildRequestV2 :param build_type: str, unused :param inner_template: str, name of inner template for BuildRequest :param outer_template: str, name of outer template for BuildRequest :param customize_conf: str, name of customization config for BuildRequest :param arrangement_version: int, value of the arrangement version :return: instance of BuildRequest or BuildRequestV2
[ "return", "instance", "of", "BuildRequest", "or", "BuildRequestV2" ]
571fe035dab3a7c02e1dccd5d65ffd75be750458
https://github.com/projectatomic/osbs-client/blob/571fe035dab3a7c02e1dccd5d65ffd75be750458/osbs/api.py#L197-L239
train
projectatomic/osbs-client
osbs/api.py
OSBS.create_build_from_buildrequest
def create_build_from_buildrequest(self, build_request): """ render provided build_request and submit build from it :param build_request: instance of build.build_request.BuildRequest :return: instance of build.build_response.BuildResponse """ build_request.set_openshift_required_version(self.os_conf.get_openshift_required_version()) build = build_request.render() response = self.os.create_build(json.dumps(build)) build_response = BuildResponse(response.json(), self) return build_response
python
def create_build_from_buildrequest(self, build_request): """ render provided build_request and submit build from it :param build_request: instance of build.build_request.BuildRequest :return: instance of build.build_response.BuildResponse """ build_request.set_openshift_required_version(self.os_conf.get_openshift_required_version()) build = build_request.render() response = self.os.create_build(json.dumps(build)) build_response = BuildResponse(response.json(), self) return build_response
[ "def", "create_build_from_buildrequest", "(", "self", ",", "build_request", ")", ":", "build_request", ".", "set_openshift_required_version", "(", "self", ".", "os_conf", ".", "get_openshift_required_version", "(", ")", ")", "build", "=", "build_request", ".", "render", "(", ")", "response", "=", "self", ".", "os", ".", "create_build", "(", "json", ".", "dumps", "(", "build", ")", ")", "build_response", "=", "BuildResponse", "(", "response", ".", "json", "(", ")", ",", "self", ")", "return", "build_response" ]
render provided build_request and submit build from it :param build_request: instance of build.build_request.BuildRequest :return: instance of build.build_response.BuildResponse
[ "render", "provided", "build_request", "and", "submit", "build", "from", "it" ]
571fe035dab3a7c02e1dccd5d65ffd75be750458
https://github.com/projectatomic/osbs-client/blob/571fe035dab3a7c02e1dccd5d65ffd75be750458/osbs/api.py#L242-L253
train
projectatomic/osbs-client
osbs/api.py
OSBS._get_existing_build_config
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 - metadata.labels.git-repo-name AND metadata.labels.git-branch are equal AND metadata.spec.source.git.uri are equal OR - metadata.name are equal """ bc_labels = build_config['metadata']['labels'] git_labels = { "label_selectors": [(key, bc_labels[key]) for key in self._GIT_LABEL_KEYS] } old_labels_kwargs = { "label_selectors": [(key, bc_labels[key]) for key in self._OLD_LABEL_KEYS], "filter_key": FILTER_KEY, "filter_value": graceful_chain_get(build_config, *FILTER_KEY.split('.')) } name = { "build_config_id": build_config['metadata']['name'] } queries = ( (self.os.get_build_config_by_labels, git_labels), (self.os.get_build_config_by_labels_filtered, old_labels_kwargs), (self.os.get_build_config, name), ) existing_bc = None for func, kwargs in queries: try: existing_bc = func(**kwargs) # build config found break except OsbsException as exc: # doesn't exist logger.info('Build config NOT found via %s: %s', func.__name__, str(exc)) continue return existing_bc
python
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 - metadata.labels.git-repo-name AND metadata.labels.git-branch are equal AND metadata.spec.source.git.uri are equal OR - metadata.name are equal """ bc_labels = build_config['metadata']['labels'] git_labels = { "label_selectors": [(key, bc_labels[key]) for key in self._GIT_LABEL_KEYS] } old_labels_kwargs = { "label_selectors": [(key, bc_labels[key]) for key in self._OLD_LABEL_KEYS], "filter_key": FILTER_KEY, "filter_value": graceful_chain_get(build_config, *FILTER_KEY.split('.')) } name = { "build_config_id": build_config['metadata']['name'] } queries = ( (self.os.get_build_config_by_labels, git_labels), (self.os.get_build_config_by_labels_filtered, old_labels_kwargs), (self.os.get_build_config, name), ) existing_bc = None for func, kwargs in queries: try: existing_bc = func(**kwargs) # build config found break except OsbsException as exc: # doesn't exist logger.info('Build config NOT found via %s: %s', func.__name__, str(exc)) continue return existing_bc
[ "def", "_get_existing_build_config", "(", "self", ",", "build_config", ")", ":", "bc_labels", "=", "build_config", "[", "'metadata'", "]", "[", "'labels'", "]", "git_labels", "=", "{", "\"label_selectors\"", ":", "[", "(", "key", ",", "bc_labels", "[", "key", "]", ")", "for", "key", "in", "self", ".", "_GIT_LABEL_KEYS", "]", "}", "old_labels_kwargs", "=", "{", "\"label_selectors\"", ":", "[", "(", "key", ",", "bc_labels", "[", "key", "]", ")", "for", "key", "in", "self", ".", "_OLD_LABEL_KEYS", "]", ",", "\"filter_key\"", ":", "FILTER_KEY", ",", "\"filter_value\"", ":", "graceful_chain_get", "(", "build_config", ",", "*", "FILTER_KEY", ".", "split", "(", "'.'", ")", ")", "}", "name", "=", "{", "\"build_config_id\"", ":", "build_config", "[", "'metadata'", "]", "[", "'name'", "]", "}", "queries", "=", "(", "(", "self", ".", "os", ".", "get_build_config_by_labels", ",", "git_labels", ")", ",", "(", "self", ".", "os", ".", "get_build_config_by_labels_filtered", ",", "old_labels_kwargs", ")", ",", "(", "self", ".", "os", ".", "get_build_config", ",", "name", ")", ",", ")", "existing_bc", "=", "None", "for", "func", ",", "kwargs", "in", "queries", ":", "try", ":", "existing_bc", "=", "func", "(", "*", "*", "kwargs", ")", "# build config found", "break", "except", "OsbsException", "as", "exc", ":", "# doesn't exist", "logger", ".", "info", "(", "'Build config NOT found via %s: %s'", ",", "func", ".", "__name__", ",", "str", "(", "exc", ")", ")", "continue", "return", "existing_bc" ]
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 metadata.spec.source.git.uri are equal OR - metadata.name are equal
[ "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", "metadata", ".", "spec", ".", "source", ".", "git", ".", "uri", "are", "equal", "OR", "-", "metadata", ".", "name", "are", "equal" ]
571fe035dab3a7c02e1dccd5d65ffd75be750458
https://github.com/projectatomic/osbs-client/blob/571fe035dab3a7c02e1dccd5d65ffd75be750458/osbs/api.py#L294-L338
train
projectatomic/osbs-client
osbs/api.py
OSBS._get_image_stream_info_for_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_stream_tag_name = None if build_request.has_ist_trigger(): image_stream_tag_id = build_request.trigger_imagestreamtag image_stream_id, image_stream_tag_name = image_stream_tag_id.split(':') try: image_stream = self.get_image_stream(image_stream_id).json() except OsbsResponseException as x: if x.status_code != 404: raise if image_stream: try: self.get_image_stream_tag(image_stream_tag_id).json() except OsbsResponseException as x: if x.status_code != 404: raise return image_stream, image_stream_tag_name
python
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_stream_tag_name = None if build_request.has_ist_trigger(): image_stream_tag_id = build_request.trigger_imagestreamtag image_stream_id, image_stream_tag_name = image_stream_tag_id.split(':') try: image_stream = self.get_image_stream(image_stream_id).json() except OsbsResponseException as x: if x.status_code != 404: raise if image_stream: try: self.get_image_stream_tag(image_stream_tag_id).json() except OsbsResponseException as x: if x.status_code != 404: raise return image_stream, image_stream_tag_name
[ "def", "_get_image_stream_info_for_build_request", "(", "self", ",", "build_request", ")", ":", "image_stream", "=", "None", "image_stream_tag_name", "=", "None", "if", "build_request", ".", "has_ist_trigger", "(", ")", ":", "image_stream_tag_id", "=", "build_request", ".", "trigger_imagestreamtag", "image_stream_id", ",", "image_stream_tag_name", "=", "image_stream_tag_id", ".", "split", "(", "':'", ")", "try", ":", "image_stream", "=", "self", ".", "get_image_stream", "(", "image_stream_id", ")", ".", "json", "(", ")", "except", "OsbsResponseException", "as", "x", ":", "if", "x", ".", "status_code", "!=", "404", ":", "raise", "if", "image_stream", ":", "try", ":", "self", ".", "get_image_stream_tag", "(", "image_stream_tag_id", ")", ".", "json", "(", ")", "except", "OsbsResponseException", "as", "x", ":", "if", "x", ".", "status_code", "!=", "404", ":", "raise", "return", "image_stream", ",", "image_stream_tag_name" ]
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.
[ "Return", "ImageStream", "and", "ImageStreamTag", "name", "for", "base_image", "of", "build_request" ]
571fe035dab3a7c02e1dccd5d65ffd75be750458
https://github.com/projectatomic/osbs-client/blob/571fe035dab3a7c02e1dccd5d65ffd75be750458/osbs/api.py#L393-L419
train
projectatomic/osbs-client
osbs/api.py
OSBS.create_prod_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 :param target: str, koji target :param architecture: str, build architecture :param yum_repourls: list, URLs for yum repos :param koji_task_id: int, koji task ID requesting build :param scratch: bool, this is a scratch build :param platform: str, the platform name :param platforms: list<str>, the name of each platform :param release: str, the release value to use :param inner_template: str, name of inner template for BuildRequest :param outer_template: str, name of outer template for BuildRequest :param customize_conf: str, name of customization config for BuildRequest :param arrangement_version: int, numbered arrangement of plugins for orchestration workflow :param signing_intent: str, signing intent of the ODCS composes :param compose_ids: list<int>, ODCS composes used :return: BuildResponse instance """ logger.warning("prod (all-in-one) builds are deprecated, " "please use create_orchestrator_build " "(support will be removed in version 0.54)") return self._do_create_prod_build(*args, **kwargs)
python
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 :param target: str, koji target :param architecture: str, build architecture :param yum_repourls: list, URLs for yum repos :param koji_task_id: int, koji task ID requesting build :param scratch: bool, this is a scratch build :param platform: str, the platform name :param platforms: list<str>, the name of each platform :param release: str, the release value to use :param inner_template: str, name of inner template for BuildRequest :param outer_template: str, name of outer template for BuildRequest :param customize_conf: str, name of customization config for BuildRequest :param arrangement_version: int, numbered arrangement of plugins for orchestration workflow :param signing_intent: str, signing intent of the ODCS composes :param compose_ids: list<int>, ODCS composes used :return: BuildResponse instance """ logger.warning("prod (all-in-one) builds are deprecated, " "please use create_orchestrator_build " "(support will be removed in version 0.54)") return self._do_create_prod_build(*args, **kwargs)
[ "def", "create_prod_build", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "logger", ".", "warning", "(", "\"prod (all-in-one) builds are deprecated, \"", "\"please use create_orchestrator_build \"", "\"(support will be removed in version 0.54)\"", ")", "return", "self", ".", "_do_create_prod_build", "(", "*", "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 :param target: str, koji target :param architecture: str, build architecture :param yum_repourls: list, URLs for yum repos :param koji_task_id: int, koji task ID requesting build :param scratch: bool, this is a scratch build :param platform: str, the platform name :param platforms: list<str>, the name of each platform :param release: str, the release value to use :param inner_template: str, name of inner template for BuildRequest :param outer_template: str, name of outer template for BuildRequest :param customize_conf: str, name of customization config for BuildRequest :param arrangement_version: int, numbered arrangement of plugins for orchestration workflow :param signing_intent: str, signing intent of the ODCS composes :param compose_ids: list<int>, ODCS composes used :return: BuildResponse instance
[ "Create", "a", "production", "build" ]
571fe035dab3a7c02e1dccd5d65ffd75be750458
https://github.com/projectatomic/osbs-client/blob/571fe035dab3a7c02e1dccd5d65ffd75be750458/osbs/api.py#L765-L793
train
projectatomic/osbs-client
osbs/api.py
OSBS.create_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 used to select which worker_inner:n.json template to use - inner template set to worker_inner:n.json if not set - outer template set to worker.json if not set - customize configuration set to worker_customize.json if not set :return: BuildResponse instance """ missing = set() for required in ('platform', 'release', 'arrangement_version'): if not kwargs.get(required): missing.add(required) if missing: raise ValueError("Worker build missing required parameters: %s" % missing) if kwargs.get('platforms'): raise ValueError("Worker build called with unwanted platforms param") arrangement_version = kwargs['arrangement_version'] kwargs.setdefault('inner_template', WORKER_INNER_TEMPLATE.format( arrangement_version=arrangement_version)) kwargs.setdefault('outer_template', WORKER_OUTER_TEMPLATE) kwargs.setdefault('customize_conf', WORKER_CUSTOMIZE_CONF) kwargs['build_type'] = BUILD_TYPE_WORKER try: return self._do_create_prod_build(**kwargs) except IOError as ex: if os.path.basename(ex.filename) == kwargs['inner_template']: raise OsbsValidationException("worker invalid arrangement_version %s" % arrangement_version) raise
python
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 used to select which worker_inner:n.json template to use - inner template set to worker_inner:n.json if not set - outer template set to worker.json if not set - customize configuration set to worker_customize.json if not set :return: BuildResponse instance """ missing = set() for required in ('platform', 'release', 'arrangement_version'): if not kwargs.get(required): missing.add(required) if missing: raise ValueError("Worker build missing required parameters: %s" % missing) if kwargs.get('platforms'): raise ValueError("Worker build called with unwanted platforms param") arrangement_version = kwargs['arrangement_version'] kwargs.setdefault('inner_template', WORKER_INNER_TEMPLATE.format( arrangement_version=arrangement_version)) kwargs.setdefault('outer_template', WORKER_OUTER_TEMPLATE) kwargs.setdefault('customize_conf', WORKER_CUSTOMIZE_CONF) kwargs['build_type'] = BUILD_TYPE_WORKER try: return self._do_create_prod_build(**kwargs) except IOError as ex: if os.path.basename(ex.filename) == kwargs['inner_template']: raise OsbsValidationException("worker invalid arrangement_version %s" % arrangement_version) raise
[ "def", "create_worker_build", "(", "self", ",", "*", "*", "kwargs", ")", ":", "missing", "=", "set", "(", ")", "for", "required", "in", "(", "'platform'", ",", "'release'", ",", "'arrangement_version'", ")", ":", "if", "not", "kwargs", ".", "get", "(", "required", ")", ":", "missing", ".", "add", "(", "required", ")", "if", "missing", ":", "raise", "ValueError", "(", "\"Worker build missing required parameters: %s\"", "%", "missing", ")", "if", "kwargs", ".", "get", "(", "'platforms'", ")", ":", "raise", "ValueError", "(", "\"Worker build called with unwanted platforms param\"", ")", "arrangement_version", "=", "kwargs", "[", "'arrangement_version'", "]", "kwargs", ".", "setdefault", "(", "'inner_template'", ",", "WORKER_INNER_TEMPLATE", ".", "format", "(", "arrangement_version", "=", "arrangement_version", ")", ")", "kwargs", ".", "setdefault", "(", "'outer_template'", ",", "WORKER_OUTER_TEMPLATE", ")", "kwargs", ".", "setdefault", "(", "'customize_conf'", ",", "WORKER_CUSTOMIZE_CONF", ")", "kwargs", "[", "'build_type'", "]", "=", "BUILD_TYPE_WORKER", "try", ":", "return", "self", ".", "_do_create_prod_build", "(", "*", "*", "kwargs", ")", "except", "IOError", "as", "ex", ":", "if", "os", ".", "path", ".", "basename", "(", "ex", ".", "filename", ")", "==", "kwargs", "[", "'inner_template'", "]", ":", "raise", "OsbsValidationException", "(", "\"worker invalid arrangement_version %s\"", "%", "arrangement_version", ")", "raise" ]
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 used to select which worker_inner:n.json template to use - inner template set to worker_inner:n.json if not set - outer template set to worker.json if not set - customize configuration set to worker_customize.json if not set :return: BuildResponse instance
[ "Create", "a", "worker", "build" ]
571fe035dab3a7c02e1dccd5d65ffd75be750458
https://github.com/projectatomic/osbs-client/blob/571fe035dab3a7c02e1dccd5d65ffd75be750458/osbs/api.py#L806-L847
train
projectatomic/osbs-client
osbs/api.py
OSBS.create_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 orchestrator_inner:n.json template to use - inner template set to orchestrator_inner:n.json if not set - outer template set to orchestrator.json if not set - customize configuration set to orchestrator_customize.json if not set :return: BuildResponse instance """ if not self.can_orchestrate(): raise OsbsOrchestratorNotEnabled("can't create orchestrate build " "when can_orchestrate isn't enabled") extra = [x for x in ('platform',) if kwargs.get(x)] if extra: raise ValueError("Orchestrator build called with unwanted parameters: %s" % extra) arrangement_version = kwargs.setdefault('arrangement_version', self.build_conf.get_arrangement_version()) if arrangement_version < REACTOR_CONFIG_ARRANGEMENT_VERSION and not kwargs.get('platforms'): raise ValueError('Orchestrator build requires platforms param') kwargs.setdefault('inner_template', ORCHESTRATOR_INNER_TEMPLATE.format( arrangement_version=arrangement_version)) kwargs.setdefault('outer_template', ORCHESTRATOR_OUTER_TEMPLATE) kwargs.setdefault('customize_conf', ORCHESTRATOR_CUSTOMIZE_CONF) kwargs['build_type'] = BUILD_TYPE_ORCHESTRATOR try: return self._do_create_prod_build(**kwargs) except IOError as ex: if os.path.basename(ex.filename) == kwargs['inner_template']: raise OsbsValidationException("orchestrator invalid arrangement_version %s" % arrangement_version) raise
python
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 orchestrator_inner:n.json template to use - inner template set to orchestrator_inner:n.json if not set - outer template set to orchestrator.json if not set - customize configuration set to orchestrator_customize.json if not set :return: BuildResponse instance """ if not self.can_orchestrate(): raise OsbsOrchestratorNotEnabled("can't create orchestrate build " "when can_orchestrate isn't enabled") extra = [x for x in ('platform',) if kwargs.get(x)] if extra: raise ValueError("Orchestrator build called with unwanted parameters: %s" % extra) arrangement_version = kwargs.setdefault('arrangement_version', self.build_conf.get_arrangement_version()) if arrangement_version < REACTOR_CONFIG_ARRANGEMENT_VERSION and not kwargs.get('platforms'): raise ValueError('Orchestrator build requires platforms param') kwargs.setdefault('inner_template', ORCHESTRATOR_INNER_TEMPLATE.format( arrangement_version=arrangement_version)) kwargs.setdefault('outer_template', ORCHESTRATOR_OUTER_TEMPLATE) kwargs.setdefault('customize_conf', ORCHESTRATOR_CUSTOMIZE_CONF) kwargs['build_type'] = BUILD_TYPE_ORCHESTRATOR try: return self._do_create_prod_build(**kwargs) except IOError as ex: if os.path.basename(ex.filename) == kwargs['inner_template']: raise OsbsValidationException("orchestrator invalid arrangement_version %s" % arrangement_version) raise
[ "def", "create_orchestrator_build", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "can_orchestrate", "(", ")", ":", "raise", "OsbsOrchestratorNotEnabled", "(", "\"can't create orchestrate build \"", "\"when can_orchestrate isn't enabled\"", ")", "extra", "=", "[", "x", "for", "x", "in", "(", "'platform'", ",", ")", "if", "kwargs", ".", "get", "(", "x", ")", "]", "if", "extra", ":", "raise", "ValueError", "(", "\"Orchestrator build called with unwanted parameters: %s\"", "%", "extra", ")", "arrangement_version", "=", "kwargs", ".", "setdefault", "(", "'arrangement_version'", ",", "self", ".", "build_conf", ".", "get_arrangement_version", "(", ")", ")", "if", "arrangement_version", "<", "REACTOR_CONFIG_ARRANGEMENT_VERSION", "and", "not", "kwargs", ".", "get", "(", "'platforms'", ")", ":", "raise", "ValueError", "(", "'Orchestrator build requires platforms param'", ")", "kwargs", ".", "setdefault", "(", "'inner_template'", ",", "ORCHESTRATOR_INNER_TEMPLATE", ".", "format", "(", "arrangement_version", "=", "arrangement_version", ")", ")", "kwargs", ".", "setdefault", "(", "'outer_template'", ",", "ORCHESTRATOR_OUTER_TEMPLATE", ")", "kwargs", ".", "setdefault", "(", "'customize_conf'", ",", "ORCHESTRATOR_CUSTOMIZE_CONF", ")", "kwargs", "[", "'build_type'", "]", "=", "BUILD_TYPE_ORCHESTRATOR", "try", ":", "return", "self", ".", "_do_create_prod_build", "(", "*", "*", "kwargs", ")", "except", "IOError", "as", "ex", ":", "if", "os", ".", "path", ".", "basename", "(", "ex", ".", "filename", ")", "==", "kwargs", "[", "'inner_template'", "]", ":", "raise", "OsbsValidationException", "(", "\"orchestrator invalid arrangement_version %s\"", "%", "arrangement_version", ")", "raise" ]
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 orchestrator_inner:n.json template to use - inner template set to orchestrator_inner:n.json if not set - outer template set to orchestrator.json if not set - customize configuration set to orchestrator_customize.json if not set :return: BuildResponse instance
[ "Create", "an", "orchestrator", "build" ]
571fe035dab3a7c02e1dccd5d65ffd75be750458
https://github.com/projectatomic/osbs-client/blob/571fe035dab3a7c02e1dccd5d65ffd75be750458/osbs/api.py#L850-L891
train
projectatomic/osbs-client
osbs/api.py
OSBS.get_build_logs
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, we return the bytes exactly as they came from the container. :param build_id: str :param follow: bool, fetch logs as they come? :param build_json: dict, to save one get-build query :param wait_if_missing: bool, if build doesn't exist, wait :param decode: bool, whether or not to decode logs as utf-8 :return: None, bytes, or iterable of bytes """ logs = self.os.logs(build_id, follow=follow, build_json=build_json, wait_if_missing=wait_if_missing) if decode and isinstance(logs, GeneratorType): return self._decode_build_logs_generator(logs) # str or None returned from self.os.logs() if decode and logs is not None: logs = logs.decode("utf-8").rstrip() return logs
python
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, we return the bytes exactly as they came from the container. :param build_id: str :param follow: bool, fetch logs as they come? :param build_json: dict, to save one get-build query :param wait_if_missing: bool, if build doesn't exist, wait :param decode: bool, whether or not to decode logs as utf-8 :return: None, bytes, or iterable of bytes """ logs = self.os.logs(build_id, follow=follow, build_json=build_json, wait_if_missing=wait_if_missing) if decode and isinstance(logs, GeneratorType): return self._decode_build_logs_generator(logs) # str or None returned from self.os.logs() if decode and logs is not None: logs = logs.decode("utf-8").rstrip() return logs
[ "def", "get_build_logs", "(", "self", ",", "build_id", ",", "follow", "=", "False", ",", "build_json", "=", "None", ",", "wait_if_missing", "=", "False", ",", "decode", "=", "False", ")", ":", "logs", "=", "self", ".", "os", ".", "logs", "(", "build_id", ",", "follow", "=", "follow", ",", "build_json", "=", "build_json", ",", "wait_if_missing", "=", "wait_if_missing", ")", "if", "decode", "and", "isinstance", "(", "logs", ",", "GeneratorType", ")", ":", "return", "self", ".", "_decode_build_logs_generator", "(", "logs", ")", "# str or None returned from self.os.logs()", "if", "decode", "and", "logs", "is", "not", "None", ":", "logs", "=", "logs", ".", "decode", "(", "\"utf-8\"", ")", ".", "rstrip", "(", ")", "return", "logs" ]
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, we return the bytes exactly as they came from the container. :param build_id: str :param follow: bool, fetch logs as they come? :param build_json: dict, to save one get-build query :param wait_if_missing: bool, if build doesn't exist, wait :param decode: bool, whether or not to decode logs as utf-8 :return: None, bytes, or iterable of bytes
[ "provide", "logs", "from", "build" ]
571fe035dab3a7c02e1dccd5d65ffd75be750458
https://github.com/projectatomic/osbs-client/blob/571fe035dab3a7c02e1dccd5d65ffd75be750458/osbs/api.py#L899-L925
train
projectatomic/osbs-client
osbs/api.py
OSBS.get_orchestrator_build_logs
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 yielding objects with attributes 'platform' and 'line' """ logs = self.get_build_logs(build_id=build_id, follow=follow, wait_if_missing=wait_if_missing, decode=True) if logs is None: return if isinstance(logs, GeneratorType): for entries in logs: for entry in entries.splitlines(): yield LogEntry(*self._parse_build_log_entry(entry)) else: for entry in logs.splitlines(): yield LogEntry(*self._parse_build_log_entry(entry))
python
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 yielding objects with attributes 'platform' and 'line' """ logs = self.get_build_logs(build_id=build_id, follow=follow, wait_if_missing=wait_if_missing, decode=True) if logs is None: return if isinstance(logs, GeneratorType): for entries in logs: for entry in entries.splitlines(): yield LogEntry(*self._parse_build_log_entry(entry)) else: for entry in logs.splitlines(): yield LogEntry(*self._parse_build_log_entry(entry))
[ "def", "get_orchestrator_build_logs", "(", "self", ",", "build_id", ",", "follow", "=", "False", ",", "wait_if_missing", "=", "False", ")", ":", "logs", "=", "self", ".", "get_build_logs", "(", "build_id", "=", "build_id", ",", "follow", "=", "follow", ",", "wait_if_missing", "=", "wait_if_missing", ",", "decode", "=", "True", ")", "if", "logs", "is", "None", ":", "return", "if", "isinstance", "(", "logs", ",", "GeneratorType", ")", ":", "for", "entries", "in", "logs", ":", "for", "entry", "in", "entries", ".", "splitlines", "(", ")", ":", "yield", "LogEntry", "(", "*", "self", ".", "_parse_build_log_entry", "(", "entry", ")", ")", "else", ":", "for", "entry", "in", "logs", ".", "splitlines", "(", ")", ":", "yield", "LogEntry", "(", "*", "self", ".", "_parse_build_log_entry", "(", "entry", ")", ")" ]
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 yielding objects with attributes 'platform' and 'line'
[ "provide", "logs", "from", "orchestrator", "build" ]
571fe035dab3a7c02e1dccd5d65ffd75be750458
https://github.com/projectatomic/osbs-client/blob/571fe035dab3a7c02e1dccd5d65ffd75be750458/osbs/api.py#L958-L978
train
projectatomic/osbs-client
osbs/api.py
OSBS.import_image
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.json') with open(stream_import_file) as f: stream_import = json.load(f) return self.os.import_image(name, stream_import, tags=tags)
python
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.json') with open(stream_import_file) as f: stream_import = json.load(f) return self.os.import_image(name, stream_import, tags=tags)
[ "def", "import_image", "(", "self", ",", "name", ",", "tags", "=", "None", ")", ":", "stream_import_file", "=", "os", ".", "path", ".", "join", "(", "self", ".", "os_conf", ".", "get_build_json_store", "(", ")", ",", "'image_stream_import.json'", ")", "with", "open", "(", "stream_import_file", ")", "as", "f", ":", "stream_import", "=", "json", ".", "load", "(", "f", ")", "return", "self", ".", "os", ".", "import_image", "(", "name", ",", "stream_import", ",", "tags", "=", "tags", ")" ]
Import image tags from a Docker registry into an ImageStream :return: bool, whether tags were imported
[ "Import", "image", "tags", "from", "a", "Docker", "registry", "into", "an", "ImageStream" ]
571fe035dab3a7c02e1dccd5d65ffd75be750458
https://github.com/projectatomic/osbs-client/blob/571fe035dab3a7c02e1dccd5d65ffd75be750458/osbs/api.py#L1021-L1031
train
projectatomic/osbs-client
osbs/api.py
OSBS.import_image_tags
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 in the format <registry>/<repository> :param insecure: bool, indicates whenever registry is secure :return: bool, whether tags were imported """ stream_import_file = os.path.join(self.os_conf.get_build_json_store(), 'image_stream_import.json') with open(stream_import_file) as f: stream_import = json.load(f) return self.os.import_image_tags(name, stream_import, tags, repository, insecure)
python
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 in the format <registry>/<repository> :param insecure: bool, indicates whenever registry is secure :return: bool, whether tags were imported """ stream_import_file = os.path.join(self.os_conf.get_build_json_store(), 'image_stream_import.json') with open(stream_import_file) as f: stream_import = json.load(f) return self.os.import_image_tags(name, stream_import, tags, repository, insecure)
[ "def", "import_image_tags", "(", "self", ",", "name", ",", "tags", ",", "repository", ",", "insecure", "=", "False", ")", ":", "stream_import_file", "=", "os", ".", "path", ".", "join", "(", "self", ".", "os_conf", ".", "get_build_json_store", "(", ")", ",", "'image_stream_import.json'", ")", "with", "open", "(", "stream_import_file", ")", "as", "f", ":", "stream_import", "=", "json", ".", "load", "(", "f", ")", "return", "self", ".", "os", ".", "import_image_tags", "(", "name", ",", "stream_import", ",", "tags", ",", "repository", ",", "insecure", ")" ]
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 in the format <registry>/<repository> :param insecure: bool, indicates whenever registry is secure :return: bool, whether tags were imported
[ "Import", "image", "tags", "from", "specified", "container", "repository", "." ]
571fe035dab3a7c02e1dccd5d65ffd75be750458
https://github.com/projectatomic/osbs-client/blob/571fe035dab3a7c02e1dccd5d65ffd75be750458/osbs/api.py#L1034-L1050
train
projectatomic/osbs-client
osbs/api.py
OSBS.ensure_image_stream_tag
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, without name of ImageStream as prefix :param scheduled: bool, if True, importPolicy.scheduled will be set to True in ImageStreamTag :param source_registry: dict, info about source registry :param organization: str, oganization for registry :param base_image: str, base image :return: bool, whether or not modifications were performed """ img_stream_tag_file = os.path.join(self.os_conf.get_build_json_store(), 'image_stream_tag.json') with open(img_stream_tag_file) as f: tag_template = json.load(f) repository = None registry = None insecure = False if source_registry: registry = RegistryURI(source_registry['url']).docker_uri insecure = source_registry.get('insecure', False) if base_image and registry: repository = self._get_enclosed_repo_with_source_registry(base_image, registry, organization) return self.os.ensure_image_stream_tag(stream, tag_name, tag_template, scheduled, repository=repository, insecure=insecure)
python
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, without name of ImageStream as prefix :param scheduled: bool, if True, importPolicy.scheduled will be set to True in ImageStreamTag :param source_registry: dict, info about source registry :param organization: str, oganization for registry :param base_image: str, base image :return: bool, whether or not modifications were performed """ img_stream_tag_file = os.path.join(self.os_conf.get_build_json_store(), 'image_stream_tag.json') with open(img_stream_tag_file) as f: tag_template = json.load(f) repository = None registry = None insecure = False if source_registry: registry = RegistryURI(source_registry['url']).docker_uri insecure = source_registry.get('insecure', False) if base_image and registry: repository = self._get_enclosed_repo_with_source_registry(base_image, registry, organization) return self.os.ensure_image_stream_tag(stream, tag_name, tag_template, scheduled, repository=repository, insecure=insecure)
[ "def", "ensure_image_stream_tag", "(", "self", ",", "stream", ",", "tag_name", ",", "scheduled", "=", "False", ",", "source_registry", "=", "None", ",", "organization", "=", "None", ",", "base_image", "=", "None", ")", ":", "img_stream_tag_file", "=", "os", ".", "path", ".", "join", "(", "self", ".", "os_conf", ".", "get_build_json_store", "(", ")", ",", "'image_stream_tag.json'", ")", "with", "open", "(", "img_stream_tag_file", ")", "as", "f", ":", "tag_template", "=", "json", ".", "load", "(", "f", ")", "repository", "=", "None", "registry", "=", "None", "insecure", "=", "False", "if", "source_registry", ":", "registry", "=", "RegistryURI", "(", "source_registry", "[", "'url'", "]", ")", ".", "docker_uri", "insecure", "=", "source_registry", ".", "get", "(", "'insecure'", ",", "False", ")", "if", "base_image", "and", "registry", ":", "repository", "=", "self", ".", "_get_enclosed_repo_with_source_registry", "(", "base_image", ",", "registry", ",", "organization", ")", "return", "self", ".", "os", ".", "ensure_image_stream_tag", "(", "stream", ",", "tag_name", ",", "tag_template", ",", "scheduled", ",", "repository", "=", "repository", ",", "insecure", "=", "insecure", ")" ]
Ensures the tag is monitored in ImageStream :param stream: dict, ImageStream object :param tag_name: str, name of tag to check, without name of ImageStream as prefix :param scheduled: bool, if True, importPolicy.scheduled will be set to True in ImageStreamTag :param source_registry: dict, info about source registry :param organization: str, oganization for registry :param base_image: str, base image :return: bool, whether or not modifications were performed
[ "Ensures", "the", "tag", "is", "monitored", "in", "ImageStream" ]
571fe035dab3a7c02e1dccd5d65ffd75be750458
https://github.com/projectatomic/osbs-client/blob/571fe035dab3a7c02e1dccd5d65ffd75be750458/osbs/api.py#L1120-L1153
train
projectatomic/osbs-client
osbs/api.py
OSBS.create_image_stream
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 repository :param insecure_registry: bool, whether plain HTTP should be used :return: response """ img_stream_file = os.path.join(self.os_conf.get_build_json_store(), 'image_stream.json') with open(img_stream_file) as f: stream = json.load(f) stream['metadata']['name'] = name stream['metadata'].setdefault('annotations', {}) stream['metadata']['annotations'][ANNOTATION_SOURCE_REPO] = docker_image_repository if insecure_registry: stream['metadata']['annotations'][ANNOTATION_INSECURE_REPO] = 'true' return self.os.create_image_stream(json.dumps(stream))
python
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 repository :param insecure_registry: bool, whether plain HTTP should be used :return: response """ img_stream_file = os.path.join(self.os_conf.get_build_json_store(), 'image_stream.json') with open(img_stream_file) as f: stream = json.load(f) stream['metadata']['name'] = name stream['metadata'].setdefault('annotations', {}) stream['metadata']['annotations'][ANNOTATION_SOURCE_REPO] = docker_image_repository if insecure_registry: stream['metadata']['annotations'][ANNOTATION_INSECURE_REPO] = 'true' return self.os.create_image_stream(json.dumps(stream))
[ "def", "create_image_stream", "(", "self", ",", "name", ",", "docker_image_repository", ",", "insecure_registry", "=", "False", ")", ":", "img_stream_file", "=", "os", ".", "path", ".", "join", "(", "self", ".", "os_conf", ".", "get_build_json_store", "(", ")", ",", "'image_stream.json'", ")", "with", "open", "(", "img_stream_file", ")", "as", "f", ":", "stream", "=", "json", ".", "load", "(", "f", ")", "stream", "[", "'metadata'", "]", "[", "'name'", "]", "=", "name", "stream", "[", "'metadata'", "]", ".", "setdefault", "(", "'annotations'", ",", "{", "}", ")", "stream", "[", "'metadata'", "]", "[", "'annotations'", "]", "[", "ANNOTATION_SOURCE_REPO", "]", "=", "docker_image_repository", "if", "insecure_registry", ":", "stream", "[", "'metadata'", "]", "[", "'annotations'", "]", "[", "ANNOTATION_INSECURE_REPO", "]", "=", "'true'", "return", "self", ".", "os", ".", "create_image_stream", "(", "json", ".", "dumps", "(", "stream", ")", ")" ]
Create an ImageStream object Raises exception on error :param name: str, name of ImageStream :param docker_image_repository: str, pull spec for docker image repository :param insecure_registry: bool, whether plain HTTP should be used :return: response
[ "Create", "an", "ImageStream", "object" ]
571fe035dab3a7c02e1dccd5d65ffd75be750458
https://github.com/projectatomic/osbs-client/blob/571fe035dab3a7c02e1dccd5d65ffd75be750458/osbs/api.py#L1175-L1197
train
projectatomic/osbs-client
osbs/api.py
OSBS.get_compression_extension
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, or else None if no compression """ build_request = BuildRequest(build_json_store=self.os_conf.get_build_json_store()) inner = build_request.inner_template postbuild_plugins = inner.get('postbuild_plugins', []) for plugin in postbuild_plugins: if plugin.get('name') == 'compress': args = plugin.get('args', {}) method = args.get('method', 'gzip') if method == 'gzip': return '.gz' elif method == 'lzma': return '.xz' raise OsbsValidationException("unknown compression method '%s'" % method) return None
python
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, or else None if no compression """ build_request = BuildRequest(build_json_store=self.os_conf.get_build_json_store()) inner = build_request.inner_template postbuild_plugins = inner.get('postbuild_plugins', []) for plugin in postbuild_plugins: if plugin.get('name') == 'compress': args = plugin.get('args', {}) method = args.get('method', 'gzip') if method == 'gzip': return '.gz' elif method == 'lzma': return '.xz' raise OsbsValidationException("unknown compression method '%s'" % method) return None
[ "def", "get_compression_extension", "(", "self", ")", ":", "build_request", "=", "BuildRequest", "(", "build_json_store", "=", "self", ".", "os_conf", ".", "get_build_json_store", "(", ")", ")", "inner", "=", "build_request", ".", "inner_template", "postbuild_plugins", "=", "inner", ".", "get", "(", "'postbuild_plugins'", ",", "[", "]", ")", "for", "plugin", "in", "postbuild_plugins", ":", "if", "plugin", ".", "get", "(", "'name'", ")", "==", "'compress'", ":", "args", "=", "plugin", ".", "get", "(", "'args'", ",", "{", "}", ")", "method", "=", "args", ".", "get", "(", "'method'", ",", "'gzip'", ")", "if", "method", "==", "'gzip'", ":", "return", "'.gz'", "elif", "method", "==", "'lzma'", ":", "return", "'.xz'", "raise", "OsbsValidationException", "(", "\"unknown compression method '%s'\"", "%", "method", ")", "return", "None" ]
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, or else None if no compression
[ "Find", "the", "filename", "extension", "for", "the", "docker", "save", "output", "which", "may", "or", "may", "not", "be", "compressed", "." ]
571fe035dab3a7c02e1dccd5d65ffd75be750458
https://github.com/projectatomic/osbs-client/blob/571fe035dab3a7c02e1dccd5d65ffd75be750458/osbs/api.py#L1267-L1292
train
projectatomic/osbs-client
osbs/api.py
OSBS.create_config_map
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 """ config_data_file = os.path.join(self.os_conf.get_build_json_store(), 'config_map.json') with open(config_data_file) as f: config_data = json.load(f) config_data['metadata']['name'] = name data_dict = {} for key, value in data.items(): data_dict[key] = json.dumps(value) config_data['data'] = data_dict response = self.os.create_config_map(config_data) config_map_response = ConfigMapResponse(response.json()) return config_map_response
python
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 """ config_data_file = os.path.join(self.os_conf.get_build_json_store(), 'config_map.json') with open(config_data_file) as f: config_data = json.load(f) config_data['metadata']['name'] = name data_dict = {} for key, value in data.items(): data_dict[key] = json.dumps(value) config_data['data'] = data_dict response = self.os.create_config_map(config_data) config_map_response = ConfigMapResponse(response.json()) return config_map_response
[ "def", "create_config_map", "(", "self", ",", "name", ",", "data", ")", ":", "config_data_file", "=", "os", ".", "path", ".", "join", "(", "self", ".", "os_conf", ".", "get_build_json_store", "(", ")", ",", "'config_map.json'", ")", "with", "open", "(", "config_data_file", ")", "as", "f", ":", "config_data", "=", "json", ".", "load", "(", "f", ")", "config_data", "[", "'metadata'", "]", "[", "'name'", "]", "=", "name", "data_dict", "=", "{", "}", "for", "key", ",", "value", "in", "data", ".", "items", "(", ")", ":", "data_dict", "[", "key", "]", "=", "json", ".", "dumps", "(", "value", ")", "config_data", "[", "'data'", "]", "=", "data_dict", "response", "=", "self", ".", "os", ".", "create_config_map", "(", "config_data", ")", "config_map_response", "=", "ConfigMapResponse", "(", "response", ".", "json", "(", ")", ")", "return", "config_map_response" ]
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
[ "Create", "an", "ConfigMap", "object", "on", "the", "server" ]
571fe035dab3a7c02e1dccd5d65ffd75be750458
https://github.com/projectatomic/osbs-client/blob/571fe035dab3a7c02e1dccd5d65ffd75be750458/osbs/api.py#L1307-L1328
train
projectatomic/osbs-client
osbs/api.py
OSBS.get_config_map
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.get_config_map(name) config_map_response = ConfigMapResponse(response.json()) return config_map_response
python
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.get_config_map(name) config_map_response = ConfigMapResponse(response.json()) return config_map_response
[ "def", "get_config_map", "(", "self", ",", "name", ")", ":", "response", "=", "self", ".", "os", ".", "get_config_map", "(", "name", ")", "config_map_response", "=", "ConfigMapResponse", "(", "response", ".", "json", "(", ")", ")", "return", "config_map_response" ]
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
[ "Get", "a", "ConfigMap", "object", "from", "the", "server" ]
571fe035dab3a7c02e1dccd5d65ffd75be750458
https://github.com/projectatomic/osbs-client/blob/571fe035dab3a7c02e1dccd5d65ffd75be750458/osbs/api.py#L1331-L1342
train
projectatomic/osbs-client
osbs/api.py
OSBS.retries_disabled
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
python
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
[ "def", "retries_disabled", "(", "self", ")", ":", "self", ".", "os", ".", "retries_enabled", "=", "False", "yield", "self", ".", "os", ".", "retries_enabled", "=", "True" ]
Context manager to disable retries on requests :returns: OSBS object
[ "Context", "manager", "to", "disable", "retries", "on", "requests", ":", "returns", ":", "OSBS", "object" ]
571fe035dab3a7c02e1dccd5d65ffd75be750458
https://github.com/projectatomic/osbs-client/blob/571fe035dab3a7c02e1dccd5d65ffd75be750458/osbs/api.py#L1356-L1363
train
SpectoLabs/hoverpy
hoverpy/hp.py
HoverPy.wipe
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) except OSError: pass
python
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) except OSError: pass
[ "def", "wipe", "(", "self", ")", ":", "try", ":", "if", "os", ".", "isfile", "(", "self", ".", "_dbpath", ")", ":", "os", ".", "remove", "(", "self", ".", "_dbpath", ")", "except", "OSError", ":", "pass" ]
Wipe the bolt database. Calling this after HoverPy has been instantiated is potentially dangerous. This function is mostly used internally for unit tests.
[ "Wipe", "the", "bolt", "database", "." ]
e153ec57f80634019d827d378f184c01fedc5a0e
https://github.com/SpectoLabs/hoverpy/blob/e153ec57f80634019d827d378f184c01fedc5a0e/hoverpy/hp.py#L95-L107
train
SpectoLabs/hoverpy
hoverpy/hp.py
HoverPy.simulation
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) """ if data: return self._session.put(self.__v2() + "/simulation", data=data) else: return self._session.get(self.__v2() + "/simulation").json()
python
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) """ if data: return self._session.put(self.__v2() + "/simulation", data=data) else: return self._session.get(self.__v2() + "/simulation").json()
[ "def", "simulation", "(", "self", ",", "data", "=", "None", ")", ":", "if", "data", ":", "return", "self", ".", "_session", ".", "put", "(", "self", ".", "__v2", "(", ")", "+", "\"/simulation\"", ",", "data", "=", "data", ")", "else", ":", "return", "self", ".", "_session", ".", "get", "(", "self", ".", "__v2", "(", ")", "+", "\"/simulation\"", ")", ".", "json", "(", ")" ]
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", "simulation", "data", "." ]
e153ec57f80634019d827d378f184c01fedc5a0e
https://github.com/SpectoLabs/hoverpy/blob/e153ec57f80634019d827d378f184c01fedc5a0e/hoverpy/hp.py#L135-L148
train
SpectoLabs/hoverpy
hoverpy/hp.py
HoverPy.destination
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( self.__v2() + "/hoverfly/destination").json()
python
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( self.__v2() + "/hoverfly/destination").json()
[ "def", "destination", "(", "self", ",", "name", "=", "\"\"", ")", ":", "if", "name", ":", "return", "self", ".", "_session", ".", "put", "(", "self", ".", "__v2", "(", ")", "+", "\"/hoverfly/destination\"", ",", "data", "=", "{", "\"destination\"", ":", "name", "}", ")", ".", "json", "(", ")", "else", ":", "return", "self", ".", "_session", ".", "get", "(", "self", ".", "__v2", "(", ")", "+", "\"/hoverfly/destination\"", ")", ".", "json", "(", ")" ]
Gets / Sets the destination data.
[ "Gets", "/", "Sets", "the", "destination", "data", "." ]
e153ec57f80634019d827d378f184c01fedc5a0e
https://github.com/SpectoLabs/hoverpy/blob/e153ec57f80634019d827d378f184c01fedc5a0e/hoverpy/hp.py#L150-L160
train
SpectoLabs/hoverpy
hoverpy/hp.py
HoverPy.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" % mode) url = self.__v2() + "/hoverfly/mode" logging.debug(url) return self._session.put( url, data=json.dumps({"mode": mode})).json()["mode"] else: return self._session.get( self.__v2() + "/hoverfly/mode").json()["mode"]
python
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" % mode) url = self.__v2() + "/hoverfly/mode" logging.debug(url) return self._session.put( url, data=json.dumps({"mode": mode})).json()["mode"] else: return self._session.get( self.__v2() + "/hoverfly/mode").json()["mode"]
[ "def", "mode", "(", "self", ",", "mode", "=", "None", ")", ":", "if", "mode", ":", "logging", ".", "debug", "(", "\"SWITCHING TO %s\"", "%", "mode", ")", "url", "=", "self", ".", "__v2", "(", ")", "+", "\"/hoverfly/mode\"", "logging", ".", "debug", "(", "url", ")", "return", "self", ".", "_session", ".", "put", "(", "url", ",", "data", "=", "json", ".", "dumps", "(", "{", "\"mode\"", ":", "mode", "}", ")", ")", ".", "json", "(", ")", "[", "\"mode\"", "]", "else", ":", "return", "self", ".", "_session", ".", "get", "(", "self", ".", "__v2", "(", ")", "+", "\"/hoverfly/mode\"", ")", ".", "json", "(", ")", "[", "\"mode\"", "]" ]
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)
[ "Gets", "/", "Sets", "the", "mode", "." ]
e153ec57f80634019d827d378f184c01fedc5a0e
https://github.com/SpectoLabs/hoverpy/blob/e153ec57f80634019d827d378f184c01fedc5a0e/hoverpy/hp.py#L168-L185
train
SpectoLabs/hoverpy
hoverpy/hp.py
HoverPy.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()
python
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()
[ "def", "metadata", "(", "self", ",", "delete", "=", "False", ")", ":", "if", "delete", ":", "return", "self", ".", "_session", ".", "delete", "(", "self", ".", "__v1", "(", ")", "+", "\"/metadata\"", ")", ".", "json", "(", ")", "else", ":", "return", "self", ".", "_session", ".", "get", "(", "self", ".", "__v1", "(", ")", "+", "\"/metadata\"", ")", ".", "json", "(", ")" ]
Gets the metadata.
[ "Gets", "the", "metadata", "." ]
e153ec57f80634019d827d378f184c01fedc5a0e
https://github.com/SpectoLabs/hoverpy/blob/e153ec57f80634019d827d378f184c01fedc5a0e/hoverpy/hp.py#L193-L200
train
SpectoLabs/hoverpy
hoverpy/hp.py
HoverPy.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()
python
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()
[ "def", "records", "(", "self", ",", "data", "=", "None", ")", ":", "if", "data", ":", "return", "self", ".", "_session", ".", "post", "(", "self", ".", "__v1", "(", ")", "+", "\"/records\"", ",", "data", "=", "data", ")", ".", "json", "(", ")", "else", ":", "return", "self", ".", "_session", ".", "get", "(", "self", ".", "__v1", "(", ")", "+", "\"/records\"", ")", ".", "json", "(", ")" ]
Gets / Sets records.
[ "Gets", "/", "Sets", "records", "." ]
e153ec57f80634019d827d378f184c01fedc5a0e
https://github.com/SpectoLabs/hoverpy/blob/e153ec57f80634019d827d378f184c01fedc5a0e/hoverpy/hp.py#L202-L210
train
SpectoLabs/hoverpy
hoverpy/hp.py
HoverPy.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()
python
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()
[ "def", "delays", "(", "self", ",", "delays", "=", "[", "]", ")", ":", "if", "delays", ":", "return", "self", ".", "_session", ".", "put", "(", "self", ".", "__v1", "(", ")", "+", "\"/delays\"", ",", "data", "=", "json", ".", "dumps", "(", "delays", ")", ")", ".", "json", "(", ")", "else", ":", "return", "self", ".", "_session", ".", "get", "(", "self", ".", "__v1", "(", ")", "+", "\"/delays\"", ")", ".", "json", "(", ")" ]
Gets / Sets the delays.
[ "Gets", "/", "Sets", "the", "delays", "." ]
e153ec57f80634019d827d378f184c01fedc5a0e
https://github.com/SpectoLabs/hoverpy/blob/e153ec57f80634019d827d378f184c01fedc5a0e/hoverpy/hp.py#L212-L220
train
SpectoLabs/hoverpy
hoverpy/hp.py
HoverPy.addDelay
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.delays(delays={"data": [delay]})
python
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.delays(delays={"data": [delay]})
[ "def", "addDelay", "(", "self", ",", "urlPattern", "=", "\"\"", ",", "delay", "=", "0", ",", "httpMethod", "=", "None", ")", ":", "print", "(", "\"addDelay is deprecated please use delays instead\"", ")", "delay", "=", "{", "\"urlPattern\"", ":", "urlPattern", ",", "\"delay\"", ":", "delay", "}", "if", "httpMethod", ":", "delay", "[", "\"httpMethod\"", "]", "=", "httpMethod", "return", "self", ".", "delays", "(", "delays", "=", "{", "\"data\"", ":", "[", "delay", "]", "}", ")" ]
Adds delays.
[ "Adds", "delays", "." ]
e153ec57f80634019d827d378f184c01fedc5a0e
https://github.com/SpectoLabs/hoverpy/blob/e153ec57f80634019d827d378f184c01fedc5a0e/hoverpy/hp.py#L222-L230
train
SpectoLabs/hoverpy
hoverpy/hp.py
HoverPy.__enableProxy
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.path.join( os.path.dirname( os.path.abspath(__file__)), "cert.pem")
python
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.path.join( os.path.dirname( os.path.abspath(__file__)), "cert.pem")
[ "def", "__enableProxy", "(", "self", ")", ":", "os", ".", "environ", "[", "\"HTTP_PROXY\"", "]", "=", "self", ".", "httpProxy", "(", ")", "os", ".", "environ", "[", "\"HTTPS_PROXY\"", "]", "=", "self", ".", "httpsProxy", "(", ")", "os", ".", "environ", "[", "\"REQUESTS_CA_BUNDLE\"", "]", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "__file__", ")", ")", ",", "\"cert.pem\"", ")" ]
Set the required environment variables to enable the use of hoverfly as a proxy.
[ "Set", "the", "required", "environment", "variables", "to", "enable", "the", "use", "of", "hoverfly", "as", "a", "proxy", "." ]
e153ec57f80634019d827d378f184c01fedc5a0e
https://github.com/SpectoLabs/hoverpy/blob/e153ec57f80634019d827d378f184c01fedc5a0e/hoverpy/hp.py#L270-L282
train
SpectoLabs/hoverpy
hoverpy/hp.py
HoverPy.__writepid
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.gettempdir() name = os.path.join(d, "hoverpy.%i.%i"%(self._proxyPort, self._adminPort)) with open(name, 'w') as f: f.write(str(pid)) logging.debug("writing to %s"%name)
python
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.gettempdir() name = os.path.join(d, "hoverpy.%i.%i"%(self._proxyPort, self._adminPort)) with open(name, 'w') as f: f.write(str(pid)) logging.debug("writing to %s"%name)
[ "def", "__writepid", "(", "self", ",", "pid", ")", ":", "import", "tempfile", "d", "=", "tempfile", ".", "gettempdir", "(", ")", "name", "=", "os", ".", "path", ".", "join", "(", "d", ",", "\"hoverpy.%i.%i\"", "%", "(", "self", ".", "_proxyPort", ",", "self", ".", "_adminPort", ")", ")", "with", "open", "(", "name", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "str", "(", "pid", ")", ")", "logging", ".", "debug", "(", "\"writing to %s\"", "%", "name", ")" ]
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.
[ "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", "." ]
e153ec57f80634019d827d378f184c01fedc5a0e
https://github.com/SpectoLabs/hoverpy/blob/e153ec57f80634019d827d378f184c01fedc5a0e/hoverpy/hp.py#L292-L304
train
SpectoLabs/hoverpy
hoverpy/hp.py
HoverPy.__rmpid
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 os.path.exists(name): os.unlink(name) logging.debug("deleting %s"%name)
python
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 os.path.exists(name): os.unlink(name) logging.debug("deleting %s"%name)
[ "def", "__rmpid", "(", "self", ")", ":", "import", "tempfile", "d", "=", "tempfile", ".", "gettempdir", "(", ")", "name", "=", "os", ".", "path", ".", "join", "(", "d", ",", "\"hoverpy.%i.%i\"", "%", "(", "self", ".", "_proxyPort", ",", "self", ".", "_adminPort", ")", ")", "if", "os", ".", "path", ".", "exists", "(", "name", ")", ":", "os", ".", "unlink", "(", "name", ")", "logging", ".", "debug", "(", "\"deleting %s\"", "%", "name", ")" ]
Remove the PID file on shutdown, unfortunately this may not get called if not given the time to shut down.
[ "Remove", "the", "PID", "file", "on", "shutdown", "unfortunately", "this", "may", "not", "get", "called", "if", "not", "given", "the", "time", "to", "shut", "down", "." ]
e153ec57f80634019d827d378f184c01fedc5a0e
https://github.com/SpectoLabs/hoverpy/blob/e153ec57f80634019d827d378f184c01fedc5a0e/hoverpy/hp.py#L306-L317
train
SpectoLabs/hoverpy
hoverpy/hp.py
HoverPy.__kill_if_not_shut_properly
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 """ import tempfile d = tempfile.gettempdir() name = os.path.join(d, "hoverpy.%i.%i"%(self._proxyPort, self._adminPort)) if os.path.exists(name): logging.debug("pid file exists.. killing it") f = open(name, "r") pid = int(f.read()) try: import signal os.kill(pid, signal.SIGTERM) logging.debug("killing %i"%pid) except: logging.debug("nothing to clean up") pass finally: os.unlink(name)
python
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 """ import tempfile d = tempfile.gettempdir() name = os.path.join(d, "hoverpy.%i.%i"%(self._proxyPort, self._adminPort)) if os.path.exists(name): logging.debug("pid file exists.. killing it") f = open(name, "r") pid = int(f.read()) try: import signal os.kill(pid, signal.SIGTERM) logging.debug("killing %i"%pid) except: logging.debug("nothing to clean up") pass finally: os.unlink(name)
[ "def", "__kill_if_not_shut_properly", "(", "self", ")", ":", "import", "tempfile", "d", "=", "tempfile", ".", "gettempdir", "(", ")", "name", "=", "os", ".", "path", ".", "join", "(", "d", ",", "\"hoverpy.%i.%i\"", "%", "(", "self", ".", "_proxyPort", ",", "self", ".", "_adminPort", ")", ")", "if", "os", ".", "path", ".", "exists", "(", "name", ")", ":", "logging", ".", "debug", "(", "\"pid file exists.. killing it\"", ")", "f", "=", "open", "(", "name", ",", "\"r\"", ")", "pid", "=", "int", "(", "f", ".", "read", "(", ")", ")", "try", ":", "import", "signal", "os", ".", "kill", "(", "pid", ",", "signal", ".", "SIGTERM", ")", "logging", ".", "debug", "(", "\"killing %i\"", "%", "pid", ")", "except", ":", "logging", ".", "debug", "(", "\"nothing to clean up\"", ")", "pass", "finally", ":", "os", ".", "unlink", "(", "name", ")" ]
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
[ "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" ]
e153ec57f80634019d827d378f184c01fedc5a0e
https://github.com/SpectoLabs/hoverpy/blob/e153ec57f80634019d827d378f184c01fedc5a0e/hoverpy/hp.py#L319-L342
train
SpectoLabs/hoverpy
hoverpy/hp.py
HoverPy.__start
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') flags = self.__flags() cmd = [hoverfly] + flags if self._showCmd: print(cmd) self._process = Popen( [hoverfly] + flags, stdin=self.FNULL, stdout=self.FNULL, stderr=subprocess.STDOUT) start = time.time() while time.time() - start < 1: try: url = "http://%s:%i/api/health" % (self._host, self._adminPort) r = self._session.get(url) j = r.json() up = "message" in j and "healthy" in j["message"] if up: logging.debug("has pid %i" % self._process.pid) self.__writepid(self._process.pid) return self._process else: time.sleep(1/100.0) except: # import traceback # traceback.print_exc() # wait 10 ms before trying again time.sleep(1/100.0) pass logging.error("Could not start hoverfly!") raise ValueError("Could not start hoverfly!")
python
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') flags = self.__flags() cmd = [hoverfly] + flags if self._showCmd: print(cmd) self._process = Popen( [hoverfly] + flags, stdin=self.FNULL, stdout=self.FNULL, stderr=subprocess.STDOUT) start = time.time() while time.time() - start < 1: try: url = "http://%s:%i/api/health" % (self._host, self._adminPort) r = self._session.get(url) j = r.json() up = "message" in j and "healthy" in j["message"] if up: logging.debug("has pid %i" % self._process.pid) self.__writepid(self._process.pid) return self._process else: time.sleep(1/100.0) except: # import traceback # traceback.print_exc() # wait 10 ms before trying again time.sleep(1/100.0) pass logging.error("Could not start hoverfly!") raise ValueError("Could not start hoverfly!")
[ "def", "__start", "(", "self", ")", ":", "logging", ".", "debug", "(", "\"starting %i\"", "%", "id", "(", "self", ")", ")", "self", ".", "__kill_if_not_shut_properly", "(", ")", "self", ".", "FNULL", "=", "open", "(", "os", ".", "devnull", ",", "'w'", ")", "flags", "=", "self", ".", "__flags", "(", ")", "cmd", "=", "[", "hoverfly", "]", "+", "flags", "if", "self", ".", "_showCmd", ":", "print", "(", "cmd", ")", "self", ".", "_process", "=", "Popen", "(", "[", "hoverfly", "]", "+", "flags", ",", "stdin", "=", "self", ".", "FNULL", ",", "stdout", "=", "self", ".", "FNULL", ",", "stderr", "=", "subprocess", ".", "STDOUT", ")", "start", "=", "time", ".", "time", "(", ")", "while", "time", ".", "time", "(", ")", "-", "start", "<", "1", ":", "try", ":", "url", "=", "\"http://%s:%i/api/health\"", "%", "(", "self", ".", "_host", ",", "self", ".", "_adminPort", ")", "r", "=", "self", ".", "_session", ".", "get", "(", "url", ")", "j", "=", "r", ".", "json", "(", ")", "up", "=", "\"message\"", "in", "j", "and", "\"healthy\"", "in", "j", "[", "\"message\"", "]", "if", "up", ":", "logging", ".", "debug", "(", "\"has pid %i\"", "%", "self", ".", "_process", ".", "pid", ")", "self", ".", "__writepid", "(", "self", ".", "_process", ".", "pid", ")", "return", "self", ".", "_process", "else", ":", "time", ".", "sleep", "(", "1", "/", "100.0", ")", "except", ":", "# import traceback", "# traceback.print_exc()", "# wait 10 ms before trying again", "time", ".", "sleep", "(", "1", "/", "100.0", ")", "pass", "logging", ".", "error", "(", "\"Could not start hoverfly!\"", ")", "raise", "ValueError", "(", "\"Could not start hoverfly!\"", ")" ]
Start the hoverfly process. This function waits until it can make contact with the hoverfly API before returning.
[ "Start", "the", "hoverfly", "process", "." ]
e153ec57f80634019d827d378f184c01fedc5a0e
https://github.com/SpectoLabs/hoverpy/blob/e153ec57f80634019d827d378f184c01fedc5a0e/hoverpy/hp.py#L344-L385
train
SpectoLabs/hoverpy
hoverpy/hp.py
HoverPy.__stop
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._process.communicate() self._process = None self.FNULL.close() self.FNULL = None self.__disableProxy() # del self._session # self._session = None self.__rmpid()
python
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._process.communicate() self._process = None self.FNULL.close() self.FNULL = None self.__disableProxy() # del self._session # self._session = None self.__rmpid()
[ "def", "__stop", "(", "self", ")", ":", "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", ".", "_process", ".", "communicate", "(", ")", "self", ".", "_process", "=", "None", "self", ".", "FNULL", ".", "close", "(", ")", "self", ".", "FNULL", "=", "None", "self", ".", "__disableProxy", "(", ")", "# del self._session", "# self._session = None", "self", ".", "__rmpid", "(", ")" ]
Stop the hoverfly process.
[ "Stop", "the", "hoverfly", "process", "." ]
e153ec57f80634019d827d378f184c01fedc5a0e
https://github.com/SpectoLabs/hoverpy/blob/e153ec57f80634019d827d378f184c01fedc5a0e/hoverpy/hp.py#L387-L404
train
SpectoLabs/hoverpy
hoverpy/hp.py
HoverPy.__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] flags += ["-db", "boltdb"] else: flags += ["-db", "memory"] if self._synthesize: assert(self._middleware) flags += ["-synthesize"] if self._simulation: flags += ["-import", self._simulation] if self._proxyPort: flags += ["-pp", str(self._proxyPort)] if self._adminPort: flags += ["-ap", str(self._adminPort)] if self._modify: flags += ["-modify"] if self._verbose: flags += ["-v"] if self._dev: flags += ["-dev"] if self._metrics: flags += ["-metrics"] if self._auth: flags += ["-auth"] if self._middleware: flags += ["-middleware", self._middleware] if self._cert: flags += ["-cert", self._cert] if self._certName: flags += ["-cert-name", self._certName] if self._certOrg: flags += ["-cert-org", self._certOrg] if self._destination: flags += ["-destination", self._destination] if self._key: flags += ["-key", self._key] if self._dest: for i in range(len(self._dest)): flags += ["-dest", self._dest[i]] if self._generateCACert: flags += ["-generate-ca-cert"] if not self._tlsVerification: flags += ["-tls-verification", "false"] logging.debug("flags:" + str(flags)) return flags
python
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] flags += ["-db", "boltdb"] else: flags += ["-db", "memory"] if self._synthesize: assert(self._middleware) flags += ["-synthesize"] if self._simulation: flags += ["-import", self._simulation] if self._proxyPort: flags += ["-pp", str(self._proxyPort)] if self._adminPort: flags += ["-ap", str(self._adminPort)] if self._modify: flags += ["-modify"] if self._verbose: flags += ["-v"] if self._dev: flags += ["-dev"] if self._metrics: flags += ["-metrics"] if self._auth: flags += ["-auth"] if self._middleware: flags += ["-middleware", self._middleware] if self._cert: flags += ["-cert", self._cert] if self._certName: flags += ["-cert-name", self._certName] if self._certOrg: flags += ["-cert-org", self._certOrg] if self._destination: flags += ["-destination", self._destination] if self._key: flags += ["-key", self._key] if self._dest: for i in range(len(self._dest)): flags += ["-dest", self._dest[i]] if self._generateCACert: flags += ["-generate-ca-cert"] if not self._tlsVerification: flags += ["-tls-verification", "false"] logging.debug("flags:" + str(flags)) return flags
[ "def", "__flags", "(", "self", ")", ":", "flags", "=", "[", "]", "if", "self", ".", "_capture", ":", "flags", ".", "append", "(", "\"-capture\"", ")", "if", "self", ".", "_spy", ":", "flags", ".", "append", "(", "\"-spy\"", ")", "if", "self", ".", "_dbpath", ":", "flags", "+=", "[", "\"-db-path\"", ",", "self", ".", "_dbpath", "]", "flags", "+=", "[", "\"-db\"", ",", "\"boltdb\"", "]", "else", ":", "flags", "+=", "[", "\"-db\"", ",", "\"memory\"", "]", "if", "self", ".", "_synthesize", ":", "assert", "(", "self", ".", "_middleware", ")", "flags", "+=", "[", "\"-synthesize\"", "]", "if", "self", ".", "_simulation", ":", "flags", "+=", "[", "\"-import\"", ",", "self", ".", "_simulation", "]", "if", "self", ".", "_proxyPort", ":", "flags", "+=", "[", "\"-pp\"", ",", "str", "(", "self", ".", "_proxyPort", ")", "]", "if", "self", ".", "_adminPort", ":", "flags", "+=", "[", "\"-ap\"", ",", "str", "(", "self", ".", "_adminPort", ")", "]", "if", "self", ".", "_modify", ":", "flags", "+=", "[", "\"-modify\"", "]", "if", "self", ".", "_verbose", ":", "flags", "+=", "[", "\"-v\"", "]", "if", "self", ".", "_dev", ":", "flags", "+=", "[", "\"-dev\"", "]", "if", "self", ".", "_metrics", ":", "flags", "+=", "[", "\"-metrics\"", "]", "if", "self", ".", "_auth", ":", "flags", "+=", "[", "\"-auth\"", "]", "if", "self", ".", "_middleware", ":", "flags", "+=", "[", "\"-middleware\"", ",", "self", ".", "_middleware", "]", "if", "self", ".", "_cert", ":", "flags", "+=", "[", "\"-cert\"", ",", "self", ".", "_cert", "]", "if", "self", ".", "_certName", ":", "flags", "+=", "[", "\"-cert-name\"", ",", "self", ".", "_certName", "]", "if", "self", ".", "_certOrg", ":", "flags", "+=", "[", "\"-cert-org\"", ",", "self", ".", "_certOrg", "]", "if", "self", ".", "_destination", ":", "flags", "+=", "[", "\"-destination\"", ",", "self", ".", "_destination", "]", "if", "self", ".", "_key", ":", "flags", "+=", "[", "\"-key\"", ",", "self", ".", "_key", "]", "if", "self", ".", "_dest", ":", "for", "i", "in", "range", "(", "len", "(", "self", ".", "_dest", ")", ")", ":", "flags", "+=", "[", "\"-dest\"", ",", "self", ".", "_dest", "[", "i", "]", "]", "if", "self", ".", "_generateCACert", ":", "flags", "+=", "[", "\"-generate-ca-cert\"", "]", "if", "not", "self", ".", "_tlsVerification", ":", "flags", "+=", "[", "\"-tls-verification\"", ",", "\"false\"", "]", "logging", ".", "debug", "(", "\"flags:\"", "+", "str", "(", "flags", ")", ")", "return", "flags" ]
Internal method. Turns arguments into flags.
[ "Internal", "method", ".", "Turns", "arguments", "into", "flags", "." ]
e153ec57f80634019d827d378f184c01fedc5a0e
https://github.com/SpectoLabs/hoverpy/blob/e153ec57f80634019d827d378f184c01fedc5a0e/hoverpy/hp.py#L406-L460
train
thombashi/pytablereader
pytablereader/json/core.py
JsonTableFileLoader.load
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 Schema (1): single table { "type": "array", "items": { "type": "object", "additionalProperties": { "anyOf": [ {"type": "string"}, {"type": "number"}, {"type": "boolean"}, {"type": "null"} ] } } } .. code-block:: json :caption: Acceptable JSON example for the JSON schema (1) [ {"attr_b": 4, "attr_c": "a", "attr_a": 1}, {"attr_b": 2.1, "attr_c": "bb", "attr_a": 2}, {"attr_b": 120.9, "attr_c": "ccc", "attr_a": 3} ] The example data will be loaded as the following tabular data: .. table:: +------+------+------+ |attr_a|attr_b|attr_c| +======+======+======+ | 1| 4.0|a | +------+------+------+ | 2| 2.1|bb | +------+------+------+ | 3| 120.9|ccc | +------+------+------+ **(2)** Single table data in a file: .. code-block:: json :caption: Acceptable JSON Schema (2): single table { "type": "object", "additionalProperties": { "type": "array", "items": { "anyOf": [ {"type": "string"}, {"type": "number"}, {"type": "boolean"}, {"type": "null"} ] } } } .. code-block:: json :caption: Acceptable JSON example for the JSON schema (2) { "attr_a": [1, 2, 3], "attr_b": [4, 2.1, 120.9], "attr_c": ["a", "bb", "ccc"] } The example data will be loaded as the following tabular data: .. table:: +------+------+------+ |attr_a|attr_b|attr_c| +======+======+======+ | 1| 4.0|a | +------+------+------+ | 2| 2.1|bb | +------+------+------+ | 3| 120.9|ccc | +------+------+------+ **(3)** Single table data in a file: .. code-block:: json :caption: Acceptable JSON Schema (3): single table { "type": "object", "additionalProperties": { "anyOf": [ {"type": "string"}, {"type": "number"}, {"type": "boolean"}, {"type": "null"} ] } } .. code-block:: json :caption: Acceptable JSON example for the JSON schema (3) { "num_ratings": 27, "support_threads": 1, "downloaded": 925716, "last_updated":"2017-12-01 6:22am GMT", "added":"2010-01-20", "num": 1.1, "hoge": null } The example data will be loaded as the following tabular data: .. table:: +---------------+---------------------+ | key | value | +===============+=====================+ |num_ratings | 27| +---------------+---------------------+ |support_threads| 1| +---------------+---------------------+ |downloaded | 925716| +---------------+---------------------+ |last_updated |2017-12-01 6:22am GMT| +---------------+---------------------+ |added |2010-01-20 | +---------------+---------------------+ |num | 1.1| +---------------+---------------------+ |hoge |None | +---------------+---------------------+ **(4)** Multiple table data in a file: .. code-block:: json :caption: Acceptable JSON Schema (4): multiple tables { "type": "object", "additionalProperties": { "type": "array", "items": { "type": "object", "additionalProperties": { "anyOf": [ {"type": "string"}, {"type": "number"}, {"type": "boolean"}, {"type": "null"} ] } } } } .. code-block:: json :caption: Acceptable JSON example for the JSON schema (4) { "table_a" : [ {"attr_b": 4, "attr_c": "a", "attr_a": 1}, {"attr_b": 2.1, "attr_c": "bb", "attr_a": 2}, {"attr_b": 120.9, "attr_c": "ccc", "attr_a": 3} ], "table_b" : [ {"a": 1, "b": 4}, {"a": 2 }, {"a": 3, "b": 120.9} ] } The example data will be loaded as the following tabular data: .. table:: table_a +------+------+------+ |attr_a|attr_b|attr_c| +======+======+======+ | 1| 4.0|a | +------+------+------+ | 2| 2.1|bb | +------+------+------+ | 3| 120.9|ccc | +------+------+------+ .. table:: table_b +-+-----+ |a| b | +=+=====+ |1| 4.0| +-+-----+ |2| None| +-+-----+ |3|120.9| +-+-----+ **(5)** Multiple table data in a file: .. code-block:: json :caption: Acceptable JSON Schema (5): multiple tables { "type": "object", "additionalProperties": { "type": "object", "additionalProperties": { "type": "array", "items": { "anyOf": [ {"type": "string"}, {"type": "number"}, {"type": "boolean"}, {"type": "null"} ] } } } } .. code-block:: json :caption: Acceptable JSON example for the JSON schema (5) { "table_a" : { "attr_a": [1, 2, 3], "attr_b": [4, 2.1, 120.9], "attr_c": ["a", "bb", "ccc"] }, "table_b" : { "a": [1, 3], "b": [4, 120.9] } } The example data will be loaded as the following tabular data: .. table:: table_a +------+------+------+ |attr_a|attr_b|attr_c| +======+======+======+ | 1| 4.0|a | +------+------+------+ | 2| 2.1|bb | +------+------+------+ | 3| 120.9|ccc | +------+------+------+ .. table:: table_b +-+-----+ |a| b | +=+=====+ |1| 4.0| +-+-----+ |3|120.9| +-+-----+ **(6)** Multiple table data in a file: .. code-block:: json :caption: Acceptable JSON Schema (6): multiple tables { "type": "object", "additionalProperties": { "type": "object", "additionalProperties": { "anyOf": [ {"type": "string"}, {"type": "number"}, {"type": "boolean"}, {"type": "null"} ] } } } .. code-block:: json :caption: Acceptable JSON example for the JSON schema (6) { "table_a": { "num_ratings": 27, "support_threads": 1, "downloaded": 925716, "last_updated":"2017-12-01 6:22am GMT", "added":"2010-01-20", "num": 1.1, "hoge": null }, "table_b": { "a": 4, "b": 120.9 } } The example data will be loaded as the following tabular data: .. table:: table_a +---------------+---------------------+ | key | value | +===============+=====================+ |num_ratings | 27| +---------------+---------------------+ |support_threads| 1| +---------------+---------------------+ |downloaded | 925716| +---------------+---------------------+ |last_updated |2017-12-01 6:22am GMT| +---------------+---------------------+ |added |2010-01-20 | +---------------+---------------------+ |num | 1.1| +---------------+---------------------+ |hoge |None | +---------------+---------------------+ .. table:: table_b +---+-----+ |key|value| +===+=====+ |a | 4.0| +---+-----+ |b |120.9| +---+-----+ :return: Loaded table data iterator. |load_table_name_desc| =================== ============================================== Format specifier Value after the replacement =================== ============================================== ``%(filename)s`` |filename_desc| ``%(key)s`` | This replaced the different value | for each single/multiple JSON tables: | [single JSON table] | ``%(format_name)s%(format_id)s`` | [multiple JSON table] Table data key. ``%(format_name)s`` ``"json"`` ``%(format_id)s`` |format_id_desc| ``%(global_id)s`` |global_id| =================== ============================================== :rtype: |TableData| iterator :raises pytablereader.DataError: If the data is invalid JSON. :raises pytablereader.error.ValidationError: If the data is not acceptable JSON format. """ formatter = JsonTableFormatter(self.load_dict()) formatter.accept(self) return formatter.to_table_data()
python
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 Schema (1): single table { "type": "array", "items": { "type": "object", "additionalProperties": { "anyOf": [ {"type": "string"}, {"type": "number"}, {"type": "boolean"}, {"type": "null"} ] } } } .. code-block:: json :caption: Acceptable JSON example for the JSON schema (1) [ {"attr_b": 4, "attr_c": "a", "attr_a": 1}, {"attr_b": 2.1, "attr_c": "bb", "attr_a": 2}, {"attr_b": 120.9, "attr_c": "ccc", "attr_a": 3} ] The example data will be loaded as the following tabular data: .. table:: +------+------+------+ |attr_a|attr_b|attr_c| +======+======+======+ | 1| 4.0|a | +------+------+------+ | 2| 2.1|bb | +------+------+------+ | 3| 120.9|ccc | +------+------+------+ **(2)** Single table data in a file: .. code-block:: json :caption: Acceptable JSON Schema (2): single table { "type": "object", "additionalProperties": { "type": "array", "items": { "anyOf": [ {"type": "string"}, {"type": "number"}, {"type": "boolean"}, {"type": "null"} ] } } } .. code-block:: json :caption: Acceptable JSON example for the JSON schema (2) { "attr_a": [1, 2, 3], "attr_b": [4, 2.1, 120.9], "attr_c": ["a", "bb", "ccc"] } The example data will be loaded as the following tabular data: .. table:: +------+------+------+ |attr_a|attr_b|attr_c| +======+======+======+ | 1| 4.0|a | +------+------+------+ | 2| 2.1|bb | +------+------+------+ | 3| 120.9|ccc | +------+------+------+ **(3)** Single table data in a file: .. code-block:: json :caption: Acceptable JSON Schema (3): single table { "type": "object", "additionalProperties": { "anyOf": [ {"type": "string"}, {"type": "number"}, {"type": "boolean"}, {"type": "null"} ] } } .. code-block:: json :caption: Acceptable JSON example for the JSON schema (3) { "num_ratings": 27, "support_threads": 1, "downloaded": 925716, "last_updated":"2017-12-01 6:22am GMT", "added":"2010-01-20", "num": 1.1, "hoge": null } The example data will be loaded as the following tabular data: .. table:: +---------------+---------------------+ | key | value | +===============+=====================+ |num_ratings | 27| +---------------+---------------------+ |support_threads| 1| +---------------+---------------------+ |downloaded | 925716| +---------------+---------------------+ |last_updated |2017-12-01 6:22am GMT| +---------------+---------------------+ |added |2010-01-20 | +---------------+---------------------+ |num | 1.1| +---------------+---------------------+ |hoge |None | +---------------+---------------------+ **(4)** Multiple table data in a file: .. code-block:: json :caption: Acceptable JSON Schema (4): multiple tables { "type": "object", "additionalProperties": { "type": "array", "items": { "type": "object", "additionalProperties": { "anyOf": [ {"type": "string"}, {"type": "number"}, {"type": "boolean"}, {"type": "null"} ] } } } } .. code-block:: json :caption: Acceptable JSON example for the JSON schema (4) { "table_a" : [ {"attr_b": 4, "attr_c": "a", "attr_a": 1}, {"attr_b": 2.1, "attr_c": "bb", "attr_a": 2}, {"attr_b": 120.9, "attr_c": "ccc", "attr_a": 3} ], "table_b" : [ {"a": 1, "b": 4}, {"a": 2 }, {"a": 3, "b": 120.9} ] } The example data will be loaded as the following tabular data: .. table:: table_a +------+------+------+ |attr_a|attr_b|attr_c| +======+======+======+ | 1| 4.0|a | +------+------+------+ | 2| 2.1|bb | +------+------+------+ | 3| 120.9|ccc | +------+------+------+ .. table:: table_b +-+-----+ |a| b | +=+=====+ |1| 4.0| +-+-----+ |2| None| +-+-----+ |3|120.9| +-+-----+ **(5)** Multiple table data in a file: .. code-block:: json :caption: Acceptable JSON Schema (5): multiple tables { "type": "object", "additionalProperties": { "type": "object", "additionalProperties": { "type": "array", "items": { "anyOf": [ {"type": "string"}, {"type": "number"}, {"type": "boolean"}, {"type": "null"} ] } } } } .. code-block:: json :caption: Acceptable JSON example for the JSON schema (5) { "table_a" : { "attr_a": [1, 2, 3], "attr_b": [4, 2.1, 120.9], "attr_c": ["a", "bb", "ccc"] }, "table_b" : { "a": [1, 3], "b": [4, 120.9] } } The example data will be loaded as the following tabular data: .. table:: table_a +------+------+------+ |attr_a|attr_b|attr_c| +======+======+======+ | 1| 4.0|a | +------+------+------+ | 2| 2.1|bb | +------+------+------+ | 3| 120.9|ccc | +------+------+------+ .. table:: table_b +-+-----+ |a| b | +=+=====+ |1| 4.0| +-+-----+ |3|120.9| +-+-----+ **(6)** Multiple table data in a file: .. code-block:: json :caption: Acceptable JSON Schema (6): multiple tables { "type": "object", "additionalProperties": { "type": "object", "additionalProperties": { "anyOf": [ {"type": "string"}, {"type": "number"}, {"type": "boolean"}, {"type": "null"} ] } } } .. code-block:: json :caption: Acceptable JSON example for the JSON schema (6) { "table_a": { "num_ratings": 27, "support_threads": 1, "downloaded": 925716, "last_updated":"2017-12-01 6:22am GMT", "added":"2010-01-20", "num": 1.1, "hoge": null }, "table_b": { "a": 4, "b": 120.9 } } The example data will be loaded as the following tabular data: .. table:: table_a +---------------+---------------------+ | key | value | +===============+=====================+ |num_ratings | 27| +---------------+---------------------+ |support_threads| 1| +---------------+---------------------+ |downloaded | 925716| +---------------+---------------------+ |last_updated |2017-12-01 6:22am GMT| +---------------+---------------------+ |added |2010-01-20 | +---------------+---------------------+ |num | 1.1| +---------------+---------------------+ |hoge |None | +---------------+---------------------+ .. table:: table_b +---+-----+ |key|value| +===+=====+ |a | 4.0| +---+-----+ |b |120.9| +---+-----+ :return: Loaded table data iterator. |load_table_name_desc| =================== ============================================== Format specifier Value after the replacement =================== ============================================== ``%(filename)s`` |filename_desc| ``%(key)s`` | This replaced the different value | for each single/multiple JSON tables: | [single JSON table] | ``%(format_name)s%(format_id)s`` | [multiple JSON table] Table data key. ``%(format_name)s`` ``"json"`` ``%(format_id)s`` |format_id_desc| ``%(global_id)s`` |global_id| =================== ============================================== :rtype: |TableData| iterator :raises pytablereader.DataError: If the data is invalid JSON. :raises pytablereader.error.ValidationError: If the data is not acceptable JSON format. """ formatter = JsonTableFormatter(self.load_dict()) formatter.accept(self) return formatter.to_table_data()
[ "def", "load", "(", "self", ")", ":", "formatter", "=", "JsonTableFormatter", "(", "self", ".", "load_dict", "(", ")", ")", "formatter", ".", "accept", "(", "self", ")", "return", "formatter", ".", "to_table_data", "(", ")" ]
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 Schema (1): single table { "type": "array", "items": { "type": "object", "additionalProperties": { "anyOf": [ {"type": "string"}, {"type": "number"}, {"type": "boolean"}, {"type": "null"} ] } } } .. code-block:: json :caption: Acceptable JSON example for the JSON schema (1) [ {"attr_b": 4, "attr_c": "a", "attr_a": 1}, {"attr_b": 2.1, "attr_c": "bb", "attr_a": 2}, {"attr_b": 120.9, "attr_c": "ccc", "attr_a": 3} ] The example data will be loaded as the following tabular data: .. table:: +------+------+------+ |attr_a|attr_b|attr_c| +======+======+======+ | 1| 4.0|a | +------+------+------+ | 2| 2.1|bb | +------+------+------+ | 3| 120.9|ccc | +------+------+------+ **(2)** Single table data in a file: .. code-block:: json :caption: Acceptable JSON Schema (2): single table { "type": "object", "additionalProperties": { "type": "array", "items": { "anyOf": [ {"type": "string"}, {"type": "number"}, {"type": "boolean"}, {"type": "null"} ] } } } .. code-block:: json :caption: Acceptable JSON example for the JSON schema (2) { "attr_a": [1, 2, 3], "attr_b": [4, 2.1, 120.9], "attr_c": ["a", "bb", "ccc"] } The example data will be loaded as the following tabular data: .. table:: +------+------+------+ |attr_a|attr_b|attr_c| +======+======+======+ | 1| 4.0|a | +------+------+------+ | 2| 2.1|bb | +------+------+------+ | 3| 120.9|ccc | +------+------+------+ **(3)** Single table data in a file: .. code-block:: json :caption: Acceptable JSON Schema (3): single table { "type": "object", "additionalProperties": { "anyOf": [ {"type": "string"}, {"type": "number"}, {"type": "boolean"}, {"type": "null"} ] } } .. code-block:: json :caption: Acceptable JSON example for the JSON schema (3) { "num_ratings": 27, "support_threads": 1, "downloaded": 925716, "last_updated":"2017-12-01 6:22am GMT", "added":"2010-01-20", "num": 1.1, "hoge": null } The example data will be loaded as the following tabular data: .. table:: +---------------+---------------------+ | key | value | +===============+=====================+ |num_ratings | 27| +---------------+---------------------+ |support_threads| 1| +---------------+---------------------+ |downloaded | 925716| +---------------+---------------------+ |last_updated |2017-12-01 6:22am GMT| +---------------+---------------------+ |added |2010-01-20 | +---------------+---------------------+ |num | 1.1| +---------------+---------------------+ |hoge |None | +---------------+---------------------+ **(4)** Multiple table data in a file: .. code-block:: json :caption: Acceptable JSON Schema (4): multiple tables { "type": "object", "additionalProperties": { "type": "array", "items": { "type": "object", "additionalProperties": { "anyOf": [ {"type": "string"}, {"type": "number"}, {"type": "boolean"}, {"type": "null"} ] } } } } .. code-block:: json :caption: Acceptable JSON example for the JSON schema (4) { "table_a" : [ {"attr_b": 4, "attr_c": "a", "attr_a": 1}, {"attr_b": 2.1, "attr_c": "bb", "attr_a": 2}, {"attr_b": 120.9, "attr_c": "ccc", "attr_a": 3} ], "table_b" : [ {"a": 1, "b": 4}, {"a": 2 }, {"a": 3, "b": 120.9} ] } The example data will be loaded as the following tabular data: .. table:: table_a +------+------+------+ |attr_a|attr_b|attr_c| +======+======+======+ | 1| 4.0|a | +------+------+------+ | 2| 2.1|bb | +------+------+------+ | 3| 120.9|ccc | +------+------+------+ .. table:: table_b +-+-----+ |a| b | +=+=====+ |1| 4.0| +-+-----+ |2| None| +-+-----+ |3|120.9| +-+-----+ **(5)** Multiple table data in a file: .. code-block:: json :caption: Acceptable JSON Schema (5): multiple tables { "type": "object", "additionalProperties": { "type": "object", "additionalProperties": { "type": "array", "items": { "anyOf": [ {"type": "string"}, {"type": "number"}, {"type": "boolean"}, {"type": "null"} ] } } } } .. code-block:: json :caption: Acceptable JSON example for the JSON schema (5) { "table_a" : { "attr_a": [1, 2, 3], "attr_b": [4, 2.1, 120.9], "attr_c": ["a", "bb", "ccc"] }, "table_b" : { "a": [1, 3], "b": [4, 120.9] } } The example data will be loaded as the following tabular data: .. table:: table_a +------+------+------+ |attr_a|attr_b|attr_c| +======+======+======+ | 1| 4.0|a | +------+------+------+ | 2| 2.1|bb | +------+------+------+ | 3| 120.9|ccc | +------+------+------+ .. table:: table_b +-+-----+ |a| b | +=+=====+ |1| 4.0| +-+-----+ |3|120.9| +-+-----+ **(6)** Multiple table data in a file: .. code-block:: json :caption: Acceptable JSON Schema (6): multiple tables { "type": "object", "additionalProperties": { "type": "object", "additionalProperties": { "anyOf": [ {"type": "string"}, {"type": "number"}, {"type": "boolean"}, {"type": "null"} ] } } } .. code-block:: json :caption: Acceptable JSON example for the JSON schema (6) { "table_a": { "num_ratings": 27, "support_threads": 1, "downloaded": 925716, "last_updated":"2017-12-01 6:22am GMT", "added":"2010-01-20", "num": 1.1, "hoge": null }, "table_b": { "a": 4, "b": 120.9 } } The example data will be loaded as the following tabular data: .. table:: table_a +---------------+---------------------+ | key | value | +===============+=====================+ |num_ratings | 27| +---------------+---------------------+ |support_threads| 1| +---------------+---------------------+ |downloaded | 925716| +---------------+---------------------+ |last_updated |2017-12-01 6:22am GMT| +---------------+---------------------+ |added |2010-01-20 | +---------------+---------------------+ |num | 1.1| +---------------+---------------------+ |hoge |None | +---------------+---------------------+ .. table:: table_b +---+-----+ |key|value| +===+=====+ |a | 4.0| +---+-----+ |b |120.9| +---+-----+ :return: Loaded table data iterator. |load_table_name_desc| =================== ============================================== Format specifier Value after the replacement =================== ============================================== ``%(filename)s`` |filename_desc| ``%(key)s`` | This replaced the different value | for each single/multiple JSON tables: | [single JSON table] | ``%(format_name)s%(format_id)s`` | [multiple JSON table] Table data key. ``%(format_name)s`` ``"json"`` ``%(format_id)s`` |format_id_desc| ``%(global_id)s`` |global_id| =================== ============================================== :rtype: |TableData| iterator :raises pytablereader.DataError: If the data is invalid JSON. :raises pytablereader.error.ValidationError: If the data is not acceptable JSON format.
[ "Extract", "tabular", "data", "as", "|TableData|", "instances", "from", "a", "JSON", "file", ".", "|load_source_desc_file|" ]
bc3c057a2cc775bcce690e0e9019c2907b638101
https://github.com/thombashi/pytablereader/blob/bc3c057a2cc775bcce690e0e9019c2907b638101/pytablereader/json/core.py#L67-L439
train
thombashi/pytablereader
pytablereader/mediawiki/core.py
MediaWikiTableFileLoader.load
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| =================== ============================================== Format specifier Value after the replacement =================== ============================================== ``%(filename)s`` |filename_desc| ``%(key)s`` | This replaced to: | **(1)** ``caption`` mark of the table | **(2)** ``%(format_name)s%(format_id)s`` | if ``caption`` mark not included | in the table. ``%(format_name)s`` ``"mediawiki"`` ``%(format_id)s`` |format_id_desc| ``%(global_id)s`` |global_id| =================== ============================================== :rtype: |TableData| iterator :raises pytablereader.DataError: If the MediaWiki data is invalid or empty. """ self._validate() self._logger.logging_load() self.encoding = get_file_encoding(self.source, self.encoding) with io.open(self.source, "r", encoding=self.encoding) as fp: formatter = MediaWikiTableFormatter(fp.read()) formatter.accept(self) return formatter.to_table_data()
python
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| =================== ============================================== Format specifier Value after the replacement =================== ============================================== ``%(filename)s`` |filename_desc| ``%(key)s`` | This replaced to: | **(1)** ``caption`` mark of the table | **(2)** ``%(format_name)s%(format_id)s`` | if ``caption`` mark not included | in the table. ``%(format_name)s`` ``"mediawiki"`` ``%(format_id)s`` |format_id_desc| ``%(global_id)s`` |global_id| =================== ============================================== :rtype: |TableData| iterator :raises pytablereader.DataError: If the MediaWiki data is invalid or empty. """ self._validate() self._logger.logging_load() self.encoding = get_file_encoding(self.source, self.encoding) with io.open(self.source, "r", encoding=self.encoding) as fp: formatter = MediaWikiTableFormatter(fp.read()) formatter.accept(self) return formatter.to_table_data()
[ "def", "load", "(", "self", ")", ":", "self", ".", "_validate", "(", ")", "self", ".", "_logger", ".", "logging_load", "(", ")", "self", ".", "encoding", "=", "get_file_encoding", "(", "self", ".", "source", ",", "self", ".", "encoding", ")", "with", "io", ".", "open", "(", "self", ".", "source", ",", "\"r\"", ",", "encoding", "=", "self", ".", "encoding", ")", "as", "fp", ":", "formatter", "=", "MediaWikiTableFormatter", "(", "fp", ".", "read", "(", ")", ")", "formatter", ".", "accept", "(", "self", ")", "return", "formatter", ".", "to_table_data", "(", ")" ]
Extract tabular data as |TableData| instances from a MediaWiki file. |load_source_desc_file| :return: Loaded table data iterator. |load_table_name_desc| =================== ============================================== Format specifier Value after the replacement =================== ============================================== ``%(filename)s`` |filename_desc| ``%(key)s`` | This replaced to: | **(1)** ``caption`` mark of the table | **(2)** ``%(format_name)s%(format_id)s`` | if ``caption`` mark not included | in the table. ``%(format_name)s`` ``"mediawiki"`` ``%(format_id)s`` |format_id_desc| ``%(global_id)s`` |global_id| =================== ============================================== :rtype: |TableData| iterator :raises pytablereader.DataError: If the MediaWiki data is invalid or empty.
[ "Extract", "tabular", "data", "as", "|TableData|", "instances", "from", "a", "MediaWiki", "file", ".", "|load_source_desc_file|" ]
bc3c057a2cc775bcce690e0e9019c2907b638101
https://github.com/thombashi/pytablereader/blob/bc3c057a2cc775bcce690e0e9019c2907b638101/pytablereader/mediawiki/core.py#L51-L86
train
thombashi/pytablereader
pytablereader/mediawiki/core.py
MediaWikiTableTextLoader.load
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| =================== ============================================== Format specifier Value after the replacement =================== ============================================== ``%(filename)s`` ``""`` ``%(key)s`` | This replaced to: | **(1)** ``caption`` mark of the table | **(2)** ``%(format_name)s%(format_id)s`` | if ``caption`` mark not included | in the table. ``%(format_name)s`` ``"mediawiki"`` ``%(format_id)s`` |format_id_desc| ``%(global_id)s`` |global_id| =================== ============================================== :rtype: |TableData| iterator :raises pytablereader.DataError: If the MediaWiki data is invalid or empty. """ self._validate() self._logger.logging_load() formatter = MediaWikiTableFormatter(self.source) formatter.accept(self) return formatter.to_table_data()
python
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| =================== ============================================== Format specifier Value after the replacement =================== ============================================== ``%(filename)s`` ``""`` ``%(key)s`` | This replaced to: | **(1)** ``caption`` mark of the table | **(2)** ``%(format_name)s%(format_id)s`` | if ``caption`` mark not included | in the table. ``%(format_name)s`` ``"mediawiki"`` ``%(format_id)s`` |format_id_desc| ``%(global_id)s`` |global_id| =================== ============================================== :rtype: |TableData| iterator :raises pytablereader.DataError: If the MediaWiki data is invalid or empty. """ self._validate() self._logger.logging_load() formatter = MediaWikiTableFormatter(self.source) formatter.accept(self) return formatter.to_table_data()
[ "def", "load", "(", "self", ")", ":", "self", ".", "_validate", "(", ")", "self", ".", "_logger", ".", "logging_load", "(", ")", "formatter", "=", "MediaWikiTableFormatter", "(", "self", ".", "source", ")", "formatter", ".", "accept", "(", "self", ")", "return", "formatter", ".", "to_table_data", "(", ")" ]
Extract tabular data as |TableData| instances from a MediaWiki text object. |load_source_desc_text| :return: Loaded table data iterator. |load_table_name_desc| =================== ============================================== Format specifier Value after the replacement =================== ============================================== ``%(filename)s`` ``""`` ``%(key)s`` | This replaced to: | **(1)** ``caption`` mark of the table | **(2)** ``%(format_name)s%(format_id)s`` | if ``caption`` mark not included | in the table. ``%(format_name)s`` ``"mediawiki"`` ``%(format_id)s`` |format_id_desc| ``%(global_id)s`` |global_id| =================== ============================================== :rtype: |TableData| iterator :raises pytablereader.DataError: If the MediaWiki data is invalid or empty.
[ "Extract", "tabular", "data", "as", "|TableData|", "instances", "from", "a", "MediaWiki", "text", "object", ".", "|load_source_desc_text|" ]
bc3c057a2cc775bcce690e0e9019c2907b638101
https://github.com/thombashi/pytablereader/blob/bc3c057a2cc775bcce690e0e9019c2907b638101/pytablereader/mediawiki/core.py#L113-L147
train
projectatomic/osbs-client
osbs/build/manipulate.py
DockJsonManipulator.get_dock_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("\"env\" is not iterable") if len(p) <= 0: raise RuntimeError("\"env\" misses key ATOMIC_REACTOR_PLUGINS") dock_json_str = p[0]['value'] dock_json = json.loads(dock_json_str) return dock_json
python
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("\"env\" is not iterable") if len(p) <= 0: raise RuntimeError("\"env\" misses key ATOMIC_REACTOR_PLUGINS") dock_json_str = p[0]['value'] dock_json = json.loads(dock_json_str) return dock_json
[ "def", "get_dock_json", "(", "self", ")", ":", "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", "(", "\"\\\"env\\\" is not iterable\"", ")", "if", "len", "(", "p", ")", "<=", "0", ":", "raise", "RuntimeError", "(", "\"\\\"env\\\" misses key ATOMIC_REACTOR_PLUGINS\"", ")", "dock_json_str", "=", "p", "[", "0", "]", "[", "'value'", "]", "dock_json", "=", "json", ".", "loads", "(", "dock_json_str", ")", "return", "dock_json" ]
return dock json from existing build json
[ "return", "dock", "json", "from", "existing", "build", "json" ]
571fe035dab3a7c02e1dccd5d65ffd75be750458
https://github.com/projectatomic/osbs-client/blob/571fe035dab3a7c02e1dccd5d65ffd75be750458/osbs/build/manipulate.py#L21-L32
train
projectatomic/osbs-client
osbs/build/manipulate.py
DockJsonManipulator.dock_json_get_plugin_conf
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.get('name') == plugin_name] return match[0]
python
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.get('name') == plugin_name] return match[0]
[ "def", "dock_json_get_plugin_conf", "(", "self", ",", "plugin_type", ",", "plugin_name", ")", ":", "match", "=", "[", "x", "for", "x", "in", "self", ".", "dock_json", "[", "plugin_type", "]", "if", "x", ".", "get", "(", "'name'", ")", "==", "plugin_name", "]", "return", "match", "[", "0", "]" ]
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.
[ "Return", "the", "configuration", "for", "a", "plugin", "." ]
571fe035dab3a7c02e1dccd5d65ffd75be750458
https://github.com/projectatomic/osbs-client/blob/571fe035dab3a7c02e1dccd5d65ffd75be750458/osbs/build/manipulate.py#L34-L42
train
projectatomic/osbs-client
osbs/build/manipulate.py
DockJsonManipulator.remove_plugin
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
python
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
[ "def", "remove_plugin", "(", "self", ",", "plugin_type", ",", "plugin_name", ")", ":", "for", "p", "in", "self", ".", "dock_json", "[", "plugin_type", "]", ":", "if", "p", ".", "get", "(", "'name'", ")", "==", "plugin_name", ":", "self", ".", "dock_json", "[", "plugin_type", "]", ".", "remove", "(", "p", ")", "break" ]
if config contains plugin, remove it
[ "if", "config", "contains", "plugin", "remove", "it" ]
571fe035dab3a7c02e1dccd5d65ffd75be750458
https://github.com/projectatomic/osbs-client/blob/571fe035dab3a7c02e1dccd5d65ffd75be750458/osbs/build/manipulate.py#L44-L51
train
projectatomic/osbs-client
osbs/build/manipulate.py
DockJsonManipulator.add_plugin
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 plugin_modified = True if not plugin_modified: self.dock_json[plugin_type].append({"name": plugin_name, "args": args_dict})
python
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 plugin_modified = True if not plugin_modified: self.dock_json[plugin_type].append({"name": plugin_name, "args": args_dict})
[ "def", "add_plugin", "(", "self", ",", "plugin_type", ",", "plugin_name", ",", "args_dict", ")", ":", "plugin_modified", "=", "False", "for", "plugin", "in", "self", ".", "dock_json", "[", "plugin_type", "]", ":", "if", "plugin", "[", "'name'", "]", "==", "plugin_name", ":", "plugin", "[", "'args'", "]", "=", "args_dict", "plugin_modified", "=", "True", "if", "not", "plugin_modified", ":", "self", ".", "dock_json", "[", "plugin_type", "]", ".", "append", "(", "{", "\"name\"", ":", "plugin_name", ",", "\"args\"", ":", "args_dict", "}", ")" ]
if config has plugin, override it, else add it
[ "if", "config", "has", "plugin", "override", "it", "else", "add", "it" ]
571fe035dab3a7c02e1dccd5d65ffd75be750458
https://github.com/projectatomic/osbs-client/blob/571fe035dab3a7c02e1dccd5d65ffd75be750458/osbs/build/manipulate.py#L53-L66
train
projectatomic/osbs-client
osbs/build/manipulate.py
DockJsonManipulator.dock_json_has_plugin_conf
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
python
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
[ "def", "dock_json_has_plugin_conf", "(", "self", ",", "plugin_type", ",", "plugin_name", ")", ":", "try", ":", "self", ".", "dock_json_get_plugin_conf", "(", "plugin_type", ",", "plugin_name", ")", "return", "True", "except", "(", "KeyError", ",", "IndexError", ")", ":", "return", "False" ]
Check whether a plugin is configured.
[ "Check", "whether", "a", "plugin", "is", "configured", "." ]
571fe035dab3a7c02e1dccd5d65ffd75be750458
https://github.com/projectatomic/osbs-client/blob/571fe035dab3a7c02e1dccd5d65ffd75be750458/osbs/build/manipulate.py#L68-L77
train
thombashi/pytablereader
pytablereader/factory/_url.py
TableUrlLoaderFactory.create_from_path
def create_from_path(self): """ Create a file loader from the file extension to loading file. Supported file extensions are as follows: ========================================= ===================================== Extension Loader ========================================= ===================================== ``"csv"`` :py:class:`~.CsvTableTextLoader` ``"xls"``/``"xlsx"`` :py:class:`~.ExcelTableFileLoader` ``"htm"``/``"html"``/``"asp"``/``"aspx"`` :py:class:`~.HtmlTableTextLoader` ``"json"`` :py:class:`~.JsonTableTextLoader` ``"jsonl"``/``"ldjson"``/``"ndjson"`` :py:class:`~.JsonLinesTableTextLoader` ``"ltsv"`` :py:class:`~.LtsvTableTextLoader` ``"md"`` :py:class:`~.MarkdownTableTextLoader` ``"sqlite"``/``"sqlite3"`` :py:class:`~.SqliteFileLoader` ``"tsv"`` :py:class:`~.TsvTableTextLoader` ========================================= ===================================== :return: Loader that coincides with the file extension of the URL. :raises pytablereader.UrlError: If unacceptable URL format. :raises pytablereader.LoaderNotFoundError: |LoaderNotFoundError_desc| loading the URL. """ import requests url_path = urlparse(self.__url).path try: url_extension = get_extension(url_path.rstrip("/")) except InvalidFilePathError: raise UrlError("url must include path") logger.debug("TableUrlLoaderFactory: extension={}".format(url_extension)) loader_class = self._get_loader_class(self._get_extension_loader_mapping(), url_extension) try: self._fetch_source(loader_class) except requests.exceptions.ProxyError as e: raise ProxyError(e) loader = self._create_from_extension(url_extension) logger.debug("TableUrlLoaderFactory: loader={}".format(loader.format_name)) return loader
python
def create_from_path(self): """ Create a file loader from the file extension to loading file. Supported file extensions are as follows: ========================================= ===================================== Extension Loader ========================================= ===================================== ``"csv"`` :py:class:`~.CsvTableTextLoader` ``"xls"``/``"xlsx"`` :py:class:`~.ExcelTableFileLoader` ``"htm"``/``"html"``/``"asp"``/``"aspx"`` :py:class:`~.HtmlTableTextLoader` ``"json"`` :py:class:`~.JsonTableTextLoader` ``"jsonl"``/``"ldjson"``/``"ndjson"`` :py:class:`~.JsonLinesTableTextLoader` ``"ltsv"`` :py:class:`~.LtsvTableTextLoader` ``"md"`` :py:class:`~.MarkdownTableTextLoader` ``"sqlite"``/``"sqlite3"`` :py:class:`~.SqliteFileLoader` ``"tsv"`` :py:class:`~.TsvTableTextLoader` ========================================= ===================================== :return: Loader that coincides with the file extension of the URL. :raises pytablereader.UrlError: If unacceptable URL format. :raises pytablereader.LoaderNotFoundError: |LoaderNotFoundError_desc| loading the URL. """ import requests url_path = urlparse(self.__url).path try: url_extension = get_extension(url_path.rstrip("/")) except InvalidFilePathError: raise UrlError("url must include path") logger.debug("TableUrlLoaderFactory: extension={}".format(url_extension)) loader_class = self._get_loader_class(self._get_extension_loader_mapping(), url_extension) try: self._fetch_source(loader_class) except requests.exceptions.ProxyError as e: raise ProxyError(e) loader = self._create_from_extension(url_extension) logger.debug("TableUrlLoaderFactory: loader={}".format(loader.format_name)) return loader
[ "def", "create_from_path", "(", "self", ")", ":", "import", "requests", "url_path", "=", "urlparse", "(", "self", ".", "__url", ")", ".", "path", "try", ":", "url_extension", "=", "get_extension", "(", "url_path", ".", "rstrip", "(", "\"/\"", ")", ")", "except", "InvalidFilePathError", ":", "raise", "UrlError", "(", "\"url must include path\"", ")", "logger", ".", "debug", "(", "\"TableUrlLoaderFactory: extension={}\"", ".", "format", "(", "url_extension", ")", ")", "loader_class", "=", "self", ".", "_get_loader_class", "(", "self", ".", "_get_extension_loader_mapping", "(", ")", ",", "url_extension", ")", "try", ":", "self", ".", "_fetch_source", "(", "loader_class", ")", "except", "requests", ".", "exceptions", ".", "ProxyError", "as", "e", ":", "raise", "ProxyError", "(", "e", ")", "loader", "=", "self", ".", "_create_from_extension", "(", "url_extension", ")", "logger", ".", "debug", "(", "\"TableUrlLoaderFactory: loader={}\"", ".", "format", "(", "loader", ".", "format_name", ")", ")", "return", "loader" ]
Create a file loader from the file extension to loading file. Supported file extensions are as follows: ========================================= ===================================== Extension Loader ========================================= ===================================== ``"csv"`` :py:class:`~.CsvTableTextLoader` ``"xls"``/``"xlsx"`` :py:class:`~.ExcelTableFileLoader` ``"htm"``/``"html"``/``"asp"``/``"aspx"`` :py:class:`~.HtmlTableTextLoader` ``"json"`` :py:class:`~.JsonTableTextLoader` ``"jsonl"``/``"ldjson"``/``"ndjson"`` :py:class:`~.JsonLinesTableTextLoader` ``"ltsv"`` :py:class:`~.LtsvTableTextLoader` ``"md"`` :py:class:`~.MarkdownTableTextLoader` ``"sqlite"``/``"sqlite3"`` :py:class:`~.SqliteFileLoader` ``"tsv"`` :py:class:`~.TsvTableTextLoader` ========================================= ===================================== :return: Loader that coincides with the file extension of the URL. :raises pytablereader.UrlError: If unacceptable URL format. :raises pytablereader.LoaderNotFoundError: |LoaderNotFoundError_desc| loading the URL.
[ "Create", "a", "file", "loader", "from", "the", "file", "extension", "to", "loading", "file", ".", "Supported", "file", "extensions", "are", "as", "follows", ":" ]
bc3c057a2cc775bcce690e0e9019c2907b638101
https://github.com/thombashi/pytablereader/blob/bc3c057a2cc775bcce690e0e9019c2907b638101/pytablereader/factory/_url.py#L53-L100
train
thombashi/pytablereader
pytablereader/factory/_url.py
TableUrlLoaderFactory.create_from_format_name
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 ========================== ====================================== ``"csv"`` :py:class:`~.CsvTableTextLoader` ``"excel"`` :py:class:`~.ExcelTableFileLoader` ``"html"`` :py:class:`~.HtmlTableTextLoader` ``"json"`` :py:class:`~.JsonTableTextLoader` ``"json_lines"`` :py:class:`~.JsonLinesTableTextLoader` ``"jsonl"`` :py:class:`~.JsonLinesTableTextLoader` ``"ldjson"`` :py:class:`~.JsonLinesTableTextLoader` ``"ltsv"`` :py:class:`~.LtsvTableTextLoader` ``"markdown"`` :py:class:`~.MarkdownTableTextLoader` ``"mediawiki"`` :py:class:`~.MediaWikiTableTextLoader` ``"ndjson"`` :py:class:`~.JsonLinesTableTextLoader` ``"sqlite"`` :py:class:`~.SqliteFileLoader` ``"ssv"`` :py:class:`~.CsvTableFileLoader` ``"tsv"`` :py:class:`~.TsvTableTextLoader` ========================== ====================================== :param str format_name: Format name string (case insensitive). :return: Loader that coincide with the ``format_name``: :raises pytablereader.LoaderNotFoundError: |LoaderNotFoundError_desc| the format. :raises TypeError: If ``format_name`` is not a string. """ import requests logger.debug("TableUrlLoaderFactory: name={}".format(format_name)) loader_class = self._get_loader_class(self._get_format_name_loader_mapping(), format_name) try: self._fetch_source(loader_class) except requests.exceptions.ProxyError as e: raise ProxyError(e) loader = self._create_from_format_name(format_name) logger.debug("TableUrlLoaderFactory: loader={}".format(loader.format_name)) return loader
python
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 ========================== ====================================== ``"csv"`` :py:class:`~.CsvTableTextLoader` ``"excel"`` :py:class:`~.ExcelTableFileLoader` ``"html"`` :py:class:`~.HtmlTableTextLoader` ``"json"`` :py:class:`~.JsonTableTextLoader` ``"json_lines"`` :py:class:`~.JsonLinesTableTextLoader` ``"jsonl"`` :py:class:`~.JsonLinesTableTextLoader` ``"ldjson"`` :py:class:`~.JsonLinesTableTextLoader` ``"ltsv"`` :py:class:`~.LtsvTableTextLoader` ``"markdown"`` :py:class:`~.MarkdownTableTextLoader` ``"mediawiki"`` :py:class:`~.MediaWikiTableTextLoader` ``"ndjson"`` :py:class:`~.JsonLinesTableTextLoader` ``"sqlite"`` :py:class:`~.SqliteFileLoader` ``"ssv"`` :py:class:`~.CsvTableFileLoader` ``"tsv"`` :py:class:`~.TsvTableTextLoader` ========================== ====================================== :param str format_name: Format name string (case insensitive). :return: Loader that coincide with the ``format_name``: :raises pytablereader.LoaderNotFoundError: |LoaderNotFoundError_desc| the format. :raises TypeError: If ``format_name`` is not a string. """ import requests logger.debug("TableUrlLoaderFactory: name={}".format(format_name)) loader_class = self._get_loader_class(self._get_format_name_loader_mapping(), format_name) try: self._fetch_source(loader_class) except requests.exceptions.ProxyError as e: raise ProxyError(e) loader = self._create_from_format_name(format_name) logger.debug("TableUrlLoaderFactory: loader={}".format(loader.format_name)) return loader
[ "def", "create_from_format_name", "(", "self", ",", "format_name", ")", ":", "import", "requests", "logger", ".", "debug", "(", "\"TableUrlLoaderFactory: name={}\"", ".", "format", "(", "format_name", ")", ")", "loader_class", "=", "self", ".", "_get_loader_class", "(", "self", ".", "_get_format_name_loader_mapping", "(", ")", ",", "format_name", ")", "try", ":", "self", ".", "_fetch_source", "(", "loader_class", ")", "except", "requests", ".", "exceptions", ".", "ProxyError", "as", "e", ":", "raise", "ProxyError", "(", "e", ")", "loader", "=", "self", ".", "_create_from_format_name", "(", "format_name", ")", "logger", ".", "debug", "(", "\"TableUrlLoaderFactory: loader={}\"", ".", "format", "(", "loader", ".", "format_name", ")", ")", "return", "loader" ]
Create a file loader from a format name. Supported file formats are as follows: ========================== ====================================== Format name Loader ========================== ====================================== ``"csv"`` :py:class:`~.CsvTableTextLoader` ``"excel"`` :py:class:`~.ExcelTableFileLoader` ``"html"`` :py:class:`~.HtmlTableTextLoader` ``"json"`` :py:class:`~.JsonTableTextLoader` ``"json_lines"`` :py:class:`~.JsonLinesTableTextLoader` ``"jsonl"`` :py:class:`~.JsonLinesTableTextLoader` ``"ldjson"`` :py:class:`~.JsonLinesTableTextLoader` ``"ltsv"`` :py:class:`~.LtsvTableTextLoader` ``"markdown"`` :py:class:`~.MarkdownTableTextLoader` ``"mediawiki"`` :py:class:`~.MediaWikiTableTextLoader` ``"ndjson"`` :py:class:`~.JsonLinesTableTextLoader` ``"sqlite"`` :py:class:`~.SqliteFileLoader` ``"ssv"`` :py:class:`~.CsvTableFileLoader` ``"tsv"`` :py:class:`~.TsvTableTextLoader` ========================== ====================================== :param str format_name: Format name string (case insensitive). :return: Loader that coincide with the ``format_name``: :raises pytablereader.LoaderNotFoundError: |LoaderNotFoundError_desc| the format. :raises TypeError: If ``format_name`` is not a string.
[ "Create", "a", "file", "loader", "from", "a", "format", "name", ".", "Supported", "file", "formats", "are", "as", "follows", ":" ]
bc3c057a2cc775bcce690e0e9019c2907b638101
https://github.com/thombashi/pytablereader/blob/bc3c057a2cc775bcce690e0e9019c2907b638101/pytablereader/factory/_url.py#L102-L148
train
thombashi/pytablereader
pytablereader/factory/_url.py
TableUrlLoaderFactory._get_extension_loader_mapping
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": HtmlTableTextLoader, "htm": HtmlTableTextLoader, "md": MarkdownTableTextLoader, "sqlite3": SqliteFileLoader, "xls": ExcelTableFileLoader, "xlsx": ExcelTableFileLoader, } ) return loader_table
python
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": HtmlTableTextLoader, "htm": HtmlTableTextLoader, "md": MarkdownTableTextLoader, "sqlite3": SqliteFileLoader, "xls": ExcelTableFileLoader, "xlsx": ExcelTableFileLoader, } ) return loader_table
[ "def", "_get_extension_loader_mapping", "(", "self", ")", ":", "loader_table", "=", "self", ".", "_get_common_loader_mapping", "(", ")", "loader_table", ".", "update", "(", "{", "\"asp\"", ":", "HtmlTableTextLoader", ",", "\"aspx\"", ":", "HtmlTableTextLoader", ",", "\"htm\"", ":", "HtmlTableTextLoader", ",", "\"md\"", ":", "MarkdownTableTextLoader", ",", "\"sqlite3\"", ":", "SqliteFileLoader", ",", "\"xls\"", ":", "ExcelTableFileLoader", ",", "\"xlsx\"", ":", "ExcelTableFileLoader", ",", "}", ")", "return", "loader_table" ]
:return: Mappings of format-extension and loader class. :rtype: dict
[ ":", "return", ":", "Mappings", "of", "format", "-", "extension", "and", "loader", "class", ".", ":", "rtype", ":", "dict" ]
bc3c057a2cc775bcce690e0e9019c2907b638101
https://github.com/thombashi/pytablereader/blob/bc3c057a2cc775bcce690e0e9019c2907b638101/pytablereader/factory/_url.py#L204-L223
train
thombashi/pytablereader
pytablereader/factory/_url.py
TableUrlLoaderFactory._get_format_name_loader_mapping
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_lines": JsonLinesTableTextLoader, "markdown": MarkdownTableTextLoader, "mediawiki": MediaWikiTableTextLoader, "ssv": CsvTableFileLoader, } ) return loader_table
python
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_lines": JsonLinesTableTextLoader, "markdown": MarkdownTableTextLoader, "mediawiki": MediaWikiTableTextLoader, "ssv": CsvTableFileLoader, } ) return loader_table
[ "def", "_get_format_name_loader_mapping", "(", "self", ")", ":", "loader_table", "=", "self", ".", "_get_common_loader_mapping", "(", ")", "loader_table", ".", "update", "(", "{", "\"excel\"", ":", "ExcelTableFileLoader", ",", "\"json_lines\"", ":", "JsonLinesTableTextLoader", ",", "\"markdown\"", ":", "MarkdownTableTextLoader", ",", "\"mediawiki\"", ":", "MediaWikiTableTextLoader", ",", "\"ssv\"", ":", "CsvTableFileLoader", ",", "}", ")", "return", "loader_table" ]
:return: Mappings of format-name and loader class. :rtype: dict
[ ":", "return", ":", "Mappings", "of", "format", "-", "name", "and", "loader", "class", ".", ":", "rtype", ":", "dict" ]
bc3c057a2cc775bcce690e0e9019c2907b638101
https://github.com/thombashi/pytablereader/blob/bc3c057a2cc775bcce690e0e9019c2907b638101/pytablereader/factory/_url.py#L225-L242
train
projectatomic/osbs-client
osbs/build/pod_response.py
PodResponse.get_container_image_ids
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, prefix): if image_id.startswith(prefix): return image_id[len(prefix):] return image_id return {status['image']: remove_prefix(status['imageID'], 'docker://') for status in statuses}
python
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, prefix): if image_id.startswith(prefix): return image_id[len(prefix):] return image_id return {status['image']: remove_prefix(status['imageID'], 'docker://') for status in statuses}
[ "def", "get_container_image_ids", "(", "self", ")", ":", "statuses", "=", "graceful_chain_get", "(", "self", ".", "json", ",", "\"status\"", ",", "\"containerStatuses\"", ")", "if", "statuses", "is", "None", ":", "return", "{", "}", "def", "remove_prefix", "(", "image_id", ",", "prefix", ")", ":", "if", "image_id", ".", "startswith", "(", "prefix", ")", ":", "return", "image_id", "[", "len", "(", "prefix", ")", ":", "]", "return", "image_id", "return", "{", "status", "[", "'image'", "]", ":", "remove_prefix", "(", "status", "[", "'imageID'", "]", ",", "'docker://'", ")", "for", "status", "in", "statuses", "}" ]
Find the image IDs the containers use. :return: dict, image tag to docker ID
[ "Find", "the", "image", "IDs", "the", "containers", "use", "." ]
571fe035dab3a7c02e1dccd5d65ffd75be750458
https://github.com/projectatomic/osbs-client/blob/571fe035dab3a7c02e1dccd5d65ffd75be750458/osbs/build/pod_response.py#L33-L51
train
projectatomic/osbs-client
osbs/build/pod_response.py
PodResponse.get_failure_reason
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 """ reason_key = 'reason' cid_key = 'containerID' exit_key = 'exitCode' pod_status = self.json.get('status', {}) statuses = pod_status.get('containerStatuses', []) # Find the first non-zero exit code from a container # and return its 'message' or 'reason' value for status in statuses: try: terminated = status['state']['terminated'] exit_code = terminated['exitCode'] if exit_code != 0: reason_dict = { exit_key: exit_code, } if 'containerID' in terminated: reason_dict[cid_key] = terminated['containerID'] for key in ['message', 'reason']: try: reason_dict[reason_key] = terminated[key] break except KeyError: continue else: # Both 'message' and 'reason' are missing reason_dict[reason_key] = 'Exit code {code}'.format( code=exit_code ) return reason_dict except KeyError: continue # Failing that, return the 'message' or 'reason' value for the # pod for key in ['message', 'reason']: try: return {reason_key: pod_status[key]} except KeyError: continue return {reason_key: pod_status['phase']}
python
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 """ reason_key = 'reason' cid_key = 'containerID' exit_key = 'exitCode' pod_status = self.json.get('status', {}) statuses = pod_status.get('containerStatuses', []) # Find the first non-zero exit code from a container # and return its 'message' or 'reason' value for status in statuses: try: terminated = status['state']['terminated'] exit_code = terminated['exitCode'] if exit_code != 0: reason_dict = { exit_key: exit_code, } if 'containerID' in terminated: reason_dict[cid_key] = terminated['containerID'] for key in ['message', 'reason']: try: reason_dict[reason_key] = terminated[key] break except KeyError: continue else: # Both 'message' and 'reason' are missing reason_dict[reason_key] = 'Exit code {code}'.format( code=exit_code ) return reason_dict except KeyError: continue # Failing that, return the 'message' or 'reason' value for the # pod for key in ['message', 'reason']: try: return {reason_key: pod_status[key]} except KeyError: continue return {reason_key: pod_status['phase']}
[ "def", "get_failure_reason", "(", "self", ")", ":", "reason_key", "=", "'reason'", "cid_key", "=", "'containerID'", "exit_key", "=", "'exitCode'", "pod_status", "=", "self", ".", "json", ".", "get", "(", "'status'", ",", "{", "}", ")", "statuses", "=", "pod_status", ".", "get", "(", "'containerStatuses'", ",", "[", "]", ")", "# Find the first non-zero exit code from a container", "# and return its 'message' or 'reason' value", "for", "status", "in", "statuses", ":", "try", ":", "terminated", "=", "status", "[", "'state'", "]", "[", "'terminated'", "]", "exit_code", "=", "terminated", "[", "'exitCode'", "]", "if", "exit_code", "!=", "0", ":", "reason_dict", "=", "{", "exit_key", ":", "exit_code", ",", "}", "if", "'containerID'", "in", "terminated", ":", "reason_dict", "[", "cid_key", "]", "=", "terminated", "[", "'containerID'", "]", "for", "key", "in", "[", "'message'", ",", "'reason'", "]", ":", "try", ":", "reason_dict", "[", "reason_key", "]", "=", "terminated", "[", "key", "]", "break", "except", "KeyError", ":", "continue", "else", ":", "# Both 'message' and 'reason' are missing", "reason_dict", "[", "reason_key", "]", "=", "'Exit code {code}'", ".", "format", "(", "code", "=", "exit_code", ")", "return", "reason_dict", "except", "KeyError", ":", "continue", "# Failing that, return the 'message' or 'reason' value for the", "# pod", "for", "key", "in", "[", "'message'", ",", "'reason'", "]", ":", "try", ":", "return", "{", "reason_key", ":", "pod_status", "[", "key", "]", "}", "except", "KeyError", ":", "continue", "return", "{", "reason_key", ":", "pod_status", "[", "'phase'", "]", "}" ]
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
[ "Find", "the", "reason", "a", "pod", "failed" ]
571fe035dab3a7c02e1dccd5d65ffd75be750458
https://github.com/projectatomic/osbs-client/blob/571fe035dab3a7c02e1dccd5d65ffd75be750458/osbs/build/pod_response.py#L53-L108
train
projectatomic/osbs-client
osbs/build/build_response.py
BuildResponse.get_error_message
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: %s" % error_message plugin = error_reason.get('plugin')[0] or None error_message = error_reason.get('plugin')[1] or None if error_message: # Plugin has non-empty error description return "Error in plugin %s: %s" % (plugin, error_message) else: return "Error in plugin %s" % plugin
python
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: %s" % error_message plugin = error_reason.get('plugin')[0] or None error_message = error_reason.get('plugin')[1] or None if error_message: # Plugin has non-empty error description return "Error in plugin %s: %s" % (plugin, error_message) else: return "Error in plugin %s" % plugin
[ "def", "get_error_message", "(", "self", ")", ":", "error_reason", "=", "self", ".", "get_error_reason", "(", ")", "if", "error_reason", ":", "error_message", "=", "error_reason", ".", "get", "(", "'pod'", ")", "or", "None", "if", "error_message", ":", "return", "\"Error in pod: %s\"", "%", "error_message", "plugin", "=", "error_reason", ".", "get", "(", "'plugin'", ")", "[", "0", "]", "or", "None", "error_message", "=", "error_reason", ".", "get", "(", "'plugin'", ")", "[", "1", "]", "or", "None", "if", "error_message", ":", "# Plugin has non-empty error description", "return", "\"Error in plugin %s: %s\"", "%", "(", "plugin", ",", "error_message", ")", "else", ":", "return", "\"Error in plugin %s\"", "%", "plugin" ]
Return an error message based on atomic-reactor's metadata
[ "Return", "an", "error", "message", "based", "on", "atomic", "-", "reactor", "s", "metadata" ]
571fe035dab3a7c02e1dccd5d65ffd75be750458
https://github.com/projectatomic/osbs-client/blob/571fe035dab3a7c02e1dccd5d65ffd75be750458/osbs/build/build_response.py#L108-L123
train
thombashi/pytablereader
pytablereader/factory/_file.py
TableFileLoaderFactory.create_from_path
def create_from_path(self): """ Create a file loader from the file extension to loading file. Supported file extensions are as follows: ========================== ======================================= Extension Loader ========================== ======================================= ``"csv"`` :py:class:`~.CsvTableFileLoader` ``"xls"``/``"xlsx"`` :py:class:`~.ExcelTableFileLoader` ``"htm"``/``"html"`` :py:class:`~.HtmlTableFileLoader` ``"json"`` :py:class:`~.JsonTableFileLoader` ``"jsonl"`` :py:class:`~.JsonLinesTableFileLoader` ``"ldjson"`` :py:class:`~.JsonLinesTableFileLoader` ``"ltsv"`` :py:class:`~.LtsvTableFileLoader` ``"md"`` :py:class:`~.MarkdownTableFileLoader` ``"ndjson"`` :py:class:`~.JsonLinesTableFileLoader` ``"sqlite"``/``"sqlite3"`` :py:class:`~.SqliteFileLoader` ``"tsv"`` :py:class:`~.TsvTableFileLoader` ========================== ======================================= :return: Loader that coincides with the file extension of the :py:attr:`.file_extension`. :raises pytablereader.LoaderNotFoundError: |LoaderNotFoundError_desc| loading the file. """ loader = self._create_from_extension(self.file_extension) logger.debug( "TableFileLoaderFactory.create_from_path: extension={}, loader={}".format( self.file_extension, loader.format_name ) ) return loader
python
def create_from_path(self): """ Create a file loader from the file extension to loading file. Supported file extensions are as follows: ========================== ======================================= Extension Loader ========================== ======================================= ``"csv"`` :py:class:`~.CsvTableFileLoader` ``"xls"``/``"xlsx"`` :py:class:`~.ExcelTableFileLoader` ``"htm"``/``"html"`` :py:class:`~.HtmlTableFileLoader` ``"json"`` :py:class:`~.JsonTableFileLoader` ``"jsonl"`` :py:class:`~.JsonLinesTableFileLoader` ``"ldjson"`` :py:class:`~.JsonLinesTableFileLoader` ``"ltsv"`` :py:class:`~.LtsvTableFileLoader` ``"md"`` :py:class:`~.MarkdownTableFileLoader` ``"ndjson"`` :py:class:`~.JsonLinesTableFileLoader` ``"sqlite"``/``"sqlite3"`` :py:class:`~.SqliteFileLoader` ``"tsv"`` :py:class:`~.TsvTableFileLoader` ========================== ======================================= :return: Loader that coincides with the file extension of the :py:attr:`.file_extension`. :raises pytablereader.LoaderNotFoundError: |LoaderNotFoundError_desc| loading the file. """ loader = self._create_from_extension(self.file_extension) logger.debug( "TableFileLoaderFactory.create_from_path: extension={}, loader={}".format( self.file_extension, loader.format_name ) ) return loader
[ "def", "create_from_path", "(", "self", ")", ":", "loader", "=", "self", ".", "_create_from_extension", "(", "self", ".", "file_extension", ")", "logger", ".", "debug", "(", "\"TableFileLoaderFactory.create_from_path: extension={}, loader={}\"", ".", "format", "(", "self", ".", "file_extension", ",", "loader", ".", "format_name", ")", ")", "return", "loader" ]
Create a file loader from the file extension to loading file. Supported file extensions are as follows: ========================== ======================================= Extension Loader ========================== ======================================= ``"csv"`` :py:class:`~.CsvTableFileLoader` ``"xls"``/``"xlsx"`` :py:class:`~.ExcelTableFileLoader` ``"htm"``/``"html"`` :py:class:`~.HtmlTableFileLoader` ``"json"`` :py:class:`~.JsonTableFileLoader` ``"jsonl"`` :py:class:`~.JsonLinesTableFileLoader` ``"ldjson"`` :py:class:`~.JsonLinesTableFileLoader` ``"ltsv"`` :py:class:`~.LtsvTableFileLoader` ``"md"`` :py:class:`~.MarkdownTableFileLoader` ``"ndjson"`` :py:class:`~.JsonLinesTableFileLoader` ``"sqlite"``/``"sqlite3"`` :py:class:`~.SqliteFileLoader` ``"tsv"`` :py:class:`~.TsvTableFileLoader` ========================== ======================================= :return: Loader that coincides with the file extension of the :py:attr:`.file_extension`. :raises pytablereader.LoaderNotFoundError: |LoaderNotFoundError_desc| loading the file.
[ "Create", "a", "file", "loader", "from", "the", "file", "extension", "to", "loading", "file", ".", "Supported", "file", "extensions", "are", "as", "follows", ":" ]
bc3c057a2cc775bcce690e0e9019c2907b638101
https://github.com/thombashi/pytablereader/blob/bc3c057a2cc775bcce690e0e9019c2907b638101/pytablereader/factory/_file.py#L49-L85
train
thombashi/pytablereader
pytablereader/factory/_file.py
TableFileLoaderFactory.create_from_format_name
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 ================ ====================================== ``"csv"`` :py:class:`~.CsvTableFileLoader` ``"excel"`` :py:class:`~.ExcelTableFileLoader` ``"html"`` :py:class:`~.HtmlTableFileLoader` ``"json"`` :py:class:`~.JsonTableFileLoader` ``"json"`` :py:class:`~.JsonTableFileLoader` ``"json_lines"`` :py:class:`~.JsonTableFileLoader` ``"jsonl"`` :py:class:`~.JsonLinesTableFileLoader` ``"ltsv"`` :py:class:`~.LtsvTableFileLoader` ``"markdown"`` :py:class:`~.MarkdownTableFileLoader` ``"mediawiki"`` :py:class:`~.MediaWikiTableFileLoader` ``"ndjson"`` :py:class:`~.JsonLinesTableFileLoader` ``"sqlite"`` :py:class:`~.SqliteFileLoader` ``"ssv"`` :py:class:`~.CsvTableFileLoader` ``"tsv"`` :py:class:`~.TsvTableFileLoader` ================ ====================================== :param str format_name: Format name string (case insensitive). :return: Loader that coincides with the ``format_name``: :raises pytablereader.LoaderNotFoundError: |LoaderNotFoundError_desc| the format. """ loader = self._create_from_format_name(format_name) logger.debug( "TableFileLoaderFactory.create_from_format_name: name={}, loader={}".format( format_name, loader.format_name ) ) return loader
python
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 ================ ====================================== ``"csv"`` :py:class:`~.CsvTableFileLoader` ``"excel"`` :py:class:`~.ExcelTableFileLoader` ``"html"`` :py:class:`~.HtmlTableFileLoader` ``"json"`` :py:class:`~.JsonTableFileLoader` ``"json"`` :py:class:`~.JsonTableFileLoader` ``"json_lines"`` :py:class:`~.JsonTableFileLoader` ``"jsonl"`` :py:class:`~.JsonLinesTableFileLoader` ``"ltsv"`` :py:class:`~.LtsvTableFileLoader` ``"markdown"`` :py:class:`~.MarkdownTableFileLoader` ``"mediawiki"`` :py:class:`~.MediaWikiTableFileLoader` ``"ndjson"`` :py:class:`~.JsonLinesTableFileLoader` ``"sqlite"`` :py:class:`~.SqliteFileLoader` ``"ssv"`` :py:class:`~.CsvTableFileLoader` ``"tsv"`` :py:class:`~.TsvTableFileLoader` ================ ====================================== :param str format_name: Format name string (case insensitive). :return: Loader that coincides with the ``format_name``: :raises pytablereader.LoaderNotFoundError: |LoaderNotFoundError_desc| the format. """ loader = self._create_from_format_name(format_name) logger.debug( "TableFileLoaderFactory.create_from_format_name: name={}, loader={}".format( format_name, loader.format_name ) ) return loader
[ "def", "create_from_format_name", "(", "self", ",", "format_name", ")", ":", "loader", "=", "self", ".", "_create_from_format_name", "(", "format_name", ")", "logger", ".", "debug", "(", "\"TableFileLoaderFactory.create_from_format_name: name={}, loader={}\"", ".", "format", "(", "format_name", ",", "loader", ".", "format_name", ")", ")", "return", "loader" ]
Create a file loader from a format name. Supported file formats are as follows: ================ ====================================== Format name Loader ================ ====================================== ``"csv"`` :py:class:`~.CsvTableFileLoader` ``"excel"`` :py:class:`~.ExcelTableFileLoader` ``"html"`` :py:class:`~.HtmlTableFileLoader` ``"json"`` :py:class:`~.JsonTableFileLoader` ``"json"`` :py:class:`~.JsonTableFileLoader` ``"json_lines"`` :py:class:`~.JsonTableFileLoader` ``"jsonl"`` :py:class:`~.JsonLinesTableFileLoader` ``"ltsv"`` :py:class:`~.LtsvTableFileLoader` ``"markdown"`` :py:class:`~.MarkdownTableFileLoader` ``"mediawiki"`` :py:class:`~.MediaWikiTableFileLoader` ``"ndjson"`` :py:class:`~.JsonLinesTableFileLoader` ``"sqlite"`` :py:class:`~.SqliteFileLoader` ``"ssv"`` :py:class:`~.CsvTableFileLoader` ``"tsv"`` :py:class:`~.TsvTableFileLoader` ================ ====================================== :param str format_name: Format name string (case insensitive). :return: Loader that coincides with the ``format_name``: :raises pytablereader.LoaderNotFoundError: |LoaderNotFoundError_desc| the format.
[ "Create", "a", "file", "loader", "from", "a", "format", "name", ".", "Supported", "file", "formats", "are", "as", "follows", ":" ]
bc3c057a2cc775bcce690e0e9019c2907b638101
https://github.com/thombashi/pytablereader/blob/bc3c057a2cc775bcce690e0e9019c2907b638101/pytablereader/factory/_file.py#L87-L125
train
thombashi/pytablereader
pytablereader/factory/_file.py
TableFileLoaderFactory._get_extension_loader_mapping
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": MarkdownTableFileLoader, "sqlite3": SqliteFileLoader, "xlsx": ExcelTableFileLoader, "xls": ExcelTableFileLoader, } ) return loader_table
python
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": MarkdownTableFileLoader, "sqlite3": SqliteFileLoader, "xlsx": ExcelTableFileLoader, "xls": ExcelTableFileLoader, } ) return loader_table
[ "def", "_get_extension_loader_mapping", "(", "self", ")", ":", "loader_table", "=", "self", ".", "_get_common_loader_mapping", "(", ")", "loader_table", ".", "update", "(", "{", "\"htm\"", ":", "HtmlTableFileLoader", ",", "\"md\"", ":", "MarkdownTableFileLoader", ",", "\"sqlite3\"", ":", "SqliteFileLoader", ",", "\"xlsx\"", ":", "ExcelTableFileLoader", ",", "\"xls\"", ":", "ExcelTableFileLoader", ",", "}", ")", "return", "loader_table" ]
:return: Mappings of format extension and loader class. :rtype: dict
[ ":", "return", ":", "Mappings", "of", "format", "extension", "and", "loader", "class", ".", ":", "rtype", ":", "dict" ]
bc3c057a2cc775bcce690e0e9019c2907b638101
https://github.com/thombashi/pytablereader/blob/bc3c057a2cc775bcce690e0e9019c2907b638101/pytablereader/factory/_file.py#L141-L158
train
thombashi/pytablereader
pytablereader/factory/_file.py
TableFileLoaderFactory._get_format_name_loader_mapping
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_lines": JsonLinesTableFileLoader, "markdown": MarkdownTableFileLoader, "mediawiki": MediaWikiTableFileLoader, "ssv": CsvTableFileLoader, } ) return loader_table
python
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_lines": JsonLinesTableFileLoader, "markdown": MarkdownTableFileLoader, "mediawiki": MediaWikiTableFileLoader, "ssv": CsvTableFileLoader, } ) return loader_table
[ "def", "_get_format_name_loader_mapping", "(", "self", ")", ":", "loader_table", "=", "self", ".", "_get_common_loader_mapping", "(", ")", "loader_table", ".", "update", "(", "{", "\"excel\"", ":", "ExcelTableFileLoader", ",", "\"json_lines\"", ":", "JsonLinesTableFileLoader", ",", "\"markdown\"", ":", "MarkdownTableFileLoader", ",", "\"mediawiki\"", ":", "MediaWikiTableFileLoader", ",", "\"ssv\"", ":", "CsvTableFileLoader", ",", "}", ")", "return", "loader_table" ]
:return: Mappings of format name and loader class. :rtype: dict
[ ":", "return", ":", "Mappings", "of", "format", "name", "and", "loader", "class", ".", ":", "rtype", ":", "dict" ]
bc3c057a2cc775bcce690e0e9019c2907b638101
https://github.com/thombashi/pytablereader/blob/bc3c057a2cc775bcce690e0e9019c2907b638101/pytablereader/factory/_file.py#L160-L177
train
thombashi/pytablereader
pytablereader/spreadsheet/excelloader.py
ExcelTableFileLoader.load
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| =================== ==================================== Format specifier Value after the replacement =================== ==================================== ``%(filename)s`` Filename of the workbook ``%(sheet)s`` Name of the sheet ``%(format_name)s`` ``"spreadsheet"`` ``%(format_id)s`` |format_id_desc| ``%(global_id)s`` |global_id| =================== ==================================== :rtype: |TableData| iterator :raises pytablereader.DataError: If the header row is not found. :raises pytablereader.error.OpenError: If failed to open the source file. """ import xlrd self._validate() self._logger.logging_load() try: workbook = xlrd.open_workbook(self.source) except xlrd.biffh.XLRDError as e: raise OpenError(e) for worksheet in workbook.sheets(): self._worksheet = worksheet if self._is_empty_sheet(): continue self.__extract_not_empty_col_idx() try: start_row_idx = self._get_start_row_idx() except DataError: continue rows = [ self.__get_row_values(row_idx) for row_idx in range(start_row_idx + 1, self._row_count) ] self.inc_table_count() headers = self.__get_row_values(start_row_idx) yield TableData( self._make_table_name(), headers, rows, dp_extractor=self.dp_extractor, type_hints=self._extract_type_hints(headers), )
python
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| =================== ==================================== Format specifier Value after the replacement =================== ==================================== ``%(filename)s`` Filename of the workbook ``%(sheet)s`` Name of the sheet ``%(format_name)s`` ``"spreadsheet"`` ``%(format_id)s`` |format_id_desc| ``%(global_id)s`` |global_id| =================== ==================================== :rtype: |TableData| iterator :raises pytablereader.DataError: If the header row is not found. :raises pytablereader.error.OpenError: If failed to open the source file. """ import xlrd self._validate() self._logger.logging_load() try: workbook = xlrd.open_workbook(self.source) except xlrd.biffh.XLRDError as e: raise OpenError(e) for worksheet in workbook.sheets(): self._worksheet = worksheet if self._is_empty_sheet(): continue self.__extract_not_empty_col_idx() try: start_row_idx = self._get_start_row_idx() except DataError: continue rows = [ self.__get_row_values(row_idx) for row_idx in range(start_row_idx + 1, self._row_count) ] self.inc_table_count() headers = self.__get_row_values(start_row_idx) yield TableData( self._make_table_name(), headers, rows, dp_extractor=self.dp_extractor, type_hints=self._extract_type_hints(headers), )
[ "def", "load", "(", "self", ")", ":", "import", "xlrd", "self", ".", "_validate", "(", ")", "self", ".", "_logger", ".", "logging_load", "(", ")", "try", ":", "workbook", "=", "xlrd", ".", "open_workbook", "(", "self", ".", "source", ")", "except", "xlrd", ".", "biffh", ".", "XLRDError", "as", "e", ":", "raise", "OpenError", "(", "e", ")", "for", "worksheet", "in", "workbook", ".", "sheets", "(", ")", ":", "self", ".", "_worksheet", "=", "worksheet", "if", "self", ".", "_is_empty_sheet", "(", ")", ":", "continue", "self", ".", "__extract_not_empty_col_idx", "(", ")", "try", ":", "start_row_idx", "=", "self", ".", "_get_start_row_idx", "(", ")", "except", "DataError", ":", "continue", "rows", "=", "[", "self", ".", "__get_row_values", "(", "row_idx", ")", "for", "row_idx", "in", "range", "(", "start_row_idx", "+", "1", ",", "self", ".", "_row_count", ")", "]", "self", ".", "inc_table_count", "(", ")", "headers", "=", "self", ".", "__get_row_values", "(", "start_row_idx", ")", "yield", "TableData", "(", "self", ".", "_make_table_name", "(", ")", ",", "headers", ",", "rows", ",", "dp_extractor", "=", "self", ".", "dp_extractor", ",", "type_hints", "=", "self", ".", "_extract_type_hints", "(", "headers", ")", ",", ")" ]
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| =================== ==================================== Format specifier Value after the replacement =================== ==================================== ``%(filename)s`` Filename of the workbook ``%(sheet)s`` Name of the sheet ``%(format_name)s`` ``"spreadsheet"`` ``%(format_id)s`` |format_id_desc| ``%(global_id)s`` |global_id| =================== ==================================== :rtype: |TableData| iterator :raises pytablereader.DataError: If the header row is not found. :raises pytablereader.error.OpenError: If failed to open the source file.
[ "Extract", "tabular", "data", "as", "|TableData|", "instances", "from", "an", "Excel", "file", ".", "|spreadsheet_load_desc|" ]
bc3c057a2cc775bcce690e0e9019c2907b638101
https://github.com/thombashi/pytablereader/blob/bc3c057a2cc775bcce690e0e9019c2907b638101/pytablereader/spreadsheet/excelloader.py#L59-L122
train
thombashi/pytablereader
pytablereader/ltsv/core.py
LtsvTableFileLoader.load
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 Value after the replacement =================== ======================================== ``%(filename)s`` |filename_desc| ``%(format_name)s`` ``"ltsv"`` ``%(format_id)s`` |format_id_desc| ``%(global_id)s`` |global_id| =================== ======================================== :rtype: |TableData| iterator :raises pytablereader.InvalidHeaderNameError: If an invalid label name is included in the LTSV file. :raises pytablereader.DataError: If the LTSV data is invalid. """ self._validate() self._logger.logging_load() self.encoding = get_file_encoding(self.source, self.encoding) self._ltsv_input_stream = io.open(self.source, "r", encoding=self.encoding) for data_matrix in self._to_data_matrix(): formatter = SingleJsonTableConverterA(data_matrix) formatter.accept(self) return formatter.to_table_data()
python
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 Value after the replacement =================== ======================================== ``%(filename)s`` |filename_desc| ``%(format_name)s`` ``"ltsv"`` ``%(format_id)s`` |format_id_desc| ``%(global_id)s`` |global_id| =================== ======================================== :rtype: |TableData| iterator :raises pytablereader.InvalidHeaderNameError: If an invalid label name is included in the LTSV file. :raises pytablereader.DataError: If the LTSV data is invalid. """ self._validate() self._logger.logging_load() self.encoding = get_file_encoding(self.source, self.encoding) self._ltsv_input_stream = io.open(self.source, "r", encoding=self.encoding) for data_matrix in self._to_data_matrix(): formatter = SingleJsonTableConverterA(data_matrix) formatter.accept(self) return formatter.to_table_data()
[ "def", "load", "(", "self", ")", ":", "self", ".", "_validate", "(", ")", "self", ".", "_logger", ".", "logging_load", "(", ")", "self", ".", "encoding", "=", "get_file_encoding", "(", "self", ".", "source", ",", "self", ".", "encoding", ")", "self", ".", "_ltsv_input_stream", "=", "io", ".", "open", "(", "self", ".", "source", ",", "\"r\"", ",", "encoding", "=", "self", ".", "encoding", ")", "for", "data_matrix", "in", "self", ".", "_to_data_matrix", "(", ")", ":", "formatter", "=", "SingleJsonTableConverterA", "(", "data_matrix", ")", "formatter", ".", "accept", "(", "self", ")", "return", "formatter", ".", "to_table_data", "(", ")" ]
Extract tabular data as |TableData| instances from a LTSV file. |load_source_desc_file| :return: Loaded table data. |load_table_name_desc| =================== ======================================== Format specifier Value after the replacement =================== ======================================== ``%(filename)s`` |filename_desc| ``%(format_name)s`` ``"ltsv"`` ``%(format_id)s`` |format_id_desc| ``%(global_id)s`` |global_id| =================== ======================================== :rtype: |TableData| iterator :raises pytablereader.InvalidHeaderNameError: If an invalid label name is included in the LTSV file. :raises pytablereader.DataError: If the LTSV data is invalid.
[ "Extract", "tabular", "data", "as", "|TableData|", "instances", "from", "a", "LTSV", "file", ".", "|load_source_desc_file|" ]
bc3c057a2cc775bcce690e0e9019c2907b638101
https://github.com/thombashi/pytablereader/blob/bc3c057a2cc775bcce690e0e9019c2907b638101/pytablereader/ltsv/core.py#L106-L140
train
thombashi/pytablereader
pytablereader/ltsv/core.py
LtsvTableTextLoader.load
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 specifier Value after the replacement =================== ======================================== ``%(filename)s`` ``""`` ``%(format_name)s`` ``"ltsv"`` ``%(format_id)s`` |format_id_desc| ``%(global_id)s`` |global_id| =================== ======================================== :rtype: |TableData| iterator :raises pytablereader.InvalidHeaderNameError: If an invalid label name is included in the LTSV file. :raises pytablereader.DataError: If the LTSV data is invalid. """ self._validate() self._logger.logging_load() self._ltsv_input_stream = self.source.splitlines() for data_matrix in self._to_data_matrix(): formatter = SingleJsonTableConverterA(data_matrix) formatter.accept(self) return formatter.to_table_data()
python
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 specifier Value after the replacement =================== ======================================== ``%(filename)s`` ``""`` ``%(format_name)s`` ``"ltsv"`` ``%(format_id)s`` |format_id_desc| ``%(global_id)s`` |global_id| =================== ======================================== :rtype: |TableData| iterator :raises pytablereader.InvalidHeaderNameError: If an invalid label name is included in the LTSV file. :raises pytablereader.DataError: If the LTSV data is invalid. """ self._validate() self._logger.logging_load() self._ltsv_input_stream = self.source.splitlines() for data_matrix in self._to_data_matrix(): formatter = SingleJsonTableConverterA(data_matrix) formatter.accept(self) return formatter.to_table_data()
[ "def", "load", "(", "self", ")", ":", "self", ".", "_validate", "(", ")", "self", ".", "_logger", ".", "logging_load", "(", ")", "self", ".", "_ltsv_input_stream", "=", "self", ".", "source", ".", "splitlines", "(", ")", "for", "data_matrix", "in", "self", ".", "_to_data_matrix", "(", ")", ":", "formatter", "=", "SingleJsonTableConverterA", "(", "data_matrix", ")", "formatter", ".", "accept", "(", "self", ")", "return", "formatter", ".", "to_table_data", "(", ")" ]
Extract tabular data as |TableData| instances from a LTSV text object. |load_source_desc_text| :return: Loaded table data. |load_table_name_desc| =================== ======================================== Format specifier Value after the replacement =================== ======================================== ``%(filename)s`` ``""`` ``%(format_name)s`` ``"ltsv"`` ``%(format_id)s`` |format_id_desc| ``%(global_id)s`` |global_id| =================== ======================================== :rtype: |TableData| iterator :raises pytablereader.InvalidHeaderNameError: If an invalid label name is included in the LTSV file. :raises pytablereader.DataError: If the LTSV data is invalid.
[ "Extract", "tabular", "data", "as", "|TableData|", "instances", "from", "a", "LTSV", "text", "object", ".", "|load_source_desc_text|" ]
bc3c057a2cc775bcce690e0e9019c2907b638101
https://github.com/thombashi/pytablereader/blob/bc3c057a2cc775bcce690e0e9019c2907b638101/pytablereader/ltsv/core.py#L164-L197
train
robhowley/nhlscrapi
nhlscrapi/games/eventsummary.py
EventSummary.totals
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','ht','gv','tk','bs'] res = { k: 0 for k in keys } res['fo'] = { 'won': 0, 'total': 0 } for _, v in d.items(): for k in keys: res[k] += v[k] for fi in res['fo'].keys(): res['fo'][fi] += v['fo'][fi] return res return self.__apply_to_both(agg)
python
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','ht','gv','tk','bs'] res = { k: 0 for k in keys } res['fo'] = { 'won': 0, 'total': 0 } for _, v in d.items(): for k in keys: res[k] += v[k] for fi in res['fo'].keys(): res['fo'][fi] += v['fo'][fi] return res return self.__apply_to_both(agg)
[ "def", "totals", "(", "self", ")", ":", "def", "agg", "(", "d", ")", ":", "keys", "=", "[", "'g'", ",", "'a'", ",", "'p'", ",", "'pm'", ",", "'pn'", ",", "'pim'", ",", "'s'", ",", "'ab'", ",", "'ms'", ",", "'ht'", ",", "'gv'", ",", "'tk'", ",", "'bs'", "]", "res", "=", "{", "k", ":", "0", "for", "k", "in", "keys", "}", "res", "[", "'fo'", "]", "=", "{", "'won'", ":", "0", ",", "'total'", ":", "0", "}", "for", "_", ",", "v", "in", "d", ".", "items", "(", ")", ":", "for", "k", "in", "keys", ":", "res", "[", "k", "]", "+=", "v", "[", "k", "]", "for", "fi", "in", "res", "[", "'fo'", "]", ".", "keys", "(", ")", ":", "res", "[", "'fo'", "]", "[", "fi", "]", "+=", "v", "[", "'fo'", "]", "[", "fi", "]", "return", "res", "return", "self", ".", "__apply_to_both", "(", "agg", ")" ]
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 } }``
[ "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", "}", "}" ]
2273683497ff27b0e92c8d1557ff0ce962dbf43b
https://github.com/robhowley/nhlscrapi/blob/2273683497ff27b0e92c8d1557ff0ce962dbf43b/nhlscrapi/games/eventsummary.py#L137-L154
train
robhowley/nhlscrapi
nhlscrapi/games/eventsummary.py
EventSummary.filter_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:func:`home_players` and :py:func:`away_players` """ def each(d): return { k: v for k, v in d.items() if pl_filter(k, v) } return self.__apply_to_both(each)
python
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:func:`home_players` and :py:func:`away_players` """ def each(d): return { k: v for k, v in d.items() if pl_filter(k, v) } return self.__apply_to_both(each)
[ "def", "filter_players", "(", "self", ",", "pl_filter", ")", ":", "def", "each", "(", "d", ")", ":", "return", "{", "k", ":", "v", "for", "k", ",", "v", "in", "d", ".", "items", "(", ")", "if", "pl_filter", "(", "k", ",", "v", ")", "}", "return", "self", ".", "__apply_to_both", "(", "each", ")" ]
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`
[ "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" ]
2273683497ff27b0e92c8d1557ff0ce962dbf43b
https://github.com/robhowley/nhlscrapi/blob/2273683497ff27b0e92c8d1557ff0ce962dbf43b/nhlscrapi/games/eventsummary.py#L156-L170
train
robhowley/nhlscrapi
nhlscrapi/games/eventsummary.py
EventSummary.sort_players
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) dict key to sort on :param sort_func: (def None) sorting function :param reverse: (optional, def False) if True, sort descending :returns: dict of the form ``{ 'home/away': { by_player_dict } }``. See :py:func:`home_players` and :py:func:`away_players` """ def each(d): t = [ ] for num, v in d.items(): ti = { vk: vv for vk, vv in v.items() } ti['num'] = num t.append(ti) if sort_key: return sorted(t, key=lambda k: k[sort_key], reverse=reverse) else: return sorted(t, key=sort_func, reverse=reverse) return self.__apply_to_both(each)
python
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) dict key to sort on :param sort_func: (def None) sorting function :param reverse: (optional, def False) if True, sort descending :returns: dict of the form ``{ 'home/away': { by_player_dict } }``. See :py:func:`home_players` and :py:func:`away_players` """ def each(d): t = [ ] for num, v in d.items(): ti = { vk: vv for vk, vv in v.items() } ti['num'] = num t.append(ti) if sort_key: return sorted(t, key=lambda k: k[sort_key], reverse=reverse) else: return sorted(t, key=sort_func, reverse=reverse) return self.__apply_to_both(each)
[ "def", "sort_players", "(", "self", ",", "sort_key", "=", "None", ",", "sort_func", "=", "None", ",", "reverse", "=", "False", ")", ":", "def", "each", "(", "d", ")", ":", "t", "=", "[", "]", "for", "num", ",", "v", "in", "d", ".", "items", "(", ")", ":", "ti", "=", "{", "vk", ":", "vv", "for", "vk", ",", "vv", "in", "v", ".", "items", "(", ")", "}", "ti", "[", "'num'", "]", "=", "num", "t", ".", "append", "(", "ti", ")", "if", "sort_key", ":", "return", "sorted", "(", "t", ",", "key", "=", "lambda", "k", ":", "k", "[", "sort_key", "]", ",", "reverse", "=", "reverse", ")", "else", ":", "return", "sorted", "(", "t", ",", "key", "=", "sort_func", ",", "reverse", "=", "reverse", ")", "return", "self", ".", "__apply_to_both", "(", "each", ")" ]
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 True, sort descending :returns: dict of the form ``{ 'home/away': { by_player_dict } }``. See :py:func:`home_players` and :py:func:`away_players`
[ "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", "True", "sort", "descending", ":", "returns", ":", "dict", "of", "the", "form", "{", "home", "/", "away", ":", "{", "by_player_dict", "}", "}", ".", "See", ":", "py", ":", "func", ":", "home_players", "and", ":", "py", ":", "func", ":", "away_players" ]
2273683497ff27b0e92c8d1557ff0ce962dbf43b
https://github.com/robhowley/nhlscrapi/blob/2273683497ff27b0e92c8d1557ff0ce962dbf43b/nhlscrapi/games/eventsummary.py#L172-L194
train
robhowley/nhlscrapi
nhlscrapi/games/eventsummary.py
EventSummary.top_by_key
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:`home_players` and :py:func:`away_players` """ res = self.sort_players(sort_key=sort_key, reverse=True) return { 'home': res['home'][0], 'away': res['away'][0] }
python
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:`home_players` and :py:func:`away_players` """ res = self.sort_players(sort_key=sort_key, reverse=True) return { 'home': res['home'][0], 'away': res['away'][0] }
[ "def", "top_by_key", "(", "self", ",", "sort_key", ")", ":", "res", "=", "self", ".", "sort_players", "(", "sort_key", "=", "sort_key", ",", "reverse", "=", "True", ")", "return", "{", "'home'", ":", "res", "[", "'home'", "]", "[", "0", "]", ",", "'away'", ":", "res", "[", "'away'", "]", "[", "0", "]", "}" ]
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`
[ "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" ]
2273683497ff27b0e92c8d1557ff0ce962dbf43b
https://github.com/robhowley/nhlscrapi/blob/2273683497ff27b0e92c8d1557ff0ce962dbf43b/nhlscrapi/games/eventsummary.py#L226-L237
train
robhowley/nhlscrapi
nhlscrapi/games/eventsummary.py
EventSummary.top_by_func
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 form ``{ 'home/away': { by_player_dict } }``. See :py:func:`home_players` and :py:func:`away_players` """ res = self.sort_players(sort_func=sort_func, reverse=True) return { 'home': res['home'][0], 'away': res['away'][0] }
python
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 form ``{ 'home/away': { by_player_dict } }``. See :py:func:`home_players` and :py:func:`away_players` """ res = self.sort_players(sort_func=sort_func, reverse=True) return { 'home': res['home'][0], 'away': res['away'][0] }
[ "def", "top_by_func", "(", "self", ",", "sort_func", ")", ":", "res", "=", "self", ".", "sort_players", "(", "sort_func", "=", "sort_func", ",", "reverse", "=", "True", ")", "return", "{", "'home'", ":", "res", "[", "'home'", "]", "[", "0", "]", ",", "'away'", ":", "res", "[", "'away'", "]", "[", "0", "]", "}" ]
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:`away_players`
[ "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", ":", "away_players" ]
2273683497ff27b0e92c8d1557ff0ce962dbf43b
https://github.com/robhowley/nhlscrapi/blob/2273683497ff27b0e92c8d1557ff0ce962dbf43b/nhlscrapi/games/eventsummary.py#L239-L251
train
ryanpetrello/python-zombie
zombie/proxy/client.py
encode
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)
python
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)
[ "def", "encode", "(", "obj", ")", ":", "if", "hasattr", "(", "obj", ",", "'json'", ")", ":", "return", "obj", ".", "json", "if", "hasattr", "(", "obj", ",", "'__json__'", ")", ":", "return", "obj", ".", "__json__", "(", ")", "return", "dumps", "(", "obj", ")" ]
Encode one argument/object to json
[ "Encode", "one", "argument", "/", "object", "to", "json" ]
638916572d8ee5ebbdb2dcfc5000a952e99f280f
https://github.com/ryanpetrello/python-zombie/blob/638916572d8ee5ebbdb2dcfc5000a952e99f280f/zombie/proxy/client.py#L14-L22
train
ryanpetrello/python-zombie
zombie/proxy/client.py
encode_args
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
python
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
[ "def", "encode_args", "(", "args", ",", "extra", "=", "False", ")", ":", "if", "not", "args", ":", "return", "''", "methodargs", "=", "', '", ".", "join", "(", "[", "encode", "(", "a", ")", "for", "a", "in", "args", "]", ")", "if", "extra", ":", "methodargs", "+=", "', '", "return", "methodargs" ]
Encode a list of arguments
[ "Encode", "a", "list", "of", "arguments" ]
638916572d8ee5ebbdb2dcfc5000a952e99f280f
https://github.com/ryanpetrello/python-zombie/blob/638916572d8ee5ebbdb2dcfc5000a952e99f280f/zombie/proxy/client.py#L25-L36
train
ryanpetrello/python-zombie
zombie/proxy/client.py
ZombieProxyClient._send
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 = ctx_switch('%s'), browser = _ctx[0], ELEMENTS = _ctx[1]; %s """ % (id(self), javascript) response = self.connection.send(message) return self._handle_response(response)
python
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 = ctx_switch('%s'), browser = _ctx[0], ELEMENTS = _ctx[1]; %s """ % (id(self), javascript) response = self.connection.send(message) return self._handle_response(response)
[ "def", "_send", "(", "self", ",", "javascript", ")", ":", "# Prepend JS to switch to the proper client context.", "message", "=", "\"\"\"\n var _ctx = ctx_switch('%s'),\n browser = _ctx[0],\n ELEMENTS = _ctx[1];\n %s\n \"\"\"", "%", "(", "id", "(", "self", ")", ",", "javascript", ")", "response", "=", "self", ".", "connection", ".", "send", "(", "message", ")", "return", "self", ".", "_handle_response", "(", "response", ")" ]
Establishes a socket connection to the zombie.js server and sends Javascript instructions. :param js: the Javascript string to execute
[ "Establishes", "a", "socket", "connection", "to", "the", "zombie", ".", "js", "server", "and", "sends", "Javascript", "instructions", "." ]
638916572d8ee5ebbdb2dcfc5000a952e99f280f
https://github.com/ryanpetrello/python-zombie/blob/638916572d8ee5ebbdb2dcfc5000a952e99f280f/zombie/proxy/client.py#L123-L141
train
ryanpetrello/python-zombie
zombie/proxy/client.py
ZombieProxyClient.wait
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 = """ %s(%s wait_callback); """ % (method, methodargs) self._send(js)
python
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 = """ %s(%s wait_callback); """ % (method, methodargs) self._send(js)
[ "def", "wait", "(", "self", ",", "method", ",", "*", "args", ")", ":", "methodargs", "=", "encode_args", "(", "args", ",", "extra", "=", "True", ")", "js", "=", "\"\"\"\n %s(%s wait_callback);\n \"\"\"", "%", "(", "method", ",", "methodargs", ")", "self", ".", "_send", "(", "js", ")" ]
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
[ "Call", "a", "method", "on", "the", "zombie", ".", "js", "Browser", "instance", "and", "wait", "on", "a", "callback", "." ]
638916572d8ee5ebbdb2dcfc5000a952e99f280f
https://github.com/ryanpetrello/python-zombie/blob/638916572d8ee5ebbdb2dcfc5000a952e99f280f/zombie/proxy/client.py#L168-L179
train
ryanpetrello/python-zombie
zombie/proxy/client.py
ZombieProxyClient.create_element
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 the following Javascript... browser.query('body > div') :param method: the method (e.g., query) to call on the browser :param selector: a string CSS selector (http://zombie.labnotes.org/selectors) :param context: an (optional) instance of :class:`zombie.dom.DOMNode` """ if args is None: arguments = '' else: arguments = "(%s)" % encode_args(args) js = """ create_element(ELEMENTS, %(method)s%(args)s); """ % { 'method': method, 'args': arguments } index = self.json(js) if index is None: return None return Element(index)
python
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 the following Javascript... browser.query('body > div') :param method: the method (e.g., query) to call on the browser :param selector: a string CSS selector (http://zombie.labnotes.org/selectors) :param context: an (optional) instance of :class:`zombie.dom.DOMNode` """ if args is None: arguments = '' else: arguments = "(%s)" % encode_args(args) js = """ create_element(ELEMENTS, %(method)s%(args)s); """ % { 'method': method, 'args': arguments } index = self.json(js) if index is None: return None return Element(index)
[ "def", "create_element", "(", "self", ",", "method", ",", "args", "=", "None", ")", ":", "if", "args", "is", "None", ":", "arguments", "=", "''", "else", ":", "arguments", "=", "\"(%s)\"", "%", "encode_args", "(", "args", ")", "js", "=", "\"\"\"\n create_element(ELEMENTS, %(method)s%(args)s);\n \"\"\"", "%", "{", "'method'", ":", "method", ",", "'args'", ":", "arguments", "}", "index", "=", "self", ".", "json", "(", "js", ")", "if", "index", "is", "None", ":", "return", "None", "return", "Element", "(", "index", ")" ]
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 the following Javascript... browser.query('body > div') :param method: the method (e.g., query) to call on the browser :param selector: a string CSS selector (http://zombie.labnotes.org/selectors) :param context: an (optional) instance of :class:`zombie.dom.DOMNode`
[ "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", "." ]
638916572d8ee5ebbdb2dcfc5000a952e99f280f
https://github.com/ryanpetrello/python-zombie/blob/638916572d8ee5ebbdb2dcfc5000a952e99f280f/zombie/proxy/client.py#L213-L245
train
ryanpetrello/python-zombie
zombie/proxy/client.py
ZombieProxyClient.create_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)) """ % { 'method': method, 'args': args, } indexes = self.json(js) return map(Element, indexes)
python
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)) """ % { 'method': method, 'args': args, } indexes = self.json(js) return map(Element, indexes)
[ "def", "create_elements", "(", "self", ",", "method", ",", "args", "=", "[", "]", ")", ":", "args", "=", "encode_args", "(", "args", ")", "js", "=", "\"\"\"\n create_elements(ELEMENTS, %(method)s(%(args)s))\n \"\"\"", "%", "{", "'method'", ":", "method", ",", "'args'", ":", "args", ",", "}", "indexes", "=", "self", ".", "json", "(", "js", ")", "return", "map", "(", "Element", ",", "indexes", ")" ]
Execute a browser method that will return a list of elements. Returns a list of the element indexes
[ "Execute", "a", "browser", "method", "that", "will", "return", "a", "list", "of", "elements", "." ]
638916572d8ee5ebbdb2dcfc5000a952e99f280f
https://github.com/ryanpetrello/python-zombie/blob/638916572d8ee5ebbdb2dcfc5000a952e99f280f/zombie/proxy/client.py#L247-L263
train
ryanpetrello/python-zombie
zombie/browser.py
Browser.fill
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, value)) return self
python
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, value)) return self
[ "def", "fill", "(", "self", ",", "field", ",", "value", ")", ":", "self", ".", "client", ".", "nowait", "(", "'browser.fill'", ",", "(", "field", ",", "value", ")", ")", "return", "self" ]
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.
[ "Fill", "a", "specified", "form", "field", "in", "the", "current", "document", "." ]
638916572d8ee5ebbdb2dcfc5000a952e99f280f
https://github.com/ryanpetrello/python-zombie/blob/638916572d8ee5ebbdb2dcfc5000a952e99f280f/zombie/browser.py#L39-L48
train
ryanpetrello/python-zombie
zombie/browser.py
Browser.query
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.labnotes.org/selectors) :param context: an (optional) instance of :class:`zombie.dom.DOMNode` """ element = self.client.create_element( 'browser.query', (selector, context)) return DOMNode.factory(element, self)
python
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.labnotes.org/selectors) :param context: an (optional) instance of :class:`zombie.dom.DOMNode` """ element = self.client.create_element( 'browser.query', (selector, context)) return DOMNode.factory(element, self)
[ "def", "query", "(", "self", ",", "selector", ",", "context", "=", "None", ")", ":", "element", "=", "self", ".", "client", ".", "create_element", "(", "'browser.query'", ",", "(", "selector", ",", "context", ")", ")", "return", "DOMNode", ".", "factory", "(", "element", ",", "self", ")" ]
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.labnotes.org/selectors) :param context: an (optional) instance of :class:`zombie.dom.DOMNode`
[ "Evaluate", "a", "CSS", "selector", "against", "the", "document", "(", "or", "an", "optional", "context", ":", "class", ":", "zombie", ".", "dom", ".", "DOMNode", ")", "and", "return", "a", "single", ":", "class", ":", "zombie", ".", "dom", ".", "DOMNode", "object", "." ]
638916572d8ee5ebbdb2dcfc5000a952e99f280f
https://github.com/ryanpetrello/python-zombie/blob/638916572d8ee5ebbdb2dcfc5000a952e99f280f/zombie/browser.py#L124-L136
train
ryanpetrello/python-zombie
zombie/browser.py
Browser.queryAll
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://zombie.labnotes.org/selectors) :param context: an (optional) instance of :class:`zombie.dom.DOMNode` """ elements = self.client.create_elements( 'browser.queryAll', (selector, context)) return [DOMNode(e, self) for e in elements]
python
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://zombie.labnotes.org/selectors) :param context: an (optional) instance of :class:`zombie.dom.DOMNode` """ elements = self.client.create_elements( 'browser.queryAll', (selector, context)) return [DOMNode(e, self) for e in elements]
[ "def", "queryAll", "(", "self", ",", "selector", ",", "context", "=", "None", ")", ":", "elements", "=", "self", ".", "client", ".", "create_elements", "(", "'browser.queryAll'", ",", "(", "selector", ",", "context", ")", ")", "return", "[", "DOMNode", "(", "e", ",", "self", ")", "for", "e", "in", "elements", "]" ]
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://zombie.labnotes.org/selectors) :param context: an (optional) instance of :class:`zombie.dom.DOMNode`
[ "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", "." ]
638916572d8ee5ebbdb2dcfc5000a952e99f280f
https://github.com/ryanpetrello/python-zombie/blob/638916572d8ee5ebbdb2dcfc5000a952e99f280f/zombie/browser.py#L138-L150
train
ryanpetrello/python-zombie
zombie/browser.py
Browser.link
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 (http://zombie.labnotes.org/selectors) or inner text """ element = self.client.create_element('browser.link', (selector,)) return DOMNode(element, self)
python
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 (http://zombie.labnotes.org/selectors) or inner text """ element = self.client.create_element('browser.link', (selector,)) return DOMNode(element, self)
[ "def", "link", "(", "self", ",", "selector", ")", ":", "element", "=", "self", ".", "client", ".", "create_element", "(", "'browser.link'", ",", "(", "selector", ",", ")", ")", "return", "DOMNode", "(", "element", ",", "self", ")" ]
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 (http://zombie.labnotes.org/selectors) or inner text
[ "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", ")", "." ]
638916572d8ee5ebbdb2dcfc5000a952e99f280f
https://github.com/ryanpetrello/python-zombie/blob/638916572d8ee5ebbdb2dcfc5000a952e99f280f/zombie/browser.py#L234-L244
train
ryanpetrello/python-zombie
zombie/browser.py
DOMNode.value
def value(self, value): """ Used to set the ``value`` of form elements. """ self.client.nowait( 'set_field', (Literal('browser'), self.element, value))
python
def value(self, value): """ Used to set the ``value`` of form elements. """ self.client.nowait( 'set_field', (Literal('browser'), self.element, value))
[ "def", "value", "(", "self", ",", "value", ")", ":", "self", ".", "client", ".", "nowait", "(", "'set_field'", ",", "(", "Literal", "(", "'browser'", ")", ",", "self", ".", "element", ",", "value", ")", ")" ]
Used to set the ``value`` of form elements.
[ "Used", "to", "set", "the", "value", "of", "form", "elements", "." ]
638916572d8ee5ebbdb2dcfc5000a952e99f280f
https://github.com/ryanpetrello/python-zombie/blob/638916572d8ee5ebbdb2dcfc5000a952e99f280f/zombie/browser.py#L527-L532
train
ryanpetrello/python-zombie
zombie/browser.py
DOMNode.fire
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
python
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
[ "def", "fire", "(", "self", ",", "event", ")", ":", "self", ".", "browser", ".", "fire", "(", "self", ".", "element", ",", "event", ")", "return", "self" ]
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.
[ "Fires", "a", "specified", "DOM", "event", "on", "the", "current", "node", "." ]
638916572d8ee5ebbdb2dcfc5000a952e99f280f
https://github.com/ryanpetrello/python-zombie/blob/638916572d8ee5ebbdb2dcfc5000a952e99f280f/zombie/browser.py#L562-L571
train
robhowley/nhlscrapi
nhlscrapi/games/game.py
Game.load_all
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() self.play_by_play.load_all() self.face_off_comp.load_all() return self except Exception as e: print(e) return None
python
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() self.play_by_play.load_all() self.face_off_comp.load_all() return self except Exception as e: print(e) return None
[ "def", "load_all", "(", "self", ")", ":", "try", ":", "self", ".", "toi", ".", "load_all", "(", ")", "self", ".", "rosters", ".", "load_all", "(", ")", "#self.summary.load_all()", "self", ".", "play_by_play", ".", "load_all", "(", ")", "self", ".", "face_off_comp", ".", "load_all", "(", ")", "return", "self", "except", "Exception", "as", "e", ":", "print", "(", "e", ")", "return", "None" ]
Force all reports to be loaded and parsed instead of lazy loading on demand. :returns: ``self`` or ``None`` if load fails
[ "Force", "all", "reports", "to", "be", "loaded", "and", "parsed", "instead", "of", "lazy", "loading", "on", "demand", ".", ":", "returns", ":", "self", "or", "None", "if", "load", "fails" ]
2273683497ff27b0e92c8d1557ff0ce962dbf43b
https://github.com/robhowley/nhlscrapi/blob/2273683497ff27b0e92c8d1557ff0ce962dbf43b/nhlscrapi/games/game.py#L135-L150
train
robhowley/nhlscrapi
nhlscrapi/games/game.py
Game.matchup
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, 'final': final, 'attendance': att, 'date': date, 'location': loc } :returns: matchup banner info :rtype: dict """ if self.play_by_play.matchup: return self.play_by_play.matchup elif self.rosters.matchup: return self.rosters.matchup elif self.toi.matchup: return self.toi.matchup else: self.face_off_comp.matchup
python
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, 'final': final, 'attendance': att, 'date': date, 'location': loc } :returns: matchup banner info :rtype: dict """ if self.play_by_play.matchup: return self.play_by_play.matchup elif self.rosters.matchup: return self.rosters.matchup elif self.toi.matchup: return self.toi.matchup else: self.face_off_comp.matchup
[ "def", "matchup", "(", "self", ")", ":", "if", "self", ".", "play_by_play", ".", "matchup", ":", "return", "self", ".", "play_by_play", ".", "matchup", "elif", "self", ".", "rosters", ".", "matchup", ":", "return", "self", ".", "rosters", ".", "matchup", "elif", "self", ".", "toi", ".", "matchup", ":", "return", "self", ".", "toi", ".", "matchup", "else", ":", "self", ".", "face_off_comp", ".", "matchup" ]
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
[ "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" ]
2273683497ff27b0e92c8d1557ff0ce962dbf43b
https://github.com/robhowley/nhlscrapi/blob/2273683497ff27b0e92c8d1557ff0ce962dbf43b/nhlscrapi/games/game.py#L159-L185
train
evansherlock/nytimesarticle
nytimesarticle.py
articleAPI._utf8_encode
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 in enumerate(v): item = item.encode('utf8').lower() v[index] = item if isinstance(v, dict): d[k] = self._utf8_encode(v) return d
python
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 in enumerate(v): item = item.encode('utf8').lower() v[index] = item if isinstance(v, dict): d[k] = self._utf8_encode(v) return d
[ "def", "_utf8_encode", "(", "self", ",", "d", ")", ":", "for", "k", ",", "v", "in", "d", ".", "items", "(", ")", ":", "if", "isinstance", "(", "v", ",", "str", ")", ":", "d", "[", "k", "]", "=", "v", ".", "encode", "(", "'utf8'", ")", ".", "lower", "(", ")", "if", "isinstance", "(", "v", ",", "list", ")", ":", "for", "index", ",", "item", "in", "enumerate", "(", "v", ")", ":", "item", "=", "item", ".", "encode", "(", "'utf8'", ")", ".", "lower", "(", ")", "v", "[", "index", "]", "=", "item", "if", "isinstance", "(", "v", ",", "dict", ")", ":", "d", "[", "k", "]", "=", "self", ".", "_utf8_encode", "(", "v", ")", "return", "d" ]
Ensures all values are encoded in UTF-8 and converts them to lowercase
[ "Ensures", "all", "values", "are", "encoded", "in", "UTF", "-", "8", "and", "converts", "them", "to", "lowercase" ]
89f551699ffb11f71b47271246d350a1043e9326
https://github.com/evansherlock/nytimesarticle/blob/89f551699ffb11f71b47271246d350a1043e9326/nytimesarticle.py#L29-L44
train
evansherlock/nytimesarticle
nytimesarticle.py
articleAPI._bool_encode
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
python
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
[ "def", "_bool_encode", "(", "self", ",", "d", ")", ":", "for", "k", ",", "v", "in", "d", ".", "items", "(", ")", ":", "if", "isinstance", "(", "v", ",", "bool", ")", ":", "d", "[", "k", "]", "=", "str", "(", "v", ")", ".", "lower", "(", ")", "return", "d" ]
Converts bool values to lowercase strings
[ "Converts", "bool", "values", "to", "lowercase", "strings" ]
89f551699ffb11f71b47271246d350a1043e9326
https://github.com/evansherlock/nytimesarticle/blob/89f551699ffb11f71b47271246d350a1043e9326/nytimesarticle.py#L46-L55
train
evansherlock/nytimesarticle
nytimesarticle.py
articleAPI._options
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(map(lambda x: '"' + x + '"', v)) else: d[k] = '"' + v + '"' values = [] for k,v in d.items(): value = '%s:(%s)' % (k,v) values.append(value) values = ' AND '.join(values) return values kwargs = self._utf8_encode(kwargs) kwargs = self._bool_encode(kwargs) values = '' for k, v in kwargs.items(): if k is 'fq' and isinstance(v, dict): v = _format_fq(v) elif isinstance(v, list): v = ','.join(v) values += '%s=%s&' % (k, v) return values
python
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(map(lambda x: '"' + x + '"', v)) else: d[k] = '"' + v + '"' values = [] for k,v in d.items(): value = '%s:(%s)' % (k,v) values.append(value) values = ' AND '.join(values) return values kwargs = self._utf8_encode(kwargs) kwargs = self._bool_encode(kwargs) values = '' for k, v in kwargs.items(): if k is 'fq' and isinstance(v, dict): v = _format_fq(v) elif isinstance(v, list): v = ','.join(v) values += '%s=%s&' % (k, v) return values
[ "def", "_options", "(", "self", ",", "*", "*", "kwargs", ")", ":", "def", "_format_fq", "(", "d", ")", ":", "for", "k", ",", "v", "in", "d", ".", "items", "(", ")", ":", "if", "isinstance", "(", "v", ",", "list", ")", ":", "d", "[", "k", "]", "=", "' '", ".", "join", "(", "map", "(", "lambda", "x", ":", "'\"'", "+", "x", "+", "'\"'", ",", "v", ")", ")", "else", ":", "d", "[", "k", "]", "=", "'\"'", "+", "v", "+", "'\"'", "values", "=", "[", "]", "for", "k", ",", "v", "in", "d", ".", "items", "(", ")", ":", "value", "=", "'%s:(%s)'", "%", "(", "k", ",", "v", ")", "values", ".", "append", "(", "value", ")", "values", "=", "' AND '", ".", "join", "(", "values", ")", "return", "values", "kwargs", "=", "self", ".", "_utf8_encode", "(", "kwargs", ")", "kwargs", "=", "self", ".", "_bool_encode", "(", "kwargs", ")", "values", "=", "''", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", ":", "if", "k", "is", "'fq'", "and", "isinstance", "(", "v", ",", "dict", ")", ":", "v", "=", "_format_fq", "(", "v", ")", "elif", "isinstance", "(", "v", ",", "list", ")", ":", "v", "=", "','", ".", "join", "(", "v", ")", "values", "+=", "'%s=%s&'", "%", "(", "k", ",", "v", ")", "return", "values" ]
Formats search parameters/values for use with API :param \*\*kwargs: search parameters/values
[ "Formats", "search", "parameters", "/", "values", "for", "use", "with", "API", ":", "param", "\\", "*", "\\", "*", "kwargs", ":", "search", "parameters", "/", "values" ]
89f551699ffb11f71b47271246d350a1043e9326
https://github.com/evansherlock/nytimesarticle/blob/89f551699ffb11f71b47271246d350a1043e9326/nytimesarticle.py#L57-L89
train
evansherlock/nytimesarticle
nytimesarticle.py
articleAPI.search
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, includes JSON (.json) and JSONP (.jsonp). Defaults to '.json'. :param key: a developer key. Defaults to key given when the articleAPI class was initialized. """ if response_format is None: response_format = self.response_format if key is None: key = self.key url = '%s%s?%sapi-key=%s' % ( API_ROOT, response_format, self._options(**kwargs), key ) r = requests.get(url) return r.json()
python
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, includes JSON (.json) and JSONP (.jsonp). Defaults to '.json'. :param key: a developer key. Defaults to key given when the articleAPI class was initialized. """ if response_format is None: response_format = self.response_format if key is None: key = self.key url = '%s%s?%sapi-key=%s' % ( API_ROOT, response_format, self._options(**kwargs), key ) r = requests.get(url) return r.json()
[ "def", "search", "(", "self", ",", "response_format", "=", "None", ",", "key", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "response_format", "is", "None", ":", "response_format", "=", "self", ".", "response_format", "if", "key", "is", "None", ":", "key", "=", "self", ".", "key", "url", "=", "'%s%s?%sapi-key=%s'", "%", "(", "API_ROOT", ",", "response_format", ",", "self", ".", "_options", "(", "*", "*", "kwargs", ")", ",", "key", ")", "r", "=", "requests", ".", "get", "(", "url", ")", "return", "r", ".", "json", "(", ")" ]
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.
[ "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", "." ]
89f551699ffb11f71b47271246d350a1043e9326
https://github.com/evansherlock/nytimesarticle/blob/89f551699ffb11f71b47271246d350a1043e9326/nytimesarticle.py#L91-L115
train
robhowley/nhlscrapi
nhlscrapi/scrapr/gamesummrep.py
parse
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
python
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
[ "def", "parse", "(", "self", ")", ":", "r", "=", "super", "(", "GameSummRep", ",", "self", ")", ".", "parse", "(", ")", "try", ":", "self", ".", "parse_scoring_summary", "(", ")", "return", "r", "and", "False", "except", ":", "return", "False" ]
Fully parses game summary report. :returns: boolean success indicator :rtype: bool
[ "Fully", "parses", "game", "summary", "report", ".", ":", "returns", ":", "boolean", "success", "indicator", ":", "rtype", ":", "bool" ]
2273683497ff27b0e92c8d1557ff0ce962dbf43b
https://github.com/robhowley/nhlscrapi/blob/2273683497ff27b0e92c8d1557ff0ce962dbf43b/nhlscrapi/scrapr/gamesummrep.py#L18-L28
train