sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def fetch_all(self, R, depth=1, **kwargs):
"Request multiple objects from API"
d, e = self._fetcher.fetch_all(R, depth, kwargs)
if e: raise e
return d | Request multiple objects from API | entailment |
def get(self, res, pk):
"Get a resource instance by primary key (id)"
B = get_backend()
return B.get_object(B.get_concrete(res), pk) | Get a resource instance by primary key (id) | entailment |
def all(self, res):
"Get resources using a filter condition"
B = get_backend()
return B.get_objects(B.get_concrete(res)) | Get resources using a filter condition | entailment |
def run_task(func):
"""
Decorator to collect and return generator results, returning a list
if there are multiple results
"""
def _wrapped(*a, **k):
gen = func(*a, **k)
return _consume_task(gen)
return _wrapped | Decorator to collect and return generator results, returning a list
if there are multiple results | entailment |
def get(self, typ, id, **kwargs):
"""
Load type by id
"""
return self._load(self._request(typ, id=id, params=kwargs)) | Load type by id | entailment |
def _request(self, typ, id=0, method='GET', params=None, data=None,
url=None):
"""
send the request, return response obj
"""
backend, backend_version = peeringdb.get_backend_info()
user_agent = 'PeeringDB/{} {}/{}'.format(peeringdb.__version__,
... | send the request, return response obj | entailment |
def wrap_generator(func):
"""
Decorator to convert a generator function to an async function which collects
and returns generator results, returning a list if there are multiple results
"""
async def _wrapped(*a, **k):
r, ret = None, []
gen = func(*a, **k)
while True:
... | Decorator to convert a generator function to an async function which collects
and returns generator results, returning a list if there are multiple results | entailment |
def run_task(func):
"""
Decorator to wrap an async function in an event loop.
Use for main sync interface methods.
"""
def _wrapped(*a, **k):
loop = asyncio.get_event_loop()
return loop.run_until_complete(func(*a, **k))
return _wrapped | Decorator to wrap an async function in an event loop.
Use for main sync interface methods. | entailment |
def split_ref(string):
""" splits a string into (tag, id) """
re_tag = re.compile('^(?P<tag>[a-zA-Z]+)[\s-]*(?P<pk>\d+)$')
m = re_tag.search(string)
if not m:
raise ValueError("unable to split string '%s'" % (string, ))
return (m.group('tag').lower(), int(m.group('pk'))) | splits a string into (tag, id) | entailment |
def prompt(msg, default=None):
"Prompt for input"
if default is not None:
msg = '{} ({})'.format(msg, repr(default))
msg = '{}: '.format(msg)
try:
s = input(msg)
except KeyboardInterrupt:
exit(1)
except EOFError:
s = ''
if not s:
s = default
return... | Prompt for input | entailment |
def limit_mem(limit=(4 * 1024**3)):
"Set soft memory limit"
rsrc = resource.RLIMIT_DATA
soft, hard = resource.getrlimit(rsrc)
resource.setrlimit(rsrc, (limit, hard)) # 4GB
softnew, _ = resource.getrlimit(rsrc)
assert softnew == limit
_log = logging.getLogger(__name__)
_log.debug('Set s... | Set soft memory limit | entailment |
def render_module(inits, calls, inputs, outputs, dst_dir, pytorch_dict, pytorch_module_name):
"""
Render model.
"""
inits = [i for i in inits if len(i) > 0]
output = pytorch_model_template.format(**{
'module_name': pytorch_module_name,
'module_name_lower': pytorch_module_name.lower... | Render model. | entailment |
def gluon2pytorch(net, args, dst_dir, pytorch_module_name, debug=True, keep_names=False):
"""
Function to convert a model.
"""
x = [mx.nd.array(np.ones(i)) for i in args]
x = net(*x)
# Get network params
params = net.collect_params()
# Create a symbol to trace net
x = [mx.sym.var(... | Function to convert a model. | entailment |
def hook_odoo(package):
""" work around Odoo 10 issue
https://github.com/acsone/setuptools-odoo/issues/10
# This hook should runs after all *-nspkg.pth files because it is named
# zzz_ and .pth file run in alphabetical order.
"""
if sys.version_info.major != 2:
return
if package.__n... | work around Odoo 10 issue
https://github.com/acsone/setuptools-odoo/issues/10
# This hook should runs after all *-nspkg.pth files because it is named
# zzz_ and .pth file run in alphabetical order. | entailment |
def getAllFtpConnections(self):
"""
Returns a dictionary containing active ftp connections.
"""
outputMsg = "Current ftp connections:\n"
counter = 1
for k in self.ftpList:
outputMsg += str(counter) + ". " + k + " "
outputMsg += str(self.ftpList[k])... | Returns a dictionary containing active ftp connections. | entailment |
def ftp_connect(self, host, user='anonymous', password='anonymous@', port=21, timeout=30, connId='default'):
"""
Constructs FTP object, opens a connection and login.
Call this function before any other (otherwise raises exception).
Returns server output.
Parameters:
-... | Constructs FTP object, opens a connection and login.
Call this function before any other (otherwise raises exception).
Returns server output.
Parameters:
- host - server host address
- user(optional) - FTP user name. If not given, 'anonymous' is used.
- passwo... | entailment |
def get_welcome(self, connId='default'):
"""
Returns wlecome message of FTP server.
Parameters:
- connId(optional) - connection identifier. By default equals 'default'
"""
thisConn = self.__getConnection(connId)
outputMsg = ""
try:
outputMsg +=... | Returns wlecome message of FTP server.
Parameters:
- connId(optional) - connection identifier. By default equals 'default' | entailment |
def dir(self, connId='default'):
"""
Returns list of raw lines returned as contens of current directory.
Parameters:
- connId(optional) - connection identifier. By default equals 'default'
"""
dirList = []
thisConn = self.__getConnection(connId)
outputMsg ... | Returns list of raw lines returned as contens of current directory.
Parameters:
- connId(optional) - connection identifier. By default equals 'default' | entailment |
def dir_names(self, connId='default'):
"""
Returns list of files (and/or directories) of current directory.
Parameters:
- connId(optional) - connection identifier. By default equals 'default'
"""
files_list = []
thisConn = self.__getConnection(connId)
try:... | Returns list of files (and/or directories) of current directory.
Parameters:
- connId(optional) - connection identifier. By default equals 'default' | entailment |
def download_file(self, remoteFileName, localFilePath=None, connId='default'):
"""
Downloads file from current directory on FTP server in binary mode. If
localFilePath is not given, file is saved in current local directory (by
default folder containing robot framework project file) with ... | Downloads file from current directory on FTP server in binary mode. If
localFilePath is not given, file is saved in current local directory (by
default folder containing robot framework project file) with the same name
as source file. Returns server output
Parameters:
- remoteFil... | entailment |
def upload_file(self, localFileName, remoteFileName=None, connId='default'):
"""
Sends file from local drive to current directory on FTP server in binary mode.
Returns server output.
Parameters:
- localFileName - file name or path to a file on a local drive.
- remoteFileN... | Sends file from local drive to current directory on FTP server in binary mode.
Returns server output.
Parameters:
- localFileName - file name or path to a file on a local drive.
- remoteFileName (optional) - a name or path containing name under which file should be saved.
- connI... | entailment |
def size(self, fileToCheck, connId='default'):
"""
Checks size of a file on FTP server. Returns size of a file in bytes (integer).
Parameters:
- fileToCheck - file name or path to a file on FTP server
- connId(optional) - connection identifier. By default equals 'default'
... | Checks size of a file on FTP server. Returns size of a file in bytes (integer).
Parameters:
- fileToCheck - file name or path to a file on FTP server
- connId(optional) - connection identifier. By default equals 'default'
Example:
| ${file1size} = | size | /home/myname/tmp/uu.txt... | entailment |
def send_cmd(self, command, connId='default'):
"""
Sends any command to FTP server. Returns server output.
Parameters:
- command - any valid command to be sent (invalid will result in exception).
- connId(optional) - connection identifier. By default equals 'default'
Exam... | Sends any command to FTP server. Returns server output.
Parameters:
- command - any valid command to be sent (invalid will result in exception).
- connId(optional) - connection identifier. By default equals 'default'
Example:
| send cmd | HELP | | entailment |
def ftp_close(self, connId='default'):
"""
Closes FTP connection. Returns None.
Parameters:
- connId(optional) - connection identifier. By default equals 'default'
"""
thisConn = self.__getConnection(connId)
try:
thisConn.quit()
self.__remo... | Closes FTP connection. Returns None.
Parameters:
- connId(optional) - connection identifier. By default equals 'default' | entailment |
def setup_logging(verbose=0, colors=False, name=None):
"""Configure console logging. Info and below go to stdout, others go to stderr.
:param int verbose: Verbosity level. > 0 print debug statements. > 1 passed to sphinx-build.
:param bool colors: Print color text in non-verbose mode.
:param str name: ... | Configure console logging. Info and below go to stdout, others go to stderr.
:param int verbose: Verbosity level. > 0 print debug statements. > 1 passed to sphinx-build.
:param bool colors: Print color text in non-verbose mode.
:param str name: Which logger name to set handlers to. Used for testing. | entailment |
def format(self, record):
"""Apply little arrow and colors to the record.
Arrow and colors are only applied to sphinxcontrib.versioning log statements.
:param logging.LogRecord record: The log record object to log.
"""
formatted = super(ColorFormatter, self).format(record)
... | Apply little arrow and colors to the record.
Arrow and colors are only applied to sphinxcontrib.versioning log statements.
:param logging.LogRecord record: The log record object to log. | entailment |
def chunk(iterator, max_size):
"""Chunk a list/set/etc.
:param iter iterator: The iterable object to chunk.
:param int max_size: Max size of each chunk. Remainder chunk may be smaller.
:return: Yield list of items.
:rtype: iter
"""
gen = iter(iterator)
while True:
chunked = lis... | Chunk a list/set/etc.
:param iter iterator: The iterable object to chunk.
:param int max_size: Max size of each chunk. Remainder chunk may be smaller.
:return: Yield list of items.
:rtype: iter | entailment |
def run_command(local_root, command, env_var=True, pipeto=None, retry=0, environ=None):
"""Run a command and return the output.
:raise CalledProcessError: Command exits non-zero.
:param str local_root: Local path to git root directory.
:param iter command: Command to run.
:param dict environ: Envi... | Run a command and return the output.
:raise CalledProcessError: Command exits non-zero.
:param str local_root: Local path to git root directory.
:param iter command: Command to run.
:param dict environ: Environment variables to set/override in the command.
:param bool env_var: Define GIT_DIR envir... | entailment |
def get_root(directory):
"""Get root directory of the local git repo from any subdirectory within it.
:raise GitError: If git command fails (dir not a git repo?).
:param str directory: Subdirectory in the local repo.
:return: Root directory of repository.
:rtype: str
"""
command = ['git',... | Get root directory of the local git repo from any subdirectory within it.
:raise GitError: If git command fails (dir not a git repo?).
:param str directory: Subdirectory in the local repo.
:return: Root directory of repository.
:rtype: str | entailment |
def list_remote(local_root):
"""Get remote branch/tag latest SHAs.
:raise GitError: When git ls-remote fails.
:param str local_root: Local path to git root directory.
:return: List of tuples containing strings. Each tuple is sha, name, kind.
:rtype: list
"""
command = ['git', 'ls-remote',... | Get remote branch/tag latest SHAs.
:raise GitError: When git ls-remote fails.
:param str local_root: Local path to git root directory.
:return: List of tuples containing strings. Each tuple is sha, name, kind.
:rtype: list | entailment |
def filter_and_date(local_root, conf_rel_paths, commits):
"""Get commit Unix timestamps and first matching conf.py path. Exclude commits with no conf.py file.
:raise CalledProcessError: Unhandled git command failure.
:raise GitError: A commit SHA has not been fetched.
:param str local_root: Local path... | Get commit Unix timestamps and first matching conf.py path. Exclude commits with no conf.py file.
:raise CalledProcessError: Unhandled git command failure.
:raise GitError: A commit SHA has not been fetched.
:param str local_root: Local path to git root directory.
:param iter conf_rel_paths: List of p... | entailment |
def fetch_commits(local_root, remotes):
"""Fetch from origin.
:raise CalledProcessError: Unhandled git command failure.
:param str local_root: Local path to git root directory.
:param iter remotes: Output of list_remote().
"""
# Fetch all known branches.
command = ['git', 'fetch', 'origin'... | Fetch from origin.
:raise CalledProcessError: Unhandled git command failure.
:param str local_root: Local path to git root directory.
:param iter remotes: Output of list_remote(). | entailment |
def export(local_root, commit, target):
"""Export git commit to directory. "Extracts" all files at the commit to the target directory.
Set mtime of RST files to last commit date.
:raise CalledProcessError: Unhandled git command failure.
:param str local_root: Local path to git root directory.
:pa... | Export git commit to directory. "Extracts" all files at the commit to the target directory.
Set mtime of RST files to last commit date.
:raise CalledProcessError: Unhandled git command failure.
:param str local_root: Local path to git root directory.
:param str commit: Git commit SHA to export.
:... | entailment |
def clone(local_root, new_root, remote, branch, rel_dest, exclude):
"""Clone "local_root" origin into a new directory and check out a specific branch. Optionally run "git rm".
:raise CalledProcessError: Unhandled git command failure.
:raise GitError: Handled git failures.
:param str local_root: Local ... | Clone "local_root" origin into a new directory and check out a specific branch. Optionally run "git rm".
:raise CalledProcessError: Unhandled git command failure.
:raise GitError: Handled git failures.
:param str local_root: Local path to git root directory.
:param str new_root: Local path empty direc... | entailment |
def commit_and_push(local_root, remote, versions):
"""Commit changed, new, and deleted files in the repo and attempt to push the branch to the remote repository.
:raise CalledProcessError: Unhandled git command failure.
:raise GitError: Conflicting changes made in remote by other client and bad git config ... | Commit changed, new, and deleted files in the repo and attempt to push the branch to the remote repository.
:raise CalledProcessError: Unhandled git command failure.
:raise GitError: Conflicting changes made in remote by other client and bad git config for commits.
:param str local_root: Local path to git... | entailment |
def semvers(names):
"""Parse versions into integers and convert non-integer meta indicators into integers with ord().
Each return list item has an indicator as the first item. 0 for valid versions and 1 for invalid. Can be used to
sort non-version names (e.g. master, feature_branch, etc) after valid versio... | Parse versions into integers and convert non-integer meta indicators into integers with ord().
Each return list item has an indicator as the first item. 0 for valid versions and 1 for invalid. Can be used to
sort non-version names (e.g. master, feature_branch, etc) after valid versions. No sorting is done in t... | entailment |
def multi_sort(remotes, sort):
"""Sort `remotes` in place. Allows sorting by multiple conditions.
This is needed because Python 3 no longer supports sorting lists of multiple types. Sort keys must all be of the
same type.
Problem: the user expects versions to be sorted latest first and timelogical to ... | Sort `remotes` in place. Allows sorting by multiple conditions.
This is needed because Python 3 no longer supports sorting lists of multiple types. Sort keys must all be of the
same type.
Problem: the user expects versions to be sorted latest first and timelogical to be most recent first (when viewing
... | entailment |
def branches(self):
"""Return list of (name and urls) only branches."""
return [(r['name'], self.vpathto(r['name'])) for r in self.remotes if r['kind'] == 'heads'] | Return list of (name and urls) only branches. | entailment |
def tags(self):
"""Return list of (name and urls) only tags."""
return [(r['name'], self.vpathto(r['name'])) for r in self.remotes if r['kind'] == 'tags'] | Return list of (name and urls) only tags. | entailment |
def vhasdoc(self, other_version):
"""Return True if the other version has the current document. Like Sphinx's hasdoc().
:raise KeyError: If other_version doesn't exist.
:param str other_version: Version to link to.
:return: If current document is in the other version.
:rtype: ... | Return True if the other version has the current document. Like Sphinx's hasdoc().
:raise KeyError: If other_version doesn't exist.
:param str other_version: Version to link to.
:return: If current document is in the other version.
:rtype: bool | entailment |
def vpathto(self, other_version):
"""Return relative path to current document in another version. Like Sphinx's pathto().
If the current document doesn't exist in the other version its master_doc path is returned instead.
:raise KeyError: If other_version doesn't exist.
:param str oth... | Return relative path to current document in another version. Like Sphinx's pathto().
If the current document doesn't exist in the other version its master_doc path is returned instead.
:raise KeyError: If other_version doesn't exist.
:param str other_version: Version to link to.
:ret... | entailment |
def read_local_conf(local_conf):
"""Search for conf.py in any rel_source directory in CWD and if found read it and return.
:param str local_conf: Path to conf.py to read.
:return: Loaded conf.py.
:rtype: dict
"""
log = logging.getLogger(__name__)
# Attempt to read.
log.info('Reading c... | Search for conf.py in any rel_source directory in CWD and if found read it and return.
:param str local_conf: Path to conf.py to read.
:return: Loaded conf.py.
:rtype: dict | entailment |
def gather_git_info(root, conf_rel_paths, whitelist_branches, whitelist_tags):
"""Gather info about the remote git repository. Get list of refs.
:raise HandledError: If function fails with a handled error. Will be logged before raising.
:param str root: Root directory of repository.
:param iter conf_r... | Gather info about the remote git repository. Get list of refs.
:raise HandledError: If function fails with a handled error. Will be logged before raising.
:param str root: Root directory of repository.
:param iter conf_rel_paths: List of possible relative paths (to git root) of Sphinx conf.py (e.g. docs/c... | entailment |
def pre_build(local_root, versions):
"""Build docs for all versions to determine root directory and master_doc names.
Need to build docs to (a) avoid filename collision with files from root_ref and branch/tag names and (b) determine
master_doc config values for all versions (in case master_doc changes from... | Build docs for all versions to determine root directory and master_doc names.
Need to build docs to (a) avoid filename collision with files from root_ref and branch/tag names and (b) determine
master_doc config values for all versions (in case master_doc changes from e.g. contents.rst to index.rst between
... | entailment |
def build_all(exported_root, destination, versions):
"""Build all versions.
:param str exported_root: Tempdir path with exported commits as subdirectories.
:param str destination: Destination directory to copy/overwrite built docs to. Does not delete old files.
:param sphinxcontrib.versioning.versions.... | Build all versions.
:param str exported_root: Tempdir path with exported commits as subdirectories.
:param str destination: Destination directory to copy/overwrite built docs to. Does not delete old files.
:param sphinxcontrib.versioning.versions.Versions versions: Versions class instance. | entailment |
def setup(app):
"""Called by Sphinx during phase 0 (initialization).
:param sphinx.application.Sphinx app: Sphinx application object.
:returns: Extension version.
:rtype: dict
"""
# Used internally. For rebuilding all pages when one or versions fail.
app.add_config_value('sphinxcontrib_ver... | Called by Sphinx during phase 0 (initialization).
:param sphinx.application.Sphinx app: Sphinx application object.
:returns: Extension version.
:rtype: dict | entailment |
def _build(argv, config, versions, current_name, is_root):
"""Build Sphinx docs via multiprocessing for isolation.
:param tuple argv: Arguments to pass to Sphinx.
:param sphinxcontrib.versioning.lib.Config config: Runtime configuration.
:param sphinxcontrib.versioning.versions.Versions versions: Versio... | Build Sphinx docs via multiprocessing for isolation.
:param tuple argv: Arguments to pass to Sphinx.
:param sphinxcontrib.versioning.lib.Config config: Runtime configuration.
:param sphinxcontrib.versioning.versions.Versions versions: Versions class instance.
:param str current_name: The ref name of th... | entailment |
def _read_config(argv, config, current_name, queue):
"""Read the Sphinx config via multiprocessing for isolation.
:param tuple argv: Arguments to pass to Sphinx.
:param sphinxcontrib.versioning.lib.Config config: Runtime configuration.
:param str current_name: The ref name of the current version being ... | Read the Sphinx config via multiprocessing for isolation.
:param tuple argv: Arguments to pass to Sphinx.
:param sphinxcontrib.versioning.lib.Config config: Runtime configuration.
:param str current_name: The ref name of the current version being built.
:param multiprocessing.queues.Queue queue: Commun... | entailment |
def build(source, target, versions, current_name, is_root):
"""Build Sphinx docs for one version. Includes Versions class instance with names/urls in the HTML context.
:raise HandledError: If sphinx-build fails. Will be logged before raising.
:param str source: Source directory to pass to sphinx-build.
... | Build Sphinx docs for one version. Includes Versions class instance with names/urls in the HTML context.
:raise HandledError: If sphinx-build fails. Will be logged before raising.
:param str source: Source directory to pass to sphinx-build.
:param str target: Destination directory to write documentation t... | entailment |
def read_config(source, current_name):
"""Read the Sphinx config for one version.
:raise HandledError: If sphinx-build fails. Will be logged before raising.
:param str source: Source directory to pass to sphinx-build.
:param str current_name: The ref name of the current version being built.
:retu... | Read the Sphinx config for one version.
:raise HandledError: If sphinx-build fails. Will be logged before raising.
:param str source: Source directory to pass to sphinx-build.
:param str current_name: The ref name of the current version being built.
:return: Specific Sphinx config values.
:rtype:... | entailment |
def builder_inited(app):
"""Update the Sphinx builder.
:param sphinx.application.Sphinx app: Sphinx application object.
"""
# Add this extension's _templates directory to Sphinx.
templates_dir = os.path.join(os.path.dirname(__file__), '_templates')
app.builder.templates.... | Update the Sphinx builder.
:param sphinx.application.Sphinx app: Sphinx application object. | entailment |
def env_updated(cls, app, env):
"""Abort Sphinx after initializing config and discovering all pages to build.
:param sphinx.application.Sphinx app: Sphinx application object.
:param sphinx.environment.BuildEnvironment env: Sphinx build environment.
"""
if cls.ABORT_AFTER_READ:
... | Abort Sphinx after initializing config and discovering all pages to build.
:param sphinx.application.Sphinx app: Sphinx application object.
:param sphinx.environment.BuildEnvironment env: Sphinx build environment. | entailment |
def html_page_context(cls, app, pagename, templatename, context, doctree):
"""Update the Jinja2 HTML context, exposes the Versions class instance to it.
:param sphinx.application.Sphinx app: Sphinx application object.
:param str pagename: Name of the page being rendered (without .html or any fi... | Update the Jinja2 HTML context, exposes the Versions class instance to it.
:param sphinx.application.Sphinx app: Sphinx application object.
:param str pagename: Name of the page being rendered (without .html or any file extension).
:param str templatename: Page name with .html.
:param d... | entailment |
def cli(config, **options):
"""Build versioned Sphinx docs for every branch and tag pushed to origin.
Supports only building locally with the "build" sub command or build and push to a remote with the "push" sub
command. For more information for either run them with their own --help.
The options below... | Build versioned Sphinx docs for every branch and tag pushed to origin.
Supports only building locally with the "build" sub command or build and push to a remote with the "push" sub
command. For more information for either run them with their own --help.
The options below are global and must be specified b... | entailment |
def build_options(func):
"""Add "build" Click options to function.
:param function func: The function to wrap.
:return: The wrapped function.
:rtype: function
"""
func = click.option('-a', '--banner-greatest-tag', is_flag=True,
help='Override banner-main-ref to be the t... | Add "build" Click options to function.
:param function func: The function to wrap.
:return: The wrapped function.
:rtype: function | entailment |
def override_root_main_ref(config, remotes, banner):
"""Override root_ref or banner_main_ref with tags in config if user requested.
:param sphinxcontrib.versioning.lib.Config config: Runtime configuration.
:param iter remotes: List of dicts from Versions.remotes.
:param bool banner: Evaluate banner mai... | Override root_ref or banner_main_ref with tags in config if user requested.
:param sphinxcontrib.versioning.lib.Config config: Runtime configuration.
:param iter remotes: List of dicts from Versions.remotes.
:param bool banner: Evaluate banner main ref instead of root ref.
:return: If root/main ref ex... | entailment |
def build(config, rel_source, destination, **options):
"""Fetch branches/tags and build all locally.
Doesn't push anything to remote. Just fetch all remote branches and tags, export them to a temporary directory, run
sphinx-build on each one, and then store all built documentation in DESTINATION.
REL_... | Fetch branches/tags and build all locally.
Doesn't push anything to remote. Just fetch all remote branches and tags, export them to a temporary directory, run
sphinx-build on each one, and then store all built documentation in DESTINATION.
REL_SOURCE is the path to the docs directory relative to the git r... | entailment |
def push(ctx, config, rel_source, dest_branch, rel_dest, **options):
"""Build locally and then push to remote branch.
First the build sub command is invoked which takes care of building all versions of your documentation in a
temporary directory. If that succeeds then all built documents will be pushed to ... | Build locally and then push to remote branch.
First the build sub command is invoked which takes care of building all versions of your documentation in a
temporary directory. If that succeeds then all built documents will be pushed to a remote branch.
REL_SOURCE is the path to the docs directory relative ... | entailment |
def custom_sort(param):
"""Custom Click(Command|Group).params sorter.
Case insensitive sort with capitals after lowercase. --version at the end since I can't sort --help.
:param click.core.Option param: Parameter to evaluate.
:return: Sort weight.
:rtype: int
"""
... | Custom Click(Command|Group).params sorter.
Case insensitive sort with capitals after lowercase. --version at the end since I can't sort --help.
:param click.core.Option param: Parameter to evaluate.
:return: Sort weight.
:rtype: int | entailment |
def get_params(self, ctx):
"""Sort order of options before displaying.
:param click.core.Context ctx: Click context.
:return: super() return value.
"""
self.params.sort(key=self.custom_sort)
return super(ClickGroup, self).get_params(ctx) | Sort order of options before displaying.
:param click.core.Context ctx: Click context.
:return: super() return value. | entailment |
def main(self, *args, **kwargs):
"""Main function called by setuptools.
:param list args: Passed to super().
:param dict kwargs: Passed to super().
:return: super() return value.
"""
argv = kwargs.pop('args', click.get_os_args())
if '--' in argv:
pos... | Main function called by setuptools.
:param list args: Passed to super().
:param dict kwargs: Passed to super().
:return: super() return value. | entailment |
def invoke(self, ctx):
"""Inject overflow arguments into context state.
:param click.core.Context ctx: Click context.
:return: super() return value.
"""
if self.overflow:
ctx.ensure_object(Config).update(dict(overflow=self.overflow))
return super(ClickGroup,... | Inject overflow arguments into context state.
:param click.core.Context ctx: Click context.
:return: super() return value. | entailment |
def from_context(cls):
"""Retrieve this class' instance from the current Click context.
:return: Instance of this class.
:rtype: Config
"""
try:
ctx = click.get_current_context()
except RuntimeError:
return cls()
return ctx.find_object(cls... | Retrieve this class' instance from the current Click context.
:return: Instance of this class.
:rtype: Config | entailment |
def update(self, params, ignore_set=False, overwrite=False):
"""Set instance values from dictionary.
:param dict params: Click context params.
:param bool ignore_set: Skip already-set values instead of raising AttributeError.
:param bool overwrite: Allow overwriting already-set values.
... | Set instance values from dictionary.
:param dict params: Click context params.
:param bool ignore_set: Skip already-set values instead of raising AttributeError.
:param bool overwrite: Allow overwriting already-set values. | entailment |
def cleanup(self):
"""Recursively delete directory."""
shutil.rmtree(self.name, onerror=lambda *a: os.chmod(a[1], __import__('stat').S_IWRITE) or os.unlink(a[1]))
if os.path.exists(self.name):
raise IOError(17, "File exists: '{}'".format(self.name)) | Recursively delete directory. | entailment |
def get_resources(cls):
"""Returns Ext Resources."""
exts = []
parent = dict(member_name=ciscohostingdevicemanager.DEVICE,
collection_name=ciscohostingdevicemanager.DEVICES)
controller = resource.Resource(
RouterHostingDeviceSchedulerController(), cb_fau... | Returns Ext Resources. | entailment |
def assign_hosting_device_to_cfg_agent(self, context, cfg_agent_id,
hosting_device_id):
"""Make config agent handle an (unassigned) hosting device."""
hd_db = self._get_hosting_device(context, hosting_device_id)
if hd_db.cfg_agent_id:
if hd_... | Make config agent handle an (unassigned) hosting device. | entailment |
def unassign_hosting_device_from_cfg_agent(self, context, cfg_agent_id,
hosting_device_id):
"""Make config agent handle an (unassigned) hosting device."""
hd_db = self._get_hosting_device(context, hosting_device_id)
if hd_db.cfg_agent_id is None and... | Make config agent handle an (unassigned) hosting device. | entailment |
def update_subports(self, port):
"""Set port attributes for trunk subports.
For baremetal deployments only, set the neutron port attributes
during the bind_port event.
"""
trunk_details = port.get('trunk_details')
subports = trunk_details['sub_ports']
host_id = ... | Set port attributes for trunk subports.
For baremetal deployments only, set the neutron port attributes
during the bind_port event. | entailment |
def read_static_uplink(self):
"""Read the static uplink from file, if given."""
if self.node_list is None or self.node_uplink_list is None:
return
for node, port in zip(self.node_list.split(','),
self.node_uplink_list.split(',')):
if node.str... | Read the static uplink from file, if given. | entailment |
def vdp_vlan_change_cb(self, port_uuid, lvid, vdp_vlan, fail_reason):
"""Callback function for updating the VDP VLAN in DB. """
LOG.info("Vlan change CB lvid %(lvid)s VDP %(vdp)s",
{'lvid': lvid, 'vdp': vdp_vlan})
self.update_vm_result(port_uuid, constants.RESULT_SUCCESS,
... | Callback function for updating the VDP VLAN in DB. | entailment |
def process_bulk_vm_event(self, msg, phy_uplink):
"""Process the VM bulk event usually after a restart. """
LOG.info("In processing Bulk VM Event status %s", msg)
time.sleep(3)
if (not self.uplink_det_compl or
phy_uplink not in self.ovs_vdp_obj_dict):
# This c... | Process the VM bulk event usually after a restart. | entailment |
def is_openstack_running(self):
"""Currently it just checks for the presence of both the bridges. """
try:
if (ovs_vdp.is_bridge_present(self.br_ex, self.root_helper) and
ovs_vdp.is_bridge_present(self.br_integ,
self.root_help... | Currently it just checks for the presence of both the bridges. | entailment |
def _fill_topology_cfg(self, topo_dict):
"""Fills the extra configurations in the topology. """
cfg_dict = {}
if topo_dict.bond_member_ports is not None:
cfg_dict.update({'bond_member_ports':
topo_dict.bond_member_ports})
if topo_dict.bond_interfa... | Fills the extra configurations in the topology. | entailment |
def uplink_bond_intf_process(self):
"""Process the case when uplink interface becomes part of a bond.
This is called to check if the phy interface became a part of the
bond. If the below condition is True, this means, a physical
interface that was not a part of a bond was earlier discov... | Process the case when uplink interface becomes part of a bond.
This is called to check if the phy interface became a part of the
bond. If the below condition is True, this means, a physical
interface that was not a part of a bond was earlier discovered as
uplink and now that interface b... | entailment |
def check_periodic_bulk_vm_notif_rcvd(self):
"""Bulk VM check handler called from periodic uplink detection.
This gets called by the 'normal' stage of uplink detection.
The bulk VM event sends all the VM's running in this agent.
Sometimes during upgrades, it was found that due to some r... | Bulk VM check handler called from periodic uplink detection.
This gets called by the 'normal' stage of uplink detection.
The bulk VM event sends all the VM's running in this agent.
Sometimes during upgrades, it was found that due to some race
condition, the server does not send the Bulk... | entailment |
def static_uplink_detect(self, veth):
"""Return the static uplink based on argument passed.
The very first time, this function is called, it returns the uplink
port read from a file.
After restart, when this function is called the first time, it
returns 'normal' assuming a veth ... | Return the static uplink based on argument passed.
The very first time, this function is called, it returns the uplink
port read from a file.
After restart, when this function is called the first time, it
returns 'normal' assuming a veth is passed to this function which will
be ... | entailment |
def vdp_uplink_proc(self):
"""Periodic handler to detect the uplink interface to the switch.
-> restart_uplink_called: should be called by agent initially to set
the stored uplink and veth from DB
-> process_uplink_ongoing: Will be set when uplink message is enqueue
and reset wh... | Periodic handler to detect the uplink interface to the switch.
-> restart_uplink_called: should be called by agent initially to set
the stored uplink and veth from DB
-> process_uplink_ongoing: Will be set when uplink message is enqueue
and reset when dequeued and processed completely
... | entailment |
def get_hosting_device_config(self, client, hosting_device_id):
"""Get config of hosting_device."""
return client.get((self.resource_path + HOSTING_DEVICE_CONFIG) %
hosting_device_id) | Get config of hosting_device. | entailment |
def get_client_class(self, client_class_name):
"""Returns a specific client class details from CPNR server."""
request_url = self._build_url(['ClientClass', client_class_name])
return self._do_request('GET', request_url) | Returns a specific client class details from CPNR server. | entailment |
def get_vpn(self, vpn_name):
"""Returns a specific VPN name details from CPNR server."""
request_url = self._build_url(['VPN', vpn_name])
return self._do_request('GET', request_url) | Returns a specific VPN name details from CPNR server. | entailment |
def get_scopes(self, vpnid='.*'):
"""Returns a list of all the scopes from CPNR server."""
request_url = self._build_url(['Scope'], vpn=vpnid)
return self._do_request('GET', request_url) | Returns a list of all the scopes from CPNR server. | entailment |
def get_scope(self, scope_name):
"""Returns a specific scope name details from CPNR server."""
request_url = self._build_url(['Scope', scope_name])
return self._do_request('GET', request_url) | Returns a specific scope name details from CPNR server. | entailment |
def get_client_entry(self, client_entry_name):
"""Returns a specific client entry name details from CPNR server."""
request_url = self._build_url(['ClientEntry', client_entry_name])
return self._do_request('GET', request_url) | Returns a specific client entry name details from CPNR server. | entailment |
def release_address(self, address, vpnid):
"""Release a specific lease, called after delete_client_entry"""
query = address + "?action=releaseAddress&vpnId=" + vpnid
request_url = self._build_url(['Lease', query])
return self._do_request('DELETE', request_url) | Release a specific lease, called after delete_client_entry | entailment |
def qsize(self, qname):
"""Return the approximate size of the queue."""
if qname in self._queues:
return self._queues[qname].qsize()
else:
raise ValueError(_("queue %s is not defined"), qname) | Return the approximate size of the queue. | entailment |
def get_nexusport_binding(port_id, vlan_id, switch_ip, instance_id):
"""Lists a nexusport binding."""
LOG.debug("get_nexusport_binding() called")
return _lookup_all_nexus_bindings(port_id=port_id,
vlan_id=vlan_id,
switch_ip=switch_i... | Lists a nexusport binding. | entailment |
def get_nexus_switchport_binding(port_id, switch_ip):
"""Lists all bindings for this switch & port."""
LOG.debug("get_nexus_switchport_binding() called")
return _lookup_all_nexus_bindings(port_id=port_id,
switch_ip=switch_ip) | Lists all bindings for this switch & port. | entailment |
def get_nexusvlan_binding(vlan_id, switch_ip):
"""Lists a vlan and switch binding."""
LOG.debug("get_nexusvlan_binding() called")
return _lookup_all_nexus_bindings(vlan_id=vlan_id, switch_ip=switch_ip) | Lists a vlan and switch binding. | entailment |
def get_reserved_bindings(vlan_id, instance_id, switch_ip=None,
port_id=None):
"""Lists reserved bindings."""
LOG.debug("get_reserved_bindings() called")
if port_id:
return _lookup_all_nexus_bindings(vlan_id=vlan_id,
switch_ip=switc... | Lists reserved bindings. | entailment |
def update_reserved_binding(vlan_id, switch_ip, instance_id,
port_id, is_switch_binding=True,
is_native=False, ch_grp=0):
"""Updates reserved binding.
This overloads port bindings to support reserved Switch binding
used to maintain the state of a swit... | Updates reserved binding.
This overloads port bindings to support reserved Switch binding
used to maintain the state of a switch so it can be viewed by
all other neutron processes. There's also the case of
a reserved port binding to keep switch information on a given
interface.
The values of t... | entailment |
def remove_reserved_binding(vlan_id, switch_ip, instance_id,
port_id):
"""Removes reserved binding.
This overloads port bindings to support reserved Switch binding
used to maintain the state of a switch so it can be viewed by
all other neutron processes. There's also the cas... | Removes reserved binding.
This overloads port bindings to support reserved Switch binding
used to maintain the state of a switch so it can be viewed by
all other neutron processes. There's also the case of
a reserved port binding to keep switch information on a given
interface.
The values of th... | entailment |
def add_reserved_switch_binding(switch_ip, state):
"""Add a reserved switch binding."""
# overload port_id to contain switch state
add_nexusport_binding(
state,
const.NO_VLAN_OR_VNI_ID,
const.NO_VLAN_OR_VNI_ID,
switch_ip,
const.RESERVED_NEXUS_SWITCH_DEVICE_ID_R1) | Add a reserved switch binding. | entailment |
def update_reserved_switch_binding(switch_ip, state):
"""Update a reserved switch binding."""
# overload port_id to contain switch state
update_reserved_binding(
const.NO_VLAN_OR_VNI_ID,
switch_ip,
const.RESERVED_NEXUS_SWITCH_DEVICE_ID_R1,
state) | Update a reserved switch binding. | entailment |
def add_nexusport_binding(port_id, vlan_id, vni, switch_ip, instance_id,
is_native=False, ch_grp=0):
"""Adds a nexusport binding."""
LOG.debug("add_nexusport_binding() called")
session = bc.get_writer_session()
binding = nexus_models_v2.NexusPortBinding(port_id=port_id,
... | Adds a nexusport binding. | entailment |
def remove_nexusport_binding(port_id, vlan_id, vni, switch_ip, instance_id):
"""Removes a nexusport binding."""
LOG.debug("remove_nexusport_binding() called")
session = bc.get_writer_session()
binding = _lookup_all_nexus_bindings(session=session,
vlan_id=vlan_id,... | Removes a nexusport binding. | entailment |
def update_nexusport_binding(port_id, new_vlan_id):
"""Updates nexusport binding."""
if not new_vlan_id:
LOG.warning("update_nexusport_binding called with no vlan")
return
LOG.debug("update_nexusport_binding called")
session = bc.get_writer_session()
binding = _lookup_one_nexus_bindi... | Updates nexusport binding. | entailment |
def remove_all_nexusport_bindings():
"""Removes all nexusport bindings."""
LOG.debug("remove_all_nexusport_bindings() called")
session = bc.get_writer_session()
session.query(nexus_models_v2.NexusPortBinding).delete()
session.flush() | Removes all nexusport bindings. | entailment |
def get_nexusvm_bindings(vlan_id, instance_id):
"""Lists nexusvm bindings."""
LOG.debug("get_nexusvm_bindings() called")
return _lookup_all_nexus_bindings(instance_id=instance_id,
vlan_id=vlan_id) | Lists nexusvm bindings. | entailment |
def get_port_vlan_switch_binding(port_id, vlan_id, switch_ip):
"""Lists nexusvm bindings."""
LOG.debug("get_port_vlan_switch_binding() called")
return _lookup_all_nexus_bindings(port_id=port_id,
switch_ip=switch_ip,
vlan_id=vlan_id) | Lists nexusvm bindings. | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.