Code
stringlengths 103
85.9k
| Summary
listlengths 0
94
|
---|---|
Please provide a description of the function:def clean(file_, imports):
modules_not_imported = compare_modules(file_, imports)
re_remove = re.compile("|".join(modules_not_imported))
to_write = []
try:
f = open_func(file_, "r+")
except OSError:
logging.error("Failed on file: {}".format(file_))
raise
else:
for i in f.readlines():
if re_remove.match(i) is None:
to_write.append(i)
f.seek(0)
f.truncate()
for i in to_write:
f.write(i)
finally:
f.close()
logging.info("Successfully cleaned up requirements in " + file_)
|
[
"Remove modules that aren't imported in project from file."
] |
Please provide a description of the function:def read_requirements(fh, resolve=False):
is_temp_file = not hasattr(fh, 'name')
for num, line in enumerate(iter_lines(fh)):
line = line.strip()
if not line:
# skip empty lines
continue
if line.startswith('#') or \
line.startswith('-i') or \
line.startswith('--index-url') or \
line.startswith('--extra-index-url') or \
line.startswith('-f') or line.startswith('--find-links') or \
line.startswith('--no-index') or line.startswith('--allow-external') or \
line.startswith('--allow-unverified') or line.startswith('-Z') or \
line.startswith('--always-unzip'):
# skip unsupported lines
continue
elif line.startswith('-r') or line.startswith('--requirement'):
# got a referenced file here, try to resolve the path
# if this is a tempfile, skip
if is_temp_file:
continue
filename = line.strip("-r ").strip("--requirement").strip()
# if there is a comment, remove it
if " #" in filename:
filename = filename.split(" #")[0].strip()
req_file_path = os.path.join(os.path.dirname(fh.name), filename)
if resolve:
# recursively yield the resolved requirements
if os.path.exists(req_file_path):
with open(req_file_path) as _fh:
for req in read_requirements(_fh, resolve=True):
yield req
else:
yield RequirementFile(path=req_file_path)
else:
try:
parseable_line = line
# multiline requirements are not parseable
if "\\" in line:
parseable_line = line.replace("\\", "")
for next_line in iter_lines(fh, num + 1):
parseable_line += next_line.strip().replace("\\", "")
line += "\n" + next_line
if "\\" in next_line:
continue
break
req, = parse_line(parseable_line)
if len(req.specifier._specs) == 1 and \
next(iter(req.specifier._specs))._spec[0] == "==":
yield Package(key=req.name, version=next(iter(req.specifier._specs))._spec[1])
else:
try:
fname = fh.name
except AttributeError:
fname = line
click.secho(
"Warning: unpinned requirement '{req}' found in {fname}, "
"unable to check.".format(req=req.name,
fname=fname),
fg="yellow",
file=sys.stderr
)
except ValueError:
continue
|
[
"\n Reads requirements from a file like object and (optionally) from referenced files.\n :param fh: file like object to read from\n :param resolve: boolean. resolves referenced files.\n :return: generator\n "
] |
Please provide a description of the function:def deprecated(reason, replacement, gone_in, issue=None):
# type: (str, Optional[str], Optional[str], Optional[int]) -> None
# Construct a nice message.
# This is purposely eagerly formatted as we want it to appear as if someone
# typed this entire message out.
message = "DEPRECATION: " + reason
if replacement is not None:
message += " A possible replacement is {}.".format(replacement)
if issue is not None:
url = "https://github.com/pypa/pip/issues/" + str(issue)
message += " You can find discussion regarding this at {}.".format(url)
# Raise as an error if it has to be removed.
if gone_in is not None and parse(current_version) >= parse(gone_in):
raise PipDeprecationWarning(message)
warnings.warn(message, category=PipDeprecationWarning, stacklevel=2)
|
[
"Helper to deprecate existing functionality.\n\n reason:\n Textual reason shown to the user about why this functionality has\n been deprecated.\n replacement:\n Textual suggestion shown to the user about what alternative\n functionality they can use.\n gone_in:\n The version of pip does this functionality should get removed in.\n Raises errors if pip's current version is greater than or equal to\n this.\n issue:\n Issue number on the tracker that would serve as a useful place for\n users to find related discussion and provide feedback.\n\n Always pass replacement, gone_in and issue as keyword arguments for clarity\n at the call site.\n "
] |
Please provide a description of the function:def _ipaddress_match(ipname, host_ip):
# OpenSSL may add a trailing newline to a subjectAltName's IP address
# Divergence from upstream: ipaddress can't handle byte str
ip = ipaddress.ip_address(_to_unicode(ipname).rstrip())
return ip == host_ip
|
[
"Exact matching of IP addresses.\n\n RFC 6125 explicitly doesn't define an algorithm for this\n (section 1.7.2 - \"Out of Scope\").\n "
] |
Please provide a description of the function:def set_metadata(candidates, traces, dependencies, pythons):
metasets_mapping = _calculate_metasets_mapping(
dependencies, pythons, copy.deepcopy(traces),
)
for key, candidate in candidates.items():
candidate.markers = _format_metasets(metasets_mapping[key])
|
[
"Add \"metadata\" to candidates based on the dependency tree.\n\n Metadata for a candidate includes markers and a specifier for Python\n version requirements.\n\n :param candidates: A key-candidate mapping. Candidates in the mapping will\n have their markers set.\n :param traces: A graph trace (produced by `traces.trace_graph`) providing\n information about dependency relationships between candidates.\n :param dependencies: A key-collection mapping containing what dependencies\n each candidate in `candidates` requested.\n :param pythons: A key-str mapping containing Requires-Python information\n of each candidate.\n\n Keys in mappings and entries in the trace are identifiers of a package, as\n implemented by the `identify` method of the resolver's provider.\n\n The candidates are modified in-place.\n "
] |
Please provide a description of the function:def _walk(top, topdown=True, onerror=None, followlinks=False):
dirs = []
nondirs = []
# We may not have read permission for top, in which case we can't
# get a list of the files the directory contains. os.walk
# always suppressed the exception then, rather than blow up for a
# minor reason when (say) a thousand readable directories are still
# left to visit. That logic is copied here.
try:
scandir_it = scandir(top)
except OSError as error:
if onerror is not None:
onerror(error)
return
while True:
try:
try:
entry = next(scandir_it)
except StopIteration:
break
except OSError as error:
if onerror is not None:
onerror(error)
return
try:
is_dir = entry.is_dir()
except OSError:
# If is_dir() raises an OSError, consider that the entry is not
# a directory, same behaviour than os.path.isdir().
is_dir = False
if is_dir:
dirs.append(entry.name)
else:
nondirs.append(entry.name)
if not topdown and is_dir:
# Bottom-up: recurse into sub-directory, but exclude symlinks to
# directories if followlinks is False
if followlinks:
walk_into = True
else:
try:
is_symlink = entry.is_symlink()
except OSError:
# If is_symlink() raises an OSError, consider that the
# entry is not a symbolic link, same behaviour than
# os.path.islink().
is_symlink = False
walk_into = not is_symlink
if walk_into:
for entry in walk(entry.path, topdown, onerror, followlinks):
yield entry
# Yield before recursion if going top down
if topdown:
yield top, dirs, nondirs
# Recurse into sub-directories
for name in dirs:
new_path = join(top, name)
# Issue #23605: os.path.islink() is used instead of caching
# entry.is_symlink() result during the loop on os.scandir() because
# the caller can replace the directory entry during the "yield"
# above.
if followlinks or not islink(new_path):
for entry in walk(new_path, topdown, onerror, followlinks):
yield entry
else:
# Yield after recursion if going bottom up
yield top, dirs, nondirs
|
[
"Like Python 3.5's implementation of os.walk() -- faster than\n the pre-Python 3.5 version as it uses scandir() internally.\n "
] |
Please provide a description of the function:def request_encode_url(self, method, url, fields=None, headers=None,
**urlopen_kw):
if headers is None:
headers = self.headers
extra_kw = {'headers': headers}
extra_kw.update(urlopen_kw)
if fields:
url += '?' + urlencode(fields)
return self.urlopen(method, url, **extra_kw)
|
[
"\n Make a request using :meth:`urlopen` with the ``fields`` encoded in\n the url. This is useful for request methods like GET, HEAD, DELETE, etc.\n "
] |
Please provide a description of the function:def request_encode_body(self, method, url, fields=None, headers=None,
encode_multipart=True, multipart_boundary=None,
**urlopen_kw):
if headers is None:
headers = self.headers
extra_kw = {'headers': {}}
if fields:
if 'body' in urlopen_kw:
raise TypeError(
"request got values for both 'fields' and 'body', can only specify one.")
if encode_multipart:
body, content_type = encode_multipart_formdata(fields, boundary=multipart_boundary)
else:
body, content_type = urlencode(fields), 'application/x-www-form-urlencoded'
extra_kw['body'] = body
extra_kw['headers'] = {'Content-Type': content_type}
extra_kw['headers'].update(headers)
extra_kw.update(urlopen_kw)
return self.urlopen(method, url, **extra_kw)
|
[
"\n Make a request using :meth:`urlopen` with the ``fields`` encoded in\n the body. This is useful for request methods like POST, PUT, PATCH, etc.\n\n When ``encode_multipart=True`` (default), then\n :meth:`urllib3.filepost.encode_multipart_formdata` is used to encode\n the payload with the appropriate content type. Otherwise\n :meth:`urllib.urlencode` is used with the\n 'application/x-www-form-urlencoded' content type.\n\n Multipart encoding must be used when posting files, and it's reasonably\n safe to use it in other times too. However, it may break request\n signing, such as with OAuth.\n\n Supports an optional ``fields`` parameter of key/value strings AND\n key/filetuple. A filetuple is a (filename, data, MIME type) tuple where\n the MIME type is optional. For example::\n\n fields = {\n 'foo': 'bar',\n 'fakefile': ('foofile.txt', 'contents of foofile'),\n 'realfile': ('barfile.txt', open('realfile').read()),\n 'typedfile': ('bazfile.bin', open('bazfile').read(),\n 'image/jpeg'),\n 'nonamefile': 'contents of nonamefile field',\n }\n\n When uploading a file, providing a filename (the first parameter of the\n tuple) is optional but recommended to best mimic behavior of browsers.\n\n Note that if ``headers`` are supplied, the 'Content-Type' header will\n be overwritten because it depends on the dynamic random boundary string\n which is used to compose the body of the request. The random boundary\n string can be explicitly set with the ``multipart_boundary`` parameter.\n "
] |
Please provide a description of the function:def pass_context(f):
def new_func(*args, **kwargs):
return f(get_current_context(), *args, **kwargs)
return update_wrapper(new_func, f)
|
[
"Marks a callback as wanting to receive the current context\n object as first argument.\n "
] |
Please provide a description of the function:def pass_obj(f):
def new_func(*args, **kwargs):
return f(get_current_context().obj, *args, **kwargs)
return update_wrapper(new_func, f)
|
[
"Similar to :func:`pass_context`, but only pass the object on the\n context onwards (:attr:`Context.obj`). This is useful if that object\n represents the state of a nested system.\n "
] |
Please provide a description of the function:def make_pass_decorator(object_type, ensure=False):
def decorator(f):
def new_func(*args, **kwargs):
ctx = get_current_context()
if ensure:
obj = ctx.ensure_object(object_type)
else:
obj = ctx.find_object(object_type)
if obj is None:
raise RuntimeError('Managed to invoke callback without a '
'context object of type %r existing'
% object_type.__name__)
return ctx.invoke(f, obj, *args, **kwargs)
return update_wrapper(new_func, f)
return decorator
|
[
"Given an object type this creates a decorator that will work\n similar to :func:`pass_obj` but instead of passing the object of the\n current context, it will find the innermost context of type\n :func:`object_type`.\n\n This generates a decorator that works roughly like this::\n\n from functools import update_wrapper\n\n def decorator(f):\n @pass_context\n def new_func(ctx, *args, **kwargs):\n obj = ctx.find_object(object_type)\n return ctx.invoke(f, obj, *args, **kwargs)\n return update_wrapper(new_func, f)\n return decorator\n\n :param object_type: the type of the object to pass.\n :param ensure: if set to `True`, a new object will be created and\n remembered on the context if it's not there yet.\n "
] |
Please provide a description of the function:def argument(*param_decls, **attrs):
def decorator(f):
ArgumentClass = attrs.pop('cls', Argument)
_param_memo(f, ArgumentClass(param_decls, **attrs))
return f
return decorator
|
[
"Attaches an argument to the command. All positional arguments are\n passed as parameter declarations to :class:`Argument`; all keyword\n arguments are forwarded unchanged (except ``cls``).\n This is equivalent to creating an :class:`Argument` instance manually\n and attaching it to the :attr:`Command.params` list.\n\n :param cls: the argument class to instantiate. This defaults to\n :class:`Argument`.\n "
] |
Please provide a description of the function:def option(*param_decls, **attrs):
def decorator(f):
# Issue 926, copy attrs, so pre-defined options can re-use the same cls=
option_attrs = attrs.copy()
if 'help' in option_attrs:
option_attrs['help'] = inspect.cleandoc(option_attrs['help'])
OptionClass = option_attrs.pop('cls', Option)
_param_memo(f, OptionClass(param_decls, **option_attrs))
return f
return decorator
|
[
"Attaches an option to the command. All positional arguments are\n passed as parameter declarations to :class:`Option`; all keyword\n arguments are forwarded unchanged (except ``cls``).\n This is equivalent to creating an :class:`Option` instance manually\n and attaching it to the :attr:`Command.params` list.\n\n :param cls: the option class to instantiate. This defaults to\n :class:`Option`.\n "
] |
Please provide a description of the function:def confirmation_option(*param_decls, **attrs):
def decorator(f):
def callback(ctx, param, value):
if not value:
ctx.abort()
attrs.setdefault('is_flag', True)
attrs.setdefault('callback', callback)
attrs.setdefault('expose_value', False)
attrs.setdefault('prompt', 'Do you want to continue?')
attrs.setdefault('help', 'Confirm the action without prompting.')
return option(*(param_decls or ('--yes',)), **attrs)(f)
return decorator
|
[
"Shortcut for confirmation prompts that can be ignored by passing\n ``--yes`` as parameter.\n\n This is equivalent to decorating a function with :func:`option` with\n the following parameters::\n\n def callback(ctx, param, value):\n if not value:\n ctx.abort()\n\n @click.command()\n @click.option('--yes', is_flag=True, callback=callback,\n expose_value=False, prompt='Do you want to continue?')\n def dropdb():\n pass\n "
] |
Please provide a description of the function:def password_option(*param_decls, **attrs):
def decorator(f):
attrs.setdefault('prompt', True)
attrs.setdefault('confirmation_prompt', True)
attrs.setdefault('hide_input', True)
return option(*(param_decls or ('--password',)), **attrs)(f)
return decorator
|
[
"Shortcut for password prompts.\n\n This is equivalent to decorating a function with :func:`option` with\n the following parameters::\n\n @click.command()\n @click.option('--password', prompt=True, confirmation_prompt=True,\n hide_input=True)\n def changeadmin(password):\n pass\n "
] |
Please provide a description of the function:def help_option(*param_decls, **attrs):
def decorator(f):
def callback(ctx, param, value):
if value and not ctx.resilient_parsing:
echo(ctx.get_help(), color=ctx.color)
ctx.exit()
attrs.setdefault('is_flag', True)
attrs.setdefault('expose_value', False)
attrs.setdefault('help', 'Show this message and exit.')
attrs.setdefault('is_eager', True)
attrs['callback'] = callback
return option(*(param_decls or ('--help',)), **attrs)(f)
return decorator
|
[
"Adds a ``--help`` option which immediately ends the program\n printing out the help page. This is usually unnecessary to add as\n this is added by default to all commands unless suppressed.\n\n Like :func:`version_option`, this is implemented as eager option that\n prints in the callback and exits.\n\n All arguments are forwarded to :func:`option`.\n "
] |
Please provide a description of the function:def was_installed_by_pip(pkg):
# type: (str) -> bool
try:
dist = pkg_resources.get_distribution(pkg)
return (dist.has_metadata('INSTALLER') and
'pip' in dist.get_metadata_lines('INSTALLER'))
except pkg_resources.DistributionNotFound:
return False
|
[
"Checks whether pkg was installed by pip\n\n This is used not to display the upgrade message when pip is in fact\n installed by system package manager, such as dnf on Fedora.\n "
] |
Please provide a description of the function:def pip_version_check(session, options):
# type: (PipSession, optparse.Values) -> None
installed_version = get_installed_version("pip")
if not installed_version:
return
pip_version = packaging_version.parse(installed_version)
pypi_version = None
try:
state = SelfCheckState(cache_dir=options.cache_dir)
current_time = datetime.datetime.utcnow()
# Determine if we need to refresh the state
if "last_check" in state.state and "pypi_version" in state.state:
last_check = datetime.datetime.strptime(
state.state["last_check"],
SELFCHECK_DATE_FMT
)
if (current_time - last_check).total_seconds() < 7 * 24 * 60 * 60:
pypi_version = state.state["pypi_version"]
# Refresh the version if we need to or just see if we need to warn
if pypi_version is None:
# Lets use PackageFinder to see what the latest pip version is
finder = PackageFinder(
find_links=options.find_links,
index_urls=[options.index_url] + options.extra_index_urls,
allow_all_prereleases=False, # Explicitly set to False
trusted_hosts=options.trusted_hosts,
session=session,
)
all_candidates = finder.find_all_candidates("pip")
if not all_candidates:
return
pypi_version = str(
max(all_candidates, key=lambda c: c.version).version
)
# save that we've performed a check
state.save(pypi_version, current_time)
remote_version = packaging_version.parse(pypi_version)
# Determine if our pypi_version is older
if (pip_version < remote_version and
pip_version.base_version != remote_version.base_version and
was_installed_by_pip('pip')):
# Advise "python -m pip" on Windows to avoid issues
# with overwriting pip.exe.
if WINDOWS:
pip_cmd = "python -m pip"
else:
pip_cmd = "pip"
logger.warning(
"You are using pip version %s, however version %s is "
"available.\nYou should consider upgrading via the "
"'%s install --upgrade pip' command.",
pip_version, pypi_version, pip_cmd
)
except Exception:
logger.debug(
"There was an error checking the latest version of pip",
exc_info=True,
)
|
[
"Check for an update for pip.\n\n Limit the frequency of checks to once per week. State is stored either in\n the active virtualenv or in the user's USER_CACHE_DIR keyed off the prefix\n of the pip script path.\n "
] |
Please provide a description of the function:def get_abbr_impl():
# type: () -> str
if hasattr(sys, 'pypy_version_info'):
pyimpl = 'pp'
elif sys.platform.startswith('java'):
pyimpl = 'jy'
elif sys.platform == 'cli':
pyimpl = 'ip'
else:
pyimpl = 'cp'
return pyimpl
|
[
"Return abbreviated implementation name."
] |
Please provide a description of the function:def get_impl_ver():
# type: () -> str
impl_ver = get_config_var("py_version_nodot")
if not impl_ver or get_abbr_impl() == 'pp':
impl_ver = ''.join(map(str, get_impl_version_info()))
return impl_ver
|
[
"Return implementation version."
] |
Please provide a description of the function:def get_impl_version_info():
# type: () -> Tuple[int, ...]
if get_abbr_impl() == 'pp':
# as per https://github.com/pypa/pip/issues/2882
# attrs exist only on pypy
return (sys.version_info[0],
sys.pypy_version_info.major, # type: ignore
sys.pypy_version_info.minor) # type: ignore
else:
return sys.version_info[0], sys.version_info[1]
|
[
"Return sys.version_info-like tuple for use in decrementing the minor\n version."
] |
Please provide a description of the function:def get_platform():
# type: () -> str
if sys.platform == 'darwin':
# distutils.util.get_platform() returns the release based on the value
# of MACOSX_DEPLOYMENT_TARGET on which Python was built, which may
# be significantly older than the user's current machine.
release, _, machine = platform.mac_ver()
split_ver = release.split('.')
if machine == "x86_64" and _is_running_32bit():
machine = "i386"
elif machine == "ppc64" and _is_running_32bit():
machine = "ppc"
return 'macosx_{}_{}_{}'.format(split_ver[0], split_ver[1], machine)
# XXX remove distutils dependency
result = distutils.util.get_platform().replace('.', '_').replace('-', '_')
if result == "linux_x86_64" and _is_running_32bit():
# 32 bit Python program (running on a 64 bit Linux): pip should only
# install and run 32 bit compiled extensions in that case.
result = "linux_i686"
return result
|
[
"Return our platform name 'win32', 'linux_x86_64'"
] |
Please provide a description of the function:def get_supported(
versions=None, # type: Optional[List[str]]
noarch=False, # type: bool
platform=None, # type: Optional[str]
impl=None, # type: Optional[str]
abi=None # type: Optional[str]
):
# type: (...) -> List[Pep425Tag]
supported = []
# Versions must be given with respect to the preference
if versions is None:
version_info = get_impl_version_info()
versions = get_all_minor_versions_as_strings(version_info)
impl = impl or get_abbr_impl()
abis = [] # type: List[str]
abi = abi or get_abi_tag()
if abi:
abis[0:0] = [abi]
abi3s = set()
for suffix in get_extension_suffixes():
if suffix.startswith('.abi'):
abi3s.add(suffix.split('.', 2)[1])
abis.extend(sorted(list(abi3s)))
abis.append('none')
if not noarch:
arch = platform or get_platform()
arch_prefix, arch_sep, arch_suffix = arch.partition('_')
if arch.startswith('macosx'):
# support macosx-10.6-intel on macosx-10.9-x86_64
match = _osx_arch_pat.match(arch)
if match:
name, major, minor, actual_arch = match.groups()
tpl = '{}_{}_%i_%s'.format(name, major)
arches = []
for m in reversed(range(int(minor) + 1)):
for a in get_darwin_arches(int(major), m, actual_arch):
arches.append(tpl % (m, a))
else:
# arch pattern didn't match (?!)
arches = [arch]
elif arch_prefix == 'manylinux2010':
# manylinux1 wheels run on most manylinux2010 systems with the
# exception of wheels depending on ncurses. PEP 571 states
# manylinux1 wheels should be considered manylinux2010 wheels:
# https://www.python.org/dev/peps/pep-0571/#backwards-compatibility-with-manylinux1-wheels
arches = [arch, 'manylinux1' + arch_sep + arch_suffix]
elif platform is None:
arches = []
if is_manylinux2010_compatible():
arches.append('manylinux2010' + arch_sep + arch_suffix)
if is_manylinux1_compatible():
arches.append('manylinux1' + arch_sep + arch_suffix)
arches.append(arch)
else:
arches = [arch]
# Current version, current API (built specifically for our Python):
for abi in abis:
for arch in arches:
supported.append(('%s%s' % (impl, versions[0]), abi, arch))
# abi3 modules compatible with older version of Python
for version in versions[1:]:
# abi3 was introduced in Python 3.2
if version in {'31', '30'}:
break
for abi in abi3s: # empty set if not Python 3
for arch in arches:
supported.append(("%s%s" % (impl, version), abi, arch))
# Has binaries, does not use the Python API:
for arch in arches:
supported.append(('py%s' % (versions[0][0]), 'none', arch))
# No abi / arch, but requires our implementation:
supported.append(('%s%s' % (impl, versions[0]), 'none', 'any'))
# Tagged specifically as being cross-version compatible
# (with just the major version specified)
supported.append(('%s%s' % (impl, versions[0][0]), 'none', 'any'))
# No abi / arch, generic Python
for i, version in enumerate(versions):
supported.append(('py%s' % (version,), 'none', 'any'))
if i == 0:
supported.append(('py%s' % (version[0]), 'none', 'any'))
return supported
|
[
"Return a list of supported tags for each version specified in\n `versions`.\n\n :param versions: a list of string versions, of the form [\"33\", \"32\"],\n or None. The first version will be assumed to support our ABI.\n :param platform: specify the exact platform you want valid\n tags for, or None. If None, use the local system platform.\n :param impl: specify the exact implementation you want valid\n tags for, or None. If None, use the local interpreter impl.\n :param abi: specify the exact abi you want valid\n tags for, or None. If None, use the local interpreter abi.\n "
] |
Please provide a description of the function:def get_netrc_auth(url, raise_errors=False):
try:
from netrc import netrc, NetrcParseError
netrc_path = None
for f in NETRC_FILES:
try:
loc = os.path.expanduser('~/{}'.format(f))
except KeyError:
# os.path.expanduser can fail when $HOME is undefined and
# getpwuid fails. See https://bugs.python.org/issue20164 &
# https://github.com/requests/requests/issues/1846
return
if os.path.exists(loc):
netrc_path = loc
break
# Abort early if there isn't one.
if netrc_path is None:
return
ri = urlparse(url)
# Strip port numbers from netloc. This weird `if...encode`` dance is
# used for Python 3.2, which doesn't support unicode literals.
splitstr = b':'
if isinstance(url, str):
splitstr = splitstr.decode('ascii')
host = ri.netloc.split(splitstr)[0]
try:
_netrc = netrc(netrc_path).authenticators(host)
if _netrc:
# Return with login / password
login_i = (0 if _netrc[0] else 1)
return (_netrc[login_i], _netrc[2])
except (NetrcParseError, IOError):
# If there was a parsing error or a permissions issue reading the file,
# we'll just skip netrc auth unless explicitly asked to raise errors.
if raise_errors:
raise
# AppEngine hackiness.
except (ImportError, AttributeError):
pass
|
[
"Returns the Requests tuple auth for a given url from netrc."
] |
Please provide a description of the function:def guess_filename(obj):
name = getattr(obj, 'name', None)
if (name and isinstance(name, basestring) and name[0] != '<' and
name[-1] != '>'):
return os.path.basename(name)
|
[
"Tries to guess the filename of the given object."
] |
Please provide a description of the function:def extract_zipped_paths(path):
if os.path.exists(path):
# this is already a valid path, no need to do anything further
return path
# find the first valid part of the provided path and treat that as a zip archive
# assume the rest of the path is the name of a member in the archive
archive, member = os.path.split(path)
while archive and not os.path.exists(archive):
archive, prefix = os.path.split(archive)
member = '/'.join([prefix, member])
if not zipfile.is_zipfile(archive):
return path
zip_file = zipfile.ZipFile(archive)
if member not in zip_file.namelist():
return path
# we have a valid zip archive and a valid member of that archive
tmp = tempfile.gettempdir()
extracted_path = os.path.join(tmp, *member.split('/'))
if not os.path.exists(extracted_path):
extracted_path = zip_file.extract(member, path=tmp)
return extracted_path
|
[
"Replace nonexistent paths that look like they refer to a member of a zip\n archive with the location of an extracted copy of the target, or else\n just return the provided path unchanged.\n "
] |
Please provide a description of the function:def from_key_val_list(value):
if value is None:
return None
if isinstance(value, (str, bytes, bool, int)):
raise ValueError('cannot encode objects that are not 2-tuples')
return OrderedDict(value)
|
[
"Take an object and test to see if it can be represented as a\n dictionary. Unless it can not be represented as such, return an\n OrderedDict, e.g.,\n\n ::\n\n >>> from_key_val_list([('key', 'val')])\n OrderedDict([('key', 'val')])\n >>> from_key_val_list('string')\n ValueError: cannot encode objects that are not 2-tuples\n >>> from_key_val_list({'key': 'val'})\n OrderedDict([('key', 'val')])\n\n :rtype: OrderedDict\n "
] |
Please provide a description of the function:def parse_list_header(value):
result = []
for item in _parse_list_header(value):
if item[:1] == item[-1:] == '"':
item = unquote_header_value(item[1:-1])
result.append(item)
return result
|
[
"Parse lists as described by RFC 2068 Section 2.\n\n In particular, parse comma-separated lists where the elements of\n the list may include quoted-strings. A quoted-string could\n contain a comma. A non-quoted string could have quotes in the\n middle. Quotes are removed automatically after parsing.\n\n It basically works like :func:`parse_set_header` just that items\n may appear multiple times and case sensitivity is preserved.\n\n The return value is a standard :class:`list`:\n\n >>> parse_list_header('token, \"quoted value\"')\n ['token', 'quoted value']\n\n To create a header from the :class:`list` again, use the\n :func:`dump_header` function.\n\n :param value: a string with a list header.\n :return: :class:`list`\n :rtype: list\n "
] |
Please provide a description of the function:def parse_dict_header(value):
result = {}
for item in _parse_list_header(value):
if '=' not in item:
result[item] = None
continue
name, value = item.split('=', 1)
if value[:1] == value[-1:] == '"':
value = unquote_header_value(value[1:-1])
result[name] = value
return result
|
[
"Parse lists of key, value pairs as described by RFC 2068 Section 2 and\n convert them into a python dict:\n\n >>> d = parse_dict_header('foo=\"is a fish\", bar=\"as well\"')\n >>> type(d) is dict\n True\n >>> sorted(d.items())\n [('bar', 'as well'), ('foo', 'is a fish')]\n\n If there is no value for a key it will be `None`:\n\n >>> parse_dict_header('key_without_value')\n {'key_without_value': None}\n\n To create a header from the :class:`dict` again, use the\n :func:`dump_header` function.\n\n :param value: a string with a dict header.\n :return: :class:`dict`\n :rtype: dict\n "
] |
Please provide a description of the function:def dict_from_cookiejar(cj):
cookie_dict = {}
for cookie in cj:
cookie_dict[cookie.name] = cookie.value
return cookie_dict
|
[
"Returns a key/value dictionary from a CookieJar.\n\n :param cj: CookieJar object to extract cookies from.\n :rtype: dict\n "
] |
Please provide a description of the function:def _parse_content_type_header(header):
tokens = header.split(';')
content_type, params = tokens[0].strip(), tokens[1:]
params_dict = {}
items_to_strip = "\"' "
for param in params:
param = param.strip()
if param:
key, value = param, True
index_of_equals = param.find("=")
if index_of_equals != -1:
key = param[:index_of_equals].strip(items_to_strip)
value = param[index_of_equals + 1:].strip(items_to_strip)
params_dict[key.lower()] = value
return content_type, params_dict
|
[
"Returns content type and parameters from given header\n\n :param header: string\n :return: tuple containing content type and dictionary of\n parameters\n "
] |
Please provide a description of the function:def get_encoding_from_headers(headers):
content_type = headers.get('content-type')
if not content_type:
return None
content_type, params = _parse_content_type_header(content_type)
if 'charset' in params:
return params['charset'].strip("'\"")
if 'text' in content_type:
return 'ISO-8859-1'
|
[
"Returns encodings from given HTTP Header Dict.\n\n :param headers: dictionary to extract encoding from.\n :rtype: str\n "
] |
Please provide a description of the function:def iter_slices(string, slice_length):
pos = 0
if slice_length is None or slice_length <= 0:
slice_length = len(string)
while pos < len(string):
yield string[pos:pos + slice_length]
pos += slice_length
|
[
"Iterate over slices of a string."
] |
Please provide a description of the function:def get_unicode_from_response(r):
warnings.warn((
'In requests 3.0, get_unicode_from_response will be removed. For '
'more information, please see the discussion on issue #2266. (This'
' warning should only appear once.)'),
DeprecationWarning)
tried_encodings = []
# Try charset from content-type
encoding = get_encoding_from_headers(r.headers)
if encoding:
try:
return str(r.content, encoding)
except UnicodeError:
tried_encodings.append(encoding)
# Fall back:
try:
return str(r.content, encoding, errors='replace')
except TypeError:
return r.content
|
[
"Returns the requested content back in unicode.\n\n :param r: Response object to get unicode content from.\n\n Tried:\n\n 1. charset from content-type\n 2. fall back and replace all unicode characters\n\n :rtype: str\n "
] |
Please provide a description of the function:def requote_uri(uri):
safe_with_percent = "!#$%&'()*+,/:;=?@[]~"
safe_without_percent = "!#$&'()*+,/:;=?@[]~"
try:
# Unquote only the unreserved characters
# Then quote only illegal characters (do not quote reserved,
# unreserved, or '%')
return quote(unquote_unreserved(uri), safe=safe_with_percent)
except InvalidURL:
# We couldn't unquote the given URI, so let's try quoting it, but
# there may be unquoted '%'s in the URI. We need to make sure they're
# properly quoted so they do not cause issues elsewhere.
return quote(uri, safe=safe_without_percent)
|
[
"Re-quote the given URI.\n\n This function passes the given URI through an unquote/quote cycle to\n ensure that it is fully and consistently quoted.\n\n :rtype: str\n "
] |
Please provide a description of the function:def address_in_network(ip, net):
ipaddr = struct.unpack('=L', socket.inet_aton(ip))[0]
netaddr, bits = net.split('/')
netmask = struct.unpack('=L', socket.inet_aton(dotted_netmask(int(bits))))[0]
network = struct.unpack('=L', socket.inet_aton(netaddr))[0] & netmask
return (ipaddr & netmask) == (network & netmask)
|
[
"This function allows you to check if an IP belongs to a network subnet\n\n Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24\n returns False if ip = 192.168.1.1 and net = 192.168.100.0/24\n\n :rtype: bool\n "
] |
Please provide a description of the function:def is_valid_cidr(string_network):
if string_network.count('/') == 1:
try:
mask = int(string_network.split('/')[1])
except ValueError:
return False
if mask < 1 or mask > 32:
return False
try:
socket.inet_aton(string_network.split('/')[0])
except socket.error:
return False
else:
return False
return True
|
[
"\n Very simple check of the cidr format in no_proxy variable.\n\n :rtype: bool\n "
] |
Please provide a description of the function:def set_environ(env_name, value):
value_changed = value is not None
if value_changed:
old_value = os.environ.get(env_name)
os.environ[env_name] = value
try:
yield
finally:
if value_changed:
if old_value is None:
del os.environ[env_name]
else:
os.environ[env_name] = old_value
|
[
"Set the environment variable 'env_name' to 'value'\n\n Save previous value, yield, and then restore the previous value stored in\n the environment variable 'env_name'.\n\n If 'value' is None, do nothing"
] |
Please provide a description of the function:def should_bypass_proxies(url, no_proxy):
# Prioritize lowercase environment variables over uppercase
# to keep a consistent behaviour with other http projects (curl, wget).
get_proxy = lambda k: os.environ.get(k) or os.environ.get(k.upper())
# First check whether no_proxy is defined. If it is, check that the URL
# we're getting isn't in the no_proxy list.
no_proxy_arg = no_proxy
if no_proxy is None:
no_proxy = get_proxy('no_proxy')
parsed = urlparse(url)
if parsed.hostname is None:
# URLs don't always have hostnames, e.g. file:/// urls.
return True
if no_proxy:
# We need to check whether we match here. We need to see if we match
# the end of the hostname, both with and without the port.
no_proxy = (
host for host in no_proxy.replace(' ', '').split(',') if host
)
if is_ipv4_address(parsed.hostname):
for proxy_ip in no_proxy:
if is_valid_cidr(proxy_ip):
if address_in_network(parsed.hostname, proxy_ip):
return True
elif parsed.hostname == proxy_ip:
# If no_proxy ip was defined in plain IP notation instead of cidr notation &
# matches the IP of the index
return True
else:
host_with_port = parsed.hostname
if parsed.port:
host_with_port += ':{}'.format(parsed.port)
for host in no_proxy:
if parsed.hostname.endswith(host) or host_with_port.endswith(host):
# The URL does match something in no_proxy, so we don't want
# to apply the proxies on this URL.
return True
with set_environ('no_proxy', no_proxy_arg):
# parsed.hostname can be `None` in cases such as a file URI.
try:
bypass = proxy_bypass(parsed.hostname)
except (TypeError, socket.gaierror):
bypass = False
if bypass:
return True
return False
|
[
"\n Returns whether we should bypass proxies or not.\n\n :rtype: bool\n "
] |
Please provide a description of the function:def select_proxy(url, proxies):
proxies = proxies or {}
urlparts = urlparse(url)
if urlparts.hostname is None:
return proxies.get(urlparts.scheme, proxies.get('all'))
proxy_keys = [
urlparts.scheme + '://' + urlparts.hostname,
urlparts.scheme,
'all://' + urlparts.hostname,
'all',
]
proxy = None
for proxy_key in proxy_keys:
if proxy_key in proxies:
proxy = proxies[proxy_key]
break
return proxy
|
[
"Select a proxy for the url, if applicable.\n\n :param url: The url being for the request\n :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs\n "
] |
Please provide a description of the function:def prepend_scheme_if_needed(url, new_scheme):
scheme, netloc, path, params, query, fragment = urlparse(url, new_scheme)
# urlparse is a finicky beast, and sometimes decides that there isn't a
# netloc present. Assume that it's being over-cautious, and switch netloc
# and path if urlparse decided there was no netloc.
if not netloc:
netloc, path = path, netloc
return urlunparse((scheme, netloc, path, params, query, fragment))
|
[
"Given a URL that may or may not have a scheme, prepend the given scheme.\n Does not replace a present scheme with the one provided as an argument.\n\n :rtype: str\n "
] |
Please provide a description of the function:def get_auth_from_url(url):
parsed = urlparse(url)
try:
auth = (unquote(parsed.username), unquote(parsed.password))
except (AttributeError, TypeError):
auth = ('', '')
return auth
|
[
"Given a url with authentication components, extract them into a tuple of\n username,password.\n\n :rtype: (str,str)\n "
] |
Please provide a description of the function:def check_header_validity(header):
name, value = header
if isinstance(value, bytes):
pat = _CLEAN_HEADER_REGEX_BYTE
else:
pat = _CLEAN_HEADER_REGEX_STR
try:
if not pat.match(value):
raise InvalidHeader("Invalid return character or leading space in header: %s" % name)
except TypeError:
raise InvalidHeader("Value for header {%s: %s} must be of type str or "
"bytes, not %s" % (name, value, type(value)))
|
[
"Verifies that header value is a string which doesn't contain\n leading whitespace or return characters. This prevents unintended\n header injection.\n\n :param header: tuple, in the format (name, value).\n "
] |
Please provide a description of the function:def urldefragauth(url):
scheme, netloc, path, params, query, fragment = urlparse(url)
# see func:`prepend_scheme_if_needed`
if not netloc:
netloc, path = path, netloc
netloc = netloc.rsplit('@', 1)[-1]
return urlunparse((scheme, netloc, path, params, query, ''))
|
[
"\n Given a url remove the fragment and the authentication part.\n\n :rtype: str\n "
] |
Please provide a description of the function:def rewind_body(prepared_request):
body_seek = getattr(prepared_request.body, 'seek', None)
if body_seek is not None and isinstance(prepared_request._body_position, integer_types):
try:
body_seek(prepared_request._body_position)
except (IOError, OSError):
raise UnrewindableBodyError("An error occurred when rewinding request "
"body for redirect.")
else:
raise UnrewindableBodyError("Unable to rewind request body for redirect.")
|
[
"Move file pointer back to its recorded starting position\n so it can be read again on redirect.\n "
] |
Please provide a description of the function:def canonicalize_version(version):
try:
version = Version(version)
except InvalidVersion:
# Legacy versions cannot be normalized
return version
parts = []
# Epoch
if version.epoch != 0:
parts.append("{0}!".format(version.epoch))
# Release segment
# NB: This strips trailing '.0's to normalize
parts.append(re.sub(r"(\.0)+$", "", ".".join(str(x) for x in version.release)))
# Pre-release
if version.pre is not None:
parts.append("".join(str(x) for x in version.pre))
# Post-release
if version.post is not None:
parts.append(".post{0}".format(version.post))
# Development release
if version.dev is not None:
parts.append(".dev{0}".format(version.dev))
# Local version segment
if version.local is not None:
parts.append("+{0}".format(version.local))
return "".join(parts)
|
[
"\n This is very similar to Version.__str__, but has one subtle differences\n with the way it handles the release segment.\n "
] |
Please provide a description of the function:def generate(node, environment, name, filename, stream=None,
defer_init=False, optimized=True):
if not isinstance(node, nodes.Template):
raise TypeError('Can\'t compile non template nodes')
generator = environment.code_generator_class(environment, name, filename,
stream, defer_init,
optimized)
generator.visit(node)
if stream is None:
return generator.stream.getvalue()
|
[
"Generate the python source for a node tree."
] |
Please provide a description of the function:def has_safe_repr(value):
if value is None or value is NotImplemented or value is Ellipsis:
return True
if type(value) in (bool, int, float, complex, range_type, Markup) + string_types:
return True
if type(value) in (tuple, list, set, frozenset):
for item in value:
if not has_safe_repr(item):
return False
return True
elif type(value) is dict:
for key, value in iteritems(value):
if not has_safe_repr(key):
return False
if not has_safe_repr(value):
return False
return True
return False
|
[
"Does the node have a safe representation?"
] |
Please provide a description of the function:def find_undeclared(nodes, names):
visitor = UndeclaredNameVisitor(names)
try:
for node in nodes:
visitor.visit(node)
except VisitorExit:
pass
return visitor.undeclared
|
[
"Check if the names passed are accessed undeclared. The return value\n is a set of all the undeclared names from the sequence of names found.\n "
] |
Please provide a description of the function:def copy(self):
rv = object.__new__(self.__class__)
rv.__dict__.update(self.__dict__)
rv.symbols = self.symbols.copy()
return rv
|
[
"Create a copy of the current one."
] |
Please provide a description of the function:def inner(self, isolated=False):
if isolated:
return Frame(self.eval_ctx, level=self.symbols.level + 1)
return Frame(self.eval_ctx, self)
|
[
"Return an inner frame."
] |
Please provide a description of the function:def fail(self, msg, lineno):
raise TemplateAssertionError(msg, lineno, self.name, self.filename)
|
[
"Fail with a :exc:`TemplateAssertionError`."
] |
Please provide a description of the function:def buffer(self, frame):
frame.buffer = self.temporary_identifier()
self.writeline('%s = []' % frame.buffer)
|
[
"Enable buffering for the frame from that point onwards."
] |
Please provide a description of the function:def return_buffer_contents(self, frame, force_unescaped=False):
if not force_unescaped:
if frame.eval_ctx.volatile:
self.writeline('if context.eval_ctx.autoescape:')
self.indent()
self.writeline('return Markup(concat(%s))' % frame.buffer)
self.outdent()
self.writeline('else:')
self.indent()
self.writeline('return concat(%s)' % frame.buffer)
self.outdent()
return
elif frame.eval_ctx.autoescape:
self.writeline('return Markup(concat(%s))' % frame.buffer)
return
self.writeline('return concat(%s)' % frame.buffer)
|
[
"Return the buffer contents of the frame."
] |
Please provide a description of the function:def start_write(self, frame, node=None):
if frame.buffer is None:
self.writeline('yield ', node)
else:
self.writeline('%s.append(' % frame.buffer, node)
|
[
"Yield or write into the frame buffer."
] |
Please provide a description of the function:def simple_write(self, s, frame, node=None):
self.start_write(frame, node)
self.write(s)
self.end_write(frame)
|
[
"Simple shortcut for start_write + write + end_write."
] |
Please provide a description of the function:def write(self, x):
if self._new_lines:
if not self._first_write:
self.stream.write('\n' * self._new_lines)
self.code_lineno += self._new_lines
if self._write_debug_info is not None:
self.debug_info.append((self._write_debug_info,
self.code_lineno))
self._write_debug_info = None
self._first_write = False
self.stream.write(' ' * self._indentation)
self._new_lines = 0
self.stream.write(x)
|
[
"Write a string into the output stream."
] |
Please provide a description of the function:def writeline(self, x, node=None, extra=0):
self.newline(node, extra)
self.write(x)
|
[
"Combination of newline and write."
] |
Please provide a description of the function:def newline(self, node=None, extra=0):
self._new_lines = max(self._new_lines, 1 + extra)
if node is not None and node.lineno != self._last_line:
self._write_debug_info = node.lineno
self._last_line = node.lineno
|
[
"Add one or more newlines before the next write."
] |
Please provide a description of the function:def signature(self, node, frame, extra_kwargs=None):
# if any of the given keyword arguments is a python keyword
# we have to make sure that no invalid call is created.
kwarg_workaround = False
for kwarg in chain((x.key for x in node.kwargs), extra_kwargs or ()):
if is_python_keyword(kwarg):
kwarg_workaround = True
break
for arg in node.args:
self.write(', ')
self.visit(arg, frame)
if not kwarg_workaround:
for kwarg in node.kwargs:
self.write(', ')
self.visit(kwarg, frame)
if extra_kwargs is not None:
for key, value in iteritems(extra_kwargs):
self.write(', %s=%s' % (key, value))
if node.dyn_args:
self.write(', *')
self.visit(node.dyn_args, frame)
if kwarg_workaround:
if node.dyn_kwargs is not None:
self.write(', **dict({')
else:
self.write(', **{')
for kwarg in node.kwargs:
self.write('%r: ' % kwarg.key)
self.visit(kwarg.value, frame)
self.write(', ')
if extra_kwargs is not None:
for key, value in iteritems(extra_kwargs):
self.write('%r: %s, ' % (key, value))
if node.dyn_kwargs is not None:
self.write('}, **')
self.visit(node.dyn_kwargs, frame)
self.write(')')
else:
self.write('}')
elif node.dyn_kwargs is not None:
self.write(', **')
self.visit(node.dyn_kwargs, frame)
|
[
"Writes a function call to the stream for the current node.\n A leading comma is added automatically. The extra keyword\n arguments may not include python keywords otherwise a syntax\n error could occour. The extra keyword arguments should be given\n as python dict.\n "
] |
Please provide a description of the function:def pull_dependencies(self, nodes):
visitor = DependencyFinderVisitor()
for node in nodes:
visitor.visit(node)
for dependency in 'filters', 'tests':
mapping = getattr(self, dependency)
for name in getattr(visitor, dependency):
if name not in mapping:
mapping[name] = self.temporary_identifier()
self.writeline('%s = environment.%s[%r]' %
(mapping[name], dependency, name))
|
[
"Pull all the dependencies."
] |
Please provide a description of the function:def macro_body(self, node, frame):
frame = frame.inner()
frame.symbols.analyze_node(node)
macro_ref = MacroRef(node)
explicit_caller = None
skip_special_params = set()
args = []
for idx, arg in enumerate(node.args):
if arg.name == 'caller':
explicit_caller = idx
if arg.name in ('kwargs', 'varargs'):
skip_special_params.add(arg.name)
args.append(frame.symbols.ref(arg.name))
undeclared = find_undeclared(node.body, ('caller', 'kwargs', 'varargs'))
if 'caller' in undeclared:
# In older Jinja2 versions there was a bug that allowed caller
# to retain the special behavior even if it was mentioned in
# the argument list. However thankfully this was only really
# working if it was the last argument. So we are explicitly
# checking this now and error out if it is anywhere else in
# the argument list.
if explicit_caller is not None:
try:
node.defaults[explicit_caller - len(node.args)]
except IndexError:
self.fail('When defining macros or call blocks the '
'special "caller" argument must be omitted '
'or be given a default.', node.lineno)
else:
args.append(frame.symbols.declare_parameter('caller'))
macro_ref.accesses_caller = True
if 'kwargs' in undeclared and not 'kwargs' in skip_special_params:
args.append(frame.symbols.declare_parameter('kwargs'))
macro_ref.accesses_kwargs = True
if 'varargs' in undeclared and not 'varargs' in skip_special_params:
args.append(frame.symbols.declare_parameter('varargs'))
macro_ref.accesses_varargs = True
# macros are delayed, they never require output checks
frame.require_output_check = False
frame.symbols.analyze_node(node)
self.writeline('%s(%s):' % (self.func('macro'), ', '.join(args)), node)
self.indent()
self.buffer(frame)
self.enter_frame(frame)
self.push_parameter_definitions(frame)
for idx, arg in enumerate(node.args):
ref = frame.symbols.ref(arg.name)
self.writeline('if %s is missing:' % ref)
self.indent()
try:
default = node.defaults[idx - len(node.args)]
except IndexError:
self.writeline('%s = undefined(%r, name=%r)' % (
ref,
'parameter %r was not provided' % arg.name,
arg.name))
else:
self.writeline('%s = ' % ref)
self.visit(default, frame)
self.mark_parameter_stored(ref)
self.outdent()
self.pop_parameter_definitions()
self.blockvisit(node.body, frame)
self.return_buffer_contents(frame, force_unescaped=True)
self.leave_frame(frame, with_python_scope=True)
self.outdent()
return frame, macro_ref
|
[
"Dump the function def of a macro or call block."
] |
Please provide a description of the function:def macro_def(self, macro_ref, frame):
arg_tuple = ', '.join(repr(x.name) for x in macro_ref.node.args)
name = getattr(macro_ref.node, 'name', None)
if len(macro_ref.node.args) == 1:
arg_tuple += ','
self.write('Macro(environment, macro, %r, (%s), %r, %r, %r, '
'context.eval_ctx.autoescape)' %
(name, arg_tuple, macro_ref.accesses_kwargs,
macro_ref.accesses_varargs, macro_ref.accesses_caller))
|
[
"Dump the macro definition for the def created by macro_body."
] |
Please provide a description of the function:def position(self, node):
rv = 'line %d' % node.lineno
if self.name is not None:
rv += ' in ' + repr(self.name)
return rv
|
[
"Return a human readable position for the node."
] |
Please provide a description of the function:def pop_assign_tracking(self, frame):
vars = self._assign_stack.pop()
if not frame.toplevel or not vars:
return
public_names = [x for x in vars if x[:1] != '_']
if len(vars) == 1:
name = next(iter(vars))
ref = frame.symbols.ref(name)
self.writeline('context.vars[%r] = %s' % (name, ref))
else:
self.writeline('context.vars.update({')
for idx, name in enumerate(vars):
if idx:
self.write(', ')
ref = frame.symbols.ref(name)
self.write('%r: %s' % (name, ref))
self.write('})')
if public_names:
if len(public_names) == 1:
self.writeline('context.exported_vars.add(%r)' %
public_names[0])
else:
self.writeline('context.exported_vars.update((%s))' %
', '.join(imap(repr, public_names)))
|
[
"Pops the topmost level for assignment tracking and updates the\n context variables if necessary.\n "
] |
Please provide a description of the function:def visit_Block(self, node, frame):
level = 0
if frame.toplevel:
# if we know that we are a child template, there is no need to
# check if we are one
if self.has_known_extends:
return
if self.extends_so_far > 0:
self.writeline('if parent_template is None:')
self.indent()
level += 1
if node.scoped:
context = self.derive_context(frame)
else:
context = self.get_context_ref()
if supports_yield_from and not self.environment.is_async and \
frame.buffer is None:
self.writeline('yield from context.blocks[%r][0](%s)' % (
node.name, context), node)
else:
loop = self.environment.is_async and 'async for' or 'for'
self.writeline('%s event in context.blocks[%r][0](%s):' % (
loop, node.name, context), node)
self.indent()
self.simple_write('event', frame)
self.outdent()
self.outdent(level)
|
[
"Call a block and register it for the template."
] |
Please provide a description of the function:def visit_Extends(self, node, frame):
if not frame.toplevel:
self.fail('cannot use extend from a non top-level scope',
node.lineno)
# if the number of extends statements in general is zero so
# far, we don't have to add a check if something extended
# the template before this one.
if self.extends_so_far > 0:
# if we have a known extends we just add a template runtime
# error into the generated code. We could catch that at compile
# time too, but i welcome it not to confuse users by throwing the
# same error at different times just "because we can".
if not self.has_known_extends:
self.writeline('if parent_template is not None:')
self.indent()
self.writeline('raise TemplateRuntimeError(%r)' %
'extended multiple times')
# if we have a known extends already we don't need that code here
# as we know that the template execution will end here.
if self.has_known_extends:
raise CompilerExit()
else:
self.outdent()
self.writeline('parent_template = environment.get_template(', node)
self.visit(node.template, frame)
self.write(', %r)' % self.name)
self.writeline('for name, parent_block in parent_template.'
'blocks.%s():' % dict_item_iter)
self.indent()
self.writeline('context.blocks.setdefault(name, []).'
'append(parent_block)')
self.outdent()
# if this extends statement was in the root level we can take
# advantage of that information and simplify the generated code
# in the top level from this point onwards
if frame.rootlevel:
self.has_known_extends = True
# and now we have one more
self.extends_so_far += 1
|
[
"Calls the extender."
] |
Please provide a description of the function:def visit_Include(self, node, frame):
if node.ignore_missing:
self.writeline('try:')
self.indent()
func_name = 'get_or_select_template'
if isinstance(node.template, nodes.Const):
if isinstance(node.template.value, string_types):
func_name = 'get_template'
elif isinstance(node.template.value, (tuple, list)):
func_name = 'select_template'
elif isinstance(node.template, (nodes.Tuple, nodes.List)):
func_name = 'select_template'
self.writeline('template = environment.%s(' % func_name, node)
self.visit(node.template, frame)
self.write(', %r)' % self.name)
if node.ignore_missing:
self.outdent()
self.writeline('except TemplateNotFound:')
self.indent()
self.writeline('pass')
self.outdent()
self.writeline('else:')
self.indent()
skip_event_yield = False
if node.with_context:
loop = self.environment.is_async and 'async for' or 'for'
self.writeline('%s event in template.root_render_func('
'template.new_context(context.get_all(), True, '
'%s)):' % (loop, self.dump_local_context(frame)))
elif self.environment.is_async:
self.writeline('for event in (await '
'template._get_default_module_async())'
'._body_stream:')
else:
if supports_yield_from:
self.writeline('yield from template._get_default_module()'
'._body_stream')
skip_event_yield = True
else:
self.writeline('for event in template._get_default_module()'
'._body_stream:')
if not skip_event_yield:
self.indent()
self.simple_write('event', frame)
self.outdent()
if node.ignore_missing:
self.outdent()
|
[
"Handles includes."
] |
Please provide a description of the function:def visit_Import(self, node, frame):
self.writeline('%s = ' % frame.symbols.ref(node.target), node)
if frame.toplevel:
self.write('context.vars[%r] = ' % node.target)
if self.environment.is_async:
self.write('await ')
self.write('environment.get_template(')
self.visit(node.template, frame)
self.write(', %r).' % self.name)
if node.with_context:
self.write('make_module%s(context.get_all(), True, %s)'
% (self.environment.is_async and '_async' or '',
self.dump_local_context(frame)))
elif self.environment.is_async:
self.write('_get_default_module_async()')
else:
self.write('_get_default_module()')
if frame.toplevel and not node.target.startswith('_'):
self.writeline('context.exported_vars.discard(%r)' % node.target)
|
[
"Visit regular imports."
] |
Please provide a description of the function:def visit_FromImport(self, node, frame):
self.newline(node)
self.write('included_template = %senvironment.get_template('
% (self.environment.is_async and 'await ' or ''))
self.visit(node.template, frame)
self.write(', %r).' % self.name)
if node.with_context:
self.write('make_module%s(context.get_all(), True, %s)'
% (self.environment.is_async and '_async' or '',
self.dump_local_context(frame)))
elif self.environment.is_async:
self.write('_get_default_module_async()')
else:
self.write('_get_default_module()')
var_names = []
discarded_names = []
for name in node.names:
if isinstance(name, tuple):
name, alias = name
else:
alias = name
self.writeline('%s = getattr(included_template, '
'%r, missing)' % (frame.symbols.ref(alias), name))
self.writeline('if %s is missing:' % frame.symbols.ref(alias))
self.indent()
self.writeline('%s = undefined(%r %% '
'included_template.__name__, '
'name=%r)' %
(frame.symbols.ref(alias),
'the template %%r (imported on %s) does '
'not export the requested name %s' % (
self.position(node),
repr(name)
), name))
self.outdent()
if frame.toplevel:
var_names.append(alias)
if not alias.startswith('_'):
discarded_names.append(alias)
if var_names:
if len(var_names) == 1:
name = var_names[0]
self.writeline('context.vars[%r] = %s' %
(name, frame.symbols.ref(name)))
else:
self.writeline('context.vars.update({%s})' % ', '.join(
'%r: %s' % (name, frame.symbols.ref(name)) for name in var_names
))
if discarded_names:
if len(discarded_names) == 1:
self.writeline('context.exported_vars.discard(%r)' %
discarded_names[0])
else:
self.writeline('context.exported_vars.difference_'
'update((%s))' % ', '.join(imap(repr, discarded_names)))
|
[
"Visit named imports."
] |
Please provide a description of the function:def detach(self):
info = self._registry.get(self)
obj = info and info.weakref()
if obj is not None and self._registry.pop(self, None):
return (obj, info.func, info.args, info.kwargs or {})
|
[
"If alive then mark as dead and return (obj, func, args, kwargs);\n otherwise return None"
] |
Please provide a description of the function:def peek(self):
info = self._registry.get(self)
obj = info and info.weakref()
if obj is not None:
return (obj, info.func, info.args, info.kwargs or {})
|
[
"If alive then return (obj, func, args, kwargs);\n otherwise return None"
] |
Please provide a description of the function:def atexit(self):
info = self._registry.get(self)
return bool(info) and info.atexit
|
[
"Whether finalizer should be called at exit"
] |
Please provide a description of the function:def tostring(element):
rv = []
def serializeElement(element):
if not hasattr(element, "tag"):
if element.docinfo.internalDTD:
if element.docinfo.doctype:
dtd_str = element.docinfo.doctype
else:
dtd_str = "<!DOCTYPE %s>" % element.docinfo.root_name
rv.append(dtd_str)
serializeElement(element.getroot())
elif element.tag == comment_type:
rv.append("<!--%s-->" % (element.text,))
else:
# This is assumed to be an ordinary element
if not element.attrib:
rv.append("<%s>" % (element.tag,))
else:
attr = " ".join(["%s=\"%s\"" % (name, value)
for name, value in element.attrib.items()])
rv.append("<%s %s>" % (element.tag, attr))
if element.text:
rv.append(element.text)
for child in element:
serializeElement(child)
rv.append("</%s>" % (element.tag,))
if hasattr(element, "tail") and element.tail:
rv.append(element.tail)
serializeElement(element)
return "".join(rv)
|
[
"Serialize an element and its child nodes to a string"
] |
Please provide a description of the function:def get_visitor(self, node):
method = 'visit_' + node.__class__.__name__
return getattr(self, method, None)
|
[
"Return the visitor function for this node or `None` if no visitor\n exists for this node. In that case the generic visit function is\n used instead.\n "
] |
Please provide a description of the function:def visit(self, node, *args, **kwargs):
f = self.get_visitor(node)
if f is not None:
return f(node, *args, **kwargs)
return self.generic_visit(node, *args, **kwargs)
|
[
"Visit a node."
] |
Please provide a description of the function:def generic_visit(self, node, *args, **kwargs):
for node in node.iter_child_nodes():
self.visit(node, *args, **kwargs)
|
[
"Called if no explicit visitor function exists for a node."
] |
Please provide a description of the function:def visit_list(self, node, *args, **kwargs):
rv = self.visit(node, *args, **kwargs)
if not isinstance(rv, list):
rv = [rv]
return rv
|
[
"As transformers may return lists in some places this method\n can be used to enforce a list as return value.\n "
] |
Please provide a description of the function:def default_subprocess_runner(cmd, cwd=None, extra_environ=None):
env = os.environ.copy()
if extra_environ:
env.update(extra_environ)
check_call(cmd, cwd=cwd, env=env)
|
[
"The default method of calling the wrapper subprocess."
] |
Please provide a description of the function:def build_wheel(
self, wheel_directory, config_settings=None,
metadata_directory=None):
if metadata_directory is not None:
metadata_directory = abspath(metadata_directory)
return self._call_hook('build_wheel', {
'wheel_directory': abspath(wheel_directory),
'config_settings': config_settings,
'metadata_directory': metadata_directory,
})
|
[
"Build a wheel from this project.\n\n Returns the name of the newly created file.\n\n In general, this will call the 'build_wheel' hook in the backend.\n However, if that was previously called by\n 'prepare_metadata_for_build_wheel', and the same metadata_directory is\n used, the previously built wheel will be copied to wheel_directory.\n "
] |
Please provide a description of the function:def bninception(num_classes=1000, pretrained='imagenet'):
r
model = BNInception(num_classes=num_classes)
if pretrained is not None:
settings = pretrained_settings['bninception'][pretrained]
assert num_classes == settings['num_classes'], \
"num_classes should be {}, but is {}".format(settings['num_classes'], num_classes)
model.load_state_dict(model_zoo.load_url(settings['url']))
model.input_space = settings['input_space']
model.input_size = settings['input_size']
model.input_range = settings['input_range']
model.mean = settings['mean']
model.std = settings['std']
return model
|
[
"BNInception model architecture from <https://arxiv.org/pdf/1502.03167.pdf>`_ paper.\n "
] |
Please provide a description of the function:def conv3x3(in_planes, out_planes, stride=1):
"3x3 convolution with padding"
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=True)
|
[] |
Please provide a description of the function:def resnet18(pretrained=False, **kwargs):
model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs)
if pretrained:
model.load_state_dict(model_zoo.load_url(model_urls['resnet18']))
return model
|
[
"Constructs a ResNet-18 model.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n "
] |
Please provide a description of the function:def resnet50(pretrained=False, **kwargs):
model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs)
if pretrained:
model.load_state_dict(model_zoo.load_url(model_urls['resnet50']))
return model
|
[
"Constructs a ResNet-50 model.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n "
] |
Please provide a description of the function:def cafferesnet101(num_classes=1000, pretrained='imagenet'):
model = ResNet(Bottleneck, [3, 4, 23, 3], num_classes=num_classes)
if pretrained is not None:
settings = pretrained_settings['cafferesnet101'][pretrained]
assert num_classes == settings['num_classes'], \
"num_classes should be {}, but is {}".format(settings['num_classes'], num_classes)
model.load_state_dict(model_zoo.load_url(settings['url']))
model.input_space = settings['input_space']
model.input_size = settings['input_size']
model.input_range = settings['input_range']
model.mean = settings['mean']
model.std = settings['std']
return model
|
[
"Constructs a ResNet-101 model.\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n "
] |
Please provide a description of the function:def fbresnet152(num_classes=1000, pretrained='imagenet'):
model = FBResNet(Bottleneck, [3, 8, 36, 3], num_classes=num_classes)
if pretrained is not None:
settings = pretrained_settings['fbresnet152'][pretrained]
assert num_classes == settings['num_classes'], \
"num_classes should be {}, but is {}".format(settings['num_classes'], num_classes)
model.load_state_dict(model_zoo.load_url(settings['url']))
model.input_space = settings['input_space']
model.input_size = settings['input_size']
model.input_range = settings['input_range']
model.mean = settings['mean']
model.std = settings['std']
return model
|
[
"Constructs a ResNet-152 model.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n "
] |
Please provide a description of the function:def alexnet(num_classes=1000, pretrained='imagenet'):
r
# https://github.com/pytorch/vision/blob/master/torchvision/models/alexnet.py
model = models.alexnet(pretrained=False)
if pretrained is not None:
settings = pretrained_settings['alexnet'][pretrained]
model = load_pretrained(model, num_classes, settings)
model = modify_alexnet(model)
return model
|
[
"AlexNet model architecture from the\n `\"One weird trick...\" <https://arxiv.org/abs/1404.5997>`_ paper.\n "
] |
Please provide a description of the function:def densenet121(num_classes=1000, pretrained='imagenet'):
r
model = models.densenet121(pretrained=False)
if pretrained is not None:
settings = pretrained_settings['densenet121'][pretrained]
model = load_pretrained(model, num_classes, settings)
model = modify_densenets(model)
return model
|
[
"Densenet-121 model from\n `\"Densely Connected Convolutional Networks\" <https://arxiv.org/pdf/1608.06993.pdf>`\n "
] |
Please provide a description of the function:def inceptionv3(num_classes=1000, pretrained='imagenet'):
r
model = models.inception_v3(pretrained=False)
if pretrained is not None:
settings = pretrained_settings['inceptionv3'][pretrained]
model = load_pretrained(model, num_classes, settings)
# Modify attributs
model.last_linear = model.fc
del model.fc
def features(self, input):
# 299 x 299 x 3
x = self.Conv2d_1a_3x3(input) # 149 x 149 x 32
x = self.Conv2d_2a_3x3(x) # 147 x 147 x 32
x = self.Conv2d_2b_3x3(x) # 147 x 147 x 64
x = F.max_pool2d(x, kernel_size=3, stride=2) # 73 x 73 x 64
x = self.Conv2d_3b_1x1(x) # 73 x 73 x 80
x = self.Conv2d_4a_3x3(x) # 71 x 71 x 192
x = F.max_pool2d(x, kernel_size=3, stride=2) # 35 x 35 x 192
x = self.Mixed_5b(x) # 35 x 35 x 256
x = self.Mixed_5c(x) # 35 x 35 x 288
x = self.Mixed_5d(x) # 35 x 35 x 288
x = self.Mixed_6a(x) # 17 x 17 x 768
x = self.Mixed_6b(x) # 17 x 17 x 768
x = self.Mixed_6c(x) # 17 x 17 x 768
x = self.Mixed_6d(x) # 17 x 17 x 768
x = self.Mixed_6e(x) # 17 x 17 x 768
if self.training and self.aux_logits:
self._out_aux = self.AuxLogits(x) # 17 x 17 x 768
x = self.Mixed_7a(x) # 8 x 8 x 1280
x = self.Mixed_7b(x) # 8 x 8 x 2048
x = self.Mixed_7c(x) # 8 x 8 x 2048
return x
def logits(self, features):
x = F.avg_pool2d(features, kernel_size=8) # 1 x 1 x 2048
x = F.dropout(x, training=self.training) # 1 x 1 x 2048
x = x.view(x.size(0), -1) # 2048
x = self.last_linear(x) # 1000 (num_classes)
if self.training and self.aux_logits:
aux = self._out_aux
self._out_aux = None
return x, aux
return x
def forward(self, input):
x = self.features(input)
x = self.logits(x)
return x
# Modify methods
model.features = types.MethodType(features, model)
model.logits = types.MethodType(logits, model)
model.forward = types.MethodType(forward, model)
return model
|
[
"Inception v3 model architecture from\n `\"Rethinking the Inception Architecture for Computer Vision\" <http://arxiv.org/abs/1512.00567>`_.\n "
] |
Please provide a description of the function:def resnet50(num_classes=1000, pretrained='imagenet'):
model = models.resnet50(pretrained=False)
if pretrained is not None:
settings = pretrained_settings['resnet50'][pretrained]
model = load_pretrained(model, num_classes, settings)
model = modify_resnets(model)
return model
|
[
"Constructs a ResNet-50 model.\n "
] |
Please provide a description of the function:def squeezenet1_0(num_classes=1000, pretrained='imagenet'):
r
model = models.squeezenet1_0(pretrained=False)
if pretrained is not None:
settings = pretrained_settings['squeezenet1_0'][pretrained]
model = load_pretrained(model, num_classes, settings)
model = modify_squeezenets(model)
return model
|
[
"SqueezeNet model architecture from the `\"SqueezeNet: AlexNet-level\n accuracy with 50x fewer parameters and <0.5MB model size\"\n <https://arxiv.org/abs/1602.07360>`_ paper.\n "
] |
Please provide a description of the function:def vgg11(num_classes=1000, pretrained='imagenet'):
model = models.vgg11(pretrained=False)
if pretrained is not None:
settings = pretrained_settings['vgg11'][pretrained]
model = load_pretrained(model, num_classes, settings)
model = modify_vggs(model)
return model
|
[
"VGG 11-layer model (configuration \"A\")\n "
] |
Please provide a description of the function:def adjust_learning_rate(optimizer, epoch):
lr = args.lr * (0.1 ** (epoch // 30))
for param_group in optimizer.param_groups:
param_group['lr'] = lr
|
[
"Sets the learning rate to the initial LR decayed by 10 every 30 epochs"
] |
Please provide a description of the function:def nasnetalarge(num_classes=1001, pretrained='imagenet'):
r
if pretrained:
settings = pretrained_settings['nasnetalarge'][pretrained]
assert num_classes == settings['num_classes'], \
"num_classes should be {}, but is {}".format(settings['num_classes'], num_classes)
# both 'imagenet'&'imagenet+background' are loaded from same parameters
model = NASNetALarge(num_classes=1001)
model.load_state_dict(model_zoo.load_url(settings['url']))
if pretrained == 'imagenet':
new_last_linear = nn.Linear(model.last_linear.in_features, 1000)
new_last_linear.weight.data = model.last_linear.weight.data[1:]
new_last_linear.bias.data = model.last_linear.bias.data[1:]
model.last_linear = new_last_linear
model.input_space = settings['input_space']
model.input_size = settings['input_size']
model.input_range = settings['input_range']
model.mean = settings['mean']
model.std = settings['std']
else:
model = NASNetALarge(num_classes=num_classes)
return model
|
[
"NASNetALarge model architecture from the\n `\"NASNet\" <https://arxiv.org/abs/1707.07012>`_ paper.\n "
] |
Please provide a description of the function:def adaptive_avgmax_pool2d(x, pool_type='avg', padding=0, count_include_pad=False):
if pool_type == 'avgmaxc':
x = torch.cat([
F.avg_pool2d(
x, kernel_size=(x.size(2), x.size(3)), padding=padding, count_include_pad=count_include_pad),
F.max_pool2d(x, kernel_size=(x.size(2), x.size(3)), padding=padding)
], dim=1)
elif pool_type == 'avgmax':
x_avg = F.avg_pool2d(
x, kernel_size=(x.size(2), x.size(3)), padding=padding, count_include_pad=count_include_pad)
x_max = F.max_pool2d(x, kernel_size=(x.size(2), x.size(3)), padding=padding)
x = 0.5 * (x_avg + x_max)
elif pool_type == 'max':
x = F.max_pool2d(x, kernel_size=(x.size(2), x.size(3)), padding=padding)
else:
if pool_type != 'avg':
print('Invalid pool type %s specified. Defaulting to average pooling.' % pool_type)
x = F.avg_pool2d(
x, kernel_size=(x.size(2), x.size(3)), padding=padding, count_include_pad=count_include_pad)
return x
|
[
"Selectable global pooling function with dynamic input kernel size\n "
] |
Please provide a description of the function:def download_url(url, destination=None, progress_bar=True):
def my_hook(t):
last_b = [0]
def inner(b=1, bsize=1, tsize=None):
if tsize is not None:
t.total = tsize
if b > 0:
t.update((b - last_b[0]) * bsize)
last_b[0] = b
return inner
if progress_bar:
with tqdm(unit='B', unit_scale=True, miniters=1, desc=url.split('/')[-1]) as t:
filename, _ = urlretrieve(url, filename=destination, reporthook=my_hook(t))
else:
filename, _ = urlretrieve(url, filename=destination)
|
[
"Download a URL to a local file.\n\n Parameters\n ----------\n url : str\n The URL to download.\n destination : str, None\n The destination of the file. If None is given the file is saved to a temporary directory.\n progress_bar : bool\n Whether to show a command-line progress bar while downloading.\n\n Returns\n -------\n filename : str\n The location of the downloaded file.\n\n Notes\n -----\n Progress bar use/example adapted from tqdm documentation: https://github.com/tqdm/tqdm\n "
] |
Please provide a description of the function:def add(self, output, target):
if not torch.is_tensor(output):
output = torch.from_numpy(output)
if not torch.is_tensor(target):
target = torch.from_numpy(target)
if output.dim() == 1:
output = output.view(-1, 1)
else:
assert output.dim() == 2, \
'wrong output size (should be 1D or 2D with one column \
per class)'
if target.dim() == 1:
target = target.view(-1, 1)
else:
assert target.dim() == 2, \
'wrong target size (should be 1D or 2D with one column \
per class)'
if self.scores.numel() > 0:
assert target.size(1) == self.targets.size(1), \
'dimensions for output should match previously added examples.'
# make sure storage is of sufficient size
if self.scores.storage().size() < self.scores.numel() + output.numel():
new_size = math.ceil(self.scores.storage().size() * 1.5)
self.scores.storage().resize_(int(new_size + output.numel()))
self.targets.storage().resize_(int(new_size + output.numel()))
# store scores and targets
offset = self.scores.size(0) if self.scores.dim() > 0 else 0
self.scores.resize_(offset + output.size(0), output.size(1))
self.targets.resize_(offset + target.size(0), target.size(1))
self.scores.narrow(0, offset, output.size(0)).copy_(output)
self.targets.narrow(0, offset, target.size(0)).copy_(target)
|
[
"\n Args:\n output (Tensor): NxK tensor that for each of the N examples\n indicates the probability of the example belonging to each of\n the K classes, according to the model. The probabilities should\n sum to one over all classes\n target (Tensor): binary NxK tensort that encodes which of the K\n classes are associated with the N-th input\n (eg: a row [0, 1, 0, 1] indicates that the example is\n associated with classes 2 and 4)\n weight (optional, Tensor): Nx1 tensor representing the weight for\n each example (each weight > 0)\n "
] |
Please provide a description of the function:def value(self):
if self.scores.numel() == 0:
return 0
ap = torch.zeros(self.scores.size(1))
rg = torch.arange(1, self.scores.size(0)).float()
# compute average precision for each class
for k in range(self.scores.size(1)):
# sort scores
scores = self.scores[:, k]
targets = self.targets[:, k]
# compute average precision
ap[k] = AveragePrecisionMeter.average_precision(scores, targets, self.difficult_examples)
return ap
|
[
"Returns the model's average precision for each class\n Return:\n ap (FloatTensor): 1xK tensor, with avg precision for each class k\n "
] |
Please provide a description of the function:def polynet(num_classes=1000, pretrained='imagenet'):
if pretrained:
settings = pretrained_settings['polynet'][pretrained]
assert num_classes == settings['num_classes'], \
'num_classes should be {}, but is {}'.format(
settings['num_classes'], num_classes)
model = PolyNet(num_classes=num_classes)
model.load_state_dict(model_zoo.load_url(settings['url']))
model.input_space = settings['input_space']
model.input_size = settings['input_size']
model.input_range = settings['input_range']
model.mean = settings['mean']
model.std = settings['std']
else:
model = PolyNet(num_classes=num_classes)
return model
|
[
"PolyNet architecture from the paper\n 'PolyNet: A Pursuit of Structural Diversity in Very Deep Networks'\n https://arxiv.org/abs/1611.05725\n "
] |
Please provide a description of the function:def unwrap(self, dt):
expires = self._expires
if expires is AlwaysExpired or expires < dt:
raise Expired(self._expires)
return self._value
|
[
"\n Get the cached value.\n\n Returns\n -------\n value : object\n The cached value.\n\n Raises\n ------\n Expired\n Raised when `dt` is greater than self.expires.\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.