docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Convert JSON in the body of the request to the parameters for the wrapped function. If the JSON is list, add it to ``*args``. If dict, add it to ``**kwargs`` in non-rewrite mode (no key in ``**kwargs`` will be overwritten). If single value, add it to ``*args``. Args: return_json (boo...
def json_to_params(fn=None, return_json=True): def json_to_params_decorator(fn): @handle_type_error @wraps(fn) def json_to_params_wrapper(*args, **kwargs): data = decode_json_body() if type(data) in [tuple, list]: args = list(args) + data ...
864,343
Decode JSON from the request and add it as ``data`` parameter for wrapped function. Args: return_json (bool, default True): Should the decorator automatically convert returned value to JSON?
def json_to_data(fn=None, return_json=True): def json_to_data_decorator(fn): @handle_type_error @wraps(fn) def get_data_wrapper(*args, **kwargs): kwargs["data"] = decode_json_body() if not return_json: return fn(*args, **kwargs) retu...
864,344
Convert bottle forms request to parameters for the wrapped function. Args: return_json (bool, default True): Should the decorator automatically convert returned value to JSON?
def form_to_params(fn=None, return_json=True): def forms_to_params_decorator(fn): @handle_type_error @wraps(fn) def forms_to_params_wrapper(*args, **kwargs): kwargs.update( dict(request.forms) ) if not return_json: ret...
864,345
Get a GCEEnricher client. A factory function that validates configuration and returns an enricher client (:interface:`gordon.interfaces.IMessageHandler`) provider. Args: config (dict): Google Compute Engine API related configuration. metrics (obj): :interface:`IMetricRelay` implementat...
def get_enricher(config, metrics, **kwargs): builder = enricher.GCEEnricherBuilder( config, metrics, **kwargs) return builder.build_enricher()
864,439
Get a GDNSPublisher client. A factory function that validates configuration and returns a publisher client (:interface:`gordon.interfaces.IMessageHandler`) provider. Args: config (dict): Google Cloud DNS API related configuration. metrics (obj): :interface:`IMetricRelay` implementation...
def get_gdns_publisher(config, metrics, **kwargs): builder = gdns_publisher.GDNSPublisherBuilder( config, metrics, **kwargs) return builder.build_publisher()
864,440
Get all active projects. You can find the endpoint documentation `here <https://cloud. google.com/resource-manager/reference/rest/v1/projects/list>`__. Args: page_size (int): hint for the client to only retrieve up to this number of results per API call. Ret...
async def list_all_active_projects(self, page_size=1000): url = f'{self.BASE_URL}/{self.api_version}/projects' params = {'pageSize': page_size} responses = await self.list_all(url, params) projects = self._parse_rsps_for_projects(responses) return [ project ...
864,597
r""" Args: other (?): CommandLine: python -m sortedcontainers.sortedlist join2 Example: >>> from utool.experimental.dynamic_connectivity import * # NOQA >>> self = EulerTourList([1, 2, 3, 2, 4, 2, 1], load=3) >>> other = EulerTourLis...
def join(self, other): r assert self._load == other._load, 'loads must be the same' self._lists.extend(other._lists) self._cumlen.extend([c + self._len for c in other._cumlen]) self._len += other._len
865,046
r""" Args: field_list (list): list of either a tuples to denote a keyword, or a strings for relacement t3ext Returns: str: repl for regex Example: >>> # ENABLE_DOCTEST >>> from utool.util_regex import * # NOQA >>> field_list = [('key',), 'unspecial stri...
def named_field_repl(field_list): r # Allow for unnamed patterns bref_field_list = [ backref_field(key[0]) if isinstance(key, tuple) else key for key in field_list ] repl = ''.join(bref_field_list) return repl
865,092
r""" regex_parse Args: regex (str): text (str): fromstart (bool): Returns: dict or None: Example: >>> # DISABLE_DOCTEST >>> from utool.util_regex import * # NOQA >>> regex = r'(?P<string>\'[^\']*\')' >>> text = " 'just' 'a' sentance wit...
def regex_parse(regex, text, fromstart=True): r match = regex_get_match(regex, text, fromstart=fromstart) if match is not None: parse_dict = match.groupdict() return parse_dict return None
865,099
r""" Prompts user to accept or checks command line for -y Args: msg (str): Returns: bool: accept or not
def are_you_sure(msg=''): r print(msg) from utool import util_arg from utool import util_str override = util_arg.get_argflag(('--yes', '--y', '-y')) if override: print('accepting based on command line flag') return True valid_ans = ['yes', 'y'] valid_prompt = util_str.con...
865,157
r""" Args: fpath (str): file path string CommandLine: python -m utool.util_dev --test-autopep8_diff --fpath ingest_data.py Example: >>> # DISABLE_DOCTEST >>> from utool.util_dev import * # NOQA >>> fpath = ut.get_argval('--fpath', type_=str, default='ingest_data.p...
def autopep8_diff(fpath): r import utool as ut args = ('autopep8', fpath, '--diff') res = ut.cmd(args, verbose=False) out, err, ret = res ut.print_difftext(out)
865,181
r""" Reads text from a file. Automatically returns utf8. Args: fpath (str): file path aslines (bool): if True returns list of lines verbose (bool): verbosity flag Returns: str: text from fpath (this is unicode) Ignore: x = b'''/whaleshark_003_fors\xc3\xb8g.wmv" />\...
def read_from(fpath, verbose=None, aslines=False, strict=True, n=None, errors='replace'): r if n is None: n = __READ_TAIL_N__ verbose = _rectify_verb_read(verbose) if verbose: print('[util_io] * Reading text file: %r ' % util_path.tail(fpath, n=n)) try: if not util_path.check...
865,341
Finds a local varable somewhere in the stack and returns the value Args: varname (str): variable name Returns: None if varname is not found else its value
def search_stack_for_localvar(varname): curr_frame = inspect.currentframe() print(' * Searching parent frames for: ' + six.text_type(varname)) frame_no = 0 while curr_frame.f_back is not None: if varname in curr_frame.f_locals.keys(): print(' * Found in frame: ' + six.text_type(...
865,456
Finds a varable (local or global) somewhere in the stack and returns the value Args: varname (str): variable name Returns: None if varname is not found else its value
def search_stack_for_var(varname, verbose=util_arg.NOT_QUIET): curr_frame = inspect.currentframe() if verbose: print(' * Searching parent frames for: ' + six.text_type(varname)) frame_no = 0 while curr_frame.f_back is not None: if varname in curr_frame.f_locals.keys(): i...
865,457
Finds the string name which has where locals_[name] is val Check the varname is in the parent namespace This will only work with objects not primatives Args: val (): some value locals_ (dict): local dictionary to search default (str): strict (bool): Returns: st...
def get_varname_from_locals(val, locals_, default='varname-not-found', strict=False, cmpfunc_=operator.is_): if val is None or isinstance(val, (int, float, bool)): # Cannot work on primative types return default try: for count, val_ in enumerate(six.iterv...
865,474
r""" Args: list_ (list): seed (int): Returns: list: list_ CommandLine: python -m utool.util_numpy --test-deterministic_shuffle Example: >>> # ENABLE_DOCTEST >>> from utool.util_numpy import * # NOQA >>> list_ = [1, 2, 3, 4, 5, 6] >>> se...
def deterministic_shuffle(list_, seed=0, rng=None): r rng = ensure_rng(seed if rng is None else rng) rng.shuffle(list_) return list_
865,591
If jedi-vim supports google style docstrings you should be able to autocomplete ColumnLists methods for `data` Args: data (utool.ColumnLists): a column list objct ibs (ibeis.IBEISController): an object
def _insource_jedi_vim_test(data, ibs): # TESTME: type a dot and tab. Hopefully autocomplete will happen. data ibs import utool as ut xdata = ut.ColumnLists() xdata import ibeis xibs = ibeis.IBEISController() xibs
865,599
r""" Args: str_ (str): Returns: float: timedelta CommandLine: python -m utool.util_time --exec-parse_timedelta_str Example: >>> # ENABLE_DOCTEST >>> from utool.util_time import * # NOQA >>> str_ = '24h' >>> timedelta = parse_timedelta_str(str_)...
def parse_timedelta_str(str_): r if str_.endswith('m'): timedelta = float(str_[0:-1]) * 60 elif str_.endswith('h'): timedelta = float(str_[0:-1]) * 60 * 60 elif str_.endswith('s'): timedelta = float(str_[0:-1]) else: raise NotImplementedError('Unknown timedelta format...
865,909
r""" Ensures that directory will exist. creates new dir with sticky bits by default Args: path (str): dpath to ensure. Can also be a tuple to send to join info (bool): if True prints extra information mode (int): octal mode of directory (default 0o1777) Returns: str: pa...
def ensuredir(path_, verbose=None, info=False, mode=0o1777): r if verbose is None: verbose = VERYVERBOSE if isinstance(path_, (list, tuple)): path_ = join(*path_) if HAVE_PATHLIB and isinstance(path_, pathlib.Path): path_ = str(path_) if not checkpath(path_, verbose=verbose, ...
866,061
r""" Creates file if it doesnt exist Args: fpath (str): file path times (None): verbose (bool): Example: >>> # DISABLE_DOCTEST >>> from utool.util_path import * # NOQA >>> fpath = '?' >>> times = None >>> verbose = True >>> result = ...
def touch(fpath, times=None, verbose=True): r try: if verbose: print('[util_path] touching %r' % fpath) with open(fpath, 'a'): os.utime(fpath, times) except Exception as ex: import utool utool.printex(ex, 'touch %s' % fpath) raise return fp...
866,062
r""" Args: src (str): file or directory to copy dst (str): directory or new file to copy to Copies src file or folder to dst. If src is a folder this copy is recursive.
def copy_single(src, dst, overwrite=True, verbose=True, deeplink=True, dryrun=False): r try: if exists(src): if not isdir(src) and isdir(dst): # copying file to directory dst = join(dst, basename(src)) if exists(dst): ...
866,066
r""" ensure_crossplat_path Args: path (str): Returns: str: crossplat_path Example(DOCTEST): >>> # ENABLE_DOCTEST >>> from utool.util_path import * # NOQA >>> path = r'C:\somedir' >>> cplat_path = ensure_crossplat_path(path) >>> result = cplat_p...
def ensure_crossplat_path(path, winroot='C:'): r cplat_path = path.replace('\\', '/') if cplat_path == winroot: cplat_path += '/' return cplat_path
866,079
returns importable name from file path get_modname_from_modpath Args: module_fpath (str): module filepath Returns: str: modname Example: >>> # ENABLE_DOCTEST >>> from utool.util_path import * # NOQA >>> import utool as ut >>> module_fpath = ut.util_pa...
def get_modname_from_modpath(module_fpath): modsubdir_list = get_module_subdir_list(module_fpath) modname = '.'.join(modsubdir_list) modname = modname.replace('.__init__', '').strip() modname = modname.replace('.__main__', '').strip() return modname
866,082
get_module_subdir_list Args: module_fpath (str): Example: >>> # ENABLE_DOCTEST >>> from utool.util_path import * # NOQA >>> import utool as ut >>> module_fpath = ut.util_path.__file__ >>> modsubdir_list = get_module_subdir_list(module_fpath) >>> result ...
def get_module_subdir_list(module_fpath): module_fpath = truepath(module_fpath) dpath, fname_ext = split(module_fpath) fname, ext = splitext(fname_ext) full_dpath = dpath dpath = full_dpath _modsubdir_list = [fname] while is_module_dir(dpath): dpath, dname = split(dpath) ...
866,083
Python implementation of sed. NOT FINISHED searches and replaces text in files Args: regexpr (str): regx patterns to find repl (str): text to replace force (bool): recursive (bool): dpath_list (list): directories to search (defaults to cwd)
def sed(regexpr, repl, force=False, recursive=False, dpath_list=None, fpath_list=None, verbose=None, include_patterns=None, exclude_patterns=[]): #_grep(r, [repl], dpath_list=dpath_list, recursive=recursive) if include_patterns is None: include_patterns = ['*.py', '*.pyx', '*.pxi', ...
866,091
r""" replaces windows drives with mingw style drives Args: win32_path (str): CommandLine: python -m utool.util_path --test-ensure_mingw_drive Example: >>> # DISABLE_DOCTEST >>> from utool.util_path import * # NOQA >>> win32_path = r'C:/Program Files/Foobar' ...
def ensure_mingw_drive(win32_path): r win32_drive, _path = splitdrive(win32_path) mingw_drive = '/' + win32_drive[:-1].lower() mingw_path = mingw_drive + _path return mingw_path
866,103
r""" Args: short (bool): (default = False) Returns: str: Example: >>> # ENABLE_DOCTEST >>> from utool.util_cplat import * # NOQA >>> short = False >>> result = python_executable(short) >>> print(result)
def python_executable(check=True, short=False): r if not check: python_exe = 'python' else: from os.path import isdir python_exe_long = unixpath(sys.executable) python_exe = python_exe_long if short: python_exe_short = basename(python_exe_long) ...
866,158
Trying to clean up cmd Args: command (str): string command shell (bool): if True, process is run in shell detatch (bool): if True, process is run in background verbose (int): verbosity mode verbout (bool): if True, `command` writes to stdout in realtime. defaults...
def cmd2(command, shell=False, detatch=False, verbose=False, verbout=None): import shlex if isinstance(command, (list, tuple)): raise ValueError('command tuple not supported yet') args = shlex.split(command, posix=not WIN32) if verbose is True: verbose = 2 if verbout is None: ...
866,174
Create Heroku Connect schema. Note: This function is only meant to be used for local development. In a production environment the schema will be created by Heroku Connect. Args: using (str): Alias for database connection. Returns: bool: ``True`` if the schema was c...
def create_heroku_connect_schema(using=DEFAULT_DB_ALIAS): connection = connections[using] with connection.cursor() as cursor: cursor.execute(_SCHEMA_EXISTS_QUERY, [settings.HEROKU_CONNECT_SCHEMA]) schema_exists = cursor.fetchone()[0] if schema_exists: return False ...
866,219
Import Heroku Connection mapping for given connection. Args: connection_id (str): Heroku Connection connection ID. mapping (dict): Heroku Connect mapping. Raises: requests.HTTPError: If an error occurs uploading the mapping. ValueError: If the mapping is not JSON serializable.
def import_mapping(connection_id, mapping): url = os.path.join(settings.HEROKU_CONNECT_API_ENDPOINT, 'connections', connection_id, 'actions', 'import') response = requests.post( url=url, json=mapping, headers=_get_authorization_headers() ) response.ra...
866,222
SHOULD TURN ANY REGISTERED ARGS INTO A A NEW PARSING CONFIG FILE FOR BETTER --help COMMANDS import utool as ut __REGISTERED_ARGS__ = ut.util_arg.__REGISTERED_ARGS__ Args: extra_args (list): (default = []) CommandLine: python -m utool.util_arg --test-autogen_argparse_block Exa...
def autogen_argparse_block(extra_args=[]): #import utool as ut # NOQA #__REGISTERED_ARGS__ # TODO FINISHME grouped_args = [] # Group similar a args for argtup in __REGISTERED_ARGS__: argstr_list, type_, default, help_ = argtup argstr_set = set(argstr_list) # <MULTI...
866,364
Plot the distribution of a real-valued feature conditioned by the target. Examples: `plot_real_feature(X, 'emb_mean_euclidean')` Args: df: Pandas dataframe containing the target column (named 'target'). feature_name: The name of the feature to plot. bins: The number of histogra...
def plot_real_feature(df, feature_name, bins=50, figsize=(15, 15)): ix_negative_target = df[df.target == 0].index ix_positive_target = df[df.target == 1].index plt.figure(figsize=figsize) ax_overall_dist = plt.subplot2grid((3, 2), (0, 0), colspan=2) ax_target_conditional_dist = plt.subplot2g...
866,398
Plot a scatterplot of two features against one another, and calculate Pearson correlation coefficient. Examples: `plot_pair(X, 'emb_mean_euclidean', 'emb_mean_cosine')` Args: df: feature_name_1: The name of the first feature. feature_name_2: The name of the second feature. ...
def plot_pair(df, feature_name_1, feature_name_2, kind='scatter', alpha=0.01, **kwargs): plt.figure() sns.jointplot( feature_name_1, feature_name_2, df, alpha=alpha, kind=kind, **kwargs ) plt.show()
866,399
Plot a correlation heatmap between every feature pair. Args: df: Pandas dataframe containing the target column (named 'target'). features: The list of features to include in the correlation plot. font_size: Font size for heatmap cells and axis labels. figsize: The size of the plot. ...
def plot_feature_correlation_heatmap(df, features, font_size=9, figsize=(15, 15), save_filename=None): features = features[:] features += ['target'] mcorr = df[features].corr() mask = np.zeros_like(mcorr, dtype=np.bool) mask[np.triu_indices_from(mask)] = True cmap = sns.diverging_palette...
866,400
Plot a scatterplot matrix for a list of features, colored by target value. Example: `scatterplot_matrix(X, X.columns.tolist(), downsample_frac=0.01)` Args: df: Pandas dataframe containing the target column (named 'target'). features: The list of features to include in the correlation plot. ...
def scatterplot_matrix(df, features, downsample_frac=None, figsize=(15, 15)): if downsample_frac: df = df.sample(frac=downsample_frac) plt.figure(figsize=figsize) sns.pairplot(df[features], hue='target') plt.show()
866,401
r""" Inspects members of a class Args: obj (class or module): CommandLine: python -m utool.util_inspect help_members Example: >>> # ENABLE_DOCTEST >>> from utool.util_inspect import * # NOQA >>> import utool as ut >>> obj = ut.DynStruct >>> res...
def help_members(obj, use_other=False): r import utool as ut attrnames = dir(obj) attr_list = [getattr(obj, attrname) for attrname in attrnames] attr_types = ut.lmap(ut.type_str, map(type, attr_list)) unique_types, groupxs = ut.group_indices(attr_types) type_to_items = ut.dzip(unique_types, ...
866,551
list_class_funcnames Args: fname (str): filepath blank_pats (list): defaults to ' #' Returns: list: funcname_list Example: >>> # DISABLE_DOCTEST >>> from utool.util_inspect import * # NOQA >>> fname = 'util_class.py' >>> blank_pats = [' #'] ...
def list_class_funcnames(fname, blank_pats=[' #']): with open(fname, 'r') as file_: lines = file_.readlines() funcname_list = [] #full_line_ = '' for lx, line in enumerate(lines): #full_line_ += line if any([line.startswith(pat) for pat in blank_pats]): funcn...
866,560
r""" Args: func (func): Returns: dict: CommandLine: python -m utool.util_inspect get_kwdefaults Example: >>> # ENABLE_DOCTEST >>> from utool.util_inspect import * # NOQA >>> import utool as ut >>> func = dummy_func >>> parse_source = Tr...
def get_kwdefaults(func, parse_source=False): r #import utool as ut #with ut.embed_on_exception_context: argspec = inspect.getargspec(func) kwdefaults = {} if argspec.args is None or argspec.defaults is None: pass else: args = argspec.args defaults = argspec.defaults ...
866,564
rebinds all class methods Args: self (object): class instance to reload class_ (type): type to reload as Example: >>> # DISABLE_DOCTEST >>> from utool.util_class import * # NOQA >>> self = '?' >>> class_ = '?' >>> result = reload_class_methods(self, cla...
def reload_class_methods(self, class_, verbose=True): if verbose: print('[util_class] Reloading self=%r as class_=%r' % (self, class_)) self.__class__ = class_ for key in dir(class_): # Get unbound reloaded method func = getattr(class_, key) if isinstance(func, types.Met...
866,668
Wait until connection state is no longer ``IMPORT_CONFIGURATION``. Args: connection_id (str): Heroku Connect connection to monitor. wait_interval (int): How frequently to poll in seconds. Raises: CommandError: If fetch connection information fails.
def wait_for_import(self, connection_id, wait_interval): self.stdout.write(self.style.NOTICE('Waiting for import'), ending='') state = utils.ConnectionStates.IMPORT_CONFIGURATION while state == utils.ConnectionStates.IMPORT_CONFIGURATION: # before you get the first state, th...
866,939
Get a QuerySet for all trigger log objects for the same connected model. Args: exclude_self (bool): Whether to exclude this log object from the result list
def related(self, *, exclude_self=False): manager = type(self)._default_manager queryset = manager.related_to(self) if exclude_self: queryset = queryset.exclude(id=self.id) return queryset
867,052
Make a new, non-archived :class:`.TriggerLog` instance with duplicate data. Args: **kwargs: Set as attributes of the new instance, overriding what would otherwise be copied from ``self``. Returns: The new (unpersisted) :class:`TriggerLog` instance.
def _to_live_trigger_log(self, **kwargs): field_names = (field.name for field in TriggerLogAbstract._meta.get_fields()) attributes = {name: getattr(self, name) for name in field_names} del attributes['id'] # this is a completely new log, it should get its own id on save attribu...
867,057
Allocates more space if needbe. Ensures len(``list_``) == ``size_``. Args: list_ (list): ``list`` to extend size_ (int): amount to exent by
def ensure_list_size(list_, size_): lendiff = (size_) - len(list_) if lendiff > 0: extension = [None for _ in range(lendiff)] list_.extend(extension)
867,158
Rebuilds unflat list from invertible_flatten1 Args: flat_list (list): the flattened list reverse_list (list): the list which undoes flattenting Returns: unflat_list2: original nested list SeeAlso: invertible_flatten1 invertible_flatten2 unflatten2
def unflatten1(flat_list, reverse_list): unflat_list2 = [[flat_list[index] for index in tup] for tup in reverse_list] return unflat_list2
867,166
checks to see if list is equal everywhere Args: list_ (list): Returns: True if all items in the list are equal
def allsame(list_, strict=True): if len(list_) == 0: return True first_item = list_[0] return list_all_eq_to(list_, first_item, strict)
867,176
checks to see if list is equal everywhere to a value Args: list_ (list): val : value to check against Returns: True if all items in the list are equal to val
def list_all_eq_to(list_, val, strict=True): if util_type.HAVE_NUMPY and isinstance(val, np.ndarray): return all([np.all(item == val) for item in list_]) try: # FUTURE WARNING # FutureWarning: comparison to `None` will result in an elementwise object comparison in the future. ...
867,177
Returns each item in item_list where not flag in flag_list Args: item_list (list): flag_list (list): Returns: dirty_items
def get_dirty_items(item_list, flag_list): assert len(item_list) == len(flag_list) dirty_items = [item for (item, flag) in zip(item_list, flag_list) if not flag] #print('num_dirty_items = %r' % len(dirty_items)) #print('item_list = %r' % (item_list,)) #prin...
867,178
like np.compress but for lists Returns items in item list where the corresponding item in flag list is True Args: item_list (list): list of items to mask flag_list (list): list of booleans used as a mask Returns: list : filtered_items - masked items
def compress(item_list, flag_list): assert len(item_list) == len(flag_list), ( 'lists should correspond. len(item_list)=%r len(flag_list)=%r' % (len(item_list), len(flag_list))) filtered_items = list(util_iter.iter_compress(item_list, flag_list)) return filtered_items
867,179
Returns items in item list where the corresponding item in flag list is true Args: item_list (list): list of items flag_list (list): list of truthy values Returns: filtered_items : items where the corresponding flag was truthy SeeAlso: util_iter.ifilterfalse_items
def filterfalse_items(item_list, flag_list): assert len(item_list) == len(flag_list) filtered_items = list(util_iter.ifilterfalse_items(item_list, flag_list)) return filtered_items
867,183
Returns a list of flags corresponding to the first time an item is seen Args: list_ (list): list of items Returns: flag_iter
def iflag_unique_items(list_): seen = set() def unseen(item): if item in seen: return False seen.add(item) return True flag_iter = (unseen(item) for item in list_) return flag_iter
867,191
like np.argsort but for lists Args: *args: multiple lists to sort by **kwargs: reverse (bool): sort order is descending if True else acscending CommandLine: python -m utool.util_list argsort Example: >>> # DISABLE_DOCTEST >>> from utool.util_list import...
def argsort(*args, **kwargs): if len(args) == 1 and isinstance(args[0], dict): dict_ = args[0] index_list = list(dict_.keys()) value_list = list(dict_.values()) return sortedby2(index_list, value_list) else: index_list = list(range(len(args[0]))) return sorte...
867,198
Returns index / key of the item with the smallest value. Args: input_ (dict or list): Note: a[argmin(a, key=key)] == min(a, key=key)
def argmin(input_, key=None): # if isinstance(input_, dict): # return list(input_.keys())[argmin(list(input_.values()))] # elif hasattr(input_, 'index'): # return input_.index(min(input_)) # else: # return min(enumerate(input_), key=operator.itemgetter(1))[0] if isinstance(i...
867,201
Map like function Args: func: function to apply input_ : either an iterable or scalar value Returns: If ``input_`` is iterable this function behaves like map otherwise applies func to ``input_``
def scalar_input_map(func, input_): if util_iter.isiterable(input_): return list(map(func, input_)) else: return func(input_)
867,213
Determines if a list is sorted Args: list_ (list): op (func): sorted operation (default=operator.le) Returns: bool : True if the list is sorted
def issorted(list_, op=operator.le): return all(op(list_[ix], list_[ix + 1]) for ix in range(len(list_) - 1))
867,218
r""" Args: items (list): Returns: dict: duplicate_map of indexes CommandLine: python -m utool.util_list --test-find_duplicate_items Example: >>> # DISABLE_DOCTEST >>> from utool.util_list import * # NOQA >>> items = [0, 1, 2, 3, 3, 0, 12, 2, 9] ...
def find_duplicate_items(items, k=2): r import utool as ut # Build item histogram duplicate_map = ut.ddict(list) for count, item in enumerate(items): duplicate_map[item].append(count) # remove singleton items singleton_keys = [] for key in six.iterkeys(duplicate_map): if ...
867,223
Returns the deepest level of nesting within a list of lists Args: list_ : a nested listlike object func : depth aggregation strategy (defaults to max) _depth : internal var Example: >>> # ENABLE_DOCTEST >>> from utool.util_list import * # NOQA >>> list_ = [[[[[...
def list_depth(list_, func=max, _depth=0): depth_list = [list_depth(item, func=func, _depth=_depth + 1) for item in list_ if util_type.is_listlike(item)] if len(depth_list) > 0: return func(depth_list) else: return _depth
867,226
r""" Args: list_ (list): Returns: list: argmaxima CommandLine: python -m utool.util_list --exec-list_argmaxima Example: >>> # ENABLE_DOCTEST >>> from utool.util_list import * # NOQA >>> list_ = np.array([1, 2, 3, 3, 3, 2, 1]) >>> argmaxima = li...
def list_argmaxima(list_): r argmax = list_argmax(list_) maxval = list_[argmax] argmaxima = np.where((np.isclose(maxval, list_)))[0] return argmaxima
867,237
r""" Args: data (?): Returns: ?: CommandLine: python -m utool.util_hash _covert_to_hashable Example: >>> # DISABLE_DOCTEST >>> from utool.util_hash import * # NOQA >>> from utool.util_hash import _covert_to_hashable # NOQA >>> import utool as ...
def _covert_to_hashable(data): r if isinstance(data, six.binary_type): hashable = data prefix = b'TXT' elif util_type.HAVE_NUMPY and isinstance(data, np.ndarray): if data.dtype.kind == 'O': msg = '[ut] hashing ndarrays with dtype=object is unstable' warnings.w...
867,263
r""" Args: num (scalar): low (scalar): high (scalar): msg (str):
def assert_inbounds(num, low, high, msg='', eq=False, verbose=not util_arg.QUIET): r from utool import util_str if util_arg.NO_ASSERTS: return passed = util_alg.inbounds(num, low, high, eq=eq) if isinstance(passed, np.ndarray): passflag = np.all(passed) else: passflag = p...
867,513
r""" Args: arr_test (ndarray or list): arr_target (ndarray or list): thresh (scalar or ndarray or list):
def assert_almost_eq(arr_test, arr_target, thresh=1E-11): r if util_arg.NO_ASSERTS: return import utool as ut arr1 = np.array(arr_test) arr2 = np.array(arr_target) passed, error = ut.almost_eq(arr1, arr2, thresh, ret_error=True) if not np.all(passed): failed_xs = np.where(np....
867,514
r""" Args: arr_test (ndarray or list): arr_target (ndarray or list): thresh (scalar or ndarray or list):
def assert_lessthan(arr_test, arr_max, msg=''): r if util_arg.NO_ASSERTS: return arr1 = np.array(arr_test) arr2 = np.array(arr_max) error = arr_max - arr_test passed = error >= 0 if not np.all(passed): failed_xs = np.where(np.logical_not(passed)) failed_error = error....
867,515
r""" Removes template comments and vim sentinals Args: code_text (str): Returns: str: code_text_
def remove_codeblock_syntax_sentinals(code_text): r flags = re.MULTILINE | re.DOTALL code_text_ = code_text code_text_ = re.sub(r'^ *# *REM [^\n]*$\n?', '', code_text_, flags=flags) code_text_ = re.sub(r'^ *# STARTBLOCK *$\n', '', code_text_, flags=flags) code_text_ = re.sub(r'^ *# ENDBLOCK *$\n...
867,588
upper diagnoal of cartesian product of self and self. Weird name. fixme Args: list_ (list): Returns: list: CommandLine: python -m utool.util_alg --exec-upper_diag_self_prodx Example: >>> # ENABLE_DOCTEST >>> from utool.util_alg import * # NOQA >>>...
def upper_diag_self_prodx(list_): return [(item1, item2) for n1, item1 in enumerate(list_) for n2, item2 in enumerate(list_) if n1 < n2]
867,671
r""" Args: num (float): References: stackoverflow.com/questions/6189956/finding-decimal-places Example: >>> # ENABLE_DOCTEST >>> from utool.util_alg import * # NOQA >>> num = 15.05 >>> result = number_of_decimals(num) >>> print(result) 2
def number_of_decimals(num): r exp = decimal.Decimal(str(num)).as_tuple().exponent return max(0, -exp)
867,693
Import a module, or a typename within a module from its name. Arguments: name: An absolute or relative (starts with a .) Python path path: If name is relative, path is prepended to it. base_path: (DEPRECATED) Same as path typename: (DEPRECATED) Same as path
def import_symbol(name=None, path=None, typename=None, base_path=None): _, symbol = _import(name or typename, path or base_path) return symbol
867,770
r""" returns a copy of dict_ without keys in the negative_keys list Args: dict_ (dict): negative_keys (list):
def dict_setdiff(dict_, negative_keys): r keys = [key for key in six.iterkeys(dict_) if key not in set(negative_keys)] subdict_ = dict_subset(dict_, keys) return subdict_
867,803
dictinfo In depth debugging info Args: dict_ (dict): Returns: str Example: >>> # DISABLE_DOCTEST >>> from utool.util_dict import * # NOQA >>> dict_ = {} >>> result = dictinfo(dict_) >>> print(result)
def dictinfo(dict_): import utool as ut if not isinstance(dict_, dict): return 'expected dict got %r' % type(dict_) keys = list(dict_.keys()) vals = list(dict_.values()) num_keys = len(keys) key_types = list(set(map(type, keys))) val_types = list(set(map(type, vals))) fmt...
867,814
Groups a list of items using the first element in each pair as the item and the second element as the groupid. Args: pair_list (list): list of 2-tuples (item, groupid) Returns: dict: groupid_to_items: maps a groupid to a list of items SeeAlso: group_items
def group_pairs(pair_list): # Initialize dict of lists groupid_to_items = defaultdict(list) # Insert each item into the correct group for item, groupid in pair_list: groupid_to_items[groupid].append(item) return groupid_to_items
867,829
Load pickled features for train and test sets, assuming they are saved in the `features` folder along with their column names. Args: feature_lists: A list containing the names of the feature lists to load. Returns: A tuple containing 3 items: train dataframe, test dataf...
def load_feature_lists(self, feature_lists): column_names = [] feature_ranges = [] running_feature_count = 0 for list_id in feature_lists: feature_list_names = load_lines(self.features_dir + 'X_train_{}.names'.format(list_id)) column_names.extend(featur...
867,873
Save features for the training and test sets to disk, along with their metadata. Args: train_features: A NumPy array of features for the training set. test_features: A NumPy array of features for the test set. feature_names: A list containing the names of the feature columns...
def save_features(self, train_features, test_features, feature_names, feature_list_id): self.save_feature_names(feature_names, feature_list_id) self.save_feature_list(train_features, 'train', feature_list_id) self.save_feature_list(test_features, 'test', feature_list_id)
867,874
Save the names of the features for the given feature list to a metadata file. Example: `save_feature_names(['num_employees', 'stock_price'], 'company')`. Args: feature_names: A list containing the names of the features, matching the column order. feature_list_id: The name for th...
def save_feature_names(self, feature_names, feature_list_id): save_lines(feature_names, self.features_dir + 'X_train_{}.names'.format(feature_list_id))
867,875
Pickle the specified feature list to a file. Example: `save_feature_list(project, X_tfidf_train, 'train', 'tfidf')`. Args: obj: The object to pickle (e.g., a numpy array or a Pandas dataframe) project: An instance of pygoose project. set_id: The id of the subset (e.g...
def save_feature_list(self, obj, set_id, feature_list_id): save(obj, self.features_dir + 'X_{}_{}.pickle'.format(set_id, feature_list_id))
867,876
Returns the weights for each class based on the frequencies of the samples. Args: y: A list of true labels (the labels must be hashable). smooth_factor: A factor that smooths extremely uneven weights. Returns: A dictionary with the weight for each class.
def get_class_weights(y, smooth_factor=0): from collections import Counter counter = Counter(y) if smooth_factor > 0: p = max(counter.values()) * smooth_factor for k in counter.keys(): counter[k] += p majority = max(counter.values()) return {cls: float(majority /...
867,984
Plots the learning history for a Keras model, assuming the validation data was provided to the 'fit' function. Args: history: The return value from the 'fit' function. figsize: The size of the plot.
def plot_loss_history(history, figsize=(15, 8)): plt.figure(figsize=figsize) plt.plot(history.history["loss"]) plt.plot(history.history["val_loss"]) plt.xlabel("# Epochs") plt.ylabel("Loss") plt.legend(["Training", "Validation"]) plt.title("Loss over time") plt.show()
867,985
Retry calling the decorated function using an exponential backoff. Args: exceptions: The exception to check. may be a tuple of exceptions to check. tries: Number of times to try (not retry) before giving up. delay: Initial delay between retries in seconds. backoff: Backo...
def retry(exceptions, tries=5, delay=1, backoff=2, logger=None): def deco_retry(func): @wraps(func) async def f_retry(self, *args, **kwargs): if not iscoroutine(func): f = coroutine(func) else: f = func mtries, mdelay = tries...
868,008
r""" Args: start (int): (default = 0) step (int): (default = 1) Returns: func: next_ CommandLine: python -m utool.util_iter --test-next_counter Example: >>> # ENABLE_DOCTEST >>> from utool.util_iter import * # NOQA >>> start = 1 >>> ste...
def next_counter(start=0, step=1): r count_gen = it.count(start, step) next_ = functools.partial(six.next, count_gen) return next_
868,024
iter_compress - like numpy compress Args: item_iter (list): flag_iter (list): of bools Returns: list: true_items Example: >>> # ENABLE_DOCTEST >>> from utool.util_iter import * # NOQA >>> item_iter = [1, 2, 3, 4, 5] >>> flag_iter = [False, True, Tr...
def iter_compress(item_iter, flag_iter): # TODO: Just use it.compress true_items = (item for (item, flag) in zip(item_iter, flag_iter) if flag) return true_items
868,029
ifilterfalse_items Args: item_iter (list): flag_iter (list): of bools Example: >>> # ENABLE_DOCTEST >>> from utool.util_iter import * # NOQA >>> item_iter = [1, 2, 3, 4, 5] >>> flag_iter = [False, True, True, False, True] >>> false_items = ifilterfalse_...
def ifilterfalse_items(item_iter, flag_iter): false_items = (item for (item, flag) in zip(item_iter, flag_iter) if not flag) return false_items
868,030
Yields `num` items from the cartesian product of items in a random order. Args: items (list of sequences): items to get caresian product of packed in a list or tuple. (note this deviates from api of it.product) Example: import utool as ut items = [(1, 2, 3), (4,...
def random_product(items, num=None, rng=None): import utool as ut rng = ut.ensure_rng(rng, 'python') seen = set() items = [list(g) for g in items] max_num = ut.prod(map(len, items)) if num is None: num = max_num if num > max_num: raise ValueError('num exceedes maximum nu...
868,039
removes all chars in char_list from str_ Args: str_ (str): char_list (list): Returns: str: outstr Example: >>> # ENABLE_DOCTEST >>> from utool.util_str import * # NOQA >>> str_ = '1, 2, 3, 4' >>> char_list = [','] >>> result = remove_chars(...
def remove_chars(str_, char_list): outstr = str_[:] for char in char_list: outstr = outstr.replace(char, '') return outstr
868,204
r""" returns the number of preceding spaces Args: text (str): unicode text Returns: int: indentation CommandLine: python -m utool.util_str --exec-get_minimum_indentation --show Example: >>> # ENABLE_DOCTEST >>> from utool.util_str import * # NOQA ...
def get_minimum_indentation(text): r lines = text.split('\n') indentations = [get_indentation(line_) for line_ in lines if len(line_.strip()) > 0] if len(indentations) == 0: return 0 return min(indentations)
868,205
r""" Convineince indentjoin similar to '\n '.join(strlist) but indent is also prefixed Args: strlist (?): indent (str): suffix (str): Returns: str: joined list
def indentjoin(strlist, indent='\n ', suffix=''): r indent_ = indent strlist = list(strlist) if len(strlist) == 0: return '' return indent_ + indent_.join([six.text_type(str_) + suffix for str_ in strlist])
868,208
r""" Args: text (str): CommandLine: python -m utool.util_str --exec-pack_paragraph --show Example: >>> # DISABLE_DOCTEST >>> from utool.util_str import * # NOQA >>> import utool as ut >>> width = 80 >>> text = lorium_ipsum() >>> result = pac...
def packtext(text, width=80): r import utool as ut import textwrap new_text = '\n'.join(textwrap.wrap(text, width)) new_text = ut.remove_doublspaces(new_text).strip() return new_text
868,212
String of function call signature Args: func (function): live python function Returns: str: callsig CommandLine: python -m utool.util_str --exec-func_callsig Example: >>> # ENABLE_DOCTEST >>> from utool.util_str import * # NOQA >>> func = func_str ...
def func_callsig(func, with_name=True): import inspect argspec = inspect.getargspec(func) (args, varargs, varkw, defaults) = argspec callsig = inspect.formatargspec(*argspec[0:3]) if with_name: callsig = get_callable_name(func) + callsig return callsig
868,226
r""" Returns: list: a list of human-readable dictionary items Args: explicit : if True uses dict(key=val,...) format instead of {key:val,...}
def dict_itemstr_list(dict_, **dictkw): r import utool as ut explicit = dictkw.get('explicit', False) dictkw['explicit'] = _rectify_countdown_or_bool(explicit) dosort = dictkw.get('sorted_', None) if dosort is None: dosort = True if dosort and not isinstance(dict_, collections.Ord...
868,236
Works on must functionlike objects including str, which has no func_name Args: func (function): Returns: str: CommandLine: python -m utool.util_str --exec-get_callable_name Example: >>> # ENABLE_DOCTEST >>> from utool.util_str import * # NOQA >>> func...
def get_callable_name(func): try: return meta_util_six.get_funcname(func) except AttributeError: if isinstance(func, type): return repr(func).replace('<type \'', '').replace('\'>', '') elif hasattr(func, '__name__'): return func.__name__ else: ...
868,242
r""" Args: text (str): Returns: str: text_with_lineno - string with numbered lines
def number_text_lines(text): r numbered_linelist = [ ''.join((('%2d' % (count + 1)), ' >>> ', line)) for count, line in enumerate(text.splitlines()) ] text_with_lineno = '\n'.join(numbered_linelist) return text_with_lineno
868,250
r""" Uses pyfiglet to create bubble text. Args: font (str): default=cybermedium, other fonts include: cybersmall and cyberlarge. References: http://www.figlet.org/ Example: >>> # ENABLE_DOCTEST >>> import utool as ut >>> bubble_text = ut.bubbletext(...
def bubbletext(text, font='cybermedium'): r import utool as ut pyfiglet = ut.tryimport('pyfiglet', 'git+https://github.com/pwaller/pyfiglet') if pyfiglet is None: return text else: bubble_text = pyfiglet.figlet_format(text, font=font) return bubble_text
868,257
r""" Args: underscore_case (?): Returns: str: title_str CommandLine: python -m utool.util_str --exec-to_title_caps Example: >>> # DISABLE_DOCTEST >>> from utool.util_str import * # NOQA >>> underscore_case = 'the_foo_bar_func' >>> title_str = t...
def to_title_caps(underscore_case): r words = underscore_case.split('_') words2 = [ word[0].upper() + word[1:] for count, word in enumerate(words) ] title_str = ' '.join(words2) return title_str
868,259
r""" Args: fpath_list (list): dpath (str): directory relative to main tex file Returns: str: figure_str CommandLine: python -m utool.util_latex --test-get_latex_figure_str Example: >>> # DISABLE_DOCTEST >>> from utool.util_latex import * # NOQA ...
def get_latex_figure_str(fpath_list, caption_str=None, label_str=None, width_str=r'\textwidth', height_str=None, nCols=None, dpath=None, colpos_sep=' ', nlsep='', use_sublbls=None, use_frame=False): r import utool as ut if nCols is ...
868,292
r""" Args: _cmdname (?): Returns: ?: command_name CommandLine: python -m utool.util_latex --exec-latex_sanitize_command_name Example: >>> # DISABLE_DOCTEST >>> from utool.util_latex import * # NOQA >>> _cmdname = '#foo bar.' >>> command_name = ...
def latex_sanitize_command_name(_cmdname): r import utool as ut command_name = _cmdname try: def subroman(match): import roman try: groupdict = match.groupdict() num = int(groupdict['num']) if num == 0: r...
868,297
Invoke the lexer on an input string an return the list of tokens. This is relatively inefficient and should only be used for testing/debugging as it slurps up all tokens into one list. Args: data: The input to be tokenized. Returns: A list of LexTokens
def tokenize(self, data, *args, **kwargs): self.lexer.input(data) tokens = list() while True: token = self.lexer.token() if not token: break tokens.append(token) return tokens
868,443
Constructs the JsonParser based on the grammar contained herein. Successful construction builds the ply.yacc instance and sets self.parser. Args: lexer: A ply.lex or JsonLexer instance that will produce JSON_TOKENS.
def __init__(self, lexer=None, **kwargs): if lexer is not None: if isinstance(lexer, JbossLexer): self.lexer = lexer.lexer else: # Assume that the lexer is a ply.lex instance or similar self.lexer = lexer else: ...
868,444
Parse the input JSON data string into a python data structure. Args: data: An input data string lexer: An optional ply.lex instance that overrides the default lexer. Returns: A python dict or list representing the input JSON data.
def parse(self, data, lexer=None, *args, **kwargs): if lexer is None: lexer = self.lexer return self.parser.parse(data, lexer=lexer, *args, **kwargs)
868,448
Generates attributes values of specific edges Args: on_missing (str): Strategy for handling nodes missing from G. Can be {'error', 'default'}. defaults to 'error'. on_keyerr (str): Strategy for handling keys missing from node dicts. Can be {'error', 'default'}. defaults to...
def nx_gen_edge_values(G, key, edges=None, default=util_const.NoParam, on_missing='error', on_keyerr='default'): if edges is None: edges = G.edges() if on_missing is None: on_missing = 'error' if on_keyerr is None: on_keyerr = 'default' if default is u...
868,674
Read a single Python file in as code and extract members from it. Args: url -- a URL either absolute (contains ':') or relative base_path -- if url is relative, base_path is prepended to it. The resulting URL needs to look something like this: https://github.com/foo/bar/blob/master/bib...
def load_location(url, base_path=None, module=False): if base_path and ':' not in url: slashes = base_path.endswith('/') + url.startswith('/') if slashes == 0: url = base_path + '/' + url elif slashes == 1: url = base_path + url else: url = ba...
868,874
r""" Opens a url in the specified or default browser Args: url (str): web url CommandLine: python -m utool.util_grabdata --test-open_url_in_browser Example: >>> # DISABLE_DOCTEST >>> # SCRIPT >>> from utool.util_grabdata import * # NOQA >>> url = 'http...
def open_url_in_browser(url, browsername=None, fallback=False): r import webbrowser print('[utool] Opening url=%r in browser' % (url,)) if browsername is None: browser = webbrowser.open(url) else: browser = get_prefered_browser(pref_list=[browsername], fallback=fallback) return b...
868,982
Serialize an object to disk using pickle protocol. Args: obj: The object to serialize. filename: Path to the output file. protocol: Version of the pickle protocol.
def save(obj, filename, protocol=4): with open(filename, 'wb') as f: pickle.dump(obj, f, protocol=protocol)
869,100
Load a JSON object from the specified file. Args: filename: Path to the input JSON file. **kwargs: Additional arguments to `json.load`. Returns: The object deserialized from JSON.
def load_json(filename, **kwargs): with open(filename, 'r', encoding='utf-8') as f: return json.load(f, **kwargs)
869,101
Save an object as a JSON file. Args: obj: The object to save. Must be JSON-serializable. filename: Path to the output file. **kwargs: Additional arguments to `json.dump`.
def save_json(obj, filename, **kwargs): with open(filename, 'w', encoding='utf-8') as f: json.dump(obj, f, **kwargs)
869,102