idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
9,000 | def list_images ( img_dpath_ , ignore_list = [ ] , recursive = False , fullpath = False , full = None , sort = True ) : #if not QUIET: # print(ignore_list) 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 ( ignor... | r Returns a list of images in a directory . By default returns relative paths . | 389 | 16 |
9,001 | 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=... | Asserts that a patha exists | 128 | 8 |
9,002 | def matching_fpaths ( dpath_list , include_patterns , exclude_dirs = [ ] , greater_exclude_dirs = [ ] , exclude_patterns = [ ] , recursive = True ) : 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 ) : # Lo... | r walks dpath lists returning all directories that match the requested pattern . | 266 | 14 |
9,003 | 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' , '*.cx... | Python implementation of sed . NOT FINISHED | 682 | 9 |
9,004 | 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 . | 184 | 12 |
9,005 | def platform_path ( path ) : try : if path == '' : raise ValueError ( 'path cannot be the empty string' ) # get path relative to cwd path1 = truepath_relative ( path ) if sys . platform . startswith ( 'win32' ) : path2 = expand_win32_shortname ( path1 ) else : path2 = path1 except Exception as ex : util_dbg . printex (... | r Returns platform specific path for pyinstaller usage | 118 | 10 |
9,006 | def find_lib_fpath ( libname , root_dir , recurse_down = True , verbose = False , debug = False ) : def get_lib_fname_list ( libname ) : """ input <libname>: library name (e.g. 'hesaff', not 'libhesaff') returns <libnames>: list of plausible library file names """ if sys . platform . startswith ( 'win32' ) : libnames =... | Search for the library | 640 | 4 |
9,007 | def ensure_mingw_drive ( win32_path ) : 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 | 68 | 9 |
9,008 | 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 | 95 | 4 |
9,009 | 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 | 383 | 11 |
9,010 | 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 . | 365 | 7 |
9,011 | 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 | 138 | 8 |
9,012 | def non_existing_path ( path_ , dpath = None , offset = 0 , suffix = None , force_fmt = False ) : 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 '%' n... | r Searches for and finds a path garuenteed to not exist . | 293 | 16 |
9,013 | def create_isobaric_quant_lookup ( quantdb , specfn_consensus_els , channelmap ) : # store quantchannels in lookup and generate a db_id vs channel map channels_store = ( ( name , ) for name , c_id in sorted ( channelmap . items ( ) , key = lambda x : x [ 1 ] ) ) quantdb . store_channelmap ( channels_store ) channelmap_... | Creates an sqlite lookup table of scannrs with quant data . | 354 | 15 |
9,014 | 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 | 171 | 23 |
9,015 | 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 | 62 | 9 |
9,016 | def get_plat_specifier ( ) : import setuptools # NOQA 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 | 94 | 8 |
9,017 | 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 . | 214 | 16 |
9,018 | 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 . | 225 | 14 |
9,019 | def startfile ( fpath , detatch = True , quote = False , verbose = False , quiet = True ) : print ( '[cplat] startfile(%r)' % fpath ) fpath = normpath ( fpath ) # print('[cplat] fpath=%s' % fpath) if not exists ( fpath ) : raise Exception ( 'Cannot start nonexistant file: %r' % fpath ) #if quote: # fpath = '"%s"' % (fp... | Uses default program defined by the system to open a file . | 304 | 13 |
9,020 | def view_directory ( dname = None , fname = None , verbose = True ) : from utool . util_arg import STRICT from utool . util_path import checkpath # from utool.util_str import SINGLE_QUOTE, DOUBLE_QUOTE if HAVE_PATHLIB and isinstance ( dname , pathlib . Path ) : dname = str ( dname ) if verbose : print ( '[cplat] view_d... | View a directory in the operating system file browser . Currently supports windows explorer mac open and linux nautlius . | 366 | 23 |
9,021 | def platform_cache_dir ( ) : if WIN32 : # nocover dpath_ = '~/AppData/Local' elif LINUX : # nocover dpath_ = '~/.cache' elif DARWIN : # nocover dpath_ = '~/Library/Caches' else : # nocover 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 . | 111 | 21 |
9,022 | def __parse_cmd_args ( args , sudo , shell ) : # Case where tuple is passed in as only argument if isinstance ( args , tuple ) and len ( args ) == 1 and isinstance ( args [ 0 ] , tuple ) : args = args [ 0 ] if shell : # When shell is True, ensure args is a string if isinstance ( args , six . string_types ) : pass elif ... | When shell is True Popen will only accept strings . No tuples Shell really should not be true . | 572 | 21 |
9,023 | 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 | 478 | 6 |
9,024 | def search_env_paths ( fname , key_list = None , verbose = None ) : import utool as ut # from os.path import join 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 .... | r Searches your PATH to see if fname exists | 264 | 11 |
9,025 | def change_term_title ( title ) : if True : # Disabled return if not WIN32 : #print("CHANGE TERM TITLE to %r" % (title,)) if title : #os.environ['PS1'] = os.environ['PS1'] + '''"\e]2;\"''' + title + '''\"\a"''' cmd_str = r'''echo -en "\033]0;''' + title + '''\a"''' os . system ( cmd_str ) | only works on unix systems only tested on Ubuntu GNOME changes text on terminal title for identifying debugging tasks . | 118 | 21 |
9,026 | def unload_module ( modname ) : import sys import gc if modname in sys . modules : referrer_list = gc . get_referrers ( sys . modules [ modname ] ) #module = sys.modules[modname] for referer in referrer_list : if referer is not sys . modules : referer [ modname ] = None #del referer[modname] #sys.modules[modname] = mod... | WARNING POTENTIALLY DANGEROUS AND MAY NOT WORK | 147 | 14 |
9,027 | 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 . | 123 | 20 |
9,028 | 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 . | 65 | 37 |
9,029 | def partition_varied_cfg_list ( cfg_list , default_cfg = None , recursive = False ) : 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 . key... | r Separates varied from non - varied parameters in a list of configs | 357 | 16 |
9,030 | def get_cfg_lbl ( cfg , name = None , nonlbl_keys = INTERNAL_CFGKEYS , key_order = None , with_name = True , default_cfg = None , sep = '' ) : import utool as ut if name is None : name = cfg . get ( '_cfgname' , '' ) if default_cfg is not None : # Remove defaulted labels cfg = ut . partition_varied_cfg_list ( [ cfg ] ,... | r Formats a flat configuration dict into a short string label . This is useful for re - creating command line strings . | 556 | 24 |
9,031 | def grid_search_generator ( grid_basis = [ ] , * args , * * kwargs ) : 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 . | 113 | 14 |
9,032 | def get_cfgdict_list_subset ( cfgdict_list , keys ) : 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_ ) cfg... | r returns list of unique dictionaries only with keys specified in keys | 145 | 13 |
9,033 | 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 | 99 | 8 |
9,034 | 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 ] # Dont print label if not varied if len ( vals ) == 1... | Show only the text in labels that mater from the cfgdict | 322 | 13 |
9,035 | 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', li... | Times a series of functions on a series of inputs | 722 | 10 |
9,036 | 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 . | 158 | 10 |
9,037 | 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 . | 86 | 8 |
9,038 | 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 . | 236 | 6 |
9,039 | 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 . | 91 | 12 |
9,040 | 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 . | 95 | 7 |
9,041 | 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 . | 89 | 9 |
9,042 | 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 . | 85 | 10 |
9,043 | 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 . | 99 | 46 |
9,044 | 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 | 124 | 9 |
9,045 | 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 | 96 | 6 |
9,046 | 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 | 99 | 10 |
9,047 | 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 | 69 | 8 |
9,048 | def store_many ( self , sql , values ) : cursor = self . get_cursor ( ) cursor . executemany ( sql , values ) self . conn . commit ( ) | Abstraction over executemany method | 39 | 8 |
9,049 | def execute_sql ( self , sql ) : cursor = self . get_cursor ( ) cursor . execute ( sql ) return cursor | Executes SQL and returns cursor for it | 28 | 8 |
9,050 | 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 | 71 | 15 |
9,051 | 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 | 154 | 11 |
9,052 | 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 ) ) # kwds = dict(buf=None, columns=None,... | monkey patch to pandas to highlight the maximum value in specified cols of a row | 810 | 17 |
9,053 | 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 . | 329 | 14 |
9,054 | def _merge ( self , value ) : if value is not None and not isinstance ( value , dict ) : # bogus value; will not pass validation but should be preserved return value if not self . _pairs : return { } collected = { } # collected.update(value) for k_validator , v_validator in self . _pairs : k_default = k_validator . get... | Returns a dictionary based on value with each value recursively merged with spec . | 203 | 16 |
9,055 | def handle_code ( code ) : code_keys = [ ] # it is a known code (e.g. {DOWN}, {ENTER}, etc) if code in CODES : code_keys . append ( VirtualKeyAction ( CODES [ code ] ) ) # it is an escaped modifier e.g. {%}, {^}, {+} elif len ( code ) == 1 : code_keys . append ( KeyAction ( code ) ) # it is a repetition or a pause {DOW... | Handle a key or sequence of keys in braces | 367 | 9 |
9,056 | def parse_keys ( string , with_spaces = False , with_tabs = False , with_newlines = False , modifiers = None ) : keys = [ ] if not modifiers : modifiers = [ ] index = 0 while index < len ( string ) : c = string [ index ] index += 1 # check if one of CTRL, SHIFT, ALT has been pressed if c in MODIFIERS . keys ( ) : modif... | Return the parsed keys | 656 | 4 |
9,057 | def SendKeys ( keys , pause = 0.05 , with_spaces = False , with_tabs = False , with_newlines = False , turn_off_numlock = True ) : 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 | 82 | 7 |
9,058 | def main ( ) : actions = """ {LWIN} {PAUSE .25} r {PAUSE .25} Notepad.exe{ENTER} {PAUSE 1} Hello{SPACE}World! {PAUSE 1} %{F4} {PAUSE .25} n """ 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{ ... | Send some test strings | 329 | 4 |
9,059 | def GetInput ( self ) : actions = 1 # if both up and down 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 . dwFlags |= flags # if we a... | Build the INPUT structure for the action | 146 | 8 |
9,060 | def Run ( self ) : inputs = self . GetInput ( ) return SendInput ( len ( inputs ) , ctypes . byref ( inputs ) , ctypes . sizeof ( INPUT ) ) | Execute the action | 41 | 4 |
9,061 | 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 | 59 | 13 |
9,062 | def key_description ( self ) : vk , scan , flags = self . _get_key_info ( ) desc = '' if vk : if vk in CODE_NAMES : desc = CODE_NAMES [ vk ] else : desc = "VK %d" % vk else : desc = "%s" % self . key return desc | Return a description of the key | 76 | 6 |
9,063 | def _get_key_info ( self ) : # copied more or less verbatim from # http://www.pinvoke.net/default.aspx/user32.sendinput if ( ( self . key >= 33 and self . key <= 46 ) or ( self . key >= 91 and self . key <= 93 ) ) : flags = KEYEVENTF_EXTENDEDKEY else : flags = 0 # This works for %{F4} - ALT + F4 #return self.key, 0, 0 ... | Virtual keys have extended flag set | 149 | 6 |
9,064 | def _get_key_info ( self ) : vkey_scan = LoByte ( VkKeyScan ( self . key ) ) return ( vkey_scan , MapVirtualKey ( vkey_scan , 0 ) , 0 ) | EscapedKeyAction doesn t send it as Unicode and the vk and scan code are generated differently | 50 | 20 |
9,065 | def setup ( self ) : self . template = self . _generate_inline_policy ( ) if self . dry_run is not True : self . client = self . _get_client ( ) username = self . _get_username_for_key ( ) policy_document = self . _generate_inline_policy ( ) self . _attach_inline_policy ( username , policy_document ) pass | Method runs the plugin attaching policies to the user in question | 88 | 11 |
9,066 | def _get_policies ( self ) : username = self . _get_username_for_key ( ) policies = self . client . list_user_policies ( UserName = username ) return policies | Returns all the policy names for a given user | 46 | 9 |
9,067 | def _get_username_for_key ( self ) : response = self . client . get_access_key_last_used ( AccessKeyId = self . compromised_resource [ 'access_key_id' ] ) username = response [ 'UserName' ] return username | Find the user for a given access key | 59 | 8 |
9,068 | def _generate_inline_policy ( self ) : template_name = self . _locate_file ( 'deny-sts-before-time.json.j2' ) template_file = open ( template_name ) template_contents = template_file . read ( ) template_file . close ( ) jinja_template = Template ( template_contents ) policy_document = jinja_template . render ( before_d... | Renders a policy from a jinja template | 111 | 10 |
9,069 | def _attach_inline_policy ( self , username , policy_document ) : response = self . client . put_user_policy ( UserName = username , PolicyName = "threatresponse-temporal-key-revocation" , PolicyDocument = policy_document ) logger . info ( 'An inline policy has been attached for' ' {u} revoking sts tokens.' . format ( ... | Attaches the policy to the user | 89 | 7 |
9,070 | def _locate_file ( self , pattern , root = os . path . dirname ( 'revokests_key.py' ) ) : for path , dirs , files in os . walk ( os . path . abspath ( root ) ) : for filename in fnmatch . filter ( files , pattern ) : return os . path . join ( path , filename ) | Locate all files matching supplied filename pattern in and below | 79 | 11 |
9,071 | def generate_tsv_pep_protein_quants ( fns ) : for fn in fns : header = get_tsv_header ( fn ) for pquant in generate_split_tsv_lines ( fn , header ) : yield os . path . basename ( fn ) , header , pquant | Unlike generate_tsv_lines_multifile this generates tsv lines from multiple files that may have different headers . Yields fn header as well as quant data for each protein quant | 68 | 39 |
9,072 | def mzmlfn_kronikfeature_generator ( mzmlfns , kronikfns ) : for mzmlfn , kronikfn in zip ( mzmlfns , kronikfns ) : for quant_el in generate_kronik_feats ( kronikfn ) : yield os . path . basename ( mzmlfn ) , quant_el | Generates tuples of spectra filename and corresponding output features from kronik | 93 | 16 |
9,073 | def generate_split_tsv_lines ( fn , header ) : for line in generate_tsv_psms_line ( fn ) : yield { x : y for ( x , y ) in zip ( header , line . strip ( ) . split ( '\t' ) ) } | Returns dicts with header - keys and psm statistic values | 62 | 12 |
9,074 | def get_proteins_from_psm ( line ) : proteins = line [ mzidtsvdata . HEADER_PROTEIN ] . split ( ';' ) outproteins = [ ] for protein in proteins : prepost_protein = re . sub ( '\(pre=.*post=.*\)' , '' , protein ) . strip ( ) outproteins . append ( prepost_protein ) return outproteins | From a line return list of proteins reported by Mzid2TSV . When unrolled lines are given this returns the single protein from the line . | 98 | 31 |
9,075 | def aug_sysargv ( cmdstr ) : import shlex argv = shlex . split ( cmdstr ) sys . argv . extend ( argv ) | DEBUG FUNC modify argv to look like you ran a command | 35 | 13 |
9,076 | def get_module_verbosity_flags ( * labels ) : verbose_prefix_list = [ '--verbose-' , '--verb' , '--verb-' ] veryverbose_prefix_list = [ '--veryverbose-' , '--veryverb' , '--veryverb-' ] verbose_flags = tuple ( [ prefix + lbl for prefix , lbl in itertools . product ( verbose_prefix_list , labels ) ] ) veryverbose_flags ... | checks for standard flags for enableing module specific verbosity | 211 | 11 |
9,077 | def get_argflag ( argstr_ , default = False , help_ = '' , return_specified = None , need_prefix = True , return_was_specified = False , argv = None , debug = None , * * kwargs ) : if argv is None : argv = sys . argv assert isinstance ( default , bool ) , 'default must be boolean' argstr_list = meta_util_iter . ensure_... | Checks if the commandline has a flag or a corresponding noflag | 773 | 14 |
9,078 | def get_arg_dict ( argv = None , prefix_list = [ '--' ] , type_hints = { } ) : if argv is None : argv = sys . argv arg_dict = { } def startswith_prefix ( arg ) : return any ( [ arg . startswith ( prefix ) for prefix in prefix_list ] ) def argx_has_value ( argv , argx ) : # Check if has a value if argv [ argx ] . find (... | r Yet another way for parsing args | 399 | 7 |
9,079 | def argv_flag_dec ( * argin , * * kwargs ) : kwargs = kwargs . copy ( ) kwargs [ 'default' ] = kwargs . get ( 'default' , False ) from utool import util_decor @ util_decor . ignores_exc_tb ( outer_wrapper = False ) def wrap_argv_flag_dec ( func ) : return __argv_flag_dec ( func , * * kwargs ) assert len ( argin ) < 2 ,... | Decorators which control program flow based on sys . argv the decorated function does not execute without its corresponding flag | 181 | 23 |
9,080 | def __argv_flag_dec ( func , default = False , quiet = QUIET , indent = False ) : from utool import util_decor flagname = meta_util_six . get_funcname ( func ) if flagname . find ( 'no' ) == 0 : flagname = flagname [ 2 : ] flags = ( '--' + flagname . replace ( '_' , '-' ) , '--' + flagname , ) @ util_decor . ignores_ex... | Logic for controlling if a function gets called based on command line | 515 | 13 |
9,081 | def get_argv_tail ( scriptname , prefer_main = None , argv = None ) : if argv is None : argv = sys . argv import utool as ut modname = ut . get_argval ( '-m' , help_ = 'specify module name to profile' , argv = argv ) if modname is not None : # hack to account for -m scripts modpath = ut . get_modpath ( modname , prefer... | r gets the rest of the arguments after a script has been invoked hack . accounts for python - m scripts . | 208 | 22 |
9,082 | def get_cmdline_varargs ( argv = None ) : if argv is None : argv = sys . argv scriptname = argv [ 0 ] if scriptname == '' : # python invoked by iteself pos_start = 0 pos_end = 0 else : pos_start = pos_end = 1 for idx in range ( pos_start , len ( argv ) ) : if argv [ idx ] . startswith ( '-' ) : pos_end = idx break else... | Returns positional args specified directly after the scriptname and before any args starting with - on the commandline . | 144 | 21 |
9,083 | def argval ( key , default = None , type = None , smartcast = True , return_exists = False , argv = None ) : defaultable_types = ( tuple , list , int , float ) if type is None and isinstance ( default , defaultable_types ) : type = builtins . type ( default ) return get_argval ( key , type_ = type , default = default ,... | alias for get_argval | 111 | 6 |
9,084 | 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_conditiona... | Plot the distribution of a real - valued feature conditioned by the target . | 432 | 14 |
9,085 | 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 ( ) | Plot a scatterplot of two features against one another and calculate Pearson correlation coefficient . | 85 | 16 |
9,086 | 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 . ... | Plot a correlation heatmap between every feature pair . | 304 | 10 |
9,087 | 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 ( ) | Plot a scatterplot matrix for a list of features colored by target value . | 82 | 15 |
9,088 | def process_nested_tags ( self , node , tag = '' ) : ##print("---------Processing: %s, %s"%(node.tag,tag)) if tag == '' : t = node . ltag else : t = tag . lower ( ) for child in node . children : self . xml_node_stack = [ child ] + self . xml_node_stack ctagl = child . ltag if ctagl in self . tag_parse_table and ctagl ... | Process child tags . | 204 | 4 |
9,089 | def parse ( self , xmltext ) : xml = LEMSXMLNode ( xe . XML ( xmltext ) ) if xml . ltag != 'lems' and xml . ltag != 'neuroml' : raise ParseError ( '<Lems> expected as root element (or even <neuroml>), found: {0}' . format ( xml . ltag ) ) ''' if xml.ltag == 'lems': if 'description' in xml.lattrib: self.description = xm... | Parse a string containing LEMS XML text . | 134 | 10 |
9,090 | def raise_error ( self , message , * params , * * key_params ) : s = 'Parser error in ' self . xml_node_stack . reverse ( ) if len ( self . xml_node_stack ) > 1 : node = self . xml_node_stack [ 0 ] s += '<{0}' . format ( node . tag ) if 'name' in node . lattrib : s += ' name=\"{0}\"' . format ( node . lattrib [ 'name' ... | Raise a parse error . | 285 | 6 |
9,091 | def parse_component_by_typename ( self , node , type_ ) : #print('Parsing component {0} by typename {1}'.format(node, type_)) if 'id' in node . lattrib : id_ = node . lattrib [ 'id' ] else : #self.raise_error('Component must have an id') id_ = node . tag #make_id() if 'type' in node . lattrib : type_ = node . lattrib [... | Parses components defined directly by component name . | 261 | 10 |
9,092 | def generate_tags_multiple_files ( input_files , tag , ignore_tags , ns = None ) : return itertools . chain . from_iterable ( [ generate_xmltags ( fn , tag , ignore_tags , ns ) for fn in input_files ] ) | Calls xmltag generator for multiple files . | 62 | 11 |
9,093 | def generate_tags_multiple_files_strings ( input_files , ns , tag , ignore_tags ) : for el in generate_tags_multiple_files ( input_files , tag , ignore_tags , ns ) : yield formatting . string_and_clear ( el , ns ) | Creates stringified xml output of elements with certain tag . | 61 | 12 |
9,094 | def generate_xmltags ( fn , returntag , ignore_tags , ns = None ) : xmlns = create_namespace ( ns ) ns_ignore = [ '{0}{1}' . format ( xmlns , x ) for x in ignore_tags ] for ac , el in etree . iterparse ( fn ) : if el . tag == '{0}{1}' . format ( xmlns , returntag ) : yield el elif el . tag in ns_ignore : formatting . c... | Base generator for percolator xml psm peptide protein output as well as for mzML mzIdentML . ignore_tags are the ones that are cleared when met by parser . | 119 | 39 |
9,095 | def add_component_type ( self , component_type ) : name = component_type . name # To handle colons in names in LEMS if ':' in name : name = name . replace ( ':' , '_' ) component_type . name = name self . component_types [ name ] = component_type | Adds a component type to the model . | 69 | 8 |
9,096 | def add ( self , child ) : if isinstance ( child , Include ) : self . add_include ( child ) elif isinstance ( child , Dimension ) : self . add_dimension ( child ) elif isinstance ( child , Unit ) : self . add_unit ( child ) elif isinstance ( child , ComponentType ) : self . add_component_type ( child ) elif isinstance ... | Adds a typed child object to the model . | 153 | 9 |
9,097 | def include_file ( self , path , include_dirs = [ ] ) : if self . include_includes : if self . debug : print ( "------------------ Including a file: %s" % path ) inc_dirs = include_dirs if include_dirs else self . include_dirs parser = LEMSFileParser ( self , inc_dirs , self . include_includes ) if os . access ( path ,... | Includes a file into the current model . | 292 | 8 |
9,098 | def import_from_file ( self , filepath ) : inc_dirs = self . include_directories [ : ] inc_dirs . append ( dirname ( filepath ) ) parser = LEMSFileParser ( self , inc_dirs , self . include_includes ) with open ( filepath ) as f : parser . parse ( f . read ( ) ) | Import a model from a file . | 80 | 7 |
9,099 | def export_to_dom ( self ) : namespaces = 'xmlns="http://www.neuroml.org/lems/%s" ' + 'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' + 'xsi:schemaLocation="http://www.neuroml.org/lems/%s %s"' namespaces = namespaces % ( self . target_lems_version , self . target_lems_version , self . schema_location ) xmlstr ... | Exports this model to a DOM . | 285 | 8 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.