partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
train
move
Recursively move a file or directory to another location. This is similar to the Unix "mv" command. If the destination is a directory or a symlink to a directory, the source is moved inside the directory. The destination path must not already exist. If the destination already exists but is not a directory, it may be overwritten depending on os.rename() semantics. If the destination is on our current filesystem, then rename() is used. Otherwise, src is copied to the destination and then removed. A lot more could be done here... A look at a mv.c shows a lot of the issues this implementation glosses over.
pipenv/vendor/distlib/_backport/shutil.py
def move(src, dst): """Recursively move a file or directory to another location. This is similar to the Unix "mv" command. If the destination is a directory or a symlink to a directory, the source is moved inside the directory. The destination path must not already exist. If the destination already exists but is not a directory, it may be overwritten depending on os.rename() semantics. If the destination is on our current filesystem, then rename() is used. Otherwise, src is copied to the destination and then removed. A lot more could be done here... A look at a mv.c shows a lot of the issues this implementation glosses over. """ real_dst = dst if os.path.isdir(dst): if _samefile(src, dst): # We might be on a case insensitive filesystem, # perform the rename anyway. os.rename(src, dst) return real_dst = os.path.join(dst, _basename(src)) if os.path.exists(real_dst): raise Error("Destination path '%s' already exists" % real_dst) try: os.rename(src, real_dst) except OSError: if os.path.isdir(src): if _destinsrc(src, dst): raise Error("Cannot move a directory '%s' into itself '%s'." % (src, dst)) copytree(src, real_dst, symlinks=True) rmtree(src) else: copy2(src, real_dst) os.unlink(src)
def move(src, dst): """Recursively move a file or directory to another location. This is similar to the Unix "mv" command. If the destination is a directory or a symlink to a directory, the source is moved inside the directory. The destination path must not already exist. If the destination already exists but is not a directory, it may be overwritten depending on os.rename() semantics. If the destination is on our current filesystem, then rename() is used. Otherwise, src is copied to the destination and then removed. A lot more could be done here... A look at a mv.c shows a lot of the issues this implementation glosses over. """ real_dst = dst if os.path.isdir(dst): if _samefile(src, dst): # We might be on a case insensitive filesystem, # perform the rename anyway. os.rename(src, dst) return real_dst = os.path.join(dst, _basename(src)) if os.path.exists(real_dst): raise Error("Destination path '%s' already exists" % real_dst) try: os.rename(src, real_dst) except OSError: if os.path.isdir(src): if _destinsrc(src, dst): raise Error("Cannot move a directory '%s' into itself '%s'." % (src, dst)) copytree(src, real_dst, symlinks=True) rmtree(src) else: copy2(src, real_dst) os.unlink(src)
[ "Recursively", "move", "a", "file", "or", "directory", "to", "another", "location", ".", "This", "is", "similar", "to", "the", "Unix", "mv", "command", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/shutil.py#L300-L338
[ "def", "move", "(", "src", ",", "dst", ")", ":", "real_dst", "=", "dst", "if", "os", ".", "path", ".", "isdir", "(", "dst", ")", ":", "if", "_samefile", "(", "src", ",", "dst", ")", ":", "# We might be on a case insensitive filesystem,", "# perform the ren...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_get_gid
Returns a gid, given a group name.
pipenv/vendor/distlib/_backport/shutil.py
def _get_gid(name): """Returns a gid, given a group name.""" if getgrnam is None or name is None: return None try: result = getgrnam(name) except KeyError: result = None if result is not None: return result[2] return None
def _get_gid(name): """Returns a gid, given a group name.""" if getgrnam is None or name is None: return None try: result = getgrnam(name) except KeyError: result = None if result is not None: return result[2] return None
[ "Returns", "a", "gid", "given", "a", "group", "name", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/shutil.py#L349-L359
[ "def", "_get_gid", "(", "name", ")", ":", "if", "getgrnam", "is", "None", "or", "name", "is", "None", ":", "return", "None", "try", ":", "result", "=", "getgrnam", "(", "name", ")", "except", "KeyError", ":", "result", "=", "None", "if", "result", "i...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_get_uid
Returns an uid, given a user name.
pipenv/vendor/distlib/_backport/shutil.py
def _get_uid(name): """Returns an uid, given a user name.""" if getpwnam is None or name is None: return None try: result = getpwnam(name) except KeyError: result = None if result is not None: return result[2] return None
def _get_uid(name): """Returns an uid, given a user name.""" if getpwnam is None or name is None: return None try: result = getpwnam(name) except KeyError: result = None if result is not None: return result[2] return None
[ "Returns", "an", "uid", "given", "a", "user", "name", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/shutil.py#L361-L371
[ "def", "_get_uid", "(", "name", ")", ":", "if", "getpwnam", "is", "None", "or", "name", "is", "None", ":", "return", "None", "try", ":", "result", "=", "getpwnam", "(", "name", ")", "except", "KeyError", ":", "result", "=", "None", "if", "result", "i...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_make_tarball
Create a (possibly compressed) tar file from all the files under 'base_dir'. 'compress' must be "gzip" (the default), "bzip2", or None. 'owner' and 'group' can be used to define an owner and a group for the archive that is being built. If not provided, the current owner and group will be used. The output tar file will be named 'base_name' + ".tar", possibly plus the appropriate compression extension (".gz", or ".bz2"). Returns the output filename.
pipenv/vendor/distlib/_backport/shutil.py
def _make_tarball(base_name, base_dir, compress="gzip", verbose=0, dry_run=0, owner=None, group=None, logger=None): """Create a (possibly compressed) tar file from all the files under 'base_dir'. 'compress' must be "gzip" (the default), "bzip2", or None. 'owner' and 'group' can be used to define an owner and a group for the archive that is being built. If not provided, the current owner and group will be used. The output tar file will be named 'base_name' + ".tar", possibly plus the appropriate compression extension (".gz", or ".bz2"). Returns the output filename. """ tar_compression = {'gzip': 'gz', None: ''} compress_ext = {'gzip': '.gz'} if _BZ2_SUPPORTED: tar_compression['bzip2'] = 'bz2' compress_ext['bzip2'] = '.bz2' # flags for compression program, each element of list will be an argument if compress is not None and compress not in compress_ext: raise ValueError("bad value for 'compress', or compression format not " "supported : {0}".format(compress)) archive_name = base_name + '.tar' + compress_ext.get(compress, '') archive_dir = os.path.dirname(archive_name) if not os.path.exists(archive_dir): if logger is not None: logger.info("creating %s", archive_dir) if not dry_run: os.makedirs(archive_dir) # creating the tarball if logger is not None: logger.info('Creating tar archive') uid = _get_uid(owner) gid = _get_gid(group) def _set_uid_gid(tarinfo): if gid is not None: tarinfo.gid = gid tarinfo.gname = group if uid is not None: tarinfo.uid = uid tarinfo.uname = owner return tarinfo if not dry_run: tar = tarfile.open(archive_name, 'w|%s' % tar_compression[compress]) try: tar.add(base_dir, filter=_set_uid_gid) finally: tar.close() return archive_name
def _make_tarball(base_name, base_dir, compress="gzip", verbose=0, dry_run=0, owner=None, group=None, logger=None): """Create a (possibly compressed) tar file from all the files under 'base_dir'. 'compress' must be "gzip" (the default), "bzip2", or None. 'owner' and 'group' can be used to define an owner and a group for the archive that is being built. If not provided, the current owner and group will be used. The output tar file will be named 'base_name' + ".tar", possibly plus the appropriate compression extension (".gz", or ".bz2"). Returns the output filename. """ tar_compression = {'gzip': 'gz', None: ''} compress_ext = {'gzip': '.gz'} if _BZ2_SUPPORTED: tar_compression['bzip2'] = 'bz2' compress_ext['bzip2'] = '.bz2' # flags for compression program, each element of list will be an argument if compress is not None and compress not in compress_ext: raise ValueError("bad value for 'compress', or compression format not " "supported : {0}".format(compress)) archive_name = base_name + '.tar' + compress_ext.get(compress, '') archive_dir = os.path.dirname(archive_name) if not os.path.exists(archive_dir): if logger is not None: logger.info("creating %s", archive_dir) if not dry_run: os.makedirs(archive_dir) # creating the tarball if logger is not None: logger.info('Creating tar archive') uid = _get_uid(owner) gid = _get_gid(group) def _set_uid_gid(tarinfo): if gid is not None: tarinfo.gid = gid tarinfo.gname = group if uid is not None: tarinfo.uid = uid tarinfo.uname = owner return tarinfo if not dry_run: tar = tarfile.open(archive_name, 'w|%s' % tar_compression[compress]) try: tar.add(base_dir, filter=_set_uid_gid) finally: tar.close() return archive_name
[ "Create", "a", "(", "possibly", "compressed", ")", "tar", "file", "from", "all", "the", "files", "under", "base_dir", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/shutil.py#L373-L433
[ "def", "_make_tarball", "(", "base_name", ",", "base_dir", ",", "compress", "=", "\"gzip\"", ",", "verbose", "=", "0", ",", "dry_run", "=", "0", ",", "owner", "=", "None", ",", "group", "=", "None", ",", "logger", "=", "None", ")", ":", "tar_compressio...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_make_zipfile
Create a zip file from all the files under 'base_dir'. The output zip file will be named 'base_name' + ".zip". Uses either the "zipfile" Python module (if available) or the InfoZIP "zip" utility (if installed and found on the default search path). If neither tool is available, raises ExecError. Returns the name of the output zip file.
pipenv/vendor/distlib/_backport/shutil.py
def _make_zipfile(base_name, base_dir, verbose=0, dry_run=0, logger=None): """Create a zip file from all the files under 'base_dir'. The output zip file will be named 'base_name' + ".zip". Uses either the "zipfile" Python module (if available) or the InfoZIP "zip" utility (if installed and found on the default search path). If neither tool is available, raises ExecError. Returns the name of the output zip file. """ zip_filename = base_name + ".zip" archive_dir = os.path.dirname(base_name) if not os.path.exists(archive_dir): if logger is not None: logger.info("creating %s", archive_dir) if not dry_run: os.makedirs(archive_dir) # If zipfile module is not available, try spawning an external 'zip' # command. try: import zipfile except ImportError: zipfile = None if zipfile is None: _call_external_zip(base_dir, zip_filename, verbose, dry_run) else: if logger is not None: logger.info("creating '%s' and adding '%s' to it", zip_filename, base_dir) if not dry_run: zip = zipfile.ZipFile(zip_filename, "w", compression=zipfile.ZIP_DEFLATED) for dirpath, dirnames, filenames in os.walk(base_dir): for name in filenames: path = os.path.normpath(os.path.join(dirpath, name)) if os.path.isfile(path): zip.write(path, path) if logger is not None: logger.info("adding '%s'", path) zip.close() return zip_filename
def _make_zipfile(base_name, base_dir, verbose=0, dry_run=0, logger=None): """Create a zip file from all the files under 'base_dir'. The output zip file will be named 'base_name' + ".zip". Uses either the "zipfile" Python module (if available) or the InfoZIP "zip" utility (if installed and found on the default search path). If neither tool is available, raises ExecError. Returns the name of the output zip file. """ zip_filename = base_name + ".zip" archive_dir = os.path.dirname(base_name) if not os.path.exists(archive_dir): if logger is not None: logger.info("creating %s", archive_dir) if not dry_run: os.makedirs(archive_dir) # If zipfile module is not available, try spawning an external 'zip' # command. try: import zipfile except ImportError: zipfile = None if zipfile is None: _call_external_zip(base_dir, zip_filename, verbose, dry_run) else: if logger is not None: logger.info("creating '%s' and adding '%s' to it", zip_filename, base_dir) if not dry_run: zip = zipfile.ZipFile(zip_filename, "w", compression=zipfile.ZIP_DEFLATED) for dirpath, dirnames, filenames in os.walk(base_dir): for name in filenames: path = os.path.normpath(os.path.join(dirpath, name)) if os.path.isfile(path): zip.write(path, path) if logger is not None: logger.info("adding '%s'", path) zip.close() return zip_filename
[ "Create", "a", "zip", "file", "from", "all", "the", "files", "under", "base_dir", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/shutil.py#L452-L497
[ "def", "_make_zipfile", "(", "base_name", ",", "base_dir", ",", "verbose", "=", "0", ",", "dry_run", "=", "0", ",", "logger", "=", "None", ")", ":", "zip_filename", "=", "base_name", "+", "\".zip\"", "archive_dir", "=", "os", ".", "path", ".", "dirname",...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
get_archive_formats
Returns a list of supported formats for archiving and unarchiving. Each element of the returned sequence is a tuple (name, description)
pipenv/vendor/distlib/_backport/shutil.py
def get_archive_formats(): """Returns a list of supported formats for archiving and unarchiving. Each element of the returned sequence is a tuple (name, description) """ formats = [(name, registry[2]) for name, registry in _ARCHIVE_FORMATS.items()] formats.sort() return formats
def get_archive_formats(): """Returns a list of supported formats for archiving and unarchiving. Each element of the returned sequence is a tuple (name, description) """ formats = [(name, registry[2]) for name, registry in _ARCHIVE_FORMATS.items()] formats.sort() return formats
[ "Returns", "a", "list", "of", "supported", "formats", "for", "archiving", "and", "unarchiving", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/shutil.py#L510-L518
[ "def", "get_archive_formats", "(", ")", ":", "formats", "=", "[", "(", "name", ",", "registry", "[", "2", "]", ")", "for", "name", ",", "registry", "in", "_ARCHIVE_FORMATS", ".", "items", "(", ")", "]", "formats", ".", "sort", "(", ")", "return", "fo...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
register_archive_format
Registers an archive format. name is the name of the format. function is the callable that will be used to create archives. If provided, extra_args is a sequence of (name, value) tuples that will be passed as arguments to the callable. description can be provided to describe the format, and will be returned by the get_archive_formats() function.
pipenv/vendor/distlib/_backport/shutil.py
def register_archive_format(name, function, extra_args=None, description=''): """Registers an archive format. name is the name of the format. function is the callable that will be used to create archives. If provided, extra_args is a sequence of (name, value) tuples that will be passed as arguments to the callable. description can be provided to describe the format, and will be returned by the get_archive_formats() function. """ if extra_args is None: extra_args = [] if not isinstance(function, collections.Callable): raise TypeError('The %s object is not callable' % function) if not isinstance(extra_args, (tuple, list)): raise TypeError('extra_args needs to be a sequence') for element in extra_args: if not isinstance(element, (tuple, list)) or len(element) !=2: raise TypeError('extra_args elements are : (arg_name, value)') _ARCHIVE_FORMATS[name] = (function, extra_args, description)
def register_archive_format(name, function, extra_args=None, description=''): """Registers an archive format. name is the name of the format. function is the callable that will be used to create archives. If provided, extra_args is a sequence of (name, value) tuples that will be passed as arguments to the callable. description can be provided to describe the format, and will be returned by the get_archive_formats() function. """ if extra_args is None: extra_args = [] if not isinstance(function, collections.Callable): raise TypeError('The %s object is not callable' % function) if not isinstance(extra_args, (tuple, list)): raise TypeError('extra_args needs to be a sequence') for element in extra_args: if not isinstance(element, (tuple, list)) or len(element) !=2: raise TypeError('extra_args elements are : (arg_name, value)') _ARCHIVE_FORMATS[name] = (function, extra_args, description)
[ "Registers", "an", "archive", "format", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/shutil.py#L520-L539
[ "def", "register_archive_format", "(", "name", ",", "function", ",", "extra_args", "=", "None", ",", "description", "=", "''", ")", ":", "if", "extra_args", "is", "None", ":", "extra_args", "=", "[", "]", "if", "not", "isinstance", "(", "function", ",", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
make_archive
Create an archive file (eg. zip or tar). 'base_name' is the name of the file to create, minus any format-specific extension; 'format' is the archive format: one of "zip", "tar", "bztar" or "gztar". 'root_dir' is a directory that will be the root directory of the archive; ie. we typically chdir into 'root_dir' before creating the archive. 'base_dir' is the directory where we start archiving from; ie. 'base_dir' will be the common prefix of all files and directories in the archive. 'root_dir' and 'base_dir' both default to the current directory. Returns the name of the archive file. 'owner' and 'group' are used when creating a tar archive. By default, uses the current owner and group.
pipenv/vendor/distlib/_backport/shutil.py
def make_archive(base_name, format, root_dir=None, base_dir=None, verbose=0, dry_run=0, owner=None, group=None, logger=None): """Create an archive file (eg. zip or tar). 'base_name' is the name of the file to create, minus any format-specific extension; 'format' is the archive format: one of "zip", "tar", "bztar" or "gztar". 'root_dir' is a directory that will be the root directory of the archive; ie. we typically chdir into 'root_dir' before creating the archive. 'base_dir' is the directory where we start archiving from; ie. 'base_dir' will be the common prefix of all files and directories in the archive. 'root_dir' and 'base_dir' both default to the current directory. Returns the name of the archive file. 'owner' and 'group' are used when creating a tar archive. By default, uses the current owner and group. """ save_cwd = os.getcwd() if root_dir is not None: if logger is not None: logger.debug("changing into '%s'", root_dir) base_name = os.path.abspath(base_name) if not dry_run: os.chdir(root_dir) if base_dir is None: base_dir = os.curdir kwargs = {'dry_run': dry_run, 'logger': logger} try: format_info = _ARCHIVE_FORMATS[format] except KeyError: raise ValueError("unknown archive format '%s'" % format) func = format_info[0] for arg, val in format_info[1]: kwargs[arg] = val if format != 'zip': kwargs['owner'] = owner kwargs['group'] = group try: filename = func(base_name, base_dir, **kwargs) finally: if root_dir is not None: if logger is not None: logger.debug("changing back to '%s'", save_cwd) os.chdir(save_cwd) return filename
def make_archive(base_name, format, root_dir=None, base_dir=None, verbose=0, dry_run=0, owner=None, group=None, logger=None): """Create an archive file (eg. zip or tar). 'base_name' is the name of the file to create, minus any format-specific extension; 'format' is the archive format: one of "zip", "tar", "bztar" or "gztar". 'root_dir' is a directory that will be the root directory of the archive; ie. we typically chdir into 'root_dir' before creating the archive. 'base_dir' is the directory where we start archiving from; ie. 'base_dir' will be the common prefix of all files and directories in the archive. 'root_dir' and 'base_dir' both default to the current directory. Returns the name of the archive file. 'owner' and 'group' are used when creating a tar archive. By default, uses the current owner and group. """ save_cwd = os.getcwd() if root_dir is not None: if logger is not None: logger.debug("changing into '%s'", root_dir) base_name = os.path.abspath(base_name) if not dry_run: os.chdir(root_dir) if base_dir is None: base_dir = os.curdir kwargs = {'dry_run': dry_run, 'logger': logger} try: format_info = _ARCHIVE_FORMATS[format] except KeyError: raise ValueError("unknown archive format '%s'" % format) func = format_info[0] for arg, val in format_info[1]: kwargs[arg] = val if format != 'zip': kwargs['owner'] = owner kwargs['group'] = group try: filename = func(base_name, base_dir, **kwargs) finally: if root_dir is not None: if logger is not None: logger.debug("changing back to '%s'", save_cwd) os.chdir(save_cwd) return filename
[ "Create", "an", "archive", "file", "(", "eg", ".", "zip", "or", "tar", ")", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/shutil.py#L544-L596
[ "def", "make_archive", "(", "base_name", ",", "format", ",", "root_dir", "=", "None", ",", "base_dir", "=", "None", ",", "verbose", "=", "0", ",", "dry_run", "=", "0", ",", "owner", "=", "None", ",", "group", "=", "None", ",", "logger", "=", "None", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
get_unpack_formats
Returns a list of supported formats for unpacking. Each element of the returned sequence is a tuple (name, extensions, description)
pipenv/vendor/distlib/_backport/shutil.py
def get_unpack_formats(): """Returns a list of supported formats for unpacking. Each element of the returned sequence is a tuple (name, extensions, description) """ formats = [(name, info[0], info[3]) for name, info in _UNPACK_FORMATS.items()] formats.sort() return formats
def get_unpack_formats(): """Returns a list of supported formats for unpacking. Each element of the returned sequence is a tuple (name, extensions, description) """ formats = [(name, info[0], info[3]) for name, info in _UNPACK_FORMATS.items()] formats.sort() return formats
[ "Returns", "a", "list", "of", "supported", "formats", "for", "unpacking", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/shutil.py#L599-L608
[ "def", "get_unpack_formats", "(", ")", ":", "formats", "=", "[", "(", "name", ",", "info", "[", "0", "]", ",", "info", "[", "3", "]", ")", "for", "name", ",", "info", "in", "_UNPACK_FORMATS", ".", "items", "(", ")", "]", "formats", ".", "sort", "...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_check_unpack_options
Checks what gets registered as an unpacker.
pipenv/vendor/distlib/_backport/shutil.py
def _check_unpack_options(extensions, function, extra_args): """Checks what gets registered as an unpacker.""" # first make sure no other unpacker is registered for this extension existing_extensions = {} for name, info in _UNPACK_FORMATS.items(): for ext in info[0]: existing_extensions[ext] = name for extension in extensions: if extension in existing_extensions: msg = '%s is already registered for "%s"' raise RegistryError(msg % (extension, existing_extensions[extension])) if not isinstance(function, collections.Callable): raise TypeError('The registered function must be a callable')
def _check_unpack_options(extensions, function, extra_args): """Checks what gets registered as an unpacker.""" # first make sure no other unpacker is registered for this extension existing_extensions = {} for name, info in _UNPACK_FORMATS.items(): for ext in info[0]: existing_extensions[ext] = name for extension in extensions: if extension in existing_extensions: msg = '%s is already registered for "%s"' raise RegistryError(msg % (extension, existing_extensions[extension])) if not isinstance(function, collections.Callable): raise TypeError('The registered function must be a callable')
[ "Checks", "what", "gets", "registered", "as", "an", "unpacker", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/shutil.py#L610-L625
[ "def", "_check_unpack_options", "(", "extensions", ",", "function", ",", "extra_args", ")", ":", "# first make sure no other unpacker is registered for this extension", "existing_extensions", "=", "{", "}", "for", "name", ",", "info", "in", "_UNPACK_FORMATS", ".", "items"...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
register_unpack_format
Registers an unpack format. `name` is the name of the format. `extensions` is a list of extensions corresponding to the format. `function` is the callable that will be used to unpack archives. The callable will receive archives to unpack. If it's unable to handle an archive, it needs to raise a ReadError exception. If provided, `extra_args` is a sequence of (name, value) tuples that will be passed as arguments to the callable. description can be provided to describe the format, and will be returned by the get_unpack_formats() function.
pipenv/vendor/distlib/_backport/shutil.py
def register_unpack_format(name, extensions, function, extra_args=None, description=''): """Registers an unpack format. `name` is the name of the format. `extensions` is a list of extensions corresponding to the format. `function` is the callable that will be used to unpack archives. The callable will receive archives to unpack. If it's unable to handle an archive, it needs to raise a ReadError exception. If provided, `extra_args` is a sequence of (name, value) tuples that will be passed as arguments to the callable. description can be provided to describe the format, and will be returned by the get_unpack_formats() function. """ if extra_args is None: extra_args = [] _check_unpack_options(extensions, function, extra_args) _UNPACK_FORMATS[name] = extensions, function, extra_args, description
def register_unpack_format(name, extensions, function, extra_args=None, description=''): """Registers an unpack format. `name` is the name of the format. `extensions` is a list of extensions corresponding to the format. `function` is the callable that will be used to unpack archives. The callable will receive archives to unpack. If it's unable to handle an archive, it needs to raise a ReadError exception. If provided, `extra_args` is a sequence of (name, value) tuples that will be passed as arguments to the callable. description can be provided to describe the format, and will be returned by the get_unpack_formats() function. """ if extra_args is None: extra_args = [] _check_unpack_options(extensions, function, extra_args) _UNPACK_FORMATS[name] = extensions, function, extra_args, description
[ "Registers", "an", "unpack", "format", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/shutil.py#L628-L648
[ "def", "register_unpack_format", "(", "name", ",", "extensions", ",", "function", ",", "extra_args", "=", "None", ",", "description", "=", "''", ")", ":", "if", "extra_args", "is", "None", ":", "extra_args", "=", "[", "]", "_check_unpack_options", "(", "exte...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_ensure_directory
Ensure that the parent directory of `path` exists
pipenv/vendor/distlib/_backport/shutil.py
def _ensure_directory(path): """Ensure that the parent directory of `path` exists""" dirname = os.path.dirname(path) if not os.path.isdir(dirname): os.makedirs(dirname)
def _ensure_directory(path): """Ensure that the parent directory of `path` exists""" dirname = os.path.dirname(path) if not os.path.isdir(dirname): os.makedirs(dirname)
[ "Ensure", "that", "the", "parent", "directory", "of", "path", "exists" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/shutil.py#L654-L658
[ "def", "_ensure_directory", "(", "path", ")", ":", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "path", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "dirname", ")", ":", "os", ".", "makedirs", "(", "dirname", ")" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_unpack_zipfile
Unpack zip `filename` to `extract_dir`
pipenv/vendor/distlib/_backport/shutil.py
def _unpack_zipfile(filename, extract_dir): """Unpack zip `filename` to `extract_dir` """ try: import zipfile except ImportError: raise ReadError('zlib not supported, cannot unpack this archive.') if not zipfile.is_zipfile(filename): raise ReadError("%s is not a zip file" % filename) zip = zipfile.ZipFile(filename) try: for info in zip.infolist(): name = info.filename # don't extract absolute paths or ones with .. in them if name.startswith('/') or '..' in name: continue target = os.path.join(extract_dir, *name.split('/')) if not target: continue _ensure_directory(target) if not name.endswith('/'): # file data = zip.read(info.filename) f = open(target, 'wb') try: f.write(data) finally: f.close() del data finally: zip.close()
def _unpack_zipfile(filename, extract_dir): """Unpack zip `filename` to `extract_dir` """ try: import zipfile except ImportError: raise ReadError('zlib not supported, cannot unpack this archive.') if not zipfile.is_zipfile(filename): raise ReadError("%s is not a zip file" % filename) zip = zipfile.ZipFile(filename) try: for info in zip.infolist(): name = info.filename # don't extract absolute paths or ones with .. in them if name.startswith('/') or '..' in name: continue target = os.path.join(extract_dir, *name.split('/')) if not target: continue _ensure_directory(target) if not name.endswith('/'): # file data = zip.read(info.filename) f = open(target, 'wb') try: f.write(data) finally: f.close() del data finally: zip.close()
[ "Unpack", "zip", "filename", "to", "extract_dir" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/shutil.py#L660-L695
[ "def", "_unpack_zipfile", "(", "filename", ",", "extract_dir", ")", ":", "try", ":", "import", "zipfile", "except", "ImportError", ":", "raise", "ReadError", "(", "'zlib not supported, cannot unpack this archive.'", ")", "if", "not", "zipfile", ".", "is_zipfile", "(...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_unpack_tarfile
Unpack tar/tar.gz/tar.bz2 `filename` to `extract_dir`
pipenv/vendor/distlib/_backport/shutil.py
def _unpack_tarfile(filename, extract_dir): """Unpack tar/tar.gz/tar.bz2 `filename` to `extract_dir` """ try: tarobj = tarfile.open(filename) except tarfile.TarError: raise ReadError( "%s is not a compressed or uncompressed tar file" % filename) try: tarobj.extractall(extract_dir) finally: tarobj.close()
def _unpack_tarfile(filename, extract_dir): """Unpack tar/tar.gz/tar.bz2 `filename` to `extract_dir` """ try: tarobj = tarfile.open(filename) except tarfile.TarError: raise ReadError( "%s is not a compressed or uncompressed tar file" % filename) try: tarobj.extractall(extract_dir) finally: tarobj.close()
[ "Unpack", "tar", "/", "tar", ".", "gz", "/", "tar", ".", "bz2", "filename", "to", "extract_dir" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/shutil.py#L697-L708
[ "def", "_unpack_tarfile", "(", "filename", ",", "extract_dir", ")", ":", "try", ":", "tarobj", "=", "tarfile", ".", "open", "(", "filename", ")", "except", "tarfile", ".", "TarError", ":", "raise", "ReadError", "(", "\"%s is not a compressed or uncompressed tar fi...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
unpack_archive
Unpack an archive. `filename` is the name of the archive. `extract_dir` is the name of the target directory, where the archive is unpacked. If not provided, the current working directory is used. `format` is the archive format: one of "zip", "tar", or "gztar". Or any other registered format. If not provided, unpack_archive will use the filename extension and see if an unpacker was registered for that extension. In case none is found, a ValueError is raised.
pipenv/vendor/distlib/_backport/shutil.py
def unpack_archive(filename, extract_dir=None, format=None): """Unpack an archive. `filename` is the name of the archive. `extract_dir` is the name of the target directory, where the archive is unpacked. If not provided, the current working directory is used. `format` is the archive format: one of "zip", "tar", or "gztar". Or any other registered format. If not provided, unpack_archive will use the filename extension and see if an unpacker was registered for that extension. In case none is found, a ValueError is raised. """ if extract_dir is None: extract_dir = os.getcwd() if format is not None: try: format_info = _UNPACK_FORMATS[format] except KeyError: raise ValueError("Unknown unpack format '{0}'".format(format)) func = format_info[1] func(filename, extract_dir, **dict(format_info[2])) else: # we need to look at the registered unpackers supported extensions format = _find_unpack_format(filename) if format is None: raise ReadError("Unknown archive format '{0}'".format(filename)) func = _UNPACK_FORMATS[format][1] kwargs = dict(_UNPACK_FORMATS[format][2]) func(filename, extract_dir, **kwargs)
def unpack_archive(filename, extract_dir=None, format=None): """Unpack an archive. `filename` is the name of the archive. `extract_dir` is the name of the target directory, where the archive is unpacked. If not provided, the current working directory is used. `format` is the archive format: one of "zip", "tar", or "gztar". Or any other registered format. If not provided, unpack_archive will use the filename extension and see if an unpacker was registered for that extension. In case none is found, a ValueError is raised. """ if extract_dir is None: extract_dir = os.getcwd() if format is not None: try: format_info = _UNPACK_FORMATS[format] except KeyError: raise ValueError("Unknown unpack format '{0}'".format(format)) func = format_info[1] func(filename, extract_dir, **dict(format_info[2])) else: # we need to look at the registered unpackers supported extensions format = _find_unpack_format(filename) if format is None: raise ReadError("Unknown archive format '{0}'".format(filename)) func = _UNPACK_FORMATS[format][1] kwargs = dict(_UNPACK_FORMATS[format][2]) func(filename, extract_dir, **kwargs)
[ "Unpack", "an", "archive", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/shutil.py#L727-L761
[ "def", "unpack_archive", "(", "filename", ",", "extract_dir", "=", "None", ",", "format", "=", "None", ")", ":", "if", "extract_dir", "is", "None", ":", "extract_dir", "=", "os", ".", "getcwd", "(", ")", "if", "format", "is", "not", "None", ":", "try",...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
parseFragment
Parse an HTML fragment as a string or file-like object into a tree :arg doc: the fragment to parse as a string or file-like object :arg container: the container context to parse the fragment in :arg treebuilder: the treebuilder to use when parsing :arg namespaceHTMLElements: whether or not to namespace HTML elements :returns: parsed tree Example: >>> from html5lib.html5libparser import parseFragment >>> parseFragment('<b>this is a fragment</b>') <Element u'DOCUMENT_FRAGMENT' at 0x7feac484b090>
pipenv/patched/notpip/_vendor/html5lib/html5parser.py
def parseFragment(doc, container="div", treebuilder="etree", namespaceHTMLElements=True, **kwargs): """Parse an HTML fragment as a string or file-like object into a tree :arg doc: the fragment to parse as a string or file-like object :arg container: the container context to parse the fragment in :arg treebuilder: the treebuilder to use when parsing :arg namespaceHTMLElements: whether or not to namespace HTML elements :returns: parsed tree Example: >>> from html5lib.html5libparser import parseFragment >>> parseFragment('<b>this is a fragment</b>') <Element u'DOCUMENT_FRAGMENT' at 0x7feac484b090> """ tb = treebuilders.getTreeBuilder(treebuilder) p = HTMLParser(tb, namespaceHTMLElements=namespaceHTMLElements) return p.parseFragment(doc, container=container, **kwargs)
def parseFragment(doc, container="div", treebuilder="etree", namespaceHTMLElements=True, **kwargs): """Parse an HTML fragment as a string or file-like object into a tree :arg doc: the fragment to parse as a string or file-like object :arg container: the container context to parse the fragment in :arg treebuilder: the treebuilder to use when parsing :arg namespaceHTMLElements: whether or not to namespace HTML elements :returns: parsed tree Example: >>> from html5lib.html5libparser import parseFragment >>> parseFragment('<b>this is a fragment</b>') <Element u'DOCUMENT_FRAGMENT' at 0x7feac484b090> """ tb = treebuilders.getTreeBuilder(treebuilder) p = HTMLParser(tb, namespaceHTMLElements=namespaceHTMLElements) return p.parseFragment(doc, container=container, **kwargs)
[ "Parse", "an", "HTML", "fragment", "as", "a", "string", "or", "file", "-", "like", "object", "into", "a", "tree" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/html5lib/html5parser.py#L50-L72
[ "def", "parseFragment", "(", "doc", ",", "container", "=", "\"div\"", ",", "treebuilder", "=", "\"etree\"", ",", "namespaceHTMLElements", "=", "True", ",", "*", "*", "kwargs", ")", ":", "tb", "=", "treebuilders", ".", "getTreeBuilder", "(", "treebuilder", ")...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
HTMLParser.parse
Parse a HTML document into a well-formed tree :arg stream: a file-like object or string containing the HTML to be parsed The optional encoding parameter must be a string that indicates the encoding. If specified, that encoding will be used, regardless of any BOM or later declaration (such as in a meta element). :arg scripting: treat noscript elements as if JavaScript was turned on :returns: parsed tree Example: >>> from html5lib.html5parser import HTMLParser >>> parser = HTMLParser() >>> parser.parse('<html><body><p>This is a doc</p></body></html>') <Element u'{http://www.w3.org/1999/xhtml}html' at 0x7feac4909db0>
pipenv/patched/notpip/_vendor/html5lib/html5parser.py
def parse(self, stream, *args, **kwargs): """Parse a HTML document into a well-formed tree :arg stream: a file-like object or string containing the HTML to be parsed The optional encoding parameter must be a string that indicates the encoding. If specified, that encoding will be used, regardless of any BOM or later declaration (such as in a meta element). :arg scripting: treat noscript elements as if JavaScript was turned on :returns: parsed tree Example: >>> from html5lib.html5parser import HTMLParser >>> parser = HTMLParser() >>> parser.parse('<html><body><p>This is a doc</p></body></html>') <Element u'{http://www.w3.org/1999/xhtml}html' at 0x7feac4909db0> """ self._parse(stream, False, None, *args, **kwargs) return self.tree.getDocument()
def parse(self, stream, *args, **kwargs): """Parse a HTML document into a well-formed tree :arg stream: a file-like object or string containing the HTML to be parsed The optional encoding parameter must be a string that indicates the encoding. If specified, that encoding will be used, regardless of any BOM or later declaration (such as in a meta element). :arg scripting: treat noscript elements as if JavaScript was turned on :returns: parsed tree Example: >>> from html5lib.html5parser import HTMLParser >>> parser = HTMLParser() >>> parser.parse('<html><body><p>This is a doc</p></body></html>') <Element u'{http://www.w3.org/1999/xhtml}html' at 0x7feac4909db0> """ self._parse(stream, False, None, *args, **kwargs) return self.tree.getDocument()
[ "Parse", "a", "HTML", "document", "into", "a", "well", "-", "formed", "tree" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/html5lib/html5parser.py#L267-L290
[ "def", "parse", "(", "self", ",", "stream", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_parse", "(", "stream", ",", "False", ",", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "self", ".", "tree", "."...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
HTMLParser.parseFragment
Parse a HTML fragment into a well-formed tree fragment :arg container: name of the element we're setting the innerHTML property if set to None, default to 'div' :arg stream: a file-like object or string containing the HTML to be parsed The optional encoding parameter must be a string that indicates the encoding. If specified, that encoding will be used, regardless of any BOM or later declaration (such as in a meta element) :arg scripting: treat noscript elements as if JavaScript was turned on :returns: parsed tree Example: >>> from html5lib.html5libparser import HTMLParser >>> parser = HTMLParser() >>> parser.parseFragment('<b>this is a fragment</b>') <Element u'DOCUMENT_FRAGMENT' at 0x7feac484b090>
pipenv/patched/notpip/_vendor/html5lib/html5parser.py
def parseFragment(self, stream, *args, **kwargs): """Parse a HTML fragment into a well-formed tree fragment :arg container: name of the element we're setting the innerHTML property if set to None, default to 'div' :arg stream: a file-like object or string containing the HTML to be parsed The optional encoding parameter must be a string that indicates the encoding. If specified, that encoding will be used, regardless of any BOM or later declaration (such as in a meta element) :arg scripting: treat noscript elements as if JavaScript was turned on :returns: parsed tree Example: >>> from html5lib.html5libparser import HTMLParser >>> parser = HTMLParser() >>> parser.parseFragment('<b>this is a fragment</b>') <Element u'DOCUMENT_FRAGMENT' at 0x7feac484b090> """ self._parse(stream, True, *args, **kwargs) return self.tree.getFragment()
def parseFragment(self, stream, *args, **kwargs): """Parse a HTML fragment into a well-formed tree fragment :arg container: name of the element we're setting the innerHTML property if set to None, default to 'div' :arg stream: a file-like object or string containing the HTML to be parsed The optional encoding parameter must be a string that indicates the encoding. If specified, that encoding will be used, regardless of any BOM or later declaration (such as in a meta element) :arg scripting: treat noscript elements as if JavaScript was turned on :returns: parsed tree Example: >>> from html5lib.html5libparser import HTMLParser >>> parser = HTMLParser() >>> parser.parseFragment('<b>this is a fragment</b>') <Element u'DOCUMENT_FRAGMENT' at 0x7feac484b090> """ self._parse(stream, True, *args, **kwargs) return self.tree.getFragment()
[ "Parse", "a", "HTML", "fragment", "into", "a", "well", "-", "formed", "tree", "fragment" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/html5lib/html5parser.py#L292-L318
[ "def", "parseFragment", "(", "self", ",", "stream", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_parse", "(", "stream", ",", "True", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "self", ".", "tree", ".", "getFr...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
construct_tree
Construct tree representation of the pkgs from the index. The keys of the dict representing the tree will be objects of type DistPackage and the values will be list of ReqPackage objects. :param dict index: dist index ie. index of pkgs by their keys :returns: tree of pkgs and their dependencies :rtype: dict
pipenv/vendor/pipdeptree.py
def construct_tree(index): """Construct tree representation of the pkgs from the index. The keys of the dict representing the tree will be objects of type DistPackage and the values will be list of ReqPackage objects. :param dict index: dist index ie. index of pkgs by their keys :returns: tree of pkgs and their dependencies :rtype: dict """ return dict((p, [ReqPackage(r, index.get(r.key)) for r in p.requires()]) for p in index.values())
def construct_tree(index): """Construct tree representation of the pkgs from the index. The keys of the dict representing the tree will be objects of type DistPackage and the values will be list of ReqPackage objects. :param dict index: dist index ie. index of pkgs by their keys :returns: tree of pkgs and their dependencies :rtype: dict """ return dict((p, [ReqPackage(r, index.get(r.key)) for r in p.requires()]) for p in index.values())
[ "Construct", "tree", "representation", "of", "the", "pkgs", "from", "the", "index", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pipdeptree.py#L42-L55
[ "def", "construct_tree", "(", "index", ")", ":", "return", "dict", "(", "(", "p", ",", "[", "ReqPackage", "(", "r", ",", "index", ".", "get", "(", "r", ".", "key", ")", ")", "for", "r", "in", "p", ".", "requires", "(", ")", "]", ")", "for", "...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
sorted_tree
Sorts the dict representation of the tree The root packages as well as the intermediate packages are sorted in the alphabetical order of the package names. :param dict tree: the pkg dependency tree obtained by calling `construct_tree` function :returns: sorted tree :rtype: collections.OrderedDict
pipenv/vendor/pipdeptree.py
def sorted_tree(tree): """Sorts the dict representation of the tree The root packages as well as the intermediate packages are sorted in the alphabetical order of the package names. :param dict tree: the pkg dependency tree obtained by calling `construct_tree` function :returns: sorted tree :rtype: collections.OrderedDict """ return OrderedDict(sorted([(k, sorted(v, key=attrgetter('key'))) for k, v in tree.items()], key=lambda kv: kv[0].key))
def sorted_tree(tree): """Sorts the dict representation of the tree The root packages as well as the intermediate packages are sorted in the alphabetical order of the package names. :param dict tree: the pkg dependency tree obtained by calling `construct_tree` function :returns: sorted tree :rtype: collections.OrderedDict """ return OrderedDict(sorted([(k, sorted(v, key=attrgetter('key'))) for k, v in tree.items()], key=lambda kv: kv[0].key))
[ "Sorts", "the", "dict", "representation", "of", "the", "tree" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pipdeptree.py#L58-L72
[ "def", "sorted_tree", "(", "tree", ")", ":", "return", "OrderedDict", "(", "sorted", "(", "[", "(", "k", ",", "sorted", "(", "v", ",", "key", "=", "attrgetter", "(", "'key'", ")", ")", ")", "for", "k", ",", "v", "in", "tree", ".", "items", "(", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
find_tree_root
Find a root in a tree by it's key :param dict tree: the pkg dependency tree obtained by calling `construct_tree` function :param str key: key of the root node to find :returns: a root node if found else None :rtype: mixed
pipenv/vendor/pipdeptree.py
def find_tree_root(tree, key): """Find a root in a tree by it's key :param dict tree: the pkg dependency tree obtained by calling `construct_tree` function :param str key: key of the root node to find :returns: a root node if found else None :rtype: mixed """ result = [p for p in tree.keys() if p.key == key] assert len(result) in [0, 1] return None if len(result) == 0 else result[0]
def find_tree_root(tree, key): """Find a root in a tree by it's key :param dict tree: the pkg dependency tree obtained by calling `construct_tree` function :param str key: key of the root node to find :returns: a root node if found else None :rtype: mixed """ result = [p for p in tree.keys() if p.key == key] assert len(result) in [0, 1] return None if len(result) == 0 else result[0]
[ "Find", "a", "root", "in", "a", "tree", "by", "it", "s", "key" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pipdeptree.py#L75-L87
[ "def", "find_tree_root", "(", "tree", ",", "key", ")", ":", "result", "=", "[", "p", "for", "p", "in", "tree", ".", "keys", "(", ")", "if", "p", ".", "key", "==", "key", "]", "assert", "len", "(", "result", ")", "in", "[", "0", ",", "1", "]",...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
reverse_tree
Reverse the dependency tree. ie. the keys of the resulting dict are objects of type ReqPackage and the values are lists of DistPackage objects. :param dict tree: the pkg dependency tree obtained by calling `construct_tree` function :returns: reversed tree :rtype: dict
pipenv/vendor/pipdeptree.py
def reverse_tree(tree): """Reverse the dependency tree. ie. the keys of the resulting dict are objects of type ReqPackage and the values are lists of DistPackage objects. :param dict tree: the pkg dependency tree obtained by calling `construct_tree` function :returns: reversed tree :rtype: dict """ rtree = defaultdict(list) child_keys = set(c.key for c in flatten(tree.values())) for k, vs in tree.items(): for v in vs: node = find_tree_root(rtree, v.key) or v rtree[node].append(k.as_required_by(v)) if k.key not in child_keys: rtree[k.as_requirement()] = [] return rtree
def reverse_tree(tree): """Reverse the dependency tree. ie. the keys of the resulting dict are objects of type ReqPackage and the values are lists of DistPackage objects. :param dict tree: the pkg dependency tree obtained by calling `construct_tree` function :returns: reversed tree :rtype: dict """ rtree = defaultdict(list) child_keys = set(c.key for c in flatten(tree.values())) for k, vs in tree.items(): for v in vs: node = find_tree_root(rtree, v.key) or v rtree[node].append(k.as_required_by(v)) if k.key not in child_keys: rtree[k.as_requirement()] = [] return rtree
[ "Reverse", "the", "dependency", "tree", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pipdeptree.py#L90-L110
[ "def", "reverse_tree", "(", "tree", ")", ":", "rtree", "=", "defaultdict", "(", "list", ")", "child_keys", "=", "set", "(", "c", ".", "key", "for", "c", "in", "flatten", "(", "tree", ".", "values", "(", ")", ")", ")", "for", "k", ",", "vs", "in",...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
guess_version
Guess the version of a pkg when pip doesn't provide it :param str pkg_key: key of the package :param str default: default version to return if unable to find :returns: version :rtype: string
pipenv/vendor/pipdeptree.py
def guess_version(pkg_key, default='?'): """Guess the version of a pkg when pip doesn't provide it :param str pkg_key: key of the package :param str default: default version to return if unable to find :returns: version :rtype: string """ try: m = import_module(pkg_key) except ImportError: return default else: return getattr(m, '__version__', default)
def guess_version(pkg_key, default='?'): """Guess the version of a pkg when pip doesn't provide it :param str pkg_key: key of the package :param str default: default version to return if unable to find :returns: version :rtype: string """ try: m = import_module(pkg_key) except ImportError: return default else: return getattr(m, '__version__', default)
[ "Guess", "the", "version", "of", "a", "pkg", "when", "pip", "doesn", "t", "provide", "it" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pipdeptree.py#L113-L127
[ "def", "guess_version", "(", "pkg_key", ",", "default", "=", "'?'", ")", ":", "try", ":", "m", "=", "import_module", "(", "pkg_key", ")", "except", "ImportError", ":", "return", "default", "else", ":", "return", "getattr", "(", "m", ",", "'__version__'", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
render_tree
Convert tree to string representation :param dict tree: the package tree :param bool list_all: whether to list all the pgks at the root level or only those that are the sub-dependencies :param set show_only: set of select packages to be shown in the output. This is optional arg, default: None. :param bool frozen: whether or not show the names of the pkgs in the output that's favourable to pip --freeze :param set exclude: set of select packages to be excluded from the output. This is optional arg, default: None. :returns: string representation of the tree :rtype: str
pipenv/vendor/pipdeptree.py
def render_tree(tree, list_all=True, show_only=None, frozen=False, exclude=None): """Convert tree to string representation :param dict tree: the package tree :param bool list_all: whether to list all the pgks at the root level or only those that are the sub-dependencies :param set show_only: set of select packages to be shown in the output. This is optional arg, default: None. :param bool frozen: whether or not show the names of the pkgs in the output that's favourable to pip --freeze :param set exclude: set of select packages to be excluded from the output. This is optional arg, default: None. :returns: string representation of the tree :rtype: str """ tree = sorted_tree(tree) branch_keys = set(r.key for r in flatten(tree.values())) nodes = tree.keys() use_bullets = not frozen key_tree = dict((k.key, v) for k, v in tree.items()) get_children = lambda n: key_tree.get(n.key, []) if show_only: nodes = [p for p in nodes if p.key in show_only or p.project_name in show_only] elif not list_all: nodes = [p for p in nodes if p.key not in branch_keys] def aux(node, parent=None, indent=0, chain=None): if exclude and (node.key in exclude or node.project_name in exclude): return [] if chain is None: chain = [node.project_name] node_str = node.render(parent, frozen) if parent: prefix = ' '*indent + ('- ' if use_bullets else '') node_str = prefix + node_str result = [node_str] children = [aux(c, node, indent=indent+2, chain=chain+[c.project_name]) for c in get_children(node) if c.project_name not in chain] result += list(flatten(children)) return result lines = flatten([aux(p) for p in nodes]) return '\n'.join(lines)
def render_tree(tree, list_all=True, show_only=None, frozen=False, exclude=None): """Convert tree to string representation :param dict tree: the package tree :param bool list_all: whether to list all the pgks at the root level or only those that are the sub-dependencies :param set show_only: set of select packages to be shown in the output. This is optional arg, default: None. :param bool frozen: whether or not show the names of the pkgs in the output that's favourable to pip --freeze :param set exclude: set of select packages to be excluded from the output. This is optional arg, default: None. :returns: string representation of the tree :rtype: str """ tree = sorted_tree(tree) branch_keys = set(r.key for r in flatten(tree.values())) nodes = tree.keys() use_bullets = not frozen key_tree = dict((k.key, v) for k, v in tree.items()) get_children = lambda n: key_tree.get(n.key, []) if show_only: nodes = [p for p in nodes if p.key in show_only or p.project_name in show_only] elif not list_all: nodes = [p for p in nodes if p.key not in branch_keys] def aux(node, parent=None, indent=0, chain=None): if exclude and (node.key in exclude or node.project_name in exclude): return [] if chain is None: chain = [node.project_name] node_str = node.render(parent, frozen) if parent: prefix = ' '*indent + ('- ' if use_bullets else '') node_str = prefix + node_str result = [node_str] children = [aux(c, node, indent=indent+2, chain=chain+[c.project_name]) for c in get_children(node) if c.project_name not in chain] result += list(flatten(children)) return result lines = flatten([aux(p) for p in nodes]) return '\n'.join(lines)
[ "Convert", "tree", "to", "string", "representation" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pipdeptree.py#L288-L337
[ "def", "render_tree", "(", "tree", ",", "list_all", "=", "True", ",", "show_only", "=", "None", ",", "frozen", "=", "False", ",", "exclude", "=", "None", ")", ":", "tree", "=", "sorted_tree", "(", "tree", ")", "branch_keys", "=", "set", "(", "r", "."...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
render_json
Converts the tree into a flat json representation. The json repr will be a list of hashes, each hash having 2 fields: - package - dependencies: list of dependencies :param dict tree: dependency tree :param int indent: no. of spaces to indent json :returns: json representation of the tree :rtype: str
pipenv/vendor/pipdeptree.py
def render_json(tree, indent): """Converts the tree into a flat json representation. The json repr will be a list of hashes, each hash having 2 fields: - package - dependencies: list of dependencies :param dict tree: dependency tree :param int indent: no. of spaces to indent json :returns: json representation of the tree :rtype: str """ return json.dumps([{'package': k.as_dict(), 'dependencies': [v.as_dict() for v in vs]} for k, vs in tree.items()], indent=indent)
def render_json(tree, indent): """Converts the tree into a flat json representation. The json repr will be a list of hashes, each hash having 2 fields: - package - dependencies: list of dependencies :param dict tree: dependency tree :param int indent: no. of spaces to indent json :returns: json representation of the tree :rtype: str """ return json.dumps([{'package': k.as_dict(), 'dependencies': [v.as_dict() for v in vs]} for k, vs in tree.items()], indent=indent)
[ "Converts", "the", "tree", "into", "a", "flat", "json", "representation", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pipdeptree.py#L340-L356
[ "def", "render_json", "(", "tree", ",", "indent", ")", ":", "return", "json", ".", "dumps", "(", "[", "{", "'package'", ":", "k", ".", "as_dict", "(", ")", ",", "'dependencies'", ":", "[", "v", ".", "as_dict", "(", ")", "for", "v", "in", "vs", "]...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
render_json_tree
Converts the tree into a nested json representation. The json repr will be a list of hashes, each hash having the following fields: - package_name - key - required_version - installed_version - dependencies: list of dependencies :param dict tree: dependency tree :param int indent: no. of spaces to indent json :returns: json representation of the tree :rtype: str
pipenv/vendor/pipdeptree.py
def render_json_tree(tree, indent): """Converts the tree into a nested json representation. The json repr will be a list of hashes, each hash having the following fields: - package_name - key - required_version - installed_version - dependencies: list of dependencies :param dict tree: dependency tree :param int indent: no. of spaces to indent json :returns: json representation of the tree :rtype: str """ tree = sorted_tree(tree) branch_keys = set(r.key for r in flatten(tree.values())) nodes = [p for p in tree.keys() if p.key not in branch_keys] key_tree = dict((k.key, v) for k, v in tree.items()) get_children = lambda n: key_tree.get(n.key, []) def aux(node, parent=None, chain=None): if chain is None: chain = [node.project_name] d = node.as_dict() if parent: d['required_version'] = node.version_spec if node.version_spec else 'Any' else: d['required_version'] = d['installed_version'] d['dependencies'] = [ aux(c, parent=node, chain=chain+[c.project_name]) for c in get_children(node) if c.project_name not in chain ] return d return json.dumps([aux(p) for p in nodes], indent=indent)
def render_json_tree(tree, indent): """Converts the tree into a nested json representation. The json repr will be a list of hashes, each hash having the following fields: - package_name - key - required_version - installed_version - dependencies: list of dependencies :param dict tree: dependency tree :param int indent: no. of spaces to indent json :returns: json representation of the tree :rtype: str """ tree = sorted_tree(tree) branch_keys = set(r.key for r in flatten(tree.values())) nodes = [p for p in tree.keys() if p.key not in branch_keys] key_tree = dict((k.key, v) for k, v in tree.items()) get_children = lambda n: key_tree.get(n.key, []) def aux(node, parent=None, chain=None): if chain is None: chain = [node.project_name] d = node.as_dict() if parent: d['required_version'] = node.version_spec if node.version_spec else 'Any' else: d['required_version'] = d['installed_version'] d['dependencies'] = [ aux(c, parent=node, chain=chain+[c.project_name]) for c in get_children(node) if c.project_name not in chain ] return d return json.dumps([aux(p) for p in nodes], indent=indent)
[ "Converts", "the", "tree", "into", "a", "nested", "json", "representation", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pipdeptree.py#L359-L399
[ "def", "render_json_tree", "(", "tree", ",", "indent", ")", ":", "tree", "=", "sorted_tree", "(", "tree", ")", "branch_keys", "=", "set", "(", "r", ".", "key", "for", "r", "in", "flatten", "(", "tree", ".", "values", "(", ")", ")", ")", "nodes", "=...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
dump_graphviz
Output dependency graph as one of the supported GraphViz output formats. :param dict tree: dependency graph :param string output_format: output format :returns: representation of tree in the specified output format :rtype: str or binary representation depending on the output format
pipenv/vendor/pipdeptree.py
def dump_graphviz(tree, output_format='dot'): """Output dependency graph as one of the supported GraphViz output formats. :param dict tree: dependency graph :param string output_format: output format :returns: representation of tree in the specified output format :rtype: str or binary representation depending on the output format """ try: from graphviz import backend, Digraph except ImportError: print('graphviz is not available, but necessary for the output ' 'option. Please install it.', file=sys.stderr) sys.exit(1) if output_format not in backend.FORMATS: print('{0} is not a supported output format.'.format(output_format), file=sys.stderr) print('Supported formats are: {0}'.format( ', '.join(sorted(backend.FORMATS))), file=sys.stderr) sys.exit(1) graph = Digraph(format=output_format) for package, deps in tree.items(): project_name = package.project_name label = '{0}\n{1}'.format(project_name, package.version) graph.node(project_name, label=label) for dep in deps: label = dep.version_spec if not label: label = 'any' graph.edge(project_name, dep.project_name, label=label) # Allow output of dot format, even if GraphViz isn't installed. if output_format == 'dot': return graph.source # As it's unknown if the selected output format is binary or not, try to # decode it as UTF8 and only print it out in binary if that's not possible. try: return graph.pipe().decode('utf-8') except UnicodeDecodeError: return graph.pipe()
def dump_graphviz(tree, output_format='dot'): """Output dependency graph as one of the supported GraphViz output formats. :param dict tree: dependency graph :param string output_format: output format :returns: representation of tree in the specified output format :rtype: str or binary representation depending on the output format """ try: from graphviz import backend, Digraph except ImportError: print('graphviz is not available, but necessary for the output ' 'option. Please install it.', file=sys.stderr) sys.exit(1) if output_format not in backend.FORMATS: print('{0} is not a supported output format.'.format(output_format), file=sys.stderr) print('Supported formats are: {0}'.format( ', '.join(sorted(backend.FORMATS))), file=sys.stderr) sys.exit(1) graph = Digraph(format=output_format) for package, deps in tree.items(): project_name = package.project_name label = '{0}\n{1}'.format(project_name, package.version) graph.node(project_name, label=label) for dep in deps: label = dep.version_spec if not label: label = 'any' graph.edge(project_name, dep.project_name, label=label) # Allow output of dot format, even if GraphViz isn't installed. if output_format == 'dot': return graph.source # As it's unknown if the selected output format is binary or not, try to # decode it as UTF8 and only print it out in binary if that's not possible. try: return graph.pipe().decode('utf-8') except UnicodeDecodeError: return graph.pipe()
[ "Output", "dependency", "graph", "as", "one", "of", "the", "supported", "GraphViz", "output", "formats", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pipdeptree.py#L402-L445
[ "def", "dump_graphviz", "(", "tree", ",", "output_format", "=", "'dot'", ")", ":", "try", ":", "from", "graphviz", "import", "backend", ",", "Digraph", "except", "ImportError", ":", "print", "(", "'graphviz is not available, but necessary for the output '", "'option. ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
print_graphviz
Dump the data generated by GraphViz to stdout. :param dump_output: The output from dump_graphviz
pipenv/vendor/pipdeptree.py
def print_graphviz(dump_output): """Dump the data generated by GraphViz to stdout. :param dump_output: The output from dump_graphviz """ if hasattr(dump_output, 'encode'): print(dump_output) else: with os.fdopen(sys.stdout.fileno(), 'wb') as bytestream: bytestream.write(dump_output)
def print_graphviz(dump_output): """Dump the data generated by GraphViz to stdout. :param dump_output: The output from dump_graphviz """ if hasattr(dump_output, 'encode'): print(dump_output) else: with os.fdopen(sys.stdout.fileno(), 'wb') as bytestream: bytestream.write(dump_output)
[ "Dump", "the", "data", "generated", "by", "GraphViz", "to", "stdout", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pipdeptree.py#L448-L457
[ "def", "print_graphviz", "(", "dump_output", ")", ":", "if", "hasattr", "(", "dump_output", ",", "'encode'", ")", ":", "print", "(", "dump_output", ")", "else", ":", "with", "os", ".", "fdopen", "(", "sys", ".", "stdout", ".", "fileno", "(", ")", ",", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
conflicting_deps
Returns dependencies which are not present or conflict with the requirements of other packages. e.g. will warn if pkg1 requires pkg2==2.0 and pkg2==1.0 is installed :param tree: the requirements tree (dict) :returns: dict of DistPackage -> list of unsatisfied/unknown ReqPackage :rtype: dict
pipenv/vendor/pipdeptree.py
def conflicting_deps(tree): """Returns dependencies which are not present or conflict with the requirements of other packages. e.g. will warn if pkg1 requires pkg2==2.0 and pkg2==1.0 is installed :param tree: the requirements tree (dict) :returns: dict of DistPackage -> list of unsatisfied/unknown ReqPackage :rtype: dict """ conflicting = defaultdict(list) for p, rs in tree.items(): for req in rs: if req.is_conflicting(): conflicting[p].append(req) return conflicting
def conflicting_deps(tree): """Returns dependencies which are not present or conflict with the requirements of other packages. e.g. will warn if pkg1 requires pkg2==2.0 and pkg2==1.0 is installed :param tree: the requirements tree (dict) :returns: dict of DistPackage -> list of unsatisfied/unknown ReqPackage :rtype: dict """ conflicting = defaultdict(list) for p, rs in tree.items(): for req in rs: if req.is_conflicting(): conflicting[p].append(req) return conflicting
[ "Returns", "dependencies", "which", "are", "not", "present", "or", "conflict", "with", "the", "requirements", "of", "other", "packages", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pipdeptree.py#L460-L476
[ "def", "conflicting_deps", "(", "tree", ")", ":", "conflicting", "=", "defaultdict", "(", "list", ")", "for", "p", ",", "rs", "in", "tree", ".", "items", "(", ")", ":", "for", "req", "in", "rs", ":", "if", "req", ".", "is_conflicting", "(", ")", ":...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
cyclic_deps
Return cyclic dependencies as list of tuples :param list pkgs: pkg_resources.Distribution instances :param dict pkg_index: mapping of pkgs with their respective keys :returns: list of tuples representing cyclic dependencies :rtype: generator
pipenv/vendor/pipdeptree.py
def cyclic_deps(tree): """Return cyclic dependencies as list of tuples :param list pkgs: pkg_resources.Distribution instances :param dict pkg_index: mapping of pkgs with their respective keys :returns: list of tuples representing cyclic dependencies :rtype: generator """ key_tree = dict((k.key, v) for k, v in tree.items()) get_children = lambda n: key_tree.get(n.key, []) cyclic = [] for p, rs in tree.items(): for req in rs: if p.key in map(attrgetter('key'), get_children(req)): cyclic.append((p, req, p)) return cyclic
def cyclic_deps(tree): """Return cyclic dependencies as list of tuples :param list pkgs: pkg_resources.Distribution instances :param dict pkg_index: mapping of pkgs with their respective keys :returns: list of tuples representing cyclic dependencies :rtype: generator """ key_tree = dict((k.key, v) for k, v in tree.items()) get_children = lambda n: key_tree.get(n.key, []) cyclic = [] for p, rs in tree.items(): for req in rs: if p.key in map(attrgetter('key'), get_children(req)): cyclic.append((p, req, p)) return cyclic
[ "Return", "cyclic", "dependencies", "as", "list", "of", "tuples" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pipdeptree.py#L479-L495
[ "def", "cyclic_deps", "(", "tree", ")", ":", "key_tree", "=", "dict", "(", "(", "k", ".", "key", ",", "v", ")", "for", "k", ",", "v", "in", "tree", ".", "items", "(", ")", ")", "get_children", "=", "lambda", "n", ":", "key_tree", ".", "get", "(...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
ReqPackage.is_conflicting
If installed version conflicts with required version
pipenv/vendor/pipdeptree.py
def is_conflicting(self): """If installed version conflicts with required version""" # unknown installed version is also considered conflicting if self.installed_version == self.UNKNOWN_VERSION: return True ver_spec = (self.version_spec if self.version_spec else '') req_version_str = '{0}{1}'.format(self.project_name, ver_spec) req_obj = pkg_resources.Requirement.parse(req_version_str) return self.installed_version not in req_obj
def is_conflicting(self): """If installed version conflicts with required version""" # unknown installed version is also considered conflicting if self.installed_version == self.UNKNOWN_VERSION: return True ver_spec = (self.version_spec if self.version_spec else '') req_version_str = '{0}{1}'.format(self.project_name, ver_spec) req_obj = pkg_resources.Requirement.parse(req_version_str) return self.installed_version not in req_obj
[ "If", "installed", "version", "conflicts", "with", "required", "version" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pipdeptree.py#L254-L262
[ "def", "is_conflicting", "(", "self", ")", ":", "# unknown installed version is also considered conflicting", "if", "self", ".", "installed_version", "==", "self", ".", "UNKNOWN_VERSION", ":", "return", "True", "ver_spec", "=", "(", "self", ".", "version_spec", "if", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Hashes.check_against_chunks
Check good hashes against ones built from iterable of chunks of data. Raise HashMismatch if none match.
pipenv/patched/notpip/_internal/utils/hashes.py
def check_against_chunks(self, chunks): # type: (Iterator[bytes]) -> None """Check good hashes against ones built from iterable of chunks of data. Raise HashMismatch if none match. """ gots = {} for hash_name in iterkeys(self._allowed): try: gots[hash_name] = hashlib.new(hash_name) except (ValueError, TypeError): raise InstallationError('Unknown hash name: %s' % hash_name) for chunk in chunks: for hash in itervalues(gots): hash.update(chunk) for hash_name, got in iteritems(gots): if got.hexdigest() in self._allowed[hash_name]: return self._raise(gots)
def check_against_chunks(self, chunks): # type: (Iterator[bytes]) -> None """Check good hashes against ones built from iterable of chunks of data. Raise HashMismatch if none match. """ gots = {} for hash_name in iterkeys(self._allowed): try: gots[hash_name] = hashlib.new(hash_name) except (ValueError, TypeError): raise InstallationError('Unknown hash name: %s' % hash_name) for chunk in chunks: for hash in itervalues(gots): hash.update(chunk) for hash_name, got in iteritems(gots): if got.hexdigest() in self._allowed[hash_name]: return self._raise(gots)
[ "Check", "good", "hashes", "against", "ones", "built", "from", "iterable", "of", "chunks", "of", "data", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/utils/hashes.py#L47-L69
[ "def", "check_against_chunks", "(", "self", ",", "chunks", ")", ":", "# type: (Iterator[bytes]) -> None", "gots", "=", "{", "}", "for", "hash_name", "in", "iterkeys", "(", "self", ".", "_allowed", ")", ":", "try", ":", "gots", "[", "hash_name", "]", "=", "...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
default_if_none
A converter that allows to replace ``None`` values by *default* or the result of *factory*. :param default: Value to be used if ``None`` is passed. Passing an instance of :class:`attr.Factory` is supported, however the ``takes_self`` option is *not*. :param callable factory: A callable that takes not parameters whose result is used if ``None`` is passed. :raises TypeError: If **neither** *default* or *factory* is passed. :raises TypeError: If **both** *default* and *factory* are passed. :raises ValueError: If an instance of :class:`attr.Factory` is passed with ``takes_self=True``. .. versionadded:: 18.2.0
pipenv/vendor/attr/converters.py
def default_if_none(default=NOTHING, factory=None): """ A converter that allows to replace ``None`` values by *default* or the result of *factory*. :param default: Value to be used if ``None`` is passed. Passing an instance of :class:`attr.Factory` is supported, however the ``takes_self`` option is *not*. :param callable factory: A callable that takes not parameters whose result is used if ``None`` is passed. :raises TypeError: If **neither** *default* or *factory* is passed. :raises TypeError: If **both** *default* and *factory* are passed. :raises ValueError: If an instance of :class:`attr.Factory` is passed with ``takes_self=True``. .. versionadded:: 18.2.0 """ if default is NOTHING and factory is None: raise TypeError("Must pass either `default` or `factory`.") if default is not NOTHING and factory is not None: raise TypeError( "Must pass either `default` or `factory` but not both." ) if factory is not None: default = Factory(factory) if isinstance(default, Factory): if default.takes_self: raise ValueError( "`takes_self` is not supported by default_if_none." ) def default_if_none_converter(val): if val is not None: return val return default.factory() else: def default_if_none_converter(val): if val is not None: return val return default return default_if_none_converter
def default_if_none(default=NOTHING, factory=None): """ A converter that allows to replace ``None`` values by *default* or the result of *factory*. :param default: Value to be used if ``None`` is passed. Passing an instance of :class:`attr.Factory` is supported, however the ``takes_self`` option is *not*. :param callable factory: A callable that takes not parameters whose result is used if ``None`` is passed. :raises TypeError: If **neither** *default* or *factory* is passed. :raises TypeError: If **both** *default* and *factory* are passed. :raises ValueError: If an instance of :class:`attr.Factory` is passed with ``takes_self=True``. .. versionadded:: 18.2.0 """ if default is NOTHING and factory is None: raise TypeError("Must pass either `default` or `factory`.") if default is not NOTHING and factory is not None: raise TypeError( "Must pass either `default` or `factory` but not both." ) if factory is not None: default = Factory(factory) if isinstance(default, Factory): if default.takes_self: raise ValueError( "`takes_self` is not supported by default_if_none." ) def default_if_none_converter(val): if val is not None: return val return default.factory() else: def default_if_none_converter(val): if val is not None: return val return default return default_if_none_converter
[ "A", "converter", "that", "allows", "to", "replace", "None", "values", "by", "*", "default", "*", "or", "the", "result", "of", "*", "factory", "*", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/attr/converters.py#L29-L78
[ "def", "default_if_none", "(", "default", "=", "NOTHING", ",", "factory", "=", "None", ")", ":", "if", "default", "is", "NOTHING", "and", "factory", "is", "None", ":", "raise", "TypeError", "(", "\"Must pass either `default` or `factory`.\"", ")", "if", "default...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
BareValidator._drop_nodes_from_errorpaths
Removes nodes by index from an errorpath, relatively to the basepaths of self. :param errors: A list of :class:`errors.ValidationError` instances. :param dp_items: A list of integers, pointing at the nodes to drop from the :attr:`document_path`. :param sp_items: Alike ``dp_items``, but for :attr:`schema_path`.
pipenv/vendor/cerberus/validator.py
def _drop_nodes_from_errorpaths(self, _errors, dp_items, sp_items): """ Removes nodes by index from an errorpath, relatively to the basepaths of self. :param errors: A list of :class:`errors.ValidationError` instances. :param dp_items: A list of integers, pointing at the nodes to drop from the :attr:`document_path`. :param sp_items: Alike ``dp_items``, but for :attr:`schema_path`. """ dp_basedepth = len(self.document_path) sp_basedepth = len(self.schema_path) for error in _errors: for i in sorted(dp_items, reverse=True): error.document_path = \ drop_item_from_tuple(error.document_path, dp_basedepth + i) for i in sorted(sp_items, reverse=True): error.schema_path = \ drop_item_from_tuple(error.schema_path, sp_basedepth + i) if error.child_errors: self._drop_nodes_from_errorpaths(error.child_errors, dp_items, sp_items)
def _drop_nodes_from_errorpaths(self, _errors, dp_items, sp_items): """ Removes nodes by index from an errorpath, relatively to the basepaths of self. :param errors: A list of :class:`errors.ValidationError` instances. :param dp_items: A list of integers, pointing at the nodes to drop from the :attr:`document_path`. :param sp_items: Alike ``dp_items``, but for :attr:`schema_path`. """ dp_basedepth = len(self.document_path) sp_basedepth = len(self.schema_path) for error in _errors: for i in sorted(dp_items, reverse=True): error.document_path = \ drop_item_from_tuple(error.document_path, dp_basedepth + i) for i in sorted(sp_items, reverse=True): error.schema_path = \ drop_item_from_tuple(error.schema_path, sp_basedepth + i) if error.child_errors: self._drop_nodes_from_errorpaths(error.child_errors, dp_items, sp_items)
[ "Removes", "nodes", "by", "index", "from", "an", "errorpath", "relatively", "to", "the", "basepaths", "of", "self", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/validator.py#L341-L361
[ "def", "_drop_nodes_from_errorpaths", "(", "self", ",", "_errors", ",", "dp_items", ",", "sp_items", ")", ":", "dp_basedepth", "=", "len", "(", "self", ".", "document_path", ")", "sp_basedepth", "=", "len", "(", "self", ".", "schema_path", ")", "for", "error...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
BareValidator._lookup_field
Searches for a field as defined by path. This method is used by the ``dependency`` evaluation logic. :param path: Path elements are separated by a ``.``. A leading ``^`` indicates that the path relates to the document root, otherwise it relates to the currently evaluated document, which is possibly a subdocument. The sequence ``^^`` at the start will be interpreted as a literal ``^``. :type path: :class:`str` :returns: Either the found field name and its value or :obj:`None` for both. :rtype: A two-value :class:`tuple`.
pipenv/vendor/cerberus/validator.py
def _lookup_field(self, path): """ Searches for a field as defined by path. This method is used by the ``dependency`` evaluation logic. :param path: Path elements are separated by a ``.``. A leading ``^`` indicates that the path relates to the document root, otherwise it relates to the currently evaluated document, which is possibly a subdocument. The sequence ``^^`` at the start will be interpreted as a literal ``^``. :type path: :class:`str` :returns: Either the found field name and its value or :obj:`None` for both. :rtype: A two-value :class:`tuple`. """ if path.startswith('^'): path = path[1:] context = self.document if path.startswith('^') \ else self.root_document else: context = self.document parts = path.split('.') for part in parts: if part not in context: return None, None context = context.get(part) return parts[-1], context
def _lookup_field(self, path): """ Searches for a field as defined by path. This method is used by the ``dependency`` evaluation logic. :param path: Path elements are separated by a ``.``. A leading ``^`` indicates that the path relates to the document root, otherwise it relates to the currently evaluated document, which is possibly a subdocument. The sequence ``^^`` at the start will be interpreted as a literal ``^``. :type path: :class:`str` :returns: Either the found field name and its value or :obj:`None` for both. :rtype: A two-value :class:`tuple`. """ if path.startswith('^'): path = path[1:] context = self.document if path.startswith('^') \ else self.root_document else: context = self.document parts = path.split('.') for part in parts: if part not in context: return None, None context = context.get(part) return parts[-1], context
[ "Searches", "for", "a", "field", "as", "defined", "by", "path", ".", "This", "method", "is", "used", "by", "the", "dependency", "evaluation", "logic", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/validator.py#L363-L391
[ "def", "_lookup_field", "(", "self", ",", "path", ")", ":", "if", "path", ".", "startswith", "(", "'^'", ")", ":", "path", "=", "path", "[", "1", ":", "]", "context", "=", "self", ".", "document", "if", "path", ".", "startswith", "(", "'^'", ")", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
BareValidator.types
The constraints that can be used for the 'type' rule. Type: A tuple of strings.
pipenv/vendor/cerberus/validator.py
def types(cls): """ The constraints that can be used for the 'type' rule. Type: A tuple of strings. """ redundant_types = \ set(cls.types_mapping) & set(cls._types_from_methods) if redundant_types: warn("These types are defined both with a method and in the" "'types_mapping' property of this validator: %s" % redundant_types) return tuple(cls.types_mapping) + cls._types_from_methods
def types(cls): """ The constraints that can be used for the 'type' rule. Type: A tuple of strings. """ redundant_types = \ set(cls.types_mapping) & set(cls._types_from_methods) if redundant_types: warn("These types are defined both with a method and in the" "'types_mapping' property of this validator: %s" % redundant_types) return tuple(cls.types_mapping) + cls._types_from_methods
[ "The", "constraints", "that", "can", "be", "used", "for", "the", "type", "rule", ".", "Type", ":", "A", "tuple", "of", "strings", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/validator.py#L524-L534
[ "def", "types", "(", "cls", ")", ":", "redundant_types", "=", "set", "(", "cls", ".", "types_mapping", ")", "&", "set", "(", "cls", ".", "_types_from_methods", ")", "if", "redundant_types", ":", "warn", "(", "\"These types are defined both with a method and in the...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
BareValidator._drop_remaining_rules
Drops rules from the queue of the rules that still need to be evaluated for the currently processed field. If no arguments are given, the whole queue is emptied.
pipenv/vendor/cerberus/validator.py
def _drop_remaining_rules(self, *rules): """ Drops rules from the queue of the rules that still need to be evaluated for the currently processed field. If no arguments are given, the whole queue is emptied. """ if rules: for rule in rules: try: self._remaining_rules.remove(rule) except ValueError: pass else: self._remaining_rules = []
def _drop_remaining_rules(self, *rules): """ Drops rules from the queue of the rules that still need to be evaluated for the currently processed field. If no arguments are given, the whole queue is emptied. """ if rules: for rule in rules: try: self._remaining_rules.remove(rule) except ValueError: pass else: self._remaining_rules = []
[ "Drops", "rules", "from", "the", "queue", "of", "the", "rules", "that", "still", "need", "to", "be", "evaluated", "for", "the", "currently", "processed", "field", ".", "If", "no", "arguments", "are", "given", "the", "whole", "queue", "is", "emptied", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/validator.py#L561-L573
[ "def", "_drop_remaining_rules", "(", "self", ",", "*", "rules", ")", ":", "if", "rules", ":", "for", "rule", "in", "rules", ":", "try", ":", "self", ".", "_remaining_rules", ".", "remove", "(", "rule", ")", "except", "ValueError", ":", "pass", "else", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
BareValidator.normalized
Returns the document normalized according to the specified rules of a schema. :param document: The document to normalize. :type document: any :term:`mapping` :param schema: The validation schema. Defaults to :obj:`None`. If not provided here, the schema must have been provided at class instantiation. :type schema: any :term:`mapping` :param always_return_document: Return the document, even if an error occurred. Defaults to: ``False``. :type always_return_document: :class:`bool` :return: A normalized copy of the provided mapping or :obj:`None` if an error occurred during normalization.
pipenv/vendor/cerberus/validator.py
def normalized(self, document, schema=None, always_return_document=False): """ Returns the document normalized according to the specified rules of a schema. :param document: The document to normalize. :type document: any :term:`mapping` :param schema: The validation schema. Defaults to :obj:`None`. If not provided here, the schema must have been provided at class instantiation. :type schema: any :term:`mapping` :param always_return_document: Return the document, even if an error occurred. Defaults to: ``False``. :type always_return_document: :class:`bool` :return: A normalized copy of the provided mapping or :obj:`None` if an error occurred during normalization. """ self.__init_processing(document, schema) self.__normalize_mapping(self.document, self.schema) self.error_handler.end(self) if self._errors and not always_return_document: return None else: return self.document
def normalized(self, document, schema=None, always_return_document=False): """ Returns the document normalized according to the specified rules of a schema. :param document: The document to normalize. :type document: any :term:`mapping` :param schema: The validation schema. Defaults to :obj:`None`. If not provided here, the schema must have been provided at class instantiation. :type schema: any :term:`mapping` :param always_return_document: Return the document, even if an error occurred. Defaults to: ``False``. :type always_return_document: :class:`bool` :return: A normalized copy of the provided mapping or :obj:`None` if an error occurred during normalization. """ self.__init_processing(document, schema) self.__normalize_mapping(self.document, self.schema) self.error_handler.end(self) if self._errors and not always_return_document: return None else: return self.document
[ "Returns", "the", "document", "normalized", "according", "to", "the", "specified", "rules", "of", "a", "schema", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/validator.py#L577-L599
[ "def", "normalized", "(", "self", ",", "document", ",", "schema", "=", "None", ",", "always_return_document", "=", "False", ")", ":", "self", ".", "__init_processing", "(", "document", ",", "schema", ")", "self", ".", "__normalize_mapping", "(", "self", ".",...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
BareValidator._normalize_coerce
{'oneof': [ {'type': 'callable'}, {'type': 'list', 'schema': {'oneof': [{'type': 'callable'}, {'type': 'string'}]}}, {'type': 'string'} ]}
pipenv/vendor/cerberus/validator.py
def _normalize_coerce(self, mapping, schema): """ {'oneof': [ {'type': 'callable'}, {'type': 'list', 'schema': {'oneof': [{'type': 'callable'}, {'type': 'string'}]}}, {'type': 'string'} ]} """ error = errors.COERCION_FAILED for field in mapping: if field in schema and 'coerce' in schema[field]: mapping[field] = self.__normalize_coerce( schema[field]['coerce'], field, mapping[field], schema[field].get('nullable', False), error) elif isinstance(self.allow_unknown, Mapping) and \ 'coerce' in self.allow_unknown: mapping[field] = self.__normalize_coerce( self.allow_unknown['coerce'], field, mapping[field], self.allow_unknown.get('nullable', False), error)
def _normalize_coerce(self, mapping, schema): """ {'oneof': [ {'type': 'callable'}, {'type': 'list', 'schema': {'oneof': [{'type': 'callable'}, {'type': 'string'}]}}, {'type': 'string'} ]} """ error = errors.COERCION_FAILED for field in mapping: if field in schema and 'coerce' in schema[field]: mapping[field] = self.__normalize_coerce( schema[field]['coerce'], field, mapping[field], schema[field].get('nullable', False), error) elif isinstance(self.allow_unknown, Mapping) and \ 'coerce' in self.allow_unknown: mapping[field] = self.__normalize_coerce( self.allow_unknown['coerce'], field, mapping[field], self.allow_unknown.get('nullable', False), error)
[ "{", "oneof", ":", "[", "{", "type", ":", "callable", "}", "{", "type", ":", "list", "schema", ":", "{", "oneof", ":", "[", "{", "type", ":", "callable", "}", "{", "type", ":", "string", "}", "]", "}}", "{", "type", ":", "string", "}", "]", "...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/validator.py#L621-L640
[ "def", "_normalize_coerce", "(", "self", ",", "mapping", ",", "schema", ")", ":", "error", "=", "errors", ".", "COERCION_FAILED", "for", "field", "in", "mapping", ":", "if", "field", "in", "schema", "and", "'coerce'", "in", "schema", "[", "field", "]", "...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
BareValidator._normalize_purge_unknown
{'type': 'boolean'}
pipenv/vendor/cerberus/validator.py
def _normalize_purge_unknown(mapping, schema): """ {'type': 'boolean'} """ for field in tuple(mapping): if field not in schema: del mapping[field] return mapping
def _normalize_purge_unknown(mapping, schema): """ {'type': 'boolean'} """ for field in tuple(mapping): if field not in schema: del mapping[field] return mapping
[ "{", "type", ":", "boolean", "}" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/validator.py#L751-L756
[ "def", "_normalize_purge_unknown", "(", "mapping", ",", "schema", ")", ":", "for", "field", "in", "tuple", "(", "mapping", ")", ":", "if", "field", "not", "in", "schema", ":", "del", "mapping", "[", "field", "]", "return", "mapping" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
BareValidator._normalize_rename
{'type': 'hashable'}
pipenv/vendor/cerberus/validator.py
def _normalize_rename(self, mapping, schema, field): """ {'type': 'hashable'} """ if 'rename' in schema[field]: mapping[schema[field]['rename']] = mapping[field] del mapping[field]
def _normalize_rename(self, mapping, schema, field): """ {'type': 'hashable'} """ if 'rename' in schema[field]: mapping[schema[field]['rename']] = mapping[field] del mapping[field]
[ "{", "type", ":", "hashable", "}" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/validator.py#L769-L773
[ "def", "_normalize_rename", "(", "self", ",", "mapping", ",", "schema", ",", "field", ")", ":", "if", "'rename'", "in", "schema", "[", "field", "]", ":", "mapping", "[", "schema", "[", "field", "]", "[", "'rename'", "]", "]", "=", "mapping", "[", "fi...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
BareValidator._normalize_rename_handler
{'oneof': [ {'type': 'callable'}, {'type': 'list', 'schema': {'oneof': [{'type': 'callable'}, {'type': 'string'}]}}, {'type': 'string'} ]}
pipenv/vendor/cerberus/validator.py
def _normalize_rename_handler(self, mapping, schema, field): """ {'oneof': [ {'type': 'callable'}, {'type': 'list', 'schema': {'oneof': [{'type': 'callable'}, {'type': 'string'}]}}, {'type': 'string'} ]} """ if 'rename_handler' not in schema[field]: return new_name = self.__normalize_coerce( schema[field]['rename_handler'], field, field, False, errors.RENAMING_FAILED) if new_name != field: mapping[new_name] = mapping[field] del mapping[field]
def _normalize_rename_handler(self, mapping, schema, field): """ {'oneof': [ {'type': 'callable'}, {'type': 'list', 'schema': {'oneof': [{'type': 'callable'}, {'type': 'string'}]}}, {'type': 'string'} ]} """ if 'rename_handler' not in schema[field]: return new_name = self.__normalize_coerce( schema[field]['rename_handler'], field, field, False, errors.RENAMING_FAILED) if new_name != field: mapping[new_name] = mapping[field] del mapping[field]
[ "{", "oneof", ":", "[", "{", "type", ":", "callable", "}", "{", "type", ":", "list", "schema", ":", "{", "oneof", ":", "[", "{", "type", ":", "callable", "}", "{", "type", ":", "string", "}", "]", "}}", "{", "type", ":", "string", "}", "]", "...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/validator.py#L775-L790
[ "def", "_normalize_rename_handler", "(", "self", ",", "mapping", ",", "schema", ",", "field", ")", ":", "if", "'rename_handler'", "not", "in", "schema", "[", "field", "]", ":", "return", "new_name", "=", "self", ".", "__normalize_coerce", "(", "schema", "[",...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
BareValidator._normalize_default_setter
{'oneof': [ {'type': 'callable'}, {'type': 'string'} ]}
pipenv/vendor/cerberus/validator.py
def _normalize_default_setter(self, mapping, schema, field): """ {'oneof': [ {'type': 'callable'}, {'type': 'string'} ]} """ if 'default_setter' in schema[field]: setter = schema[field]['default_setter'] if isinstance(setter, _str_type): setter = self.__get_rule_handler('normalize_default_setter', setter) mapping[field] = setter(mapping)
def _normalize_default_setter(self, mapping, schema, field): """ {'oneof': [ {'type': 'callable'}, {'type': 'string'} ]} """ if 'default_setter' in schema[field]: setter = schema[field]['default_setter'] if isinstance(setter, _str_type): setter = self.__get_rule_handler('normalize_default_setter', setter) mapping[field] = setter(mapping)
[ "{", "oneof", ":", "[", "{", "type", ":", "callable", "}", "{", "type", ":", "string", "}", "]", "}" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/validator.py#L832-L842
[ "def", "_normalize_default_setter", "(", "self", ",", "mapping", ",", "schema", ",", "field", ")", ":", "if", "'default_setter'", "in", "schema", "[", "field", "]", ":", "setter", "=", "schema", "[", "field", "]", "[", "'default_setter'", "]", "if", "isins...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
BareValidator.validate
Normalizes and validates a mapping against a validation-schema of defined rules. :param document: The document to normalize. :type document: any :term:`mapping` :param schema: The validation schema. Defaults to :obj:`None`. If not provided here, the schema must have been provided at class instantiation. :type schema: any :term:`mapping` :param update: If ``True``, required fields won't be checked. :type update: :class:`bool` :param normalize: If ``True``, normalize the document before validation. :type normalize: :class:`bool` :return: ``True`` if validation succeeds, otherwise ``False``. Check the :func:`errors` property for a list of processing errors. :rtype: :class:`bool`
pipenv/vendor/cerberus/validator.py
def validate(self, document, schema=None, update=False, normalize=True): """ Normalizes and validates a mapping against a validation-schema of defined rules. :param document: The document to normalize. :type document: any :term:`mapping` :param schema: The validation schema. Defaults to :obj:`None`. If not provided here, the schema must have been provided at class instantiation. :type schema: any :term:`mapping` :param update: If ``True``, required fields won't be checked. :type update: :class:`bool` :param normalize: If ``True``, normalize the document before validation. :type normalize: :class:`bool` :return: ``True`` if validation succeeds, otherwise ``False``. Check the :func:`errors` property for a list of processing errors. :rtype: :class:`bool` """ self.update = update self._unrequired_by_excludes = set() self.__init_processing(document, schema) if normalize: self.__normalize_mapping(self.document, self.schema) for field in self.document: if self.ignore_none_values and self.document[field] is None: continue definitions = self.schema.get(field) if definitions is not None: self.__validate_definitions(definitions, field) else: self.__validate_unknown_fields(field) if not self.update: self.__validate_required_fields(self.document) self.error_handler.end(self) return not bool(self._errors)
def validate(self, document, schema=None, update=False, normalize=True): """ Normalizes and validates a mapping against a validation-schema of defined rules. :param document: The document to normalize. :type document: any :term:`mapping` :param schema: The validation schema. Defaults to :obj:`None`. If not provided here, the schema must have been provided at class instantiation. :type schema: any :term:`mapping` :param update: If ``True``, required fields won't be checked. :type update: :class:`bool` :param normalize: If ``True``, normalize the document before validation. :type normalize: :class:`bool` :return: ``True`` if validation succeeds, otherwise ``False``. Check the :func:`errors` property for a list of processing errors. :rtype: :class:`bool` """ self.update = update self._unrequired_by_excludes = set() self.__init_processing(document, schema) if normalize: self.__normalize_mapping(self.document, self.schema) for field in self.document: if self.ignore_none_values and self.document[field] is None: continue definitions = self.schema.get(field) if definitions is not None: self.__validate_definitions(definitions, field) else: self.__validate_unknown_fields(field) if not self.update: self.__validate_required_fields(self.document) self.error_handler.end(self) return not bool(self._errors)
[ "Normalizes", "and", "validates", "a", "mapping", "against", "a", "validation", "-", "schema", "of", "defined", "rules", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/validator.py#L846-L886
[ "def", "validate", "(", "self", ",", "document", ",", "schema", "=", "None", ",", "update", "=", "False", ",", "normalize", "=", "True", ")", ":", "self", ".", "update", "=", "update", "self", ".", "_unrequired_by_excludes", "=", "set", "(", ")", "self...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
BareValidator.validated
Wrapper around :meth:`~cerberus.Validator.validate` that returns the normalized and validated document or :obj:`None` if validation failed.
pipenv/vendor/cerberus/validator.py
def validated(self, *args, **kwargs): """ Wrapper around :meth:`~cerberus.Validator.validate` that returns the normalized and validated document or :obj:`None` if validation failed. """ always_return_document = kwargs.pop('always_return_document', False) self.validate(*args, **kwargs) if self._errors and not always_return_document: return None else: return self.document
def validated(self, *args, **kwargs): """ Wrapper around :meth:`~cerberus.Validator.validate` that returns the normalized and validated document or :obj:`None` if validation failed. """ always_return_document = kwargs.pop('always_return_document', False) self.validate(*args, **kwargs) if self._errors and not always_return_document: return None else: return self.document
[ "Wrapper", "around", ":", "meth", ":", "~cerberus", ".", "Validator", ".", "validate", "that", "returns", "the", "normalized", "and", "validated", "document", "or", ":", "obj", ":", "None", "if", "validation", "failed", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/validator.py#L890-L899
[ "def", "validated", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "always_return_document", "=", "kwargs", ".", "pop", "(", "'always_return_document'", ",", "False", ")", "self", ".", "validate", "(", "*", "args", ",", "*", "*", "kw...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
BareValidator._validate_allowed
{'type': 'list'}
pipenv/vendor/cerberus/validator.py
def _validate_allowed(self, allowed_values, field, value): """ {'type': 'list'} """ if isinstance(value, Iterable) and not isinstance(value, _str_type): unallowed = set(value) - set(allowed_values) if unallowed: self._error(field, errors.UNALLOWED_VALUES, list(unallowed)) else: if value not in allowed_values: self._error(field, errors.UNALLOWED_VALUE, value)
def _validate_allowed(self, allowed_values, field, value): """ {'type': 'list'} """ if isinstance(value, Iterable) and not isinstance(value, _str_type): unallowed = set(value) - set(allowed_values) if unallowed: self._error(field, errors.UNALLOWED_VALUES, list(unallowed)) else: if value not in allowed_values: self._error(field, errors.UNALLOWED_VALUE, value)
[ "{", "type", ":", "list", "}" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/validator.py#L957-L965
[ "def", "_validate_allowed", "(", "self", ",", "allowed_values", ",", "field", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "Iterable", ")", "and", "not", "isinstance", "(", "value", ",", "_str_type", ")", ":", "unallowed", "=", "set", "...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
BareValidator._validate_empty
{'type': 'boolean'}
pipenv/vendor/cerberus/validator.py
def _validate_empty(self, empty, field, value): """ {'type': 'boolean'} """ if isinstance(value, Iterable) and len(value) == 0: self._drop_remaining_rules( 'allowed', 'forbidden', 'items', 'minlength', 'maxlength', 'regex', 'validator') if not empty: self._error(field, errors.EMPTY_NOT_ALLOWED)
def _validate_empty(self, empty, field, value): """ {'type': 'boolean'} """ if isinstance(value, Iterable) and len(value) == 0: self._drop_remaining_rules( 'allowed', 'forbidden', 'items', 'minlength', 'maxlength', 'regex', 'validator') if not empty: self._error(field, errors.EMPTY_NOT_ALLOWED)
[ "{", "type", ":", "boolean", "}" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/validator.py#L1005-L1012
[ "def", "_validate_empty", "(", "self", ",", "empty", ",", "field", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "Iterable", ")", "and", "len", "(", "value", ")", "==", "0", ":", "self", ".", "_drop_remaining_rules", "(", "'allowed'", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
BareValidator._validate_excludes
{'type': ('hashable', 'list'), 'schema': {'type': 'hashable'}}
pipenv/vendor/cerberus/validator.py
def _validate_excludes(self, excludes, field, value): """ {'type': ('hashable', 'list'), 'schema': {'type': 'hashable'}} """ if isinstance(excludes, Hashable): excludes = [excludes] # Save required field to be checked latter if 'required' in self.schema[field] and self.schema[field]['required']: self._unrequired_by_excludes.add(field) for exclude in excludes: if (exclude in self.schema and 'required' in self.schema[exclude] and self.schema[exclude]['required']): self._unrequired_by_excludes.add(exclude) if [True for key in excludes if key in self.document]: # Wrap each field in `excludes` list between quotes exclusion_str = ', '.join("'{0}'" .format(word) for word in excludes) self._error(field, errors.EXCLUDES_FIELD, exclusion_str)
def _validate_excludes(self, excludes, field, value): """ {'type': ('hashable', 'list'), 'schema': {'type': 'hashable'}} """ if isinstance(excludes, Hashable): excludes = [excludes] # Save required field to be checked latter if 'required' in self.schema[field] and self.schema[field]['required']: self._unrequired_by_excludes.add(field) for exclude in excludes: if (exclude in self.schema and 'required' in self.schema[exclude] and self.schema[exclude]['required']): self._unrequired_by_excludes.add(exclude) if [True for key in excludes if key in self.document]: # Wrap each field in `excludes` list between quotes exclusion_str = ', '.join("'{0}'" .format(word) for word in excludes) self._error(field, errors.EXCLUDES_FIELD, exclusion_str)
[ "{", "type", ":", "(", "hashable", "list", ")", "schema", ":", "{", "type", ":", "hashable", "}}" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/validator.py#L1014-L1034
[ "def", "_validate_excludes", "(", "self", ",", "excludes", ",", "field", ",", "value", ")", ":", "if", "isinstance", "(", "excludes", ",", "Hashable", ")", ":", "excludes", "=", "[", "excludes", "]", "# Save required field to be checked latter", "if", "'required...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
BareValidator._validate_forbidden
{'type': 'list'}
pipenv/vendor/cerberus/validator.py
def _validate_forbidden(self, forbidden_values, field, value): """ {'type': 'list'} """ if isinstance(value, _str_type): if value in forbidden_values: self._error(field, errors.FORBIDDEN_VALUE, value) elif isinstance(value, Sequence): forbidden = set(value) & set(forbidden_values) if forbidden: self._error(field, errors.FORBIDDEN_VALUES, list(forbidden)) elif isinstance(value, int): if value in forbidden_values: self._error(field, errors.FORBIDDEN_VALUE, value)
def _validate_forbidden(self, forbidden_values, field, value): """ {'type': 'list'} """ if isinstance(value, _str_type): if value in forbidden_values: self._error(field, errors.FORBIDDEN_VALUE, value) elif isinstance(value, Sequence): forbidden = set(value) & set(forbidden_values) if forbidden: self._error(field, errors.FORBIDDEN_VALUES, list(forbidden)) elif isinstance(value, int): if value in forbidden_values: self._error(field, errors.FORBIDDEN_VALUE, value)
[ "{", "type", ":", "list", "}" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/validator.py#L1036-L1047
[ "def", "_validate_forbidden", "(", "self", ",", "forbidden_values", ",", "field", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "_str_type", ")", ":", "if", "value", "in", "forbidden_values", ":", "self", ".", "_error", "(", "field", ",", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
BareValidator.__validate_logical
Validates value against all definitions and logs errors according to the operator.
pipenv/vendor/cerberus/validator.py
def __validate_logical(self, operator, definitions, field, value): """ Validates value against all definitions and logs errors according to the operator. """ valid_counter = 0 _errors = errors.ErrorList() for i, definition in enumerate(definitions): schema = {field: definition.copy()} for rule in ('allow_unknown', 'type'): if rule not in schema[field] and rule in self.schema[field]: schema[field][rule] = self.schema[field][rule] if 'allow_unknown' not in schema[field]: schema[field]['allow_unknown'] = self.allow_unknown validator = self._get_child_validator( schema_crumb=(field, operator, i), schema=schema, allow_unknown=True) if validator(self.document, update=self.update, normalize=False): valid_counter += 1 else: self._drop_nodes_from_errorpaths(validator._errors, [], [3]) _errors.extend(validator._errors) return valid_counter, _errors
def __validate_logical(self, operator, definitions, field, value): """ Validates value against all definitions and logs errors according to the operator. """ valid_counter = 0 _errors = errors.ErrorList() for i, definition in enumerate(definitions): schema = {field: definition.copy()} for rule in ('allow_unknown', 'type'): if rule not in schema[field] and rule in self.schema[field]: schema[field][rule] = self.schema[field][rule] if 'allow_unknown' not in schema[field]: schema[field]['allow_unknown'] = self.allow_unknown validator = self._get_child_validator( schema_crumb=(field, operator, i), schema=schema, allow_unknown=True) if validator(self.document, update=self.update, normalize=False): valid_counter += 1 else: self._drop_nodes_from_errorpaths(validator._errors, [], [3]) _errors.extend(validator._errors) return valid_counter, _errors
[ "Validates", "value", "against", "all", "definitions", "and", "logs", "errors", "according", "to", "the", "operator", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/validator.py#L1062-L1085
[ "def", "__validate_logical", "(", "self", ",", "operator", ",", "definitions", ",", "field", ",", "value", ")", ":", "valid_counter", "=", "0", "_errors", "=", "errors", ".", "ErrorList", "(", ")", "for", "i", ",", "definition", "in", "enumerate", "(", "...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
BareValidator._validate_anyof
{'type': 'list', 'logical': 'anyof'}
pipenv/vendor/cerberus/validator.py
def _validate_anyof(self, definitions, field, value): """ {'type': 'list', 'logical': 'anyof'} """ valids, _errors = \ self.__validate_logical('anyof', definitions, field, value) if valids < 1: self._error(field, errors.ANYOF, _errors, valids, len(definitions))
def _validate_anyof(self, definitions, field, value): """ {'type': 'list', 'logical': 'anyof'} """ valids, _errors = \ self.__validate_logical('anyof', definitions, field, value) if valids < 1: self._error(field, errors.ANYOF, _errors, valids, len(definitions))
[ "{", "type", ":", "list", "logical", ":", "anyof", "}" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/validator.py#L1087-L1093
[ "def", "_validate_anyof", "(", "self", ",", "definitions", ",", "field", ",", "value", ")", ":", "valids", ",", "_errors", "=", "self", ".", "__validate_logical", "(", "'anyof'", ",", "definitions", ",", "field", ",", "value", ")", "if", "valids", "<", "...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
BareValidator._validate_allof
{'type': 'list', 'logical': 'allof'}
pipenv/vendor/cerberus/validator.py
def _validate_allof(self, definitions, field, value): """ {'type': 'list', 'logical': 'allof'} """ valids, _errors = \ self.__validate_logical('allof', definitions, field, value) if valids < len(definitions): self._error(field, errors.ALLOF, _errors, valids, len(definitions))
def _validate_allof(self, definitions, field, value): """ {'type': 'list', 'logical': 'allof'} """ valids, _errors = \ self.__validate_logical('allof', definitions, field, value) if valids < len(definitions): self._error(field, errors.ALLOF, _errors, valids, len(definitions))
[ "{", "type", ":", "list", "logical", ":", "allof", "}" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/validator.py#L1095-L1101
[ "def", "_validate_allof", "(", "self", ",", "definitions", ",", "field", ",", "value", ")", ":", "valids", ",", "_errors", "=", "self", ".", "__validate_logical", "(", "'allof'", ",", "definitions", ",", "field", ",", "value", ")", "if", "valids", "<", "...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
BareValidator._validate_noneof
{'type': 'list', 'logical': 'noneof'}
pipenv/vendor/cerberus/validator.py
def _validate_noneof(self, definitions, field, value): """ {'type': 'list', 'logical': 'noneof'} """ valids, _errors = \ self.__validate_logical('noneof', definitions, field, value) if valids > 0: self._error(field, errors.NONEOF, _errors, valids, len(definitions))
def _validate_noneof(self, definitions, field, value): """ {'type': 'list', 'logical': 'noneof'} """ valids, _errors = \ self.__validate_logical('noneof', definitions, field, value) if valids > 0: self._error(field, errors.NONEOF, _errors, valids, len(definitions))
[ "{", "type", ":", "list", "logical", ":", "noneof", "}" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/validator.py#L1103-L1109
[ "def", "_validate_noneof", "(", "self", ",", "definitions", ",", "field", ",", "value", ")", ":", "valids", ",", "_errors", "=", "self", ".", "__validate_logical", "(", "'noneof'", ",", "definitions", ",", "field", ",", "value", ")", "if", "valids", ">", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
BareValidator._validate_oneof
{'type': 'list', 'logical': 'oneof'}
pipenv/vendor/cerberus/validator.py
def _validate_oneof(self, definitions, field, value): """ {'type': 'list', 'logical': 'oneof'} """ valids, _errors = \ self.__validate_logical('oneof', definitions, field, value) if valids != 1: self._error(field, errors.ONEOF, _errors, valids, len(definitions))
def _validate_oneof(self, definitions, field, value): """ {'type': 'list', 'logical': 'oneof'} """ valids, _errors = \ self.__validate_logical('oneof', definitions, field, value) if valids != 1: self._error(field, errors.ONEOF, _errors, valids, len(definitions))
[ "{", "type", ":", "list", "logical", ":", "oneof", "}" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/validator.py#L1111-L1117
[ "def", "_validate_oneof", "(", "self", ",", "definitions", ",", "field", ",", "value", ")", ":", "valids", ",", "_errors", "=", "self", ".", "__validate_logical", "(", "'oneof'", ",", "definitions", ",", "field", ",", "value", ")", "if", "valids", "!=", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
BareValidator._validate_max
{'nullable': False }
pipenv/vendor/cerberus/validator.py
def _validate_max(self, max_value, field, value): """ {'nullable': False } """ try: if value > max_value: self._error(field, errors.MAX_VALUE) except TypeError: pass
def _validate_max(self, max_value, field, value): """ {'nullable': False } """ try: if value > max_value: self._error(field, errors.MAX_VALUE) except TypeError: pass
[ "{", "nullable", ":", "False", "}" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/validator.py#L1119-L1125
[ "def", "_validate_max", "(", "self", ",", "max_value", ",", "field", ",", "value", ")", ":", "try", ":", "if", "value", ">", "max_value", ":", "self", ".", "_error", "(", "field", ",", "errors", ".", "MAX_VALUE", ")", "except", "TypeError", ":", "pass"...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
BareValidator._validate_min
{'nullable': False }
pipenv/vendor/cerberus/validator.py
def _validate_min(self, min_value, field, value): """ {'nullable': False } """ try: if value < min_value: self._error(field, errors.MIN_VALUE) except TypeError: pass
def _validate_min(self, min_value, field, value): """ {'nullable': False } """ try: if value < min_value: self._error(field, errors.MIN_VALUE) except TypeError: pass
[ "{", "nullable", ":", "False", "}" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/validator.py#L1127-L1133
[ "def", "_validate_min", "(", "self", ",", "min_value", ",", "field", ",", "value", ")", ":", "try", ":", "if", "value", "<", "min_value", ":", "self", ".", "_error", "(", "field", ",", "errors", ".", "MIN_VALUE", ")", "except", "TypeError", ":", "pass"...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
BareValidator._validate_maxlength
{'type': 'integer'}
pipenv/vendor/cerberus/validator.py
def _validate_maxlength(self, max_length, field, value): """ {'type': 'integer'} """ if isinstance(value, Iterable) and len(value) > max_length: self._error(field, errors.MAX_LENGTH, len(value))
def _validate_maxlength(self, max_length, field, value): """ {'type': 'integer'} """ if isinstance(value, Iterable) and len(value) > max_length: self._error(field, errors.MAX_LENGTH, len(value))
[ "{", "type", ":", "integer", "}" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/validator.py#L1135-L1138
[ "def", "_validate_maxlength", "(", "self", ",", "max_length", ",", "field", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "Iterable", ")", "and", "len", "(", "value", ")", ">", "max_length", ":", "self", ".", "_error", "(", "field", ",...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
BareValidator._validate_minlength
{'type': 'integer'}
pipenv/vendor/cerberus/validator.py
def _validate_minlength(self, min_length, field, value): """ {'type': 'integer'} """ if isinstance(value, Iterable) and len(value) < min_length: self._error(field, errors.MIN_LENGTH, len(value))
def _validate_minlength(self, min_length, field, value): """ {'type': 'integer'} """ if isinstance(value, Iterable) and len(value) < min_length: self._error(field, errors.MIN_LENGTH, len(value))
[ "{", "type", ":", "integer", "}" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/validator.py#L1140-L1143
[ "def", "_validate_minlength", "(", "self", ",", "min_length", ",", "field", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "Iterable", ")", "and", "len", "(", "value", ")", "<", "min_length", ":", "self", ".", "_error", "(", "field", ",...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
BareValidator._validate_keyschema
{'type': ['dict', 'string'], 'validator': 'bulk_schema', 'forbidden': ['rename', 'rename_handler']}
pipenv/vendor/cerberus/validator.py
def _validate_keyschema(self, schema, field, value): """ {'type': ['dict', 'string'], 'validator': 'bulk_schema', 'forbidden': ['rename', 'rename_handler']} """ if isinstance(value, Mapping): validator = self._get_child_validator( document_crumb=field, schema_crumb=(field, 'keyschema'), schema=dict(((k, schema) for k in value.keys()))) if not validator(dict(((k, k) for k in value.keys())), normalize=False): self._drop_nodes_from_errorpaths(validator._errors, [], [2, 4]) self._error(field, errors.KEYSCHEMA, validator._errors)
def _validate_keyschema(self, schema, field, value): """ {'type': ['dict', 'string'], 'validator': 'bulk_schema', 'forbidden': ['rename', 'rename_handler']} """ if isinstance(value, Mapping): validator = self._get_child_validator( document_crumb=field, schema_crumb=(field, 'keyschema'), schema=dict(((k, schema) for k in value.keys()))) if not validator(dict(((k, k) for k in value.keys())), normalize=False): self._drop_nodes_from_errorpaths(validator._errors, [], [2, 4]) self._error(field, errors.KEYSCHEMA, validator._errors)
[ "{", "type", ":", "[", "dict", "string", "]", "validator", ":", "bulk_schema", "forbidden", ":", "[", "rename", "rename_handler", "]", "}" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/validator.py#L1155-L1167
[ "def", "_validate_keyschema", "(", "self", ",", "schema", ",", "field", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "Mapping", ")", ":", "validator", "=", "self", ".", "_get_child_validator", "(", "document_crumb", "=", "field", ",", "sc...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
BareValidator._validate_readonly
{'type': 'boolean'}
pipenv/vendor/cerberus/validator.py
def _validate_readonly(self, readonly, field, value): """ {'type': 'boolean'} """ if readonly: if not self._is_normalized: self._error(field, errors.READONLY_FIELD) # If the document was normalized (and therefore already been # checked for readonly fields), we still have to return True # if an error was filed. has_error = errors.READONLY_FIELD in \ self.document_error_tree.fetch_errors_from( self.document_path + (field,)) if self._is_normalized and has_error: self._drop_remaining_rules()
def _validate_readonly(self, readonly, field, value): """ {'type': 'boolean'} """ if readonly: if not self._is_normalized: self._error(field, errors.READONLY_FIELD) # If the document was normalized (and therefore already been # checked for readonly fields), we still have to return True # if an error was filed. has_error = errors.READONLY_FIELD in \ self.document_error_tree.fetch_errors_from( self.document_path + (field,)) if self._is_normalized and has_error: self._drop_remaining_rules()
[ "{", "type", ":", "boolean", "}" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/validator.py#L1169-L1181
[ "def", "_validate_readonly", "(", "self", ",", "readonly", ",", "field", ",", "value", ")", ":", "if", "readonly", ":", "if", "not", "self", ".", "_is_normalized", ":", "self", ".", "_error", "(", "field", ",", "errors", ".", "READONLY_FIELD", ")", "# If...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
BareValidator._validate_regex
{'type': 'string'}
pipenv/vendor/cerberus/validator.py
def _validate_regex(self, pattern, field, value): """ {'type': 'string'} """ if not isinstance(value, _str_type): return if not pattern.endswith('$'): pattern += '$' re_obj = re.compile(pattern) if not re_obj.match(value): self._error(field, errors.REGEX_MISMATCH)
def _validate_regex(self, pattern, field, value): """ {'type': 'string'} """ if not isinstance(value, _str_type): return if not pattern.endswith('$'): pattern += '$' re_obj = re.compile(pattern) if not re_obj.match(value): self._error(field, errors.REGEX_MISMATCH)
[ "{", "type", ":", "string", "}" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/validator.py#L1183-L1191
[ "def", "_validate_regex", "(", "self", ",", "pattern", ",", "field", ",", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "_str_type", ")", ":", "return", "if", "not", "pattern", ".", "endswith", "(", "'$'", ")", ":", "pattern", "+=", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
BareValidator.__validate_required_fields
Validates that required fields are not missing. :param document: The document being validated.
pipenv/vendor/cerberus/validator.py
def __validate_required_fields(self, document): """ Validates that required fields are not missing. :param document: The document being validated. """ try: required = set(field for field, definition in self.schema.items() if self._resolve_rules_set(definition). get('required') is True) except AttributeError: if self.is_child and self.schema_path[-1] == 'schema': raise _SchemaRuleTypeError else: raise required -= self._unrequired_by_excludes missing = required - set(field for field in document if document.get(field) is not None or not self.ignore_none_values) for field in missing: self._error(field, errors.REQUIRED_FIELD) # At least on field from self._unrequired_by_excludes should be # present in document if self._unrequired_by_excludes: fields = set(field for field in document if document.get(field) is not None) if self._unrequired_by_excludes.isdisjoint(fields): for field in self._unrequired_by_excludes - fields: self._error(field, errors.REQUIRED_FIELD)
def __validate_required_fields(self, document): """ Validates that required fields are not missing. :param document: The document being validated. """ try: required = set(field for field, definition in self.schema.items() if self._resolve_rules_set(definition). get('required') is True) except AttributeError: if self.is_child and self.schema_path[-1] == 'schema': raise _SchemaRuleTypeError else: raise required -= self._unrequired_by_excludes missing = required - set(field for field in document if document.get(field) is not None or not self.ignore_none_values) for field in missing: self._error(field, errors.REQUIRED_FIELD) # At least on field from self._unrequired_by_excludes should be # present in document if self._unrequired_by_excludes: fields = set(field for field in document if document.get(field) is not None) if self._unrequired_by_excludes.isdisjoint(fields): for field in self._unrequired_by_excludes - fields: self._error(field, errors.REQUIRED_FIELD)
[ "Validates", "that", "required", "fields", "are", "not", "missing", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/validator.py#L1195-L1224
[ "def", "__validate_required_fields", "(", "self", ",", "document", ")", ":", "try", ":", "required", "=", "set", "(", "field", "for", "field", ",", "definition", "in", "self", ".", "schema", ".", "items", "(", ")", "if", "self", ".", "_resolve_rules_set", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
BareValidator._validate_schema
{'type': ['dict', 'string'], 'anyof': [{'validator': 'schema'}, {'validator': 'bulk_schema'}]}
pipenv/vendor/cerberus/validator.py
def _validate_schema(self, schema, field, value): """ {'type': ['dict', 'string'], 'anyof': [{'validator': 'schema'}, {'validator': 'bulk_schema'}]} """ if schema is None: return if isinstance(value, Sequence) and not isinstance(value, _str_type): self.__validate_schema_sequence(field, schema, value) elif isinstance(value, Mapping): self.__validate_schema_mapping(field, schema, value)
def _validate_schema(self, schema, field, value): """ {'type': ['dict', 'string'], 'anyof': [{'validator': 'schema'}, {'validator': 'bulk_schema'}]} """ if schema is None: return if isinstance(value, Sequence) and not isinstance(value, _str_type): self.__validate_schema_sequence(field, schema, value) elif isinstance(value, Mapping): self.__validate_schema_mapping(field, schema, value)
[ "{", "type", ":", "[", "dict", "string", "]", "anyof", ":", "[", "{", "validator", ":", "schema", "}", "{", "validator", ":", "bulk_schema", "}", "]", "}" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/validator.py#L1226-L1236
[ "def", "_validate_schema", "(", "self", ",", "schema", ",", "field", ",", "value", ")", ":", "if", "schema", "is", "None", ":", "return", "if", "isinstance", "(", "value", ",", "Sequence", ")", "and", "not", "isinstance", "(", "value", ",", "_str_type", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
BareValidator._validate_type
{'type': ['string', 'list'], 'validator': 'type'}
pipenv/vendor/cerberus/validator.py
def _validate_type(self, data_type, field, value): """ {'type': ['string', 'list'], 'validator': 'type'} """ if not data_type: return types = (data_type,) if isinstance(data_type, _str_type) else data_type for _type in types: # TODO remove this block on next major release # this implementation still supports custom type validation methods type_definition = self.types_mapping.get(_type) if type_definition is not None: matched = isinstance(value, type_definition.included_types) \ and not isinstance(value, type_definition.excluded_types) else: type_handler = self.__get_rule_handler('validate_type', _type) matched = type_handler(value) if matched: return # TODO uncomment this block on next major release # when _validate_type_* methods were deprecated: # type_definition = self.types_mapping[_type] # if isinstance(value, type_definition.included_types) \ # and not isinstance(value, type_definition.excluded_types): # noqa 501 # return self._error(field, errors.BAD_TYPE) self._drop_remaining_rules()
def _validate_type(self, data_type, field, value): """ {'type': ['string', 'list'], 'validator': 'type'} """ if not data_type: return types = (data_type,) if isinstance(data_type, _str_type) else data_type for _type in types: # TODO remove this block on next major release # this implementation still supports custom type validation methods type_definition = self.types_mapping.get(_type) if type_definition is not None: matched = isinstance(value, type_definition.included_types) \ and not isinstance(value, type_definition.excluded_types) else: type_handler = self.__get_rule_handler('validate_type', _type) matched = type_handler(value) if matched: return # TODO uncomment this block on next major release # when _validate_type_* methods were deprecated: # type_definition = self.types_mapping[_type] # if isinstance(value, type_definition.included_types) \ # and not isinstance(value, type_definition.excluded_types): # noqa 501 # return self._error(field, errors.BAD_TYPE) self._drop_remaining_rules()
[ "{", "type", ":", "[", "string", "list", "]", "validator", ":", "type", "}" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/validator.py#L1265-L1294
[ "def", "_validate_type", "(", "self", ",", "data_type", ",", "field", ",", "value", ")", ":", "if", "not", "data_type", ":", "return", "types", "=", "(", "data_type", ",", ")", "if", "isinstance", "(", "data_type", ",", "_str_type", ")", "else", "data_ty...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
BareValidator._validate_validator
{'oneof': [ {'type': 'callable'}, {'type': 'list', 'schema': {'oneof': [{'type': 'callable'}, {'type': 'string'}]}}, {'type': 'string'} ]}
pipenv/vendor/cerberus/validator.py
def _validate_validator(self, validator, field, value): """ {'oneof': [ {'type': 'callable'}, {'type': 'list', 'schema': {'oneof': [{'type': 'callable'}, {'type': 'string'}]}}, {'type': 'string'} ]} """ if isinstance(validator, _str_type): validator = self.__get_rule_handler('validator', validator) validator(field, value) elif isinstance(validator, Iterable): for v in validator: self._validate_validator(v, field, value) else: validator(field, value, self._error)
def _validate_validator(self, validator, field, value): """ {'oneof': [ {'type': 'callable'}, {'type': 'list', 'schema': {'oneof': [{'type': 'callable'}, {'type': 'string'}]}}, {'type': 'string'} ]} """ if isinstance(validator, _str_type): validator = self.__get_rule_handler('validator', validator) validator(field, value) elif isinstance(validator, Iterable): for v in validator: self._validate_validator(v, field, value) else: validator(field, value, self._error)
[ "{", "oneof", ":", "[", "{", "type", ":", "callable", "}", "{", "type", ":", "list", "schema", ":", "{", "oneof", ":", "[", "{", "type", ":", "callable", "}", "{", "type", ":", "string", "}", "]", "}}", "{", "type", ":", "string", "}", "]", "...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/validator.py#L1296-L1311
[ "def", "_validate_validator", "(", "self", ",", "validator", ",", "field", ",", "value", ")", ":", "if", "isinstance", "(", "validator", ",", "_str_type", ")", ":", "validator", "=", "self", ".", "__get_rule_handler", "(", "'validator'", ",", "validator", ")...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
BareValidator._validate_valueschema
{'type': ['dict', 'string'], 'validator': 'bulk_schema', 'forbidden': ['rename', 'rename_handler']}
pipenv/vendor/cerberus/validator.py
def _validate_valueschema(self, schema, field, value): """ {'type': ['dict', 'string'], 'validator': 'bulk_schema', 'forbidden': ['rename', 'rename_handler']} """ schema_crumb = (field, 'valueschema') if isinstance(value, Mapping): validator = self._get_child_validator( document_crumb=field, schema_crumb=schema_crumb, schema=dict((k, schema) for k in value)) validator(value, update=self.update, normalize=False) if validator._errors: self._drop_nodes_from_errorpaths(validator._errors, [], [2]) self._error(field, errors.VALUESCHEMA, validator._errors)
def _validate_valueschema(self, schema, field, value): """ {'type': ['dict', 'string'], 'validator': 'bulk_schema', 'forbidden': ['rename', 'rename_handler']} """ schema_crumb = (field, 'valueschema') if isinstance(value, Mapping): validator = self._get_child_validator( document_crumb=field, schema_crumb=schema_crumb, schema=dict((k, schema) for k in value)) validator(value, update=self.update, normalize=False) if validator._errors: self._drop_nodes_from_errorpaths(validator._errors, [], [2]) self._error(field, errors.VALUESCHEMA, validator._errors)
[ "{", "type", ":", "[", "dict", "string", "]", "validator", ":", "bulk_schema", "forbidden", ":", "[", "rename", "rename_handler", "]", "}" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/validator.py#L1313-L1324
[ "def", "_validate_valueschema", "(", "self", ",", "schema", ",", "field", ",", "value", ")", ":", "schema_crumb", "=", "(", "field", ",", "'valueschema'", ")", "if", "isinstance", "(", "value", ",", "Mapping", ")", ":", "validator", "=", "self", ".", "_g...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
make_attrgetter
Returns a callable that looks up the given attribute from a passed object with the rules of the environment. Dots are allowed to access attributes of attributes. Integer parts in paths are looked up as integers.
pipenv/vendor/jinja2/filters.py
def make_attrgetter(environment, attribute, postprocess=None): """Returns a callable that looks up the given attribute from a passed object with the rules of the environment. Dots are allowed to access attributes of attributes. Integer parts in paths are looked up as integers. """ if attribute is None: attribute = [] elif isinstance(attribute, string_types): attribute = [int(x) if x.isdigit() else x for x in attribute.split('.')] else: attribute = [attribute] def attrgetter(item): for part in attribute: item = environment.getitem(item, part) if postprocess is not None: item = postprocess(item) return item return attrgetter
def make_attrgetter(environment, attribute, postprocess=None): """Returns a callable that looks up the given attribute from a passed object with the rules of the environment. Dots are allowed to access attributes of attributes. Integer parts in paths are looked up as integers. """ if attribute is None: attribute = [] elif isinstance(attribute, string_types): attribute = [int(x) if x.isdigit() else x for x in attribute.split('.')] else: attribute = [attribute] def attrgetter(item): for part in attribute: item = environment.getitem(item, part) if postprocess is not None: item = postprocess(item) return item return attrgetter
[ "Returns", "a", "callable", "that", "looks", "up", "the", "given", "attribute", "from", "a", "passed", "object", "with", "the", "rules", "of", "the", "environment", ".", "Dots", "are", "allowed", "to", "access", "attributes", "of", "attributes", ".", "Intege...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/filters.py#L62-L84
[ "def", "make_attrgetter", "(", "environment", ",", "attribute", ",", "postprocess", "=", "None", ")", ":", "if", "attribute", "is", "None", ":", "attribute", "=", "[", "]", "elif", "isinstance", "(", "attribute", ",", "string_types", ")", ":", "attribute", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
do_forceescape
Enforce HTML escaping. This will probably double escape variables.
pipenv/vendor/jinja2/filters.py
def do_forceescape(value): """Enforce HTML escaping. This will probably double escape variables.""" if hasattr(value, '__html__'): value = value.__html__() return escape(text_type(value))
def do_forceescape(value): """Enforce HTML escaping. This will probably double escape variables.""" if hasattr(value, '__html__'): value = value.__html__() return escape(text_type(value))
[ "Enforce", "HTML", "escaping", ".", "This", "will", "probably", "double", "escape", "variables", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/filters.py#L87-L91
[ "def", "do_forceescape", "(", "value", ")", ":", "if", "hasattr", "(", "value", ",", "'__html__'", ")", ":", "value", "=", "value", ".", "__html__", "(", ")", "return", "escape", "(", "text_type", "(", "value", ")", ")" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
do_urlencode
Escape strings for use in URLs (uses UTF-8 encoding). It accepts both dictionaries and regular strings as well as pairwise iterables. .. versionadded:: 2.7
pipenv/vendor/jinja2/filters.py
def do_urlencode(value): """Escape strings for use in URLs (uses UTF-8 encoding). It accepts both dictionaries and regular strings as well as pairwise iterables. .. versionadded:: 2.7 """ itemiter = None if isinstance(value, dict): itemiter = iteritems(value) elif not isinstance(value, string_types): try: itemiter = iter(value) except TypeError: pass if itemiter is None: return unicode_urlencode(value) return u'&'.join(unicode_urlencode(k) + '=' + unicode_urlencode(v, for_qs=True) for k, v in itemiter)
def do_urlencode(value): """Escape strings for use in URLs (uses UTF-8 encoding). It accepts both dictionaries and regular strings as well as pairwise iterables. .. versionadded:: 2.7 """ itemiter = None if isinstance(value, dict): itemiter = iteritems(value) elif not isinstance(value, string_types): try: itemiter = iter(value) except TypeError: pass if itemiter is None: return unicode_urlencode(value) return u'&'.join(unicode_urlencode(k) + '=' + unicode_urlencode(v, for_qs=True) for k, v in itemiter)
[ "Escape", "strings", "for", "use", "in", "URLs", "(", "uses", "UTF", "-", "8", "encoding", ")", ".", "It", "accepts", "both", "dictionaries", "and", "regular", "strings", "as", "well", "as", "pairwise", "iterables", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/filters.py#L94-L112
[ "def", "do_urlencode", "(", "value", ")", ":", "itemiter", "=", "None", "if", "isinstance", "(", "value", ",", "dict", ")", ":", "itemiter", "=", "iteritems", "(", "value", ")", "elif", "not", "isinstance", "(", "value", ",", "string_types", ")", ":", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
do_title
Return a titlecased version of the value. I.e. words will start with uppercase letters, all remaining characters are lowercase.
pipenv/vendor/jinja2/filters.py
def do_title(s): """Return a titlecased version of the value. I.e. words will start with uppercase letters, all remaining characters are lowercase. """ return ''.join( [item[0].upper() + item[1:].lower() for item in _word_beginning_split_re.split(soft_unicode(s)) if item])
def do_title(s): """Return a titlecased version of the value. I.e. words will start with uppercase letters, all remaining characters are lowercase. """ return ''.join( [item[0].upper() + item[1:].lower() for item in _word_beginning_split_re.split(soft_unicode(s)) if item])
[ "Return", "a", "titlecased", "version", "of", "the", "value", ".", "I", ".", "e", ".", "words", "will", "start", "with", "uppercase", "letters", "all", "remaining", "characters", "are", "lowercase", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/filters.py#L196-L203
[ "def", "do_title", "(", "s", ")", ":", "return", "''", ".", "join", "(", "[", "item", "[", "0", "]", ".", "upper", "(", ")", "+", "item", "[", "1", ":", "]", ".", "lower", "(", ")", "for", "item", "in", "_word_beginning_split_re", ".", "split", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
do_dictsort
Sort a dict and yield (key, value) pairs. Because python dicts are unsorted you may want to use this function to order them by either key or value: .. sourcecode:: jinja {% for item in mydict|dictsort %} sort the dict by key, case insensitive {% for item in mydict|dictsort(reverse=true) %} sort the dict by key, case insensitive, reverse order {% for item in mydict|dictsort(true) %} sort the dict by key, case sensitive {% for item in mydict|dictsort(false, 'value') %} sort the dict by value, case insensitive
pipenv/vendor/jinja2/filters.py
def do_dictsort(value, case_sensitive=False, by='key', reverse=False): """Sort a dict and yield (key, value) pairs. Because python dicts are unsorted you may want to use this function to order them by either key or value: .. sourcecode:: jinja {% for item in mydict|dictsort %} sort the dict by key, case insensitive {% for item in mydict|dictsort(reverse=true) %} sort the dict by key, case insensitive, reverse order {% for item in mydict|dictsort(true) %} sort the dict by key, case sensitive {% for item in mydict|dictsort(false, 'value') %} sort the dict by value, case insensitive """ if by == 'key': pos = 0 elif by == 'value': pos = 1 else: raise FilterArgumentError( 'You can only sort by either "key" or "value"' ) def sort_func(item): value = item[pos] if not case_sensitive: value = ignore_case(value) return value return sorted(value.items(), key=sort_func, reverse=reverse)
def do_dictsort(value, case_sensitive=False, by='key', reverse=False): """Sort a dict and yield (key, value) pairs. Because python dicts are unsorted you may want to use this function to order them by either key or value: .. sourcecode:: jinja {% for item in mydict|dictsort %} sort the dict by key, case insensitive {% for item in mydict|dictsort(reverse=true) %} sort the dict by key, case insensitive, reverse order {% for item in mydict|dictsort(true) %} sort the dict by key, case sensitive {% for item in mydict|dictsort(false, 'value') %} sort the dict by value, case insensitive """ if by == 'key': pos = 0 elif by == 'value': pos = 1 else: raise FilterArgumentError( 'You can only sort by either "key" or "value"' ) def sort_func(item): value = item[pos] if not case_sensitive: value = ignore_case(value) return value return sorted(value.items(), key=sort_func, reverse=reverse)
[ "Sort", "a", "dict", "and", "yield", "(", "key", "value", ")", "pairs", ".", "Because", "python", "dicts", "are", "unsorted", "you", "may", "want", "to", "use", "this", "function", "to", "order", "them", "by", "either", "key", "or", "value", ":" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/filters.py#L206-L242
[ "def", "do_dictsort", "(", "value", ",", "case_sensitive", "=", "False", ",", "by", "=", "'key'", ",", "reverse", "=", "False", ")", ":", "if", "by", "==", "'key'", ":", "pos", "=", "0", "elif", "by", "==", "'value'", ":", "pos", "=", "1", "else", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
do_sort
Sort an iterable. Per default it sorts ascending, if you pass it true as first argument it will reverse the sorting. If the iterable is made of strings the third parameter can be used to control the case sensitiveness of the comparison which is disabled by default. .. sourcecode:: jinja {% for item in iterable|sort %} ... {% endfor %} It is also possible to sort by an attribute (for example to sort by the date of an object) by specifying the `attribute` parameter: .. sourcecode:: jinja {% for item in iterable|sort(attribute='date') %} ... {% endfor %} .. versionchanged:: 2.6 The `attribute` parameter was added.
pipenv/vendor/jinja2/filters.py
def do_sort( environment, value, reverse=False, case_sensitive=False, attribute=None ): """Sort an iterable. Per default it sorts ascending, if you pass it true as first argument it will reverse the sorting. If the iterable is made of strings the third parameter can be used to control the case sensitiveness of the comparison which is disabled by default. .. sourcecode:: jinja {% for item in iterable|sort %} ... {% endfor %} It is also possible to sort by an attribute (for example to sort by the date of an object) by specifying the `attribute` parameter: .. sourcecode:: jinja {% for item in iterable|sort(attribute='date') %} ... {% endfor %} .. versionchanged:: 2.6 The `attribute` parameter was added. """ key_func = make_attrgetter( environment, attribute, postprocess=ignore_case if not case_sensitive else None ) return sorted(value, key=key_func, reverse=reverse)
def do_sort( environment, value, reverse=False, case_sensitive=False, attribute=None ): """Sort an iterable. Per default it sorts ascending, if you pass it true as first argument it will reverse the sorting. If the iterable is made of strings the third parameter can be used to control the case sensitiveness of the comparison which is disabled by default. .. sourcecode:: jinja {% for item in iterable|sort %} ... {% endfor %} It is also possible to sort by an attribute (for example to sort by the date of an object) by specifying the `attribute` parameter: .. sourcecode:: jinja {% for item in iterable|sort(attribute='date') %} ... {% endfor %} .. versionchanged:: 2.6 The `attribute` parameter was added. """ key_func = make_attrgetter( environment, attribute, postprocess=ignore_case if not case_sensitive else None ) return sorted(value, key=key_func, reverse=reverse)
[ "Sort", "an", "iterable", ".", "Per", "default", "it", "sorts", "ascending", "if", "you", "pass", "it", "true", "as", "first", "argument", "it", "will", "reverse", "the", "sorting", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/filters.py#L246-L278
[ "def", "do_sort", "(", "environment", ",", "value", ",", "reverse", "=", "False", ",", "case_sensitive", "=", "False", ",", "attribute", "=", "None", ")", ":", "key_func", "=", "make_attrgetter", "(", "environment", ",", "attribute", ",", "postprocess", "=",...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
do_unique
Returns a list of unique items from the the given iterable. .. sourcecode:: jinja {{ ['foo', 'bar', 'foobar', 'FooBar']|unique }} -> ['foo', 'bar', 'foobar'] The unique items are yielded in the same order as their first occurrence in the iterable passed to the filter. :param case_sensitive: Treat upper and lower case strings as distinct. :param attribute: Filter objects with unique values for this attribute.
pipenv/vendor/jinja2/filters.py
def do_unique(environment, value, case_sensitive=False, attribute=None): """Returns a list of unique items from the the given iterable. .. sourcecode:: jinja {{ ['foo', 'bar', 'foobar', 'FooBar']|unique }} -> ['foo', 'bar', 'foobar'] The unique items are yielded in the same order as their first occurrence in the iterable passed to the filter. :param case_sensitive: Treat upper and lower case strings as distinct. :param attribute: Filter objects with unique values for this attribute. """ getter = make_attrgetter( environment, attribute, postprocess=ignore_case if not case_sensitive else None ) seen = set() for item in value: key = getter(item) if key not in seen: seen.add(key) yield item
def do_unique(environment, value, case_sensitive=False, attribute=None): """Returns a list of unique items from the the given iterable. .. sourcecode:: jinja {{ ['foo', 'bar', 'foobar', 'FooBar']|unique }} -> ['foo', 'bar', 'foobar'] The unique items are yielded in the same order as their first occurrence in the iterable passed to the filter. :param case_sensitive: Treat upper and lower case strings as distinct. :param attribute: Filter objects with unique values for this attribute. """ getter = make_attrgetter( environment, attribute, postprocess=ignore_case if not case_sensitive else None ) seen = set() for item in value: key = getter(item) if key not in seen: seen.add(key) yield item
[ "Returns", "a", "list", "of", "unique", "items", "from", "the", "the", "given", "iterable", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/filters.py#L282-L307
[ "def", "do_unique", "(", "environment", ",", "value", ",", "case_sensitive", "=", "False", ",", "attribute", "=", "None", ")", ":", "getter", "=", "make_attrgetter", "(", "environment", ",", "attribute", ",", "postprocess", "=", "ignore_case", "if", "not", "...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
do_min
Return the smallest item from the sequence. .. sourcecode:: jinja {{ [1, 2, 3]|min }} -> 1 :param case_sensitive: Treat upper and lower case strings as distinct. :param attribute: Get the object with the max value of this attribute.
pipenv/vendor/jinja2/filters.py
def do_min(environment, value, case_sensitive=False, attribute=None): """Return the smallest item from the sequence. .. sourcecode:: jinja {{ [1, 2, 3]|min }} -> 1 :param case_sensitive: Treat upper and lower case strings as distinct. :param attribute: Get the object with the max value of this attribute. """ return _min_or_max(environment, value, min, case_sensitive, attribute)
def do_min(environment, value, case_sensitive=False, attribute=None): """Return the smallest item from the sequence. .. sourcecode:: jinja {{ [1, 2, 3]|min }} -> 1 :param case_sensitive: Treat upper and lower case strings as distinct. :param attribute: Get the object with the max value of this attribute. """ return _min_or_max(environment, value, min, case_sensitive, attribute)
[ "Return", "the", "smallest", "item", "from", "the", "sequence", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/filters.py#L326-L337
[ "def", "do_min", "(", "environment", ",", "value", ",", "case_sensitive", "=", "False", ",", "attribute", "=", "None", ")", ":", "return", "_min_or_max", "(", "environment", ",", "value", ",", "min", ",", "case_sensitive", ",", "attribute", ")" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
do_max
Return the largest item from the sequence. .. sourcecode:: jinja {{ [1, 2, 3]|max }} -> 3 :param case_sensitive: Treat upper and lower case strings as distinct. :param attribute: Get the object with the max value of this attribute.
pipenv/vendor/jinja2/filters.py
def do_max(environment, value, case_sensitive=False, attribute=None): """Return the largest item from the sequence. .. sourcecode:: jinja {{ [1, 2, 3]|max }} -> 3 :param case_sensitive: Treat upper and lower case strings as distinct. :param attribute: Get the object with the max value of this attribute. """ return _min_or_max(environment, value, max, case_sensitive, attribute)
def do_max(environment, value, case_sensitive=False, attribute=None): """Return the largest item from the sequence. .. sourcecode:: jinja {{ [1, 2, 3]|max }} -> 3 :param case_sensitive: Treat upper and lower case strings as distinct. :param attribute: Get the object with the max value of this attribute. """ return _min_or_max(environment, value, max, case_sensitive, attribute)
[ "Return", "the", "largest", "item", "from", "the", "sequence", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/filters.py#L341-L352
[ "def", "do_max", "(", "environment", ",", "value", ",", "case_sensitive", "=", "False", ",", "attribute", "=", "None", ")", ":", "return", "_min_or_max", "(", "environment", ",", "value", ",", "max", ",", "case_sensitive", ",", "attribute", ")" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
do_join
Return a string which is the concatenation of the strings in the sequence. The separator between elements is an empty string per default, you can define it with the optional parameter: .. sourcecode:: jinja {{ [1, 2, 3]|join('|') }} -> 1|2|3 {{ [1, 2, 3]|join }} -> 123 It is also possible to join certain attributes of an object: .. sourcecode:: jinja {{ users|join(', ', attribute='username') }} .. versionadded:: 2.6 The `attribute` parameter was added.
pipenv/vendor/jinja2/filters.py
def do_join(eval_ctx, value, d=u'', attribute=None): """Return a string which is the concatenation of the strings in the sequence. The separator between elements is an empty string per default, you can define it with the optional parameter: .. sourcecode:: jinja {{ [1, 2, 3]|join('|') }} -> 1|2|3 {{ [1, 2, 3]|join }} -> 123 It is also possible to join certain attributes of an object: .. sourcecode:: jinja {{ users|join(', ', attribute='username') }} .. versionadded:: 2.6 The `attribute` parameter was added. """ if attribute is not None: value = imap(make_attrgetter(eval_ctx.environment, attribute), value) # no automatic escaping? joining is a lot eaiser then if not eval_ctx.autoescape: return text_type(d).join(imap(text_type, value)) # if the delimiter doesn't have an html representation we check # if any of the items has. If yes we do a coercion to Markup if not hasattr(d, '__html__'): value = list(value) do_escape = False for idx, item in enumerate(value): if hasattr(item, '__html__'): do_escape = True else: value[idx] = text_type(item) if do_escape: d = escape(d) else: d = text_type(d) return d.join(value) # no html involved, to normal joining return soft_unicode(d).join(imap(soft_unicode, value))
def do_join(eval_ctx, value, d=u'', attribute=None): """Return a string which is the concatenation of the strings in the sequence. The separator between elements is an empty string per default, you can define it with the optional parameter: .. sourcecode:: jinja {{ [1, 2, 3]|join('|') }} -> 1|2|3 {{ [1, 2, 3]|join }} -> 123 It is also possible to join certain attributes of an object: .. sourcecode:: jinja {{ users|join(', ', attribute='username') }} .. versionadded:: 2.6 The `attribute` parameter was added. """ if attribute is not None: value = imap(make_attrgetter(eval_ctx.environment, attribute), value) # no automatic escaping? joining is a lot eaiser then if not eval_ctx.autoescape: return text_type(d).join(imap(text_type, value)) # if the delimiter doesn't have an html representation we check # if any of the items has. If yes we do a coercion to Markup if not hasattr(d, '__html__'): value = list(value) do_escape = False for idx, item in enumerate(value): if hasattr(item, '__html__'): do_escape = True else: value[idx] = text_type(item) if do_escape: d = escape(d) else: d = text_type(d) return d.join(value) # no html involved, to normal joining return soft_unicode(d).join(imap(soft_unicode, value))
[ "Return", "a", "string", "which", "is", "the", "concatenation", "of", "the", "strings", "in", "the", "sequence", ".", "The", "separator", "between", "elements", "is", "an", "empty", "string", "per", "default", "you", "can", "define", "it", "with", "the", "...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/filters.py#L378-L424
[ "def", "do_join", "(", "eval_ctx", ",", "value", ",", "d", "=", "u''", ",", "attribute", "=", "None", ")", ":", "if", "attribute", "is", "not", "None", ":", "value", "=", "imap", "(", "make_attrgetter", "(", "eval_ctx", ".", "environment", ",", "attrib...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
do_last
Return the last item of a sequence.
pipenv/vendor/jinja2/filters.py
def do_last(environment, seq): """Return the last item of a sequence.""" try: return next(iter(reversed(seq))) except StopIteration: return environment.undefined('No last item, sequence was empty.')
def do_last(environment, seq): """Return the last item of a sequence.""" try: return next(iter(reversed(seq))) except StopIteration: return environment.undefined('No last item, sequence was empty.')
[ "Return", "the", "last", "item", "of", "a", "sequence", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/filters.py#L442-L447
[ "def", "do_last", "(", "environment", ",", "seq", ")", ":", "try", ":", "return", "next", "(", "iter", "(", "reversed", "(", "seq", ")", ")", ")", "except", "StopIteration", ":", "return", "environment", ".", "undefined", "(", "'No last item, sequence was em...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
do_random
Return a random item from the sequence.
pipenv/vendor/jinja2/filters.py
def do_random(context, seq): """Return a random item from the sequence.""" try: return random.choice(seq) except IndexError: return context.environment.undefined('No random item, sequence was empty.')
def do_random(context, seq): """Return a random item from the sequence.""" try: return random.choice(seq) except IndexError: return context.environment.undefined('No random item, sequence was empty.')
[ "Return", "a", "random", "item", "from", "the", "sequence", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/filters.py#L451-L456
[ "def", "do_random", "(", "context", ",", "seq", ")", ":", "try", ":", "return", "random", ".", "choice", "(", "seq", ")", "except", "IndexError", ":", "return", "context", ".", "environment", ".", "undefined", "(", "'No random item, sequence was empty.'", ")" ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
do_filesizeformat
Format the value like a 'human-readable' file size (i.e. 13 kB, 4.1 MB, 102 Bytes, etc). Per default decimal prefixes are used (Mega, Giga, etc.), if the second parameter is set to `True` the binary prefixes are used (Mebi, Gibi).
pipenv/vendor/jinja2/filters.py
def do_filesizeformat(value, binary=False): """Format the value like a 'human-readable' file size (i.e. 13 kB, 4.1 MB, 102 Bytes, etc). Per default decimal prefixes are used (Mega, Giga, etc.), if the second parameter is set to `True` the binary prefixes are used (Mebi, Gibi). """ bytes = float(value) base = binary and 1024 or 1000 prefixes = [ (binary and 'KiB' or 'kB'), (binary and 'MiB' or 'MB'), (binary and 'GiB' or 'GB'), (binary and 'TiB' or 'TB'), (binary and 'PiB' or 'PB'), (binary and 'EiB' or 'EB'), (binary and 'ZiB' or 'ZB'), (binary and 'YiB' or 'YB') ] if bytes == 1: return '1 Byte' elif bytes < base: return '%d Bytes' % bytes else: for i, prefix in enumerate(prefixes): unit = base ** (i + 2) if bytes < unit: return '%.1f %s' % ((base * bytes / unit), prefix) return '%.1f %s' % ((base * bytes / unit), prefix)
def do_filesizeformat(value, binary=False): """Format the value like a 'human-readable' file size (i.e. 13 kB, 4.1 MB, 102 Bytes, etc). Per default decimal prefixes are used (Mega, Giga, etc.), if the second parameter is set to `True` the binary prefixes are used (Mebi, Gibi). """ bytes = float(value) base = binary and 1024 or 1000 prefixes = [ (binary and 'KiB' or 'kB'), (binary and 'MiB' or 'MB'), (binary and 'GiB' or 'GB'), (binary and 'TiB' or 'TB'), (binary and 'PiB' or 'PB'), (binary and 'EiB' or 'EB'), (binary and 'ZiB' or 'ZB'), (binary and 'YiB' or 'YB') ] if bytes == 1: return '1 Byte' elif bytes < base: return '%d Bytes' % bytes else: for i, prefix in enumerate(prefixes): unit = base ** (i + 2) if bytes < unit: return '%.1f %s' % ((base * bytes / unit), prefix) return '%.1f %s' % ((base * bytes / unit), prefix)
[ "Format", "the", "value", "like", "a", "human", "-", "readable", "file", "size", "(", "i", ".", "e", ".", "13", "kB", "4", ".", "1", "MB", "102", "Bytes", "etc", ")", ".", "Per", "default", "decimal", "prefixes", "are", "used", "(", "Mega", "Giga",...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/filters.py#L459-L486
[ "def", "do_filesizeformat", "(", "value", ",", "binary", "=", "False", ")", ":", "bytes", "=", "float", "(", "value", ")", "base", "=", "binary", "and", "1024", "or", "1000", "prefixes", "=", "[", "(", "binary", "and", "'KiB'", "or", "'kB'", ")", ","...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
do_urlize
Converts URLs in plain text into clickable links. If you pass the filter an additional integer it will shorten the urls to that number. Also a third argument exists that makes the urls "nofollow": .. sourcecode:: jinja {{ mytext|urlize(40, true) }} links are shortened to 40 chars and defined with rel="nofollow" If *target* is specified, the ``target`` attribute will be added to the ``<a>`` tag: .. sourcecode:: jinja {{ mytext|urlize(40, target='_blank') }} .. versionchanged:: 2.8+ The *target* parameter was added.
pipenv/vendor/jinja2/filters.py
def do_urlize(eval_ctx, value, trim_url_limit=None, nofollow=False, target=None, rel=None): """Converts URLs in plain text into clickable links. If you pass the filter an additional integer it will shorten the urls to that number. Also a third argument exists that makes the urls "nofollow": .. sourcecode:: jinja {{ mytext|urlize(40, true) }} links are shortened to 40 chars and defined with rel="nofollow" If *target* is specified, the ``target`` attribute will be added to the ``<a>`` tag: .. sourcecode:: jinja {{ mytext|urlize(40, target='_blank') }} .. versionchanged:: 2.8+ The *target* parameter was added. """ policies = eval_ctx.environment.policies rel = set((rel or '').split() or []) if nofollow: rel.add('nofollow') rel.update((policies['urlize.rel'] or '').split()) if target is None: target = policies['urlize.target'] rel = ' '.join(sorted(rel)) or None rv = urlize(value, trim_url_limit, rel=rel, target=target) if eval_ctx.autoescape: rv = Markup(rv) return rv
def do_urlize(eval_ctx, value, trim_url_limit=None, nofollow=False, target=None, rel=None): """Converts URLs in plain text into clickable links. If you pass the filter an additional integer it will shorten the urls to that number. Also a third argument exists that makes the urls "nofollow": .. sourcecode:: jinja {{ mytext|urlize(40, true) }} links are shortened to 40 chars and defined with rel="nofollow" If *target* is specified, the ``target`` attribute will be added to the ``<a>`` tag: .. sourcecode:: jinja {{ mytext|urlize(40, target='_blank') }} .. versionchanged:: 2.8+ The *target* parameter was added. """ policies = eval_ctx.environment.policies rel = set((rel or '').split() or []) if nofollow: rel.add('nofollow') rel.update((policies['urlize.rel'] or '').split()) if target is None: target = policies['urlize.target'] rel = ' '.join(sorted(rel)) or None rv = urlize(value, trim_url_limit, rel=rel, target=target) if eval_ctx.autoescape: rv = Markup(rv) return rv
[ "Converts", "URLs", "in", "plain", "text", "into", "clickable", "links", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/filters.py#L499-L533
[ "def", "do_urlize", "(", "eval_ctx", ",", "value", ",", "trim_url_limit", "=", "None", ",", "nofollow", "=", "False", ",", "target", "=", "None", ",", "rel", "=", "None", ")", ":", "policies", "=", "eval_ctx", ".", "environment", ".", "policies", "rel", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
do_indent
Return a copy of the string with each line indented by 4 spaces. The first line and blank lines are not indented by default. :param width: Number of spaces to indent by. :param first: Don't skip indenting the first line. :param blank: Don't skip indenting empty lines. .. versionchanged:: 2.10 Blank lines are not indented by default. Rename the ``indentfirst`` argument to ``first``.
pipenv/vendor/jinja2/filters.py
def do_indent( s, width=4, first=False, blank=False, indentfirst=None ): """Return a copy of the string with each line indented by 4 spaces. The first line and blank lines are not indented by default. :param width: Number of spaces to indent by. :param first: Don't skip indenting the first line. :param blank: Don't skip indenting empty lines. .. versionchanged:: 2.10 Blank lines are not indented by default. Rename the ``indentfirst`` argument to ``first``. """ if indentfirst is not None: warnings.warn(DeprecationWarning( 'The "indentfirst" argument is renamed to "first".' ), stacklevel=2) first = indentfirst s += u'\n' # this quirk is necessary for splitlines method indention = u' ' * width if blank: rv = (u'\n' + indention).join(s.splitlines()) else: lines = s.splitlines() rv = lines.pop(0) if lines: rv += u'\n' + u'\n'.join( indention + line if line else line for line in lines ) if first: rv = indention + rv return rv
def do_indent( s, width=4, first=False, blank=False, indentfirst=None ): """Return a copy of the string with each line indented by 4 spaces. The first line and blank lines are not indented by default. :param width: Number of spaces to indent by. :param first: Don't skip indenting the first line. :param blank: Don't skip indenting empty lines. .. versionchanged:: 2.10 Blank lines are not indented by default. Rename the ``indentfirst`` argument to ``first``. """ if indentfirst is not None: warnings.warn(DeprecationWarning( 'The "indentfirst" argument is renamed to "first".' ), stacklevel=2) first = indentfirst s += u'\n' # this quirk is necessary for splitlines method indention = u' ' * width if blank: rv = (u'\n' + indention).join(s.splitlines()) else: lines = s.splitlines() rv = lines.pop(0) if lines: rv += u'\n' + u'\n'.join( indention + line if line else line for line in lines ) if first: rv = indention + rv return rv
[ "Return", "a", "copy", "of", "the", "string", "with", "each", "line", "indented", "by", "4", "spaces", ".", "The", "first", "line", "and", "blank", "lines", "are", "not", "indented", "by", "default", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/filters.py#L536-L574
[ "def", "do_indent", "(", "s", ",", "width", "=", "4", ",", "first", "=", "False", ",", "blank", "=", "False", ",", "indentfirst", "=", "None", ")", ":", "if", "indentfirst", "is", "not", "None", ":", "warnings", ".", "warn", "(", "DeprecationWarning", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
do_truncate
Return a truncated copy of the string. The length is specified with the first parameter which defaults to ``255``. If the second parameter is ``true`` the filter will cut the text at length. Otherwise it will discard the last word. If the text was in fact truncated it will append an ellipsis sign (``"..."``). If you want a different ellipsis sign than ``"..."`` you can specify it using the third parameter. Strings that only exceed the length by the tolerance margin given in the fourth parameter will not be truncated. .. sourcecode:: jinja {{ "foo bar baz qux"|truncate(9) }} -> "foo..." {{ "foo bar baz qux"|truncate(9, True) }} -> "foo ba..." {{ "foo bar baz qux"|truncate(11) }} -> "foo bar baz qux" {{ "foo bar baz qux"|truncate(11, False, '...', 0) }} -> "foo bar..." The default leeway on newer Jinja2 versions is 5 and was 0 before but can be reconfigured globally.
pipenv/vendor/jinja2/filters.py
def do_truncate(env, s, length=255, killwords=False, end='...', leeway=None): """Return a truncated copy of the string. The length is specified with the first parameter which defaults to ``255``. If the second parameter is ``true`` the filter will cut the text at length. Otherwise it will discard the last word. If the text was in fact truncated it will append an ellipsis sign (``"..."``). If you want a different ellipsis sign than ``"..."`` you can specify it using the third parameter. Strings that only exceed the length by the tolerance margin given in the fourth parameter will not be truncated. .. sourcecode:: jinja {{ "foo bar baz qux"|truncate(9) }} -> "foo..." {{ "foo bar baz qux"|truncate(9, True) }} -> "foo ba..." {{ "foo bar baz qux"|truncate(11) }} -> "foo bar baz qux" {{ "foo bar baz qux"|truncate(11, False, '...', 0) }} -> "foo bar..." The default leeway on newer Jinja2 versions is 5 and was 0 before but can be reconfigured globally. """ if leeway is None: leeway = env.policies['truncate.leeway'] assert length >= len(end), 'expected length >= %s, got %s' % (len(end), length) assert leeway >= 0, 'expected leeway >= 0, got %s' % leeway if len(s) <= length + leeway: return s if killwords: return s[:length - len(end)] + end result = s[:length - len(end)].rsplit(' ', 1)[0] return result + end
def do_truncate(env, s, length=255, killwords=False, end='...', leeway=None): """Return a truncated copy of the string. The length is specified with the first parameter which defaults to ``255``. If the second parameter is ``true`` the filter will cut the text at length. Otherwise it will discard the last word. If the text was in fact truncated it will append an ellipsis sign (``"..."``). If you want a different ellipsis sign than ``"..."`` you can specify it using the third parameter. Strings that only exceed the length by the tolerance margin given in the fourth parameter will not be truncated. .. sourcecode:: jinja {{ "foo bar baz qux"|truncate(9) }} -> "foo..." {{ "foo bar baz qux"|truncate(9, True) }} -> "foo ba..." {{ "foo bar baz qux"|truncate(11) }} -> "foo bar baz qux" {{ "foo bar baz qux"|truncate(11, False, '...', 0) }} -> "foo bar..." The default leeway on newer Jinja2 versions is 5 and was 0 before but can be reconfigured globally. """ if leeway is None: leeway = env.policies['truncate.leeway'] assert length >= len(end), 'expected length >= %s, got %s' % (len(end), length) assert leeway >= 0, 'expected leeway >= 0, got %s' % leeway if len(s) <= length + leeway: return s if killwords: return s[:length - len(end)] + end result = s[:length - len(end)].rsplit(' ', 1)[0] return result + end
[ "Return", "a", "truncated", "copy", "of", "the", "string", ".", "The", "length", "is", "specified", "with", "the", "first", "parameter", "which", "defaults", "to", "255", ".", "If", "the", "second", "parameter", "is", "true", "the", "filter", "will", "cut"...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/filters.py#L578-L611
[ "def", "do_truncate", "(", "env", ",", "s", ",", "length", "=", "255", ",", "killwords", "=", "False", ",", "end", "=", "'...'", ",", "leeway", "=", "None", ")", ":", "if", "leeway", "is", "None", ":", "leeway", "=", "env", ".", "policies", "[", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
do_wordwrap
Return a copy of the string passed to the filter wrapped after ``79`` characters. You can override this default using the first parameter. If you set the second parameter to `false` Jinja will not split words apart if they are longer than `width`. By default, the newlines will be the default newlines for the environment, but this can be changed using the wrapstring keyword argument. .. versionadded:: 2.7 Added support for the `wrapstring` parameter.
pipenv/vendor/jinja2/filters.py
def do_wordwrap(environment, s, width=79, break_long_words=True, wrapstring=None): """ Return a copy of the string passed to the filter wrapped after ``79`` characters. You can override this default using the first parameter. If you set the second parameter to `false` Jinja will not split words apart if they are longer than `width`. By default, the newlines will be the default newlines for the environment, but this can be changed using the wrapstring keyword argument. .. versionadded:: 2.7 Added support for the `wrapstring` parameter. """ if not wrapstring: wrapstring = environment.newline_sequence import textwrap return wrapstring.join(textwrap.wrap(s, width=width, expand_tabs=False, replace_whitespace=False, break_long_words=break_long_words))
def do_wordwrap(environment, s, width=79, break_long_words=True, wrapstring=None): """ Return a copy of the string passed to the filter wrapped after ``79`` characters. You can override this default using the first parameter. If you set the second parameter to `false` Jinja will not split words apart if they are longer than `width`. By default, the newlines will be the default newlines for the environment, but this can be changed using the wrapstring keyword argument. .. versionadded:: 2.7 Added support for the `wrapstring` parameter. """ if not wrapstring: wrapstring = environment.newline_sequence import textwrap return wrapstring.join(textwrap.wrap(s, width=width, expand_tabs=False, replace_whitespace=False, break_long_words=break_long_words))
[ "Return", "a", "copy", "of", "the", "string", "passed", "to", "the", "filter", "wrapped", "after", "79", "characters", ".", "You", "can", "override", "this", "default", "using", "the", "first", "parameter", ".", "If", "you", "set", "the", "second", "parame...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/filters.py#L615-L633
[ "def", "do_wordwrap", "(", "environment", ",", "s", ",", "width", "=", "79", ",", "break_long_words", "=", "True", ",", "wrapstring", "=", "None", ")", ":", "if", "not", "wrapstring", ":", "wrapstring", "=", "environment", ".", "newline_sequence", "import", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
do_int
Convert the value into an integer. If the conversion doesn't work it will return ``0``. You can override this default using the first parameter. You can also override the default base (10) in the second parameter, which handles input with prefixes such as 0b, 0o and 0x for bases 2, 8 and 16 respectively. The base is ignored for decimal numbers and non-string values.
pipenv/vendor/jinja2/filters.py
def do_int(value, default=0, base=10): """Convert the value into an integer. If the conversion doesn't work it will return ``0``. You can override this default using the first parameter. You can also override the default base (10) in the second parameter, which handles input with prefixes such as 0b, 0o and 0x for bases 2, 8 and 16 respectively. The base is ignored for decimal numbers and non-string values. """ try: if isinstance(value, string_types): return int(value, base) return int(value) except (TypeError, ValueError): # this quirk is necessary so that "42.23"|int gives 42. try: return int(float(value)) except (TypeError, ValueError): return default
def do_int(value, default=0, base=10): """Convert the value into an integer. If the conversion doesn't work it will return ``0``. You can override this default using the first parameter. You can also override the default base (10) in the second parameter, which handles input with prefixes such as 0b, 0o and 0x for bases 2, 8 and 16 respectively. The base is ignored for decimal numbers and non-string values. """ try: if isinstance(value, string_types): return int(value, base) return int(value) except (TypeError, ValueError): # this quirk is necessary so that "42.23"|int gives 42. try: return int(float(value)) except (TypeError, ValueError): return default
[ "Convert", "the", "value", "into", "an", "integer", ".", "If", "the", "conversion", "doesn", "t", "work", "it", "will", "return", "0", ".", "You", "can", "override", "this", "default", "using", "the", "first", "parameter", ".", "You", "can", "also", "ove...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/filters.py#L641-L659
[ "def", "do_int", "(", "value", ",", "default", "=", "0", ",", "base", "=", "10", ")", ":", "try", ":", "if", "isinstance", "(", "value", ",", "string_types", ")", ":", "return", "int", "(", "value", ",", "base", ")", "return", "int", "(", "value", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
do_format
Apply python string formatting on an object: .. sourcecode:: jinja {{ "%s - %s"|format("Hello?", "Foo!") }} -> Hello? - Foo!
pipenv/vendor/jinja2/filters.py
def do_format(value, *args, **kwargs): """ Apply python string formatting on an object: .. sourcecode:: jinja {{ "%s - %s"|format("Hello?", "Foo!") }} -> Hello? - Foo! """ if args and kwargs: raise FilterArgumentError('can\'t handle positional and keyword ' 'arguments at the same time') return soft_unicode(value) % (kwargs or args)
def do_format(value, *args, **kwargs): """ Apply python string formatting on an object: .. sourcecode:: jinja {{ "%s - %s"|format("Hello?", "Foo!") }} -> Hello? - Foo! """ if args and kwargs: raise FilterArgumentError('can\'t handle positional and keyword ' 'arguments at the same time') return soft_unicode(value) % (kwargs or args)
[ "Apply", "python", "string", "formatting", "on", "an", "object", ":" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/filters.py#L673-L685
[ "def", "do_format", "(", "value", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "args", "and", "kwargs", ":", "raise", "FilterArgumentError", "(", "'can\\'t handle positional and keyword '", "'arguments at the same time'", ")", "return", "soft_unicode",...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
do_striptags
Strip SGML/XML tags and replace adjacent whitespace by one space.
pipenv/vendor/jinja2/filters.py
def do_striptags(value): """Strip SGML/XML tags and replace adjacent whitespace by one space. """ if hasattr(value, '__html__'): value = value.__html__() return Markup(text_type(value)).striptags()
def do_striptags(value): """Strip SGML/XML tags and replace adjacent whitespace by one space. """ if hasattr(value, '__html__'): value = value.__html__() return Markup(text_type(value)).striptags()
[ "Strip", "SGML", "/", "XML", "tags", "and", "replace", "adjacent", "whitespace", "by", "one", "space", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/filters.py#L693-L698
[ "def", "do_striptags", "(", "value", ")", ":", "if", "hasattr", "(", "value", ",", "'__html__'", ")", ":", "value", "=", "value", ".", "__html__", "(", ")", "return", "Markup", "(", "text_type", "(", "value", ")", ")", ".", "striptags", "(", ")" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
do_slice
Slice an iterator and return a list of lists containing those items. Useful if you want to create a div containing three ul tags that represent columns: .. sourcecode:: html+jinja <div class="columwrapper"> {%- for column in items|slice(3) %} <ul class="column-{{ loop.index }}"> {%- for item in column %} <li>{{ item }}</li> {%- endfor %} </ul> {%- endfor %} </div> If you pass it a second argument it's used to fill missing values on the last iteration.
pipenv/vendor/jinja2/filters.py
def do_slice(value, slices, fill_with=None): """Slice an iterator and return a list of lists containing those items. Useful if you want to create a div containing three ul tags that represent columns: .. sourcecode:: html+jinja <div class="columwrapper"> {%- for column in items|slice(3) %} <ul class="column-{{ loop.index }}"> {%- for item in column %} <li>{{ item }}</li> {%- endfor %} </ul> {%- endfor %} </div> If you pass it a second argument it's used to fill missing values on the last iteration. """ seq = list(value) length = len(seq) items_per_slice = length // slices slices_with_extra = length % slices offset = 0 for slice_number in range(slices): start = offset + slice_number * items_per_slice if slice_number < slices_with_extra: offset += 1 end = offset + (slice_number + 1) * items_per_slice tmp = seq[start:end] if fill_with is not None and slice_number >= slices_with_extra: tmp.append(fill_with) yield tmp
def do_slice(value, slices, fill_with=None): """Slice an iterator and return a list of lists containing those items. Useful if you want to create a div containing three ul tags that represent columns: .. sourcecode:: html+jinja <div class="columwrapper"> {%- for column in items|slice(3) %} <ul class="column-{{ loop.index }}"> {%- for item in column %} <li>{{ item }}</li> {%- endfor %} </ul> {%- endfor %} </div> If you pass it a second argument it's used to fill missing values on the last iteration. """ seq = list(value) length = len(seq) items_per_slice = length // slices slices_with_extra = length % slices offset = 0 for slice_number in range(slices): start = offset + slice_number * items_per_slice if slice_number < slices_with_extra: offset += 1 end = offset + (slice_number + 1) * items_per_slice tmp = seq[start:end] if fill_with is not None and slice_number >= slices_with_extra: tmp.append(fill_with) yield tmp
[ "Slice", "an", "iterator", "and", "return", "a", "list", "of", "lists", "containing", "those", "items", ".", "Useful", "if", "you", "want", "to", "create", "a", "div", "containing", "three", "ul", "tags", "that", "represent", "columns", ":" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/filters.py#L701-L734
[ "def", "do_slice", "(", "value", ",", "slices", ",", "fill_with", "=", "None", ")", ":", "seq", "=", "list", "(", "value", ")", "length", "=", "len", "(", "seq", ")", "items_per_slice", "=", "length", "//", "slices", "slices_with_extra", "=", "length", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
do_batch
A filter that batches items. It works pretty much like `slice` just the other way round. It returns a list of lists with the given number of items. If you provide a second parameter this is used to fill up missing items. See this example: .. sourcecode:: html+jinja <table> {%- for row in items|batch(3, '&nbsp;') %} <tr> {%- for column in row %} <td>{{ column }}</td> {%- endfor %} </tr> {%- endfor %} </table>
pipenv/vendor/jinja2/filters.py
def do_batch(value, linecount, fill_with=None): """ A filter that batches items. It works pretty much like `slice` just the other way round. It returns a list of lists with the given number of items. If you provide a second parameter this is used to fill up missing items. See this example: .. sourcecode:: html+jinja <table> {%- for row in items|batch(3, '&nbsp;') %} <tr> {%- for column in row %} <td>{{ column }}</td> {%- endfor %} </tr> {%- endfor %} </table> """ tmp = [] for item in value: if len(tmp) == linecount: yield tmp tmp = [] tmp.append(item) if tmp: if fill_with is not None and len(tmp) < linecount: tmp += [fill_with] * (linecount - len(tmp)) yield tmp
def do_batch(value, linecount, fill_with=None): """ A filter that batches items. It works pretty much like `slice` just the other way round. It returns a list of lists with the given number of items. If you provide a second parameter this is used to fill up missing items. See this example: .. sourcecode:: html+jinja <table> {%- for row in items|batch(3, '&nbsp;') %} <tr> {%- for column in row %} <td>{{ column }}</td> {%- endfor %} </tr> {%- endfor %} </table> """ tmp = [] for item in value: if len(tmp) == linecount: yield tmp tmp = [] tmp.append(item) if tmp: if fill_with is not None and len(tmp) < linecount: tmp += [fill_with] * (linecount - len(tmp)) yield tmp
[ "A", "filter", "that", "batches", "items", ".", "It", "works", "pretty", "much", "like", "slice", "just", "the", "other", "way", "round", ".", "It", "returns", "a", "list", "of", "lists", "with", "the", "given", "number", "of", "items", ".", "If", "you...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/filters.py#L737-L765
[ "def", "do_batch", "(", "value", ",", "linecount", ",", "fill_with", "=", "None", ")", ":", "tmp", "=", "[", "]", "for", "item", "in", "value", ":", "if", "len", "(", "tmp", ")", "==", "linecount", ":", "yield", "tmp", "tmp", "=", "[", "]", "tmp"...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
do_round
Round the number to a given precision. The first parameter specifies the precision (default is ``0``), the second the rounding method: - ``'common'`` rounds either up or down - ``'ceil'`` always rounds up - ``'floor'`` always rounds down If you don't specify a method ``'common'`` is used. .. sourcecode:: jinja {{ 42.55|round }} -> 43.0 {{ 42.55|round(1, 'floor') }} -> 42.5 Note that even if rounded to 0 precision, a float is returned. If you need a real integer, pipe it through `int`: .. sourcecode:: jinja {{ 42.55|round|int }} -> 43
pipenv/vendor/jinja2/filters.py
def do_round(value, precision=0, method='common'): """Round the number to a given precision. The first parameter specifies the precision (default is ``0``), the second the rounding method: - ``'common'`` rounds either up or down - ``'ceil'`` always rounds up - ``'floor'`` always rounds down If you don't specify a method ``'common'`` is used. .. sourcecode:: jinja {{ 42.55|round }} -> 43.0 {{ 42.55|round(1, 'floor') }} -> 42.5 Note that even if rounded to 0 precision, a float is returned. If you need a real integer, pipe it through `int`: .. sourcecode:: jinja {{ 42.55|round|int }} -> 43 """ if not method in ('common', 'ceil', 'floor'): raise FilterArgumentError('method must be common, ceil or floor') if method == 'common': return round(value, precision) func = getattr(math, method) return func(value * (10 ** precision)) / (10 ** precision)
def do_round(value, precision=0, method='common'): """Round the number to a given precision. The first parameter specifies the precision (default is ``0``), the second the rounding method: - ``'common'`` rounds either up or down - ``'ceil'`` always rounds up - ``'floor'`` always rounds down If you don't specify a method ``'common'`` is used. .. sourcecode:: jinja {{ 42.55|round }} -> 43.0 {{ 42.55|round(1, 'floor') }} -> 42.5 Note that even if rounded to 0 precision, a float is returned. If you need a real integer, pipe it through `int`: .. sourcecode:: jinja {{ 42.55|round|int }} -> 43 """ if not method in ('common', 'ceil', 'floor'): raise FilterArgumentError('method must be common, ceil or floor') if method == 'common': return round(value, precision) func = getattr(math, method) return func(value * (10 ** precision)) / (10 ** precision)
[ "Round", "the", "number", "to", "a", "given", "precision", ".", "The", "first", "parameter", "specifies", "the", "precision", "(", "default", "is", "0", ")", "the", "second", "the", "rounding", "method", ":" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/filters.py#L768-L799
[ "def", "do_round", "(", "value", ",", "precision", "=", "0", ",", "method", "=", "'common'", ")", ":", "if", "not", "method", "in", "(", "'common'", ",", "'ceil'", ",", "'floor'", ")", ":", "raise", "FilterArgumentError", "(", "'method must be common, ceil o...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
do_groupby
Group a sequence of objects by a common attribute. If you for example have a list of dicts or objects that represent persons with `gender`, `first_name` and `last_name` attributes and you want to group all users by genders you can do something like the following snippet: .. sourcecode:: html+jinja <ul> {% for group in persons|groupby('gender') %} <li>{{ group.grouper }}<ul> {% for person in group.list %} <li>{{ person.first_name }} {{ person.last_name }}</li> {% endfor %}</ul></li> {% endfor %} </ul> Additionally it's possible to use tuple unpacking for the grouper and list: .. sourcecode:: html+jinja <ul> {% for grouper, list in persons|groupby('gender') %} ... {% endfor %} </ul> As you can see the item we're grouping by is stored in the `grouper` attribute and the `list` contains all the objects that have this grouper in common. .. versionchanged:: 2.6 It's now possible to use dotted notation to group by the child attribute of another attribute.
pipenv/vendor/jinja2/filters.py
def do_groupby(environment, value, attribute): """Group a sequence of objects by a common attribute. If you for example have a list of dicts or objects that represent persons with `gender`, `first_name` and `last_name` attributes and you want to group all users by genders you can do something like the following snippet: .. sourcecode:: html+jinja <ul> {% for group in persons|groupby('gender') %} <li>{{ group.grouper }}<ul> {% for person in group.list %} <li>{{ person.first_name }} {{ person.last_name }}</li> {% endfor %}</ul></li> {% endfor %} </ul> Additionally it's possible to use tuple unpacking for the grouper and list: .. sourcecode:: html+jinja <ul> {% for grouper, list in persons|groupby('gender') %} ... {% endfor %} </ul> As you can see the item we're grouping by is stored in the `grouper` attribute and the `list` contains all the objects that have this grouper in common. .. versionchanged:: 2.6 It's now possible to use dotted notation to group by the child attribute of another attribute. """ expr = make_attrgetter(environment, attribute) return [_GroupTuple(key, list(values)) for key, values in groupby(sorted(value, key=expr), expr)]
def do_groupby(environment, value, attribute): """Group a sequence of objects by a common attribute. If you for example have a list of dicts or objects that represent persons with `gender`, `first_name` and `last_name` attributes and you want to group all users by genders you can do something like the following snippet: .. sourcecode:: html+jinja <ul> {% for group in persons|groupby('gender') %} <li>{{ group.grouper }}<ul> {% for person in group.list %} <li>{{ person.first_name }} {{ person.last_name }}</li> {% endfor %}</ul></li> {% endfor %} </ul> Additionally it's possible to use tuple unpacking for the grouper and list: .. sourcecode:: html+jinja <ul> {% for grouper, list in persons|groupby('gender') %} ... {% endfor %} </ul> As you can see the item we're grouping by is stored in the `grouper` attribute and the `list` contains all the objects that have this grouper in common. .. versionchanged:: 2.6 It's now possible to use dotted notation to group by the child attribute of another attribute. """ expr = make_attrgetter(environment, attribute) return [_GroupTuple(key, list(values)) for key, values in groupby(sorted(value, key=expr), expr)]
[ "Group", "a", "sequence", "of", "objects", "by", "a", "common", "attribute", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/filters.py#L812-L852
[ "def", "do_groupby", "(", "environment", ",", "value", ",", "attribute", ")", ":", "expr", "=", "make_attrgetter", "(", "environment", ",", "attribute", ")", "return", "[", "_GroupTuple", "(", "key", ",", "list", "(", "values", ")", ")", "for", "key", ",...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
do_sum
Returns the sum of a sequence of numbers plus the value of parameter 'start' (which defaults to 0). When the sequence is empty it returns start. It is also possible to sum up only certain attributes: .. sourcecode:: jinja Total: {{ items|sum(attribute='price') }} .. versionchanged:: 2.6 The `attribute` parameter was added to allow suming up over attributes. Also the `start` parameter was moved on to the right.
pipenv/vendor/jinja2/filters.py
def do_sum(environment, iterable, attribute=None, start=0): """Returns the sum of a sequence of numbers plus the value of parameter 'start' (which defaults to 0). When the sequence is empty it returns start. It is also possible to sum up only certain attributes: .. sourcecode:: jinja Total: {{ items|sum(attribute='price') }} .. versionchanged:: 2.6 The `attribute` parameter was added to allow suming up over attributes. Also the `start` parameter was moved on to the right. """ if attribute is not None: iterable = imap(make_attrgetter(environment, attribute), iterable) return sum(iterable, start)
def do_sum(environment, iterable, attribute=None, start=0): """Returns the sum of a sequence of numbers plus the value of parameter 'start' (which defaults to 0). When the sequence is empty it returns start. It is also possible to sum up only certain attributes: .. sourcecode:: jinja Total: {{ items|sum(attribute='price') }} .. versionchanged:: 2.6 The `attribute` parameter was added to allow suming up over attributes. Also the `start` parameter was moved on to the right. """ if attribute is not None: iterable = imap(make_attrgetter(environment, attribute), iterable) return sum(iterable, start)
[ "Returns", "the", "sum", "of", "a", "sequence", "of", "numbers", "plus", "the", "value", "of", "parameter", "start", "(", "which", "defaults", "to", "0", ")", ".", "When", "the", "sequence", "is", "empty", "it", "returns", "start", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/filters.py#L856-L873
[ "def", "do_sum", "(", "environment", ",", "iterable", ",", "attribute", "=", "None", ",", "start", "=", "0", ")", ":", "if", "attribute", "is", "not", "None", ":", "iterable", "=", "imap", "(", "make_attrgetter", "(", "environment", ",", "attribute", ")"...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
do_reverse
Reverse the object or return an iterator that iterates over it the other way round.
pipenv/vendor/jinja2/filters.py
def do_reverse(value): """Reverse the object or return an iterator that iterates over it the other way round. """ if isinstance(value, string_types): return value[::-1] try: return reversed(value) except TypeError: try: rv = list(value) rv.reverse() return rv except TypeError: raise FilterArgumentError('argument must be iterable')
def do_reverse(value): """Reverse the object or return an iterator that iterates over it the other way round. """ if isinstance(value, string_types): return value[::-1] try: return reversed(value) except TypeError: try: rv = list(value) rv.reverse() return rv except TypeError: raise FilterArgumentError('argument must be iterable')
[ "Reverse", "the", "object", "or", "return", "an", "iterator", "that", "iterates", "over", "it", "the", "other", "way", "round", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/filters.py#L895-L909
[ "def", "do_reverse", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "string_types", ")", ":", "return", "value", "[", ":", ":", "-", "1", "]", "try", ":", "return", "reversed", "(", "value", ")", "except", "TypeError", ":", "try", ":"...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
do_attr
Get an attribute of an object. ``foo|attr("bar")`` works like ``foo.bar`` just that always an attribute is returned and items are not looked up. See :ref:`Notes on subscriptions <notes-on-subscriptions>` for more details.
pipenv/vendor/jinja2/filters.py
def do_attr(environment, obj, name): """Get an attribute of an object. ``foo|attr("bar")`` works like ``foo.bar`` just that always an attribute is returned and items are not looked up. See :ref:`Notes on subscriptions <notes-on-subscriptions>` for more details. """ try: name = str(name) except UnicodeError: pass else: try: value = getattr(obj, name) except AttributeError: pass else: if environment.sandboxed and not \ environment.is_safe_attribute(obj, name, value): return environment.unsafe_undefined(obj, name) return value return environment.undefined(obj=obj, name=name)
def do_attr(environment, obj, name): """Get an attribute of an object. ``foo|attr("bar")`` works like ``foo.bar`` just that always an attribute is returned and items are not looked up. See :ref:`Notes on subscriptions <notes-on-subscriptions>` for more details. """ try: name = str(name) except UnicodeError: pass else: try: value = getattr(obj, name) except AttributeError: pass else: if environment.sandboxed and not \ environment.is_safe_attribute(obj, name, value): return environment.unsafe_undefined(obj, name) return value return environment.undefined(obj=obj, name=name)
[ "Get", "an", "attribute", "of", "an", "object", ".", "foo|attr", "(", "bar", ")", "works", "like", "foo", ".", "bar", "just", "that", "always", "an", "attribute", "is", "returned", "and", "items", "are", "not", "looked", "up", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/filters.py#L913-L934
[ "def", "do_attr", "(", "environment", ",", "obj", ",", "name", ")", ":", "try", ":", "name", "=", "str", "(", "name", ")", "except", "UnicodeError", ":", "pass", "else", ":", "try", ":", "value", "=", "getattr", "(", "obj", ",", "name", ")", "excep...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
do_map
Applies a filter on a sequence of objects or looks up an attribute. This is useful when dealing with lists of objects but you are really only interested in a certain value of it. The basic usage is mapping on an attribute. Imagine you have a list of users but you are only interested in a list of usernames: .. sourcecode:: jinja Users on this page: {{ users|map(attribute='username')|join(', ') }} Alternatively you can let it invoke a filter by passing the name of the filter and the arguments afterwards. A good example would be applying a text conversion filter on a sequence: .. sourcecode:: jinja Users on this page: {{ titles|map('lower')|join(', ') }} .. versionadded:: 2.7
pipenv/vendor/jinja2/filters.py
def do_map(*args, **kwargs): """Applies a filter on a sequence of objects or looks up an attribute. This is useful when dealing with lists of objects but you are really only interested in a certain value of it. The basic usage is mapping on an attribute. Imagine you have a list of users but you are only interested in a list of usernames: .. sourcecode:: jinja Users on this page: {{ users|map(attribute='username')|join(', ') }} Alternatively you can let it invoke a filter by passing the name of the filter and the arguments afterwards. A good example would be applying a text conversion filter on a sequence: .. sourcecode:: jinja Users on this page: {{ titles|map('lower')|join(', ') }} .. versionadded:: 2.7 """ seq, func = prepare_map(args, kwargs) if seq: for item in seq: yield func(item)
def do_map(*args, **kwargs): """Applies a filter on a sequence of objects or looks up an attribute. This is useful when dealing with lists of objects but you are really only interested in a certain value of it. The basic usage is mapping on an attribute. Imagine you have a list of users but you are only interested in a list of usernames: .. sourcecode:: jinja Users on this page: {{ users|map(attribute='username')|join(', ') }} Alternatively you can let it invoke a filter by passing the name of the filter and the arguments afterwards. A good example would be applying a text conversion filter on a sequence: .. sourcecode:: jinja Users on this page: {{ titles|map('lower')|join(', ') }} .. versionadded:: 2.7 """ seq, func = prepare_map(args, kwargs) if seq: for item in seq: yield func(item)
[ "Applies", "a", "filter", "on", "a", "sequence", "of", "objects", "or", "looks", "up", "an", "attribute", ".", "This", "is", "useful", "when", "dealing", "with", "lists", "of", "objects", "but", "you", "are", "really", "only", "interested", "in", "a", "c...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/filters.py#L938-L963
[ "def", "do_map", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "seq", ",", "func", "=", "prepare_map", "(", "args", ",", "kwargs", ")", "if", "seq", ":", "for", "item", "in", "seq", ":", "yield", "func", "(", "item", ")" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
do_tojson
Dumps a structure to JSON so that it's safe to use in ``<script>`` tags. It accepts the same arguments and returns a JSON string. Note that this is available in templates through the ``|tojson`` filter which will also mark the result as safe. Due to how this function escapes certain characters this is safe even if used outside of ``<script>`` tags. The following characters are escaped in strings: - ``<`` - ``>`` - ``&`` - ``'`` This makes it safe to embed such strings in any place in HTML with the notable exception of double quoted attributes. In that case single quote your attributes or HTML escape it in addition. The indent parameter can be used to enable pretty printing. Set it to the number of spaces that the structures should be indented with. Note that this filter is for use in HTML contexts only. .. versionadded:: 2.9
pipenv/vendor/jinja2/filters.py
def do_tojson(eval_ctx, value, indent=None): """Dumps a structure to JSON so that it's safe to use in ``<script>`` tags. It accepts the same arguments and returns a JSON string. Note that this is available in templates through the ``|tojson`` filter which will also mark the result as safe. Due to how this function escapes certain characters this is safe even if used outside of ``<script>`` tags. The following characters are escaped in strings: - ``<`` - ``>`` - ``&`` - ``'`` This makes it safe to embed such strings in any place in HTML with the notable exception of double quoted attributes. In that case single quote your attributes or HTML escape it in addition. The indent parameter can be used to enable pretty printing. Set it to the number of spaces that the structures should be indented with. Note that this filter is for use in HTML contexts only. .. versionadded:: 2.9 """ policies = eval_ctx.environment.policies dumper = policies['json.dumps_function'] options = policies['json.dumps_kwargs'] if indent is not None: options = dict(options) options['indent'] = indent return htmlsafe_json_dumps(value, dumper=dumper, **options)
def do_tojson(eval_ctx, value, indent=None): """Dumps a structure to JSON so that it's safe to use in ``<script>`` tags. It accepts the same arguments and returns a JSON string. Note that this is available in templates through the ``|tojson`` filter which will also mark the result as safe. Due to how this function escapes certain characters this is safe even if used outside of ``<script>`` tags. The following characters are escaped in strings: - ``<`` - ``>`` - ``&`` - ``'`` This makes it safe to embed such strings in any place in HTML with the notable exception of double quoted attributes. In that case single quote your attributes or HTML escape it in addition. The indent parameter can be used to enable pretty printing. Set it to the number of spaces that the structures should be indented with. Note that this filter is for use in HTML contexts only. .. versionadded:: 2.9 """ policies = eval_ctx.environment.policies dumper = policies['json.dumps_function'] options = policies['json.dumps_kwargs'] if indent is not None: options = dict(options) options['indent'] = indent return htmlsafe_json_dumps(value, dumper=dumper, **options)
[ "Dumps", "a", "structure", "to", "JSON", "so", "that", "it", "s", "safe", "to", "use", "in", "<script", ">", "tags", ".", "It", "accepts", "the", "same", "arguments", "and", "returns", "a", "JSON", "string", ".", "Note", "that", "this", "is", "availabl...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/filters.py#L1047-L1078
[ "def", "do_tojson", "(", "eval_ctx", ",", "value", ",", "indent", "=", "None", ")", ":", "policies", "=", "eval_ctx", ".", "environment", ".", "policies", "dumper", "=", "policies", "[", "'json.dumps_function'", "]", "options", "=", "policies", "[", "'json.d...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
autocomplete
Entry Point for completion of main and subcommand options.
pipenv/patched/notpip/_internal/cli/autocompletion.py
def autocomplete(): """Entry Point for completion of main and subcommand options. """ # Don't complete if user hasn't sourced bash_completion file. if 'PIP_AUTO_COMPLETE' not in os.environ: return cwords = os.environ['COMP_WORDS'].split()[1:] cword = int(os.environ['COMP_CWORD']) try: current = cwords[cword - 1] except IndexError: current = '' subcommands = [cmd for cmd, summary in get_summaries()] options = [] # subcommand try: subcommand_name = [w for w in cwords if w in subcommands][0] except IndexError: subcommand_name = None parser = create_main_parser() # subcommand options if subcommand_name: # special case: 'help' subcommand has no options if subcommand_name == 'help': sys.exit(1) # special case: list locally installed dists for show and uninstall should_list_installed = ( subcommand_name in ['show', 'uninstall'] and not current.startswith('-') ) if should_list_installed: installed = [] lc = current.lower() for dist in get_installed_distributions(local_only=True): if dist.key.startswith(lc) and dist.key not in cwords[1:]: installed.append(dist.key) # if there are no dists installed, fall back to option completion if installed: for dist in installed: print(dist) sys.exit(1) subcommand = commands_dict[subcommand_name]() for opt in subcommand.parser.option_list_all: if opt.help != optparse.SUPPRESS_HELP: for opt_str in opt._long_opts + opt._short_opts: options.append((opt_str, opt.nargs)) # filter out previously specified options from available options prev_opts = [x.split('=')[0] for x in cwords[1:cword - 1]] options = [(x, v) for (x, v) in options if x not in prev_opts] # filter options by current input options = [(k, v) for k, v in options if k.startswith(current)] # get completion type given cwords and available subcommand options completion_type = get_path_completion_type( cwords, cword, subcommand.parser.option_list_all, ) # get completion files and directories if ``completion_type`` is # ``<file>``, ``<dir>`` or ``<path>`` if completion_type: options = auto_complete_paths(current, completion_type) options = ((opt, 0) for opt in options) for option in options: opt_label = option[0] # append '=' to options which require args if option[1] and option[0][:2] == "--": opt_label += '=' print(opt_label) else: # show main parser options only when necessary opts = [i.option_list for i in parser.option_groups] opts.append(parser.option_list) opts = (o for it in opts for o in it) if current.startswith('-'): for opt in opts: if opt.help != optparse.SUPPRESS_HELP: subcommands += opt._long_opts + opt._short_opts else: # get completion type given cwords and all available options completion_type = get_path_completion_type(cwords, cword, opts) if completion_type: subcommands = auto_complete_paths(current, completion_type) print(' '.join([x for x in subcommands if x.startswith(current)])) sys.exit(1)
def autocomplete(): """Entry Point for completion of main and subcommand options. """ # Don't complete if user hasn't sourced bash_completion file. if 'PIP_AUTO_COMPLETE' not in os.environ: return cwords = os.environ['COMP_WORDS'].split()[1:] cword = int(os.environ['COMP_CWORD']) try: current = cwords[cword - 1] except IndexError: current = '' subcommands = [cmd for cmd, summary in get_summaries()] options = [] # subcommand try: subcommand_name = [w for w in cwords if w in subcommands][0] except IndexError: subcommand_name = None parser = create_main_parser() # subcommand options if subcommand_name: # special case: 'help' subcommand has no options if subcommand_name == 'help': sys.exit(1) # special case: list locally installed dists for show and uninstall should_list_installed = ( subcommand_name in ['show', 'uninstall'] and not current.startswith('-') ) if should_list_installed: installed = [] lc = current.lower() for dist in get_installed_distributions(local_only=True): if dist.key.startswith(lc) and dist.key not in cwords[1:]: installed.append(dist.key) # if there are no dists installed, fall back to option completion if installed: for dist in installed: print(dist) sys.exit(1) subcommand = commands_dict[subcommand_name]() for opt in subcommand.parser.option_list_all: if opt.help != optparse.SUPPRESS_HELP: for opt_str in opt._long_opts + opt._short_opts: options.append((opt_str, opt.nargs)) # filter out previously specified options from available options prev_opts = [x.split('=')[0] for x in cwords[1:cword - 1]] options = [(x, v) for (x, v) in options if x not in prev_opts] # filter options by current input options = [(k, v) for k, v in options if k.startswith(current)] # get completion type given cwords and available subcommand options completion_type = get_path_completion_type( cwords, cword, subcommand.parser.option_list_all, ) # get completion files and directories if ``completion_type`` is # ``<file>``, ``<dir>`` or ``<path>`` if completion_type: options = auto_complete_paths(current, completion_type) options = ((opt, 0) for opt in options) for option in options: opt_label = option[0] # append '=' to options which require args if option[1] and option[0][:2] == "--": opt_label += '=' print(opt_label) else: # show main parser options only when necessary opts = [i.option_list for i in parser.option_groups] opts.append(parser.option_list) opts = (o for it in opts for o in it) if current.startswith('-'): for opt in opts: if opt.help != optparse.SUPPRESS_HELP: subcommands += opt._long_opts + opt._short_opts else: # get completion type given cwords and all available options completion_type = get_path_completion_type(cwords, cword, opts) if completion_type: subcommands = auto_complete_paths(current, completion_type) print(' '.join([x for x in subcommands if x.startswith(current)])) sys.exit(1)
[ "Entry", "Point", "for", "completion", "of", "main", "and", "subcommand", "options", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/cli/autocompletion.py#L13-L101
[ "def", "autocomplete", "(", ")", ":", "# Don't complete if user hasn't sourced bash_completion file.", "if", "'PIP_AUTO_COMPLETE'", "not", "in", "os", ".", "environ", ":", "return", "cwords", "=", "os", ".", "environ", "[", "'COMP_WORDS'", "]", ".", "split", "(", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
get_path_completion_type
Get the type of path completion (``file``, ``dir``, ``path`` or None) :param cwords: same as the environmental variable ``COMP_WORDS`` :param cword: same as the environmental variable ``COMP_CWORD`` :param opts: The available options to check :return: path completion type (``file``, ``dir``, ``path`` or None)
pipenv/patched/notpip/_internal/cli/autocompletion.py
def get_path_completion_type(cwords, cword, opts): """Get the type of path completion (``file``, ``dir``, ``path`` or None) :param cwords: same as the environmental variable ``COMP_WORDS`` :param cword: same as the environmental variable ``COMP_CWORD`` :param opts: The available options to check :return: path completion type (``file``, ``dir``, ``path`` or None) """ if cword < 2 or not cwords[cword - 2].startswith('-'): return for opt in opts: if opt.help == optparse.SUPPRESS_HELP: continue for o in str(opt).split('/'): if cwords[cword - 2].split('=')[0] == o: if not opt.metavar or any( x in ('path', 'file', 'dir') for x in opt.metavar.split('/')): return opt.metavar
def get_path_completion_type(cwords, cword, opts): """Get the type of path completion (``file``, ``dir``, ``path`` or None) :param cwords: same as the environmental variable ``COMP_WORDS`` :param cword: same as the environmental variable ``COMP_CWORD`` :param opts: The available options to check :return: path completion type (``file``, ``dir``, ``path`` or None) """ if cword < 2 or not cwords[cword - 2].startswith('-'): return for opt in opts: if opt.help == optparse.SUPPRESS_HELP: continue for o in str(opt).split('/'): if cwords[cword - 2].split('=')[0] == o: if not opt.metavar or any( x in ('path', 'file', 'dir') for x in opt.metavar.split('/')): return opt.metavar
[ "Get", "the", "type", "of", "path", "completion", "(", "file", "dir", "path", "or", "None", ")" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/cli/autocompletion.py#L104-L122
[ "def", "get_path_completion_type", "(", "cwords", ",", "cword", ",", "opts", ")", ":", "if", "cword", "<", "2", "or", "not", "cwords", "[", "cword", "-", "2", "]", ".", "startswith", "(", "'-'", ")", ":", "return", "for", "opt", "in", "opts", ":", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
auto_complete_paths
If ``completion_type`` is ``file`` or ``path``, list all regular files and directories starting with ``current``; otherwise only list directories starting with ``current``. :param current: The word to be completed :param completion_type: path completion type(`file`, `path` or `dir`)i :return: A generator of regular files and/or directories
pipenv/patched/notpip/_internal/cli/autocompletion.py
def auto_complete_paths(current, completion_type): """If ``completion_type`` is ``file`` or ``path``, list all regular files and directories starting with ``current``; otherwise only list directories starting with ``current``. :param current: The word to be completed :param completion_type: path completion type(`file`, `path` or `dir`)i :return: A generator of regular files and/or directories """ directory, filename = os.path.split(current) current_path = os.path.abspath(directory) # Don't complete paths if they can't be accessed if not os.access(current_path, os.R_OK): return filename = os.path.normcase(filename) # list all files that start with ``filename`` file_list = (x for x in os.listdir(current_path) if os.path.normcase(x).startswith(filename)) for f in file_list: opt = os.path.join(current_path, f) comp_file = os.path.normcase(os.path.join(directory, f)) # complete regular files when there is not ``<dir>`` after option # complete directories when there is ``<file>``, ``<path>`` or # ``<dir>``after option if completion_type != 'dir' and os.path.isfile(opt): yield comp_file elif os.path.isdir(opt): yield os.path.join(comp_file, '')
def auto_complete_paths(current, completion_type): """If ``completion_type`` is ``file`` or ``path``, list all regular files and directories starting with ``current``; otherwise only list directories starting with ``current``. :param current: The word to be completed :param completion_type: path completion type(`file`, `path` or `dir`)i :return: A generator of regular files and/or directories """ directory, filename = os.path.split(current) current_path = os.path.abspath(directory) # Don't complete paths if they can't be accessed if not os.access(current_path, os.R_OK): return filename = os.path.normcase(filename) # list all files that start with ``filename`` file_list = (x for x in os.listdir(current_path) if os.path.normcase(x).startswith(filename)) for f in file_list: opt = os.path.join(current_path, f) comp_file = os.path.normcase(os.path.join(directory, f)) # complete regular files when there is not ``<dir>`` after option # complete directories when there is ``<file>``, ``<path>`` or # ``<dir>``after option if completion_type != 'dir' and os.path.isfile(opt): yield comp_file elif os.path.isdir(opt): yield os.path.join(comp_file, '')
[ "If", "completion_type", "is", "file", "or", "path", "list", "all", "regular", "files", "and", "directories", "starting", "with", "current", ";", "otherwise", "only", "list", "directories", "starting", "with", "current", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/cli/autocompletion.py#L125-L152
[ "def", "auto_complete_paths", "(", "current", ",", "completion_type", ")", ":", "directory", ",", "filename", "=", "os", ".", "path", ".", "split", "(", "current", ")", "current_path", "=", "os", ".", "path", ".", "abspath", "(", "directory", ")", "# Don't...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_build_wheel_modern
Build a wheel. * ireq: The InstallRequirement object to build * output_dir: The directory to build the wheel in. * finder: pip's internal Finder object to find the source out of ireq. * kwargs: Various keyword arguments from `_prepare_wheel_building_kwargs`.
pipenv/vendor/passa/internals/_pip_shims.py
def _build_wheel_modern(ireq, output_dir, finder, wheel_cache, kwargs): """Build a wheel. * ireq: The InstallRequirement object to build * output_dir: The directory to build the wheel in. * finder: pip's internal Finder object to find the source out of ireq. * kwargs: Various keyword arguments from `_prepare_wheel_building_kwargs`. """ kwargs.update({"progress_bar": "off", "build_isolation": False}) with pip_shims.RequirementTracker() as req_tracker: if req_tracker: kwargs["req_tracker"] = req_tracker preparer = pip_shims.RequirementPreparer(**kwargs) builder = pip_shims.WheelBuilder(finder, preparer, wheel_cache) return builder._build_one(ireq, output_dir)
def _build_wheel_modern(ireq, output_dir, finder, wheel_cache, kwargs): """Build a wheel. * ireq: The InstallRequirement object to build * output_dir: The directory to build the wheel in. * finder: pip's internal Finder object to find the source out of ireq. * kwargs: Various keyword arguments from `_prepare_wheel_building_kwargs`. """ kwargs.update({"progress_bar": "off", "build_isolation": False}) with pip_shims.RequirementTracker() as req_tracker: if req_tracker: kwargs["req_tracker"] = req_tracker preparer = pip_shims.RequirementPreparer(**kwargs) builder = pip_shims.WheelBuilder(finder, preparer, wheel_cache) return builder._build_one(ireq, output_dir)
[ "Build", "a", "wheel", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/passa/internals/_pip_shims.py#L24-L38
[ "def", "_build_wheel_modern", "(", "ireq", ",", "output_dir", ",", "finder", ",", "wheel_cache", ",", "kwargs", ")", ":", "kwargs", ".", "update", "(", "{", "\"progress_bar\"", ":", "\"off\"", ",", "\"build_isolation\"", ":", "False", "}", ")", "with", "pip_...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
get_python_version
Get python version string using subprocess from a given path.
pipenv/vendor/pythonfinder/utils.py
def get_python_version(path): # type: (str) -> str """Get python version string using subprocess from a given path.""" version_cmd = [path, "-c", "import sys; print(sys.version.split()[0])"] try: c = vistir.misc.run( version_cmd, block=True, nospin=True, return_object=True, combine_stderr=False, write_to_stdout=False, ) except OSError: raise InvalidPythonVersion("%s is not a valid python path" % path) if not c.out: raise InvalidPythonVersion("%s is not a valid python path" % path) return c.out.strip()
def get_python_version(path): # type: (str) -> str """Get python version string using subprocess from a given path.""" version_cmd = [path, "-c", "import sys; print(sys.version.split()[0])"] try: c = vistir.misc.run( version_cmd, block=True, nospin=True, return_object=True, combine_stderr=False, write_to_stdout=False, ) except OSError: raise InvalidPythonVersion("%s is not a valid python path" % path) if not c.out: raise InvalidPythonVersion("%s is not a valid python path" % path) return c.out.strip()
[ "Get", "python", "version", "string", "using", "subprocess", "from", "a", "given", "path", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pythonfinder/utils.py#L87-L104
[ "def", "get_python_version", "(", "path", ")", ":", "# type: (str) -> str", "version_cmd", "=", "[", "path", ",", "\"-c\"", ",", "\"import sys; print(sys.version.split()[0])\"", "]", "try", ":", "c", "=", "vistir", ".", "misc", ".", "run", "(", "version_cmd", ",...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde