idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
9,000
def tryload_cache_list_with_compute ( use_cache , dpath , fname , cfgstr_list , compute_fn , * args ) : if use_cache is False : data_list = [ None ] * len ( cfgstr_list ) ismiss_list = [ True ] * len ( cfgstr_list ) data_list = compute_fn ( ismiss_list , * args ) return data_list else : data_list , ismiss_list = tryloa...
tries to load data but computes it if it can t give a compute function
9,001
def to_json ( val , allow_pickle = False , pretty = False ) : r UtoolJSONEncoder = make_utool_json_encoder ( allow_pickle ) json_kw = { } json_kw [ 'cls' ] = UtoolJSONEncoder if pretty : json_kw [ 'indent' ] = 4 json_kw [ 'separators' ] = ( ',' , ': ' ) json_str = json . dumps ( val , ** json_kw ) return json_str
r Converts a python object to a JSON string using the utool convention
9,002
def from_json ( json_str , allow_pickle = False ) : if six . PY3 : if isinstance ( json_str , bytes ) : json_str = json_str . decode ( 'utf-8' ) UtoolJSONEncoder = make_utool_json_encoder ( allow_pickle ) object_hook = UtoolJSONEncoder . _json_object_hook val = json . loads ( json_str , object_hook = object_hook ) retu...
Decodes a JSON object specified in the utool convention
9,003
def cachestr_repr ( val ) : try : memview = memoryview ( val ) return memview . tobytes ( ) except Exception : try : return to_json ( val ) except Exception : if repr ( val . __class__ ) == "<class 'ibeis.control.IBEISControl.IBEISController'>" : return val . get_dbname ( )
Representation of an object as a cache string .
9,004
def cached_func ( fname = None , cache_dir = 'default' , appname = 'utool' , key_argx = None , key_kwds = None , use_cache = None , verbose = None ) : r if verbose is None : verbose = VERBOSE_CACHE def cached_closure ( func ) : from utool import util_decor import utool as ut fname_ = util_inspect . get_funcname ( func ...
r Wraps a function with a Cacher object
9,005
def get_global_shelf_fpath ( appname = 'default' , ensure = False ) : global_cache_dir = get_global_cache_dir ( appname , ensure = ensure ) shelf_fpath = join ( global_cache_dir , meta_util_constants . global_cache_fname ) return shelf_fpath
Returns the filepath to the global shelf
9,006
def global_cache_write ( key , val , appname = 'default' ) : with GlobalShelfContext ( appname ) as shelf : shelf [ key ] = val
Writes cache files to a safe place in each operating system
9,007
def delete_global_cache ( appname = 'default' ) : shelf_fpath = get_global_shelf_fpath ( appname ) util_path . remove_file ( shelf_fpath , verbose = True , dryrun = False )
Reads cache files to a safe place in each operating system
9,008
def existing_versions ( self ) : import glob pattern = self . fname + '_*' + self . ext for fname in glob . glob1 ( self . dpath , pattern ) : fpath = join ( self . dpath , fname ) yield fpath
Returns data with different cfgstr values that were previously computed with this cacher .
9,009
def tryload ( self , cfgstr = None ) : if cfgstr is None : cfgstr = self . cfgstr if cfgstr is None : import warnings warnings . warn ( 'No cfgstr given in Cacher constructor or call' ) cfgstr = '' if not self . enabled : if self . verbose > 0 : print ( '[cache] ... %s Cacher disabled' % ( self . fname ) ) return None ...
Like load but returns None if the load fails
9,010
def fuzzyload ( self , cachedir = None , partial_cfgstr = '' , ** kwargs ) : valid_targets = self . glob_valid_targets ( cachedir , partial_cfgstr ) if len ( valid_targets ) != 1 : import utool as ut msg = 'need to further specify target. valid_targets=%s' % ( ut . repr3 ( valid_targets , ) ) raise ValueError ( msg ) f...
Try and load from a partially specified configuration string
9,011
def load ( self , cachedir = None , cfgstr = None , fpath = None , verbose = None , quiet = QUIET , ignore_keys = None ) : if verbose is None : verbose = getattr ( self , 'verbose' , VERBOSE ) if fpath is None : fpath = self . get_fpath ( cachedir , cfgstr = cfgstr ) if verbose : print ( '[Cachable] cache tryload: %r' ...
Loads the result from the given database
9,012
def truepath_relative ( path , otherpath = None ) : if otherpath is None : otherpath = os . getcwd ( ) otherpath = truepath ( otherpath ) path_ = normpath ( relpath ( path , otherpath ) ) return path_
Normalizes and returns absolute path with so specs
9,013
def tail ( fpath , n = 2 , trailing = True ) : return path_ndir_split ( fpath , n = n , trailing = trailing )
Alias for path_ndir_split
9,014
def unexpanduser ( path ) : r homedir = expanduser ( '~' ) if path . startswith ( homedir ) : path = '~' + path [ len ( homedir ) : ] return path
r Replaces home directory with ~
9,015
def path_ndir_split ( path_ , n , force_unix = True , winroot = 'C:' , trailing = True ) : r if not isinstance ( path_ , six . string_types ) : return path_ if n is None : cplat_path = ensure_crossplat_path ( path_ ) elif n == 0 : cplat_path = '' else : sep = '/' if force_unix else os . sep ndirs_list = [ ] head = path...
r Shows only a little bit of the path . Up to the n bottom - level directories
9,016
def augpath ( path , augsuf = '' , augext = '' , augpref = '' , augdir = None , newext = None , newfname = None , ensure = False , prefix = None , suffix = None ) : if prefix is not None : augpref = prefix if suffix is not None : augsuf = suffix dpath , fname = split ( path ) fname_noext , ext = splitext ( fname ) if n...
augments end of path before the extension .
9,017
def remove_files_in_dir ( dpath , fname_pattern_list = '*' , recursive = False , verbose = VERBOSE , dryrun = False , ignore_errors = False ) : if isinstance ( fname_pattern_list , six . string_types ) : fname_pattern_list = [ fname_pattern_list ] if verbose > 2 : print ( '[util_path] Removing files:' ) print ( ' * fr...
Removes files matching a pattern from a directory
9,018
def delete ( path , dryrun = False , recursive = True , verbose = None , print_exists = True , ignore_errors = True ) : if verbose is None : verbose = VERBOSE if not QUIET : verbose = 1 if verbose > 0 : print ( '[util_path] Deleting path=%r' % path ) exists_flag = exists ( path ) link_flag = islink ( path ) if not exis...
Removes a file directory or symlink
9,019
def remove_existing_fpaths ( fpath_list , verbose = VERBOSE , quiet = QUIET , strict = False , print_caller = PRINT_CALLER , lbl = 'files' ) : import utool as ut if print_caller : print ( util_dbg . get_caller_name ( range ( 1 , 4 ) ) + ' called remove_existing_fpaths' ) fpath_list_ = ut . filter_Nones ( fpath_list ) e...
checks existance before removing . then tries to remove exisint paths
9,020
def remove_fpaths ( fpaths , verbose = VERBOSE , quiet = QUIET , strict = False , print_caller = PRINT_CALLER , lbl = 'files' ) : import utool as ut if print_caller : print ( util_dbg . get_caller_name ( range ( 1 , 4 ) ) + ' called remove_fpaths' ) n_total = len ( fpaths ) _verbose = ( not quiet and n_total > 0 ) or V...
Removes multiple file paths
9,021
def longest_existing_path ( _path ) : r existing_path = _path while True : _path_new = os . path . dirname ( existing_path ) if exists ( _path_new ) : existing_path = _path_new break if _path_new == existing_path : print ( '!!! [utool] This is a very illformated path indeed.' ) existing_path = '' break existing_path = ...
r Returns the longest root of _path that exists
9,022
def get_path_type ( path_ ) : r path_type = '' if isfile ( path_ ) : path_type += 'file' if isdir ( path_ ) : path_type += 'directory' if islink ( path_ ) : path_type += 'link' if ismount ( path_ ) : path_type += 'mount' return path_type
r returns if a path is a file directory link or mount
9,023
def checkpath ( path_ , verbose = VERYVERBOSE , n = None , info = VERYVERBOSE ) : r assert isinstance ( path_ , six . string_types ) , ( 'path_=%r is not a string. type(path_) = %r' % ( path_ , type ( path_ ) ) ) path_ = normpath ( path_ ) if sys . platform . startswith ( 'win32' ) : if path_ . startswith ( '\\' ) : di...
r verbose wrapper around os . path . exists
9,024
def ensurepath ( path_ , verbose = None ) : if verbose is None : verbose = VERYVERBOSE return ensuredir ( path_ , verbose = verbose )
DEPRICATE - alias - use ensuredir instead
9,025
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 , in...
r Ensures that directory will exist . creates new dir with sticky bits by default
9,026
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 fpath
r Creates file if it doesnt exist
9,027
def copy_list ( src_list , dst_list , lbl = 'Copying' , ioerr_ok = False , sherro_ok = False , oserror_ok = False ) : task_iter = zip ( src_list , dst_list ) def docopy ( src , dst ) : try : shutil . copy2 ( src , dst ) except OSError : if ioerr_ok : return False raise except shutil . Error : if sherro_ok : return Fals...
Copies all data and stat info
9,028
def glob ( dpath , pattern = None , recursive = False , with_files = True , with_dirs = True , maxdepth = None , exclude_dirs = [ ] , fullpath = True , ** kwargs ) : r gen = iglob ( dpath , pattern , recursive = recursive , with_files = with_files , with_dirs = with_dirs , maxdepth = maxdepth , fullpath = fullpath , ex...
r Globs directory for pattern
9,029
def num_images_in_dir ( path ) : num_imgs = 0 for root , dirs , files in os . walk ( path ) : for fname in files : if fpath_has_imgext ( fname ) : num_imgs += 1 return num_imgs
returns the number of images in a directory
9,030
def fpath_has_ext ( fname , exts , case_sensitive = False ) : fname_ = fname . lower ( ) if not case_sensitive else fname if case_sensitive : ext_pats = [ '*' + ext for ext in exts ] else : ext_pats = [ '*' + ext . lower ( ) for ext in exts ] return any ( [ fnmatch . fnmatch ( fname_ , pat ) for pat in ext_pats ] )
returns true if the filename has any of the given extensions
9,031
def get_modpath ( modname , prefer_pkg = False , prefer_main = False ) : r import importlib if isinstance ( modname , six . string_types ) : module = importlib . import_module ( modname ) else : module = modname modpath = module . __file__ . replace ( '.pyc' , '.py' ) initname = '__init__.py' mainname = '__main__.py' i...
r Returns path to module
9,032
def get_relative_modpath ( module_fpath ) : modsubdir_list = get_module_subdir_list ( module_fpath ) _ , ext = splitext ( module_fpath ) rel_modpath = join ( * modsubdir_list ) + ext rel_modpath = ensure_crossplat_path ( rel_modpath ) return rel_modpath
Returns path to module relative to the package root
9,033
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
returns importable name from file path
9,034
def ls ( path , pattern = '*' ) : path_iter = glob ( path , pattern , recursive = False ) return sorted ( list ( path_iter ) )
like unix ls - lists all files and dirs in path
9,035
def ls_moduledirs ( path , private = True , full = True ) : dir_list = ls_dirs ( path ) module_dir_iter = filter ( is_module_dir , dir_list ) if not private : module_dir_iter = filterfalse ( is_private_module , module_dir_iter ) if not full : module_dir_iter = map ( basename , module_dir_iter ) return list ( module_dir...
lists all dirs which are python modules in path
9,036
def list_images ( img_dpath_ , ignore_list = [ ] , recursive = False , fullpath = False , full = None , sort = True ) : r if full is not None : fullpath = fullpath or full img_dpath_ = util_str . ensure_unicode ( img_dpath_ ) img_dpath = realpath ( img_dpath_ ) ignore_set = set ( ignore_list ) gname_list_ = [ ] assertp...
r Returns a list of images in a directory . By default returns relative paths .
9,037
def assertpath ( path_ , msg = '' , ** kwargs ) : if NO_ASSERTS : return if path_ is None : raise AssertionError ( 'path is None! %s' % ( path_ , msg ) ) if path_ == '' : raise AssertionError ( 'path=%r is the empty string! %s' % ( path_ , msg ) ) if not checkpath ( path_ , ** kwargs ) : raise AssertionError ( 'path=%r...
Asserts that a patha exists
9,038
def matching_fpaths ( dpath_list , include_patterns , exclude_dirs = [ ] , greater_exclude_dirs = [ ] , exclude_patterns = [ ] , recursive = True ) : r if isinstance ( dpath_list , six . string_types ) : dpath_list = [ dpath_list ] for dpath in dpath_list : for root , dname_list , fname_list in os . walk ( dpath ) : su...
r walks dpath lists returning all directories that match the requested pattern .
9,039
def sed ( regexpr , repl , force = False , recursive = False , dpath_list = None , fpath_list = None , verbose = None , include_patterns = None , exclude_patterns = [ ] ) : if include_patterns is None : include_patterns = [ '*.py' , '*.pyx' , '*.pxi' , '*.cxx' , '*.cpp' , '*.hxx' , '*.hpp' , '*.c' , '*.h' , '*.html' , ...
Python implementation of sed . NOT FINISHED
9,040
def grep ( regex_list , recursive = True , dpath_list = None , include_patterns = None , exclude_dirs = [ ] , greater_exclude_dirs = None , inverse = False , exclude_patterns = [ ] , verbose = VERBOSE , fpath_list = None , reflags = 0 , cache = None ) : r from utool import util_regex from utool import util_list if incl...
r greps for patterns Python implementation of grep . NOT FINISHED
9,041
def get_win32_short_path_name ( long_name ) : import ctypes from ctypes import wintypes _GetShortPathNameW = ctypes . windll . kernel32 . GetShortPathNameW _GetShortPathNameW . argtypes = [ wintypes . LPCWSTR , wintypes . LPWSTR , wintypes . DWORD ] _GetShortPathNameW . restype = wintypes . DWORD output_buf_size = 0 wh...
Gets the short path name of a given long path .
9,042
def platform_path ( path ) : r try : if path == '' : raise ValueError ( 'path cannot be the empty string' ) path1 = truepath_relative ( path ) if sys . platform . startswith ( 'win32' ) : path2 = expand_win32_shortname ( path1 ) else : path2 = path1 except Exception as ex : util_dbg . printex ( ex , keys = [ 'path' , '...
r Returns platform specific path for pyinstaller usage
9,043
def find_lib_fpath ( libname , root_dir , recurse_down = True , verbose = False , debug = False ) : def get_lib_fname_list ( libname ) : if sys . platform . startswith ( 'win32' ) : libnames = [ 'lib' + libname + '.dll' , libname + '.dll' ] elif sys . platform . startswith ( 'darwin' ) : libnames = [ 'lib' + libname + ...
Search for the library
9,044
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
r replaces windows drives with mingw style drives
9,045
def ancestor_paths ( start = None , limit = { } ) : import utool as ut limit = ut . ensure_iterable ( limit ) limit = { expanduser ( p ) for p in limit } . union ( set ( limit ) ) if start is None : start = os . getcwd ( ) path = start prev = None while path != prev and prev not in limit : yield path prev = path path =...
All paths above you
9,046
def search_candidate_paths ( candidate_path_list , candidate_name_list = None , priority_paths = None , required_subpaths = [ ] , verbose = None ) : import utool as ut if verbose is None : verbose = 0 if QUIET else 1 if verbose >= 1 : print ( '[search_candidate_paths] Searching for candidate paths' ) if candidate_name_...
searches for existing paths that meed a requirement
9,047
def symlink ( real_path , link_path , overwrite = False , on_error = 'raise' , verbose = 2 ) : path = normpath ( real_path ) link = normpath ( link_path ) if verbose : print ( '[util_path] Creating symlink: path={} link={}' . format ( path , link ) ) if os . path . islink ( link ) : if verbose : print ( '[util_path] sy...
Attempt to create a symbolic link .
9,048
def remove_broken_links ( dpath , verbose = True ) : fname_list = [ join ( dpath , fname ) for fname in os . listdir ( dpath ) ] broken_links = list ( filterfalse ( exists , filter ( islink , fname_list ) ) ) num_broken = len ( broken_links ) if verbose : if verbose > 1 or num_broken > 0 : print ( '[util_path] Removing...
Removes all broken links in a directory
9,049
def non_existing_path ( path_ , dpath = None , offset = 0 , suffix = None , force_fmt = False ) : r import utool as ut from os . path import basename , dirname if dpath is None : dpath = dirname ( path_ ) base_fmtstr = basename ( path_ ) if suffix is not None : base_fmtstr = ut . augpath ( base_fmtstr , suffix ) if '%'...
r Searches for and finds a path garuenteed to not exist .
9,050
def create_isobaric_quant_lookup ( quantdb , specfn_consensus_els , channelmap ) : channels_store = ( ( name , ) for name , c_id in sorted ( channelmap . items ( ) , key = lambda x : x [ 1 ] ) ) quantdb . store_channelmap ( channels_store ) channelmap_dbid = { channelmap [ ch_name ] : ch_id for ch_id , ch_name in quant...
Creates an sqlite lookup table of scannrs with quant data .
9,051
def get_precursors_from_window ( quantdb , minmz ) : featmap = { } mz = False features = quantdb . get_precursor_quant_window ( FEATURE_ALIGN_WINDOW_AMOUNT , minmz ) for feat_id , fn_id , charge , mz , rt in features : try : featmap [ fn_id ] [ charge ] . append ( ( mz , rt , feat_id ) ) except KeyError : try : featmap...
Returns a dict of a specified amount of features from the ms1 quant database and the highest mz of those features
9,052
def get_quant_data ( cons_el ) : quant_out = { } for reporter in cons_el . findall ( './/element' ) : quant_out [ reporter . attrib [ 'map' ] ] = reporter . attrib [ 'it' ] return quant_out
Gets quant data from consensusXML element
9,053
def get_plat_specifier ( ) : import setuptools import distutils plat_name = distutils . util . get_platform ( ) plat_specifier = ".%s-%s" % ( plat_name , sys . version [ 0 : 3 ] ) if hasattr ( sys , 'gettotalrefcount' ) : plat_specifier += '-pydebug' return plat_specifier
Standard platform specifier used by distutils
9,054
def get_system_python_library ( ) : import os import utool as ut from os . path import basename , realpath pyname = basename ( realpath ( sys . executable ) ) ld_library_path = os . environ [ 'LD_LIBRARY_PATH' ] libdirs = [ x for x in ld_library_path . split ( os . pathsep ) if x ] + [ '/usr/lib' ] libfiles = ut . flat...
FIXME ; hacky way of finding python library . Not cross platform yet .
9,055
def get_dynlib_dependencies ( lib_path ) : if LINUX : ldd_fpath = '/usr/bin/ldd' depend_out , depend_err , ret = cmd ( ldd_fpath , lib_path , verbose = False ) elif DARWIN : otool_fpath = '/opt/local/bin/otool' depend_out , depend_err , ret = cmd ( otool_fpath , '-L' , lib_path , verbose = False ) elif WIN32 : depend_o...
Executes tools for inspecting dynamic library dependencies depending on the current platform .
9,056
def startfile ( fpath , detatch = True , quote = False , verbose = False , quiet = True ) : print ( '[cplat] startfile(%r)' % fpath ) fpath = normpath ( fpath ) if not exists ( fpath ) : raise Exception ( 'Cannot start nonexistant file: %r' % fpath ) if not WIN32 : fpath = pipes . quote ( fpath ) if LINUX : outtup = cm...
Uses default program defined by the system to open a file .
9,057
def view_directory ( dname = None , fname = None , verbose = True ) : from utool . util_arg import STRICT from utool . util_path import checkpath if HAVE_PATHLIB and isinstance ( dname , pathlib . Path ) : dname = str ( dname ) if verbose : print ( '[cplat] view_directory(%r) ' % dname ) dname = os . getcwd ( ) if dnam...
View a directory in the operating system file browser . Currently supports windows explorer mac open and linux nautlius .
9,058
def platform_cache_dir ( ) : if WIN32 : dpath_ = '~/AppData/Local' elif LINUX : dpath_ = '~/.cache' elif DARWIN : dpath_ = '~/Library/Caches' else : raise NotImplementedError ( 'Unknown Platform %r' % ( sys . platform , ) ) dpath = normpath ( expanduser ( dpath_ ) ) return dpath
Returns a directory which should be writable for any application This should be used for temporary deletable data .
9,059
def __parse_cmd_args ( args , sudo , shell ) : if isinstance ( args , tuple ) and len ( args ) == 1 and isinstance ( args [ 0 ] , tuple ) : args = args [ 0 ] if shell : if isinstance ( args , six . string_types ) : pass elif isinstance ( args , ( list , tuple ) ) and len ( args ) > 1 : args = ' ' . join ( args ) elif i...
When shell is True Popen will only accept strings . No tuples Shell really should not be true .
9,060
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 : verbou...
Trying to clean up cmd
9,061
def search_env_paths ( fname , key_list = None , verbose = None ) : r import utool as ut if key_list is None : key_list = [ key for key in os . environ if key . find ( 'PATH' ) > - 1 ] print ( 'key_list = %r' % ( key_list , ) ) found = ut . ddict ( list ) for key in key_list : dpath_list = os . environ [ key ] . split ...
r Searches your PATH to see if fname exists
9,062
def change_term_title ( title ) : if True : return if not WIN32 : if title : cmd_str = r + title + os . system ( cmd_str )
only works on unix systems only tested on Ubuntu GNOME changes text on terminal title for identifying debugging tasks .
9,063
def unload_module ( modname ) : import sys import gc if modname in sys . modules : referrer_list = gc . get_referrers ( sys . modules [ modname ] ) for referer in referrer_list : if referer is not sys . modules : referer [ modname ] = None refcount = sys . getrefcount ( sys . modules [ modname ] ) print ( '%s refcount=...
WARNING POTENTIALLY DANGEROUS AND MAY NOT WORK
9,064
def base_add_isoquant_data ( features , quantfeatures , acc_col , quantacc_col , quantfields ) : quant_map = get_quantmap ( quantfeatures , quantacc_col , quantfields ) for feature in features : feat_acc = feature [ acc_col ] outfeat = { k : v for k , v in feature . items ( ) } try : outfeat . update ( quant_map [ feat...
Generic function that takes a peptide or protein table and adds quant data from ANOTHER such table .
9,065
def get_quantmap ( features , acc_col , quantfields ) : qmap = { } for feature in features : feat_acc = feature . pop ( acc_col ) qmap [ feat_acc ] = { qf : feature [ qf ] for qf in quantfields } return qmap
Runs through proteins that are in a quanted protein table extracts and maps their information based on the quantfields list input . Map is a dict with protein_accessions as keys .
9,066
def partition_varied_cfg_list ( cfg_list , default_cfg = None , recursive = False ) : r import utool as ut if default_cfg is None : nonvaried_cfg = reduce ( ut . dict_intersection , cfg_list ) else : nonvaried_cfg = reduce ( ut . dict_intersection , [ default_cfg ] + cfg_list ) nonvaried_keys = list ( nonvaried_cfg . k...
r Separates varied from non - varied parameters in a list of configs
9,067
def get_cfg_lbl ( cfg , name = None , nonlbl_keys = INTERNAL_CFGKEYS , key_order = None , with_name = True , default_cfg = None , sep = '' ) : r import utool as ut if name is None : name = cfg . get ( '_cfgname' , '' ) if default_cfg is not None : cfg = ut . partition_varied_cfg_list ( [ cfg ] , default_cfg ) [ 1 ] [ 0...
r Formats a flat configuration dict into a short string label . This is useful for re - creating command line strings .
9,068
def parse_cfgstr_list2 ( cfgstr_list , named_defaults_dict = None , cfgtype = None , alias_keys = None , valid_keys = None , expand_nested = True , strict = True , special_join_dict = None , is_nestedcfgtype = False , metadata = None ) : r import utool as ut cfg_combos_list = [ ] cfgstr_list_ = [ ] dyndef_named_default...
r Parses config strings . By looking up name in a dict of configs
9,069
def grid_search_generator ( grid_basis = [ ] , * args , ** kwargs ) : r grid_basis_ = grid_basis + list ( args ) + list ( kwargs . items ( ) ) grid_basis_dict = OrderedDict ( grid_basis_ ) grid_point_iter = util_dict . iter_all_dict_combinations_ordered ( grid_basis_dict ) for grid_point in grid_point_iter : yield grid...
r Iteratively yeilds individual configuration points inside a defined basis .
9,070
def get_cfgdict_list_subset ( cfgdict_list , keys ) : r import utool as ut cfgdict_sublist_ = [ ut . dict_subset ( cfgdict , keys ) for cfgdict in cfgdict_list ] cfgtups_sublist_ = [ tuple ( ut . dict_to_keyvals ( cfgdict ) ) for cfgdict in cfgdict_sublist_ ] cfgtups_sublist = ut . unique_ordered ( cfgtups_sublist_ ) c...
r returns list of unique dictionaries only with keys specified in keys
9,071
def constrain_cfgdict_list ( cfgdict_list_ , constraint_func ) : cfgdict_list = [ ] for cfg_ in cfgdict_list_ : cfg = cfg_ . copy ( ) if constraint_func ( cfg ) is not False and len ( cfg ) > 0 : if cfg not in cfgdict_list : cfgdict_list . append ( cfg ) return cfgdict_list
constrains configurations and removes duplicates
9,072
def make_cfglbls ( cfgdict_list , varied_dict ) : import textwrap wrapper = textwrap . TextWrapper ( width = 50 ) cfglbl_list = [ ] for cfgdict_ in cfgdict_list : cfgdict = cfgdict_ . copy ( ) for key in six . iterkeys ( cfgdict_ ) : try : vals = varied_dict [ key ] if len ( vals ) == 1 : del cfgdict [ key ] else : if ...
Show only the text in labels that mater from the cfgdict
9,073
def gridsearch_timer ( func_list , args_list , niters = None , ** searchkw ) : import utool as ut timings = ut . ddict ( list ) if niters is None : niters = len ( args_list ) if ut . is_funclike ( args_list ) : get_args = args_list else : get_args = args_list . __getitem__ func_labels = searchkw . get ( 'func_labels' ,...
Times a series of functions on a series of inputs
9,074
def get_mapping ( version = 1 , exported_at = None , app_name = None ) : if exported_at is None : exported_at = timezone . now ( ) app_name = app_name or settings . HEROKU_CONNECT_APP_NAME return { 'version' : version , 'connection' : { 'organization_id' : settings . HEROKU_CONNECT_ORGANIZATION_ID , 'app_name' : app_na...
Return Heroku Connect mapping for the entire project .
9,075
def get_heroku_connect_models ( ) : from django . apps import apps apps . check_models_ready ( ) from heroku_connect . db . models import HerokuConnectModel return ( model for models in apps . all_models . values ( ) for model in models . values ( ) if issubclass ( model , HerokuConnectModel ) and not model . _meta . m...
Return all registered Heroku Connect Models .
9,076
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 cursor . execute ( "CRE...
Create Heroku Connect schema .
9,077
def get_connections ( app ) : payload = { 'app' : app } url = os . path . join ( settings . HEROKU_CONNECT_API_ENDPOINT , 'connections' ) response = requests . get ( url , params = payload , headers = _get_authorization_headers ( ) ) response . raise_for_status ( ) return response . json ( ) [ 'results' ]
Return all Heroku Connect connections setup with the given application .
9,078
def get_connection ( connection_id , deep = False ) : url = os . path . join ( settings . HEROKU_CONNECT_API_ENDPOINT , 'connections' , connection_id ) payload = { 'deep' : deep } response = requests . get ( url , params = payload , headers = _get_authorization_headers ( ) ) response . raise_for_status ( ) return respo...
Get Heroku Connection connection information .
9,079
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 . raise_for_status ( )
Import Heroku Connection mapping for given connection .
9,080
def link_connection_to_account ( app ) : url = os . path . join ( settings . HEROKU_CONNECT_API_ENDPOINT , 'users' , 'me' , 'apps' , app , 'auth' ) response = requests . post ( url = url , headers = _get_authorization_headers ( ) ) response . raise_for_status ( )
Link the connection to your Heroku user account .
9,081
def fetch_cvparams_values_from_subel ( base , subelname , paramnames , ns ) : sub_el = basereader . find_element_xpath ( base , subelname , ns ) cvparams = get_all_cvparams ( sub_el , ns ) output = [ ] for param in paramnames : output . append ( fetch_cvparam_value_by_name ( cvparams , param ) ) return output
Searches a base element for subelement by name then takes the cvParams of that subelement and returns the values as a list for the paramnames that match . Value order in list equals input paramnames order .
9,082
def create_tables ( self , tables ) : cursor = self . get_cursor ( ) for table in tables : columns = mslookup_tables [ table ] try : cursor . execute ( 'CREATE TABLE {0}({1})' . format ( table , ', ' . join ( columns ) ) ) except sqlite3 . OperationalError as error : print ( error ) print ( 'Warning: Table {} already e...
Creates database tables in sqlite lookup db
9,083
def connect ( self , fn ) : self . conn = sqlite3 . connect ( fn ) cur = self . get_cursor ( ) cur . execute ( 'PRAGMA page_size=4096' ) cur . execute ( 'PRAGMA FOREIGN_KEYS=ON' ) cur . execute ( 'PRAGMA cache_size=10000' ) cur . execute ( 'PRAGMA journal_mode=MEMORY' )
SQLite connect method initialize db
9,084
def index_column ( self , index_name , table , column ) : cursor = self . get_cursor ( ) try : cursor . execute ( 'CREATE INDEX {0} on {1}({2})' . format ( index_name , table , column ) ) except sqlite3 . OperationalError as error : print ( error ) print ( 'Skipping index creation and assuming it exists already' ) else...
Called by interfaces to index specific column in table
9,085
def get_sql_select ( self , columns , table , distinct = False ) : sql = 'SELECT {0} {1} FROM {2}' dist = { True : 'DISTINCT' , False : '' } [ distinct ] return sql . format ( dist , ', ' . join ( columns ) , table )
Creates and returns an SQL SELECT statement
9,086
def store_many ( self , sql , values ) : cursor = self . get_cursor ( ) cursor . executemany ( sql , values ) self . conn . commit ( )
Abstraction over executemany method
9,087
def execute_sql ( self , sql ) : cursor = self . get_cursor ( ) cursor . execute ( sql ) return cursor
Executes SQL and returns cursor for it
9,088
def get_mzmlfile_map ( self ) : cursor = self . get_cursor ( ) cursor . execute ( 'SELECT mzmlfile_id, mzmlfilename FROM mzmlfiles' ) return { fn : fnid for fnid , fn in cursor . fetchall ( ) }
Returns dict of mzmlfilenames and their db ids
9,089
def get_spectra_id ( self , fn_id , retention_time = None , scan_nr = None ) : cursor = self . get_cursor ( ) sql = 'SELECT spectra_id FROM mzml WHERE mzmlfile_id=? ' values = [ fn_id ] if retention_time is not None : sql = '{0} AND retention_time=?' . format ( sql ) values . append ( retention_time ) if scan_nr is not...
Returns spectra id for spectra filename and retention time
9,090
def to_string_monkey ( df , highlight_cols = None , latex = False ) : try : import pandas as pd import utool as ut import numpy as np import six if isinstance ( highlight_cols , six . string_types ) and highlight_cols == 'all' : highlight_cols = np . arange ( len ( df . columns ) ) try : self = pd . formats . format . ...
monkey patch to pandas to highlight the maximum value in specified cols of a row
9,091
def translate ( value ) : if isinstance ( value , BaseValidator ) : return value if value is None : return Anything ( ) if isinstance ( value , type ) : return IsA ( value ) if type ( value ) in compat . func_types : real_value = value ( ) return IsA ( type ( real_value ) , default = real_value ) if isinstance ( value ...
Translates given schema from pythonic syntax to a validator .
9,092
def _merge ( self , value ) : if value is not None and not isinstance ( value , dict ) : return value if not self . _pairs : return { } collected = { } for k_validator , v_validator in self . _pairs : k_default = k_validator . get_default_for ( None ) if k_default is None : continue if value : v_for_this_k = value . ge...
Returns a dictionary based on value with each value recursively merged with spec .
9,093
def handle_code ( code ) : "Handle a key or sequence of keys in braces" code_keys = [ ] if code in CODES : code_keys . append ( VirtualKeyAction ( CODES [ code ] ) ) elif len ( code ) == 1 : code_keys . append ( KeyAction ( code ) ) elif ' ' in code : to_repeat , count = code . rsplit ( None , 1 ) if to_repeat == "PAUS...
Handle a key or sequence of keys in braces
9,094
def parse_keys ( string , with_spaces = False , with_tabs = False , with_newlines = False , modifiers = None ) : "Return the parsed keys" keys = [ ] if not modifiers : modifiers = [ ] index = 0 while index < len ( string ) : c = string [ index ] index += 1 if c in MODIFIERS . keys ( ) : modifier = MODIFIERS [ c ] modif...
Return the parsed keys
9,095
def SendKeys ( keys , pause = 0.05 , with_spaces = False , with_tabs = False , with_newlines = False , turn_off_numlock = True ) : "Parse the keys and type them" keys = parse_keys ( keys , with_spaces , with_tabs , with_newlines ) for k in keys : k . Run ( ) time . sleep ( pause )
Parse the keys and type them
9,096
def main ( ) : "Send some test strings" actions = SendKeys ( actions , pause = .1 ) keys = parse_keys ( actions ) for k in keys : print ( k ) k . Run ( ) time . sleep ( .1 ) test_strings = [ "\n" "(aa)some text\n" , "(a)some{ }text\n" , "(b)some{{}text\n" , "(c)some{+}text\n" , "(d)so%me{ab 4}text" , "(e)so%me{LEFT 4}t...
Send some test strings
9,097
def GetInput ( self ) : "Build the INPUT structure for the action" actions = 1 if self . up and self . down : actions = 2 inputs = ( INPUT * actions ) ( ) vk , scan , flags = self . _get_key_info ( ) for inp in inputs : inp . type = INPUT_KEYBOARD inp . _ . ki . wVk = vk inp . _ . ki . wScan = scan inp . _ . ki . dwFla...
Build the INPUT structure for the action
9,098
def Run ( self ) : "Execute the action" inputs = self . GetInput ( ) return SendInput ( len ( inputs ) , ctypes . byref ( inputs ) , ctypes . sizeof ( INPUT ) )
Execute the action
9,099
def _get_down_up_string ( self ) : down_up = "" if not ( self . down and self . up ) : if self . down : down_up = "down" elif self . up : down_up = "up" return down_up
Return a string that will show whether the string is up or down