_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q254000 | OAuth1Session.fetch_access_token | validation | def fetch_access_token(self, url, verifier=None, **request_kwargs):
"""Fetch an access token.
This is the final step in the OAuth 1 workflow. An access token is
obtained using all previously obtained credentials, including the
verifier from the authorization step.
Note that a p... | python | {
"resource": ""
} |
q254001 | OAuth1Session.parse_authorization_response | validation | def parse_authorization_response(self, url):
"""Extract parameters from the post authorization redirect response URL.
:param url: The full URL that resulted from the user being redirected
back from the OAuth provider to you, the client.
:returns: A dict of parameters extract... | python | {
"resource": ""
} |
q254002 | OAuth1Session.rebuild_auth | validation | def rebuild_auth(self, prepared_request, response):
"""
When being redirected we should always strip Authorization
header, since nonce may not be reused as per OAuth spec.
"""
if "Authorization" in prepared_request.headers:
# If we get redirected to a new host, we | python | {
"resource": ""
} |
q254003 | Cacher.existing_versions | validation | def existing_versions(self):
"""
Returns data with different cfgstr values that were previously computed
with this cacher.
Example:
>>> from ubelt.util_cache import Cacher
>>> # Ensure that some data exists
>>> known_fnames = set()
>>> cac... | python | {
"resource": ""
} |
q254004 | Cacher.clear | validation | def clear(self, cfgstr=None):
"""
Removes the saved cache and metadata from disk
"""
data_fpath = self.get_fpath(cfgstr)
if self.verbose > 0:
self.log('[cacher] clear cache')
if exists(data_fpath):
if self.verbose > 0:
self.log('[ca... | python | {
"resource": ""
} |
q254005 | Cacher.tryload | validation | def tryload(self, cfgstr=None, on_error='raise'):
"""
Like load, but returns None if the load fails due to a cache miss.
Args:
on_error (str): How to handle non-io errors errors. Either raise,
which re-raises the exception, or clear which deletes the cache
... | python | {
"resource": ""
} |
q254006 | Cacher.load | validation | def load(self, cfgstr=None):
"""
Loads the data
Raises:
IOError - if the data is unable to be loaded. This could be due to
a cache miss or because the cache is disabled.
Example:
>>> from ubelt.util_cache import * # NOQA
>>> # Settin... | python | {
"resource": ""
} |
q254007 | Cacher.ensure | validation | def ensure(self, func, *args, **kwargs):
r"""
Wraps around a function. A cfgstr must be stored in the base cacher.
Args:
func (callable): function that will compute data on cache miss
*args: passed to func
**kwargs: passed to func
Example:
... | python | {
"resource": ""
} |
q254008 | CacheStamp._get_certificate | validation | def _get_certificate(self, cfgstr=None):
"""
Returns the stamp certificate if it exists
"""
| python | {
"resource": ""
} |
q254009 | CacheStamp._rectify_products | validation | def _rectify_products(self, product=None):
""" puts products in a normalized format """
products = self.product if product is None else product
if products is None:
return None
| python | {
"resource": ""
} |
q254010 | CacheStamp._product_file_hash | validation | def _product_file_hash(self, product=None):
"""
Get the hash of the each product file
"""
if self.hasher is None:
return None
else:
products = self._rectify_products(product)
product_file_hash = | python | {
"resource": ""
} |
q254011 | CacheStamp.expired | validation | def expired(self, cfgstr=None, product=None):
"""
Check to see if a previously existing stamp is still valid and if the
expected result of that computation still exists.
Args:
cfgstr (str, optional): override the default cfgstr if specified
product (PathLike or S... | python | {
"resource": ""
} |
q254012 | CacheStamp.renew | validation | def renew(self, cfgstr=None, product=None):
"""
Recertify that the product has been recomputed by writing a new
certificate to disk.
"""
products = self._rectify_products(product)
certificate = {
'timestamp': util_time.timestamp(),
'product': produ... | python | {
"resource": ""
} |
q254013 | TeeStringIO.isatty | validation | def isatty(self): # nocover
"""
Returns true of the redirect is a terminal.
Notes:
Needed for IPython.embed to work properly when this class is used
to override stdout / stderr.
"""
| python | {
"resource": ""
} |
q254014 | TeeStringIO.encoding | validation | def encoding(self):
"""
Gets the encoding of the `redirect` IO object
Doctest:
>>> redirect = io.StringIO()
>>> assert TeeStringIO(redirect).encoding is None
>>> assert TeeStringIO(None).encoding is None
>>> assert TeeStringIO(sys.stdout).encoding... | python | {
"resource": ""
} |
q254015 | TeeStringIO.write | validation | def write(self, msg):
"""
Write to this and the redirected stream
"""
if self.redirect is not None:
| python | {
"resource": ""
} |
q254016 | TeeStringIO.flush | validation | def flush(self): # nocover
"""
Flush to this and the redirected stream
| python | {
"resource": ""
} |
q254017 | CaptureStdout.log_part | validation | def log_part(self):
""" Log what has been captured so far """
self.cap_stdout.seek(self._pos)
text = self.cap_stdout.read()
| python | {
"resource": ""
} |
q254018 | platform_data_dir | validation | def platform_data_dir():
"""
Returns path for user-specific data files
Returns:
PathLike : path to the data dir used by the current operating system
"""
if LINUX: # nocover
dpath_ = os.environ.get('XDG_DATA_HOME', '~/.local/share')
elif DARWIN: # nocover
dpath_ = '~/L... | python | {
"resource": ""
} |
q254019 | platform_config_dir | validation | def platform_config_dir():
"""
Returns a directory which should be writable for any application
This should be used for persistent configuration files.
Returns:
PathLike : path to the cahce dir used by the current operating system
"""
if LINUX: # nocover
dpath_ = os.environ.get... | python | {
"resource": ""
} |
q254020 | ensure_app_data_dir | validation | def ensure_app_data_dir(appname, *args):
"""
Calls `get_app_data_dir` but ensures the directory exists.
Args:
appname (str): the name of the application
*args: any other subdirectories may be specified
SeeAlso:
get_app_data_dir
Example:
>>> import ubelt as | python | {
"resource": ""
} |
q254021 | ensure_app_config_dir | validation | def ensure_app_config_dir(appname, *args):
"""
Calls `get_app_config_dir` but ensures the directory exists.
Args:
appname (str): the name of the application
*args: any other subdirectories may be specified
SeeAlso:
get_app_config_dir
Example:
>>> import ubelt as | python | {
"resource": ""
} |
q254022 | ensure_app_cache_dir | validation | def ensure_app_cache_dir(appname, *args):
"""
Calls `get_app_cache_dir` but ensures the directory exists.
Args:
appname (str): the name of the application
*args: any other subdirectories may be specified
SeeAlso:
get_app_cache_dir
Example:
>>> import ubelt as | python | {
"resource": ""
} |
q254023 | startfile | validation | def startfile(fpath, verbose=True): # nocover
"""
Uses default program defined by the system to open a file.
This is done via `os.startfile` on windows, `open` on mac, and `xdg-open`
on linux.
Args:
fpath (PathLike): a file to open using the program associated with the
files ex... | python | {
"resource": ""
} |
q254024 | find_exe | validation | def find_exe(name, multi=False, path=None):
"""
Locate a command.
Search your local filesystem for an executable and return the first
matching file with executable permission.
Args:
name (str): globstr of matching filename
multi (bool): if True return all matches instead of just t... | python | {
"resource": ""
} |
q254025 | userhome | validation | def userhome(username=None):
"""
Returns the user's home directory.
If `username` is None, this is the directory for the current user.
Args:
username (str): name of a user on the system
Returns:
PathLike: userhome_dpath: path to the home directory
Example:
>>> import g... | python | {
"resource": ""
} |
q254026 | compressuser | validation | def compressuser(path, home='~'):
"""
Inverse of `os.path.expanduser`
Args:
path (PathLike): path in system file structure
home (str): symbol used to replace the home path. Defaults to '~', but
you might want to use '$HOME' or '%USERPROFILE%' instead.
Returns:
PathL... | python | {
"resource": ""
} |
q254027 | truepath | validation | def truepath(path, real=False):
"""
Normalizes a string representation of a path and does shell-like expansion.
Args:
path (PathLike): string representation of a path
real (bool): if True, all symbolic links are followed. (default: False)
Returns:
PathLike : normalized path
... | python | {
"resource": ""
} |
q254028 | ensuredir | validation | def ensuredir(dpath, mode=0o1777, verbose=None):
r"""
Ensures that directory will exist. Creates new dir with sticky bits by
default
Args:
dpath (PathLike): dir to ensure. Can also be a tuple to send to join
mode (int): octal mode of directory (default 0o1777)
verbose (int): ver... | python | {
"resource": ""
} |
q254029 | parse_requirements_alt | validation | def parse_requirements_alt(fname='requirements.txt'):
"""
pip install requirements-parser
fname='requirements.txt'
"""
import requirements
from os.path import dirname, join, exists
require_fpath = join(dirname(__file__), | python | {
"resource": ""
} |
q254030 | parse_requirements | validation | def parse_requirements(fname='requirements.txt'):
"""
Parse the package dependencies listed in a requirements file but strips
specific versioning information.
TODO:
perhaps use https://github.com/davidfischer/requirements-parser instead
CommandLine:
python -c "import setup; print(s... | python | {
"resource": ""
} |
q254031 | inject_method | validation | def inject_method(self, func, name=None):
"""
Injects a function into an object instance as a bound method
The main use case of this function is for monkey patching. While monkey
patching is sometimes necessary it should generally be avoided. Thus, we
simply remind the developer that there might be... | python | {
"resource": ""
} |
q254032 | touch | validation | def touch(fpath, mode=0o666, dir_fd=None, verbose=0, **kwargs):
"""
change file timestamps
Works like the touch unix utility
Args:
fpath (PathLike): name of the file
mode (int): file permissions (python3 and unix only)
dir_fd (file): optional directory file descriptor. If speci... | python | {
"resource": ""
} |
q254033 | delete | validation | def delete(path, verbose=False):
"""
Removes a file or recursively removes a directory.
If a path does not exist, then this is does nothing.
Args:
path (PathLike): file or directory to remove
verbose (bool): if True prints what is being done
SeeAlso:
send2trash - A cross-pl... | python | {
"resource": ""
} |
q254034 | repr2 | validation | def repr2(data, **kwargs):
"""
Makes a pretty and easy-to-doctest string representation!
This is an alternative to repr, and `pprint.pformat` that attempts to be
both more configurable and generate output that is consistent between
python versions.
Notes:
This function has many keyword... | python | {
"resource": ""
} |
q254035 | _join_itemstrs | validation | def _join_itemstrs(itemstrs, itemsep, newlines, _leaf_info, nobraces,
trailing_sep, compact_brace, lbr, rbr):
"""
Joins string-ified items with separators newlines and container-braces.
"""
# positive newlines means start counting from the root
use_newline = newlines > 0
# ne... | python | {
"resource": ""
} |
q254036 | _dict_itemstrs | validation | def _dict_itemstrs(dict_, **kwargs):
"""
Create a string representation for each item in a dict.
Example:
>>> from ubelt.util_format import *
>>> dict_ = {'b': .1, 'l': 'st', 'g': 1.0, 's': 10, 'm': 0.9, 'w': .5}
>>> kwargs = {'strkeys': True}
>>> itemstrs, _ = _dict_itemst... | python | {
"resource": ""
} |
q254037 | _list_itemstrs | validation | def _list_itemstrs(list_, **kwargs):
"""
Create a string representation for each item in a list.
"""
items = list(list_)
kwargs['_return_info'] = True
_tups = [repr2(item, **kwargs) for item in items]
itemstrs = [t[0] for t in _tups]
max_height = max([t[1]['max_height'] for t in _tups]) ... | python | {
"resource": ""
} |
q254038 | _rectify_countdown_or_bool | validation | def _rectify_countdown_or_bool(count_or_bool):
"""
used by recursive functions to specify which level to turn a bool on in
counting down yields True, True, ..., False
counting up yields False, False, False, ... True
Args:
count_or_bool (bool or int): if positive and an integer, it will coun... | python | {
"resource": ""
} |
q254039 | FormatterExtensions.register | validation | def register(self, type):
"""
Registers a custom formatting function with ub.repr2
"""
def _decorator(func):
if isinstance(type, tuple):
for t in type:
| python | {
"resource": ""
} |
q254040 | FormatterExtensions.lookup | validation | def lookup(self, data):
"""
Returns an appropriate function to format `data` if one has been
registered.
"""
for func in self.lazy_init:
func()
| python | {
"resource": ""
} |
q254041 | _rectify_hasher | validation | def _rectify_hasher(hasher):
"""
Convert a string-based key into a hasher class
Notes:
In terms of speed on 64bit systems, sha1 is the fastest followed by md5
and sha512. The slowest algorithm is sha256. If xxhash is installed
the fastest algorithm is xxh64.
Example:
>>... | python | {
"resource": ""
} |
q254042 | _rectify_base | validation | def _rectify_base(base):
"""
transforms base shorthand into the full list representation
Example:
>>> assert _rectify_base(NoParam) is DEFAULT_ALPHABET
>>> assert _rectify_base('hex') is _ALPHABET_16
>>> assert _rectify_base('abc') is _ALPHABET_26
>>> assert _rectify_base(10... | python | {
"resource": ""
} |
q254043 | _hashable_sequence | validation | def _hashable_sequence(data, types=True):
r"""
Extracts the sequence of bytes that would be hashed by hash_data
Example:
>>> data = [2, (3, 4)]
>>> result1 = (b''.join(_hashable_sequence(data, types=False)))
| python | {
"resource": ""
} |
q254044 | _convert_to_hashable | validation | def _convert_to_hashable(data, types=True):
r"""
Converts `data` into a hashable byte representation if an appropriate
hashing function is known.
Args:
data (object): ordered data with structure
types (bool): include type prefixes in the hash
Returns:
tuple(bytes, bytes): p... | python | {
"resource": ""
} |
q254045 | _update_hasher | validation | def _update_hasher(hasher, data, types=True):
"""
Converts `data` into a byte representation and calls update on the hasher
`hashlib.HASH` algorithm.
Args:
hasher (HASH): instance of a hashlib algorithm
data (object): ordered data with structure
types (bool): include type prefix... | python | {
"resource": ""
} |
q254046 | _convert_hexstr_base | validation | def _convert_hexstr_base(hexstr, base):
r"""
Packs a long hexstr into a shorter length string with a larger base.
Args:
hexstr (str): string of hexidecimal symbols to convert
base (list): symbols of the conversion base
Example:
>>> print(_convert_hexstr_base('ffffffff', _ALPHAB... | python | {
"resource": ""
} |
q254047 | _digest_hasher | validation | def _digest_hasher(hasher, hashlen, base):
""" counterpart to _update_hasher """
# Get a 128 character hex string
hex_text = hasher.hexdigest()
# Shorten length of string (by increasing base)
| python | {
"resource": ""
} |
q254048 | hash_data | validation | def hash_data(data, hasher=NoParam, base=NoParam, types=False,
hashlen=NoParam, convert=False):
"""
Get a unique hash depending on the state of the data.
Args:
data (object):
Any sort of loosely organized data
hasher (str or HASHER):
Hash algorithm fro... | python | {
"resource": ""
} |
q254049 | hash_file | validation | def hash_file(fpath, blocksize=65536, stride=1, hasher=NoParam,
hashlen=NoParam, base=NoParam):
"""
Hashes the data in a file on disk.
Args:
fpath (PathLike): file path string
blocksize (int): 2 ** 16. Affects speed of reading file
stride (int): strides > 1 skip dat... | python | {
"resource": ""
} |
q254050 | HashableExtensions.register | validation | def register(self, hash_types):
"""
Registers a function to generate a hash for data of the appropriate
types. This can be used to register custom classes. Internally this is
used to define how to hash non-builtin objects like ndarrays and uuids.
The registered function should r... | python | {
"resource": ""
} |
q254051 | HashableExtensions.lookup | validation | def lookup(self, data):
"""
Returns an appropriate function to hash `data` if one has been
registered.
Raises:
TypeError : if data has no registered hash methods
Example:
>>> import ubelt as ub
>>> import pytest
>>> if not ub.modn... | python | {
"resource": ""
} |
q254052 | HashableExtensions._register_numpy_extensions | validation | def _register_numpy_extensions(self):
"""
Numpy extensions are builtin
"""
# system checks
import numpy as np
numpy_floating_types = (np.float16, np.float32, np.float64)
if hasattr(np, 'float128'): # nocover
numpy_floating_types = numpy_floating_types... | python | {
"resource": ""
} |
q254053 | HashableExtensions._register_builtin_class_extensions | validation | def _register_builtin_class_extensions(self):
"""
Register hashing extensions for a selection of classes included in
python stdlib.
Example:
>>> data = uuid.UUID('7e9d206b-dc02-4240-8bdb-fffe858121d0')
>>> print(hash_data(data, base='abc', hasher='sha512', types=... | python | {
"resource": ""
} |
q254054 | _proc_async_iter_stream | validation | def _proc_async_iter_stream(proc, stream, buffersize=1):
"""
Reads output from a process in a separate thread
"""
from six.moves import queue
from threading import Thread
def enqueue_output(proc, stream, stream_queue):
while proc.poll() is None:
line = stream.readline()
... | python | {
"resource": ""
} |
q254055 | _tee_output | validation | def _tee_output(make_proc, stdout=None, stderr=None, backend='auto'):
"""
Simultaneously reports and captures stdout and stderr from a process
subprocess must be created using (stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
"""
logged_out = []
logged_err = []
if backend == 'auto':
... | python | {
"resource": ""
} |
q254056 | timestamp | validation | def timestamp(method='iso8601'):
"""
make an iso8601 timestamp
Args:
method (str): type of timestamp
Example:
>>> stamp = timestamp()
>>> print('stamp = {!r}'.format(stamp))
stamp = ...-...-...T...
"""
if method == 'iso8601':
| python | {
"resource": ""
} |
q254057 | import_module_from_path | validation | def import_module_from_path(modpath, index=-1):
"""
Imports a module via its path
Args:
modpath (PathLike): path to the module on disk or within a zipfile.
Returns:
module: the imported module
References:
https://stackoverflow.com/questions/67631/import-module-given-path
... | python | {
"resource": ""
} |
q254058 | _extension_module_tags | validation | def _extension_module_tags():
"""
Returns valid tags an extension module might have
"""
import sysconfig
tags = []
if six.PY2:
# see also 'SHLIB_EXT'
multiarch = sysconfig.get_config_var('MULTIARCH')
if multiarch is not None:
tags.append(multiarch)
else:
... | python | {
"resource": ""
} |
q254059 | _syspath_modname_to_modpath | validation | def _syspath_modname_to_modpath(modname, sys_path=None, exclude=None):
"""
syspath version of modname_to_modpath
Args:
modname (str): name of module to find
sys_path (List[PathLike], default=None):
if specified overrides `sys.path`
exclude (List[PathLike], default=None):... | python | {
"resource": ""
} |
q254060 | modname_to_modpath | validation | def modname_to_modpath(modname, hide_init=True, hide_main=False, sys_path=None):
"""
Finds the path to a python module from its name.
Determines the path to a python module without directly import it
Converts the name of a module (__name__) to the path (__file__) where it is
located without import... | python | {
"resource": ""
} |
q254061 | modpath_to_modname | validation | def modpath_to_modname(modpath, hide_init=True, hide_main=False, check=True,
relativeto=None):
"""
Determines importable name from file path
Converts the path to a module (__file__) to the importable python name
(__name__) without importing the module.
The filename is conver... | python | {
"resource": ""
} |
q254062 | split_modpath | validation | def split_modpath(modpath, check=True):
"""
Splits the modpath into the dir that must be in PYTHONPATH for the module
to be imported and the modulepath relative to this directory.
Args:
modpath (str): module filepath
check (bool): if False, does not raise an error if modpath is a
... | python | {
"resource": ""
} |
q254063 | argval | validation | def argval(key, default=util_const.NoParam, argv=None):
"""
Get the value of a keyword argument specified on the command line.
Values can be specified as `<key> <value>` or `<key>=<value>`
Args:
key (str or tuple): string or tuple of strings. Each key should be
prefixed with two hy... | python | {
"resource": ""
} |
q254064 | argflag | validation | def argflag(key, argv=None):
"""
Determines if a key is specified on the command line
Args:
key (str or tuple): string or tuple of strings. Each key should be
prefixed with two hyphens (i.e. `--`)
argv (Optional[list]): overrides `sys.argv` if specified
Returns:
boo... | python | {
"resource": ""
} |
q254065 | hzcat | validation | def hzcat(args, sep=''):
"""
Horizontally concatenates strings preserving indentation
Concatenates a list of objects ensuring that the next item in the list is
all the way to the right of any previous items.
Args:
args (List[str]): strings to concatenate
sep (str): separator (defau... | python | {
"resource": ""
} |
q254066 | symlink | validation | def symlink(real_path, link_path, overwrite=False, verbose=0):
"""
Create a symbolic link.
This will work on linux or windows, however windows does have some corner
cases. For more details see notes in `ubelt._win32_links`.
Args:
path (PathLike): path to real file or directory
link... | python | {
"resource": ""
} |
q254067 | _make_signature_key | validation | def _make_signature_key(args, kwargs):
"""
Transforms function args into a key that can be used by the cache
CommandLine:
xdoctest -m ubelt.util_memoize _make_signature_key
Example:
>>> args = (4, [1, 2])
>>> kwargs = {'a': 'b'}
>>> key = _make_signature_key(args, kwarg... | python | {
"resource": ""
} |
q254068 | memoize | validation | def memoize(func):
"""
memoization decorator that respects args and kwargs
References:
https://wiki.python.org/moin/PythonDecoratorLibrary#Memoize
Args:
func (Callable): live python function
Returns:
func: memoized wrapper
CommandLine:
xdoctest -m ubelt.util_m... | python | {
"resource": ""
} |
q254069 | memoize_property | validation | def memoize_property(fget):
"""
Return a property attribute for new-style classes that only calls its
getter on the first access. The result is stored and on subsequent accesses
is returned, preventing the need to call the getter any more.
This decorator can either be used by itself or by decoratin... | python | {
"resource": ""
} |
q254070 | highlight_code | validation | def highlight_code(text, lexer_name='python', **kwargs):
"""
Highlights a block of text using ANSI tags based on language syntax.
Args:
text (str): plain text to highlight
lexer_name (str): name of language
**kwargs: passed to pygments.lexers.get_lexer_by_name
Returns:
... | python | {
"resource": ""
} |
q254071 | color_text | validation | def color_text(text, color):
r"""
Colorizes text a single color using ansii tags.
Args:
text (str): text to colorize
color (str): may be one of the following: yellow, blink, lightgray,
underline, darkyellow, blue, darkblue, faint, fuchsia, black,
white, red, brown, t... | python | {
"resource": ""
} |
q254072 | iterable | validation | def iterable(obj, strok=False):
"""
Checks if the input implements the iterator interface. An exception is made
for strings, which return False unless `strok` is True
Args:
obj (object): a scalar or iterable input
strok (bool): if True allow strings to be interpreted as iterable
R... | python | {
"resource": ""
} |
q254073 | unique | validation | def unique(items, key=None):
"""
Generates unique items in the order they appear.
Args:
items (Iterable): list of items
key (Callable, optional): custom normalization function.
If specified returns items where `key(item)` is unique.
Yields:
object: a unique item fr... | python | {
"resource": ""
} |
q254074 | argunique | validation | def argunique(items, key=None):
"""
Returns indices corresponding to the first instance of each unique item.
Args:
items (Sequence): indexable collection of items
key (Callable, optional): custom normalization function.
If specified returns items where `key(item)` is unique.
... | python | {
"resource": ""
} |
q254075 | unique_flags | validation | def unique_flags(items, key=None):
"""
Returns a list of booleans corresponding to the first instance of each
unique item.
Args:
items (Sequence): indexable collection of items
key (Callable, optional): custom normalization function.
If specified returns items where `key(it... | python | {
"resource": ""
} |
q254076 | boolmask | validation | def boolmask(indices, maxval=None):
"""
Constructs a list of booleans where an item is True if its position is in
`indices` otherwise it is False.
Args:
indices (list): list of integer indices
maxval (int): length of the returned list. If not specified
this is inferred from... | python | {
"resource": ""
} |
q254077 | allsame | validation | def allsame(iterable, eq=operator.eq):
"""
Determine if all items in a sequence are the same
Args:
iterable (Iterable): items to determine if they are all the same
eq (Callable, optional): function to determine equality
(default: operator.eq)
Example:
>>> allsame([... | python | {
"resource": ""
} |
q254078 | argsort | validation | def argsort(indexable, key=None, reverse=False):
"""
Returns the indices that would sort a indexable object.
This is similar to `numpy.argsort`, but it is written in pure python and
works on both lists and dictionaries.
Args:
indexable (Iterable or Mapping): indexable to sort by
k... | python | {
"resource": ""
} |
q254079 | dzip | validation | def dzip(items1, items2, cls=dict):
"""
Zips elementwise pairs between items1 and items2 into a dictionary. Values
from items2 can be broadcast onto items1.
Args:
items1 (Iterable): full sequence
items2 (Iterable): can either be a sequence of one item or a sequence
of equal ... | python | {
"resource": ""
} |
q254080 | group_items | validation | def group_items(items, groupids):
r"""
Groups a list of items by group id.
Args:
items (Iterable): a list of items to group
groupids (Iterable or Callable): a corresponding list of item groupids
or a function mapping an item to a groupid.
Returns:
dict: groupid_to_i... | python | {
"resource": ""
} |
q254081 | dict_hist | validation | def dict_hist(item_list, weight_list=None, ordered=False, labels=None):
"""
Builds a histogram of items, counting the number of time each item appears
in the input.
Args:
item_list (Iterable): hashable items (usually containing duplicates)
weight_list (Iterable): corresponding weights f... | python | {
"resource": ""
} |
q254082 | find_duplicates | validation | def find_duplicates(items, k=2, key=None):
"""
Find all duplicate items in a list.
Search for all items that appear more than `k` times and return a mapping
from each (k)-duplicate item to the positions it appeared in.
Args:
items (Iterable): hashable items possibly containing duplicates
... | python | {
"resource": ""
} |
q254083 | dict_take | validation | def dict_take(dict_, keys, default=util_const.NoParam):
r"""
Generates values from a dictionary
Args:
dict_ (Mapping): a dictionary to take from
keys (Iterable): the keys to take
default (object, optional): if specified uses default if keys are missing
CommandLine:
pyth... | python | {
"resource": ""
} |
q254084 | dict_union | validation | def dict_union(*args):
"""
Combines the disjoint keys in multiple dictionaries. For intersecting keys,
dictionaries towards the end of the sequence are given precedence.
Args:
*args : a sequence of dictionaries
Returns:
Dict | OrderedDict :
OrderedDict if the first argu... | python | {
"resource": ""
} |
q254085 | dict_isect | validation | def dict_isect(*args):
"""
Constructs a dictionary that contains keys common between all inputs.
The returned values will only belong to the first dictionary.
Args:
*args : a sequence of dictionaries (or sets of keys)
Returns:
Dict | OrderedDict :
OrderedDict if the fir... | python | {
"resource": ""
} |
q254086 | map_vals | validation | def map_vals(func, dict_):
"""
applies a function to each of the keys in a dictionary
Args:
func (callable): a function or indexable object
dict_ (dict): a dictionary
Returns:
newdict: transformed dictionary
CommandLine:
python -m ubelt.util_dict map_vals
Exam... | python | {
"resource": ""
} |
q254087 | invert_dict | validation | def invert_dict(dict_, unique_vals=True):
r"""
Swaps the keys and values in a dictionary.
Args:
dict_ (dict): dictionary to invert
unique_vals (bool): if False, inverted keys are returned in a set.
The default is True.
Returns:
dict: inverted
Notes:
The... | python | {
"resource": ""
} |
q254088 | AutoDict.to_dict | validation | def to_dict(self):
"""
Recursively casts a AutoDict into a regular dictionary. All nested
AutoDict values are also converted.
Returns:
dict: a copy of this dict without autovivification
Example:
>>> from ubelt.util_dict import AutoDict
>>> au... | python | {
"resource": ""
} |
q254089 | _symlink | validation | def _symlink(path, link, overwrite=0, verbose=0):
"""
Windows helper for ub.symlink
"""
if exists(link) and not os.path.islink(link):
# On windows a broken link might still exist as a hard link or a
# junction. Overwrite it if it is a file and we cannot symlink.
# However, if it ... | python | {
"resource": ""
} |
q254090 | _win32_symlink2 | validation | def _win32_symlink2(path, link, allow_fallback=True, verbose=0):
"""
Perform a real symbolic link if possible. However, on most versions of
windows you need special privledges to create a real symlink. Therefore, we
try to create a symlink, but if that fails we fallback to using a junction.
AFAIK, ... | python | {
"resource": ""
} |
q254091 | _win32_symlink | validation | def _win32_symlink(path, link, verbose=0):
"""
Creates real symlink. This will only work in versions greater than Windows
Vista. Creating real symlinks requires admin permissions or at least
specially enabled symlink permissions. On Windows 10 enabling developer
mode should give you these permission... | python | {
"resource": ""
} |
q254092 | _win32_is_junction | validation | def _win32_is_junction(path):
"""
Determines if a path is a win32 junction
CommandLine:
python -m ubelt._win32_links _win32_is_junction
Example:
>>> # xdoc: +REQUIRES(WIN32)
>>> import ubelt as ub
>>> root = ub.ensure_app_cache_dir('ubelt', 'win32_junction')
>>>... | python | {
"resource": ""
} |
q254093 | _win32_read_junction | validation | def _win32_read_junction(path):
"""
Returns the location that the junction points, raises ValueError if path is
not a junction.
CommandLine:
python -m ubelt._win32_links _win32_read_junction
Example:
>>> # xdoc: +REQUIRES(WIN32)
>>> import ubelt as ub
>>> root = ub.... | python | {
"resource": ""
} |
q254094 | _win32_rmtree | validation | def _win32_rmtree(path, verbose=0):
"""
rmtree for win32 that treats junctions like directory symlinks.
The junction removal portion may not be safe on race conditions.
There is a known issue that prevents shutil.rmtree from
deleting directories with junctions.
https://bugs.python.org/issue3122... | python | {
"resource": ""
} |
q254095 | _win32_is_hardlinked | validation | def _win32_is_hardlinked(fpath1, fpath2):
"""
Test if two hard links point to the same location
CommandLine:
python -m ubelt._win32_links _win32_is_hardlinked
Example:
>>> # xdoc: +REQUIRES(WIN32)
>>> import ubelt as ub
>>> root = ub.ensure_app_cache_dir('ubelt', 'win32... | python | {
"resource": ""
} |
q254096 | _win32_dir | validation | def _win32_dir(path, star=''):
"""
Using the windows cmd shell to get information about a directory
"""
from ubelt import util_cmd
import re
wrapper = 'cmd /S /C "{}"' # the /S will preserve all inner quotes
command = 'dir /-C "{}"{}'.format(path, star)
wrapped = wrapper.format(command)... | python | {
"resource": ""
} |
q254097 | parse_generator_doubling | validation | def parse_generator_doubling(config):
""" Returns generators that double with each value returned
Config includes optional start value """
start = 1
if 'start' in config: | python | {
"resource": ""
} |
q254098 | ContainsValidator.parse | validation | def parse(config):
""" Parse a contains validator, which takes as the config a simple string to find """
if not isinstance(config, basestring):
raise TypeError("Contains input must be | python | {
"resource": ""
} |
q254099 | retrieve_adjacency_matrix | validation | def retrieve_adjacency_matrix(graph, order_nodes=None, weight=False):
"""Retrieve the adjacency matrix from the nx.DiGraph or numpy array."""
if isinstance(graph, np.ndarray):
return graph
elif isinstance(graph, nx.DiGraph):
if order_nodes is None:
order_nodes = graph.nodes()
... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.