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,400 | def inject_colored_exceptions ( ) : #COLORED_INJECTS = '--nocolorex' not in sys.argv #COLORED_INJECTS = '--colorex' in sys.argv # Ignore colored exceptions on win32 if VERBOSE : print ( '[inject] injecting colored exceptions' ) if not sys . platform . startswith ( 'win32' ) : if VERYVERBOSE : print ( '[inject] injectin... | Causes exceptions to be colored if not already | 170 | 9 |
9,401 | def inject_print_functions ( module_name = None , module_prefix = '[???]' , DEBUG = False , module = None ) : module = _get_module ( module_name , module ) if SILENT : def print ( * args ) : """ silent builtins.print """ pass def printDBG ( * args ) : """ silent debug print """ pass def print_ ( * args ) : """ silent s... | makes print functions to be injected into the module | 656 | 9 |
9,402 | def make_module_reload_func ( module_name = None , module_prefix = '[???]' , module = None ) : module = _get_module ( module_name , module , register = False ) if module_name is None : module_name = str ( module . __name__ ) def rrr ( verbose = True ) : """ Dynamic module reloading """ if not __RELOAD_OK__ : raise Exce... | Injects dynamic module reloading | 202 | 7 |
9,403 | def noinject ( module_name = None , module_prefix = '[???]' , DEBUG = False , module = None , N = 0 , via = None ) : if PRINT_INJECT_ORDER : from utool . _internal import meta_util_dbg callername = meta_util_dbg . get_caller_name ( N = N + 1 , strict = False ) lineno = meta_util_dbg . get_caller_lineno ( N = N + 1 , st... | Use in modules that do not have inject in them | 327 | 10 |
9,404 | def inject ( module_name = None , module_prefix = '[???]' , DEBUG = False , module = None , N = 1 ) : #noinject(module_name, module_prefix, DEBUG, module, N=1) noinject ( module_name , module_prefix , DEBUG , module , N = N ) module = _get_module ( module_name , module ) rrr = make_module_reload_func ( None , module_pr... | Injects your module with utool magic | 178 | 9 |
9,405 | def inject2 ( module_name = None , module_prefix = None , DEBUG = False , module = None , N = 1 ) : if module_prefix is None : module_prefix = '[%s]' % ( module_name , ) noinject ( module_name , module_prefix , DEBUG , module , N = N ) module = _get_module ( module_name , module ) rrr = make_module_reload_func ( None ,... | wrapper that depricates print_ and printDBG | 143 | 11 |
9,406 | def inject_python_code2 ( fpath , patch_code , tag ) : import utool as ut text = ut . readfrom ( fpath ) start_tag = '# <%s>' % tag end_tag = '# </%s>' % tag new_text = ut . replace_between_tags ( text , patch_code , start_tag , end_tag ) ut . writeto ( fpath , new_text ) | Does autogeneration stuff | 97 | 6 |
9,407 | def inject_python_code ( fpath , patch_code , tag = None , inject_location = 'after_imports' ) : import utool as ut assert tag is not None , 'TAG MUST BE SPECIFIED IN INJECTED CODETEXT' text = ut . read_from ( fpath ) comment_start_tag = '# <util_inject:%s>' % tag comment_end_tag = '# </util_inject:%s>' % tag tagstart_... | DEPRICATE puts code into files on disk | 554 | 10 |
9,408 | def printableType ( val , name = None , parent = None ) : import numpy as np if parent is not None and hasattr ( parent , 'customPrintableType' ) : # Hack for non - trivial preference types _typestr = parent . customPrintableType ( name ) if _typestr is not None : return _typestr if isinstance ( val , np . ndarray ) : ... | Tries to make a nice type string for a value . Can also pass in a Printable parent object | 225 | 21 |
9,409 | def printableVal ( val , type_bit = True , justlength = False ) : from utool import util_dev # Move to util_dev # NUMPY ARRAY import numpy as np if type ( val ) is np . ndarray : info = npArrInfo ( val ) if info . dtypestr . startswith ( 'bool' ) : _valstr = '{ shape:' + info . shapestr + ' bittotal: ' + info . bittota... | Very old way of doing pretty printing . Need to update and refactor . DEPRICATE | 514 | 19 |
9,410 | def npArrInfo ( arr ) : from utool . DynamicStruct import DynStruct info = DynStruct ( ) info . shapestr = '[' + ' x ' . join ( [ str ( x ) for x in arr . shape ] ) + ']' info . dtypestr = str ( arr . dtype ) if info . dtypestr == 'bool' : info . bittotal = 'T=%d, F=%d' % ( sum ( arr ) , sum ( 1 - arr ) ) elif info . d... | OLD update and refactor | 208 | 5 |
9,411 | def get_isobaric_ratios ( psmfn , psmheader , channels , denom_channels , min_int , targetfn , accessioncol , normalize , normratiofn ) : psm_or_feat_ratios = get_psmratios ( psmfn , psmheader , channels , denom_channels , min_int , accessioncol ) if normalize and normratiofn : normheader = reader . get_tsv_header ( no... | Main function to calculate ratios for PSMs peptides proteins genes . Can do simple ratios median - of - ratios and median - centering normalization . | 484 | 30 |
9,412 | def sanitize ( value ) : value = unicodedata . normalize ( 'NFKD' , value ) value = value . strip ( ) value = re . sub ( '[^./\w\s-]' , '' , value ) value = re . sub ( '[-\s]+' , '-' , value ) return value | Strips all undesirable characters out of potential file paths . | 72 | 12 |
9,413 | def remove_on_exception ( dirname , remove = True ) : os . makedirs ( dirname ) try : yield except : if remove : shutil . rmtree ( dirname , ignore_errors = True ) raise | Creates a directory yields to the caller and removes that directory if an exception is thrown . | 50 | 18 |
9,414 | def add_percolator_to_mzidtsv ( mzidfn , tsvfn , multipsm , oldheader ) : namespace = readers . get_mzid_namespace ( mzidfn ) try : xmlns = '{%s}' % namespace [ 'xmlns' ] except TypeError : xmlns = '' specfnids = readers . get_mzid_specfile_ids ( mzidfn , namespace ) mzidpepmap = { } for peptide in readers . generate_m... | Takes a MSGF + tsv and corresponding mzId adds percolatordata to tsv lines . Generator yields the lines . Multiple PSMs per scan can be delivered in which case rank is also reported . | 477 | 45 |
9,415 | def parse_rawprofile_blocks ( text ) : # The total time reported in the raw output is from pystone not kernprof # The pystone total time is actually the average time spent in the function delim = 'Total time: ' delim2 = 'Pystone time: ' #delim = 'File: ' profile_block_list = ut . regex_split ( '^' + delim , text ) for ... | Split the file into blocks along delimters and and put delimeters back in the list | 133 | 17 |
9,416 | def parse_timemap_from_blocks ( profile_block_list ) : prefix_list = [ ] timemap = ut . ddict ( list ) for ix in range ( len ( profile_block_list ) ) : block = profile_block_list [ ix ] total_time = get_block_totaltime ( block ) # Blocks without time go at the front of sorted output if total_time is None : prefix_list ... | Build a map from times to line_profile blocks | 142 | 10 |
9,417 | def clean_line_profile_text ( text ) : # profile_block_list = parse_rawprofile_blocks ( text ) #profile_block_list = fix_rawprofile_blocks(profile_block_list) #--- # FIXME can be written much nicer prefix_list , timemap = parse_timemap_from_blocks ( profile_block_list ) # Sort the blocks by time sorted_lists = sorted (... | Sorts the output from line profile by execution time Removes entries which were not run | 196 | 17 |
9,418 | def clean_lprof_file ( input_fname , output_fname = None ) : # Read the raw .lprof text dump text = ut . read_from ( input_fname ) # Sort and clean the text output_text = clean_line_profile_text ( text ) return output_text | Reads a . lprof file and cleans it | 67 | 10 |
9,419 | 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 / count ) for cls , c... | Returns the weights for each class based on the frequencies of the samples . | 95 | 14 |
9,420 | 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" ) pl... | Plots the learning history for a Keras model assuming the validation data was provided to the fit function . | 117 | 21 |
9,421 | def iter_window ( iterable , size = 2 , step = 1 , wrap = False ) : # it.tee may be slow, but works on all iterables iter_list = it . tee ( iterable , size ) if wrap : # Secondary iterables need to be cycled for wraparound iter_list = [ iter_list [ 0 ] ] + list ( map ( it . cycle , iter_list [ 1 : ] ) ) # Step each ite... | r iterates through iterable with a window size generalizeation of itertwo | 201 | 17 |
9,422 | 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 | iter_compress - like numpy compress | 55 | 9 |
9,423 | def ichunks ( iterable , chunksize , bordermode = None ) : if bordermode is None : return ichunks_noborder ( iterable , chunksize ) elif bordermode == 'cycle' : return ichunks_cycle ( iterable , chunksize ) elif bordermode == 'replicate' : return ichunks_replicate ( iterable , chunksize ) else : raise ValueError ( 'unk... | r generates successive n - sized chunks from iterable . | 104 | 11 |
9,424 | def ichunks_list ( list_ , chunksize ) : return ( list_ [ ix : ix + chunksize ] for ix in range ( 0 , len ( list_ ) , chunksize ) ) | input must be a list . | 46 | 6 |
9,425 | def interleave ( args ) : arg_iters = list ( map ( iter , args ) ) cycle_iter = it . cycle ( arg_iters ) for iter_ in cycle_iter : yield six . next ( iter_ ) | r zip followed by flatten | 50 | 6 |
9,426 | 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 number of produ... | Yields num items from the cartesian product of items in a random order . | 243 | 17 |
9,427 | def random_combinations ( items , size , num = None , rng = None ) : import scipy . misc import numpy as np import utool as ut rng = ut . ensure_rng ( rng , impl = 'python' ) num_ = np . inf if num is None else num # Ensure we dont request more than is possible n_max = int ( scipy . misc . comb ( len ( items ) , size )... | Yields num combinations of length size from items in random order | 265 | 13 |
9,428 | def parse_dsn ( dsn_string ) : dsn = urlparse ( dsn_string ) scheme = dsn . scheme . split ( '+' ) [ 0 ] username = password = host = port = None host = dsn . netloc if '@' in host : username , host = host . split ( '@' ) if ':' in username : username , password = username . split ( ':' ) password = unquote ( password ... | Parse a connection string and return the associated driver | 434 | 10 |
9,429 | def db_for_write ( self , model , * * hints ) : try : if model . sf_access == READ_ONLY : raise WriteNotSupportedError ( "%r is a read-only model." % model ) except AttributeError : pass return None | Prevent write actions on read - only tables . | 57 | 10 |
9,430 | def run_hook ( self , hook , * args , * * kwargs ) : for plugin in self . raw_plugins : if hasattr ( plugin , hook ) : self . logger . debug ( 'Calling hook {0} in plugin {1}' . format ( hook , plugin . __name__ ) ) getattr ( plugin , hook ) ( * args , * * kwargs ) | Loop over all plugins and invoke function hook with args and kwargs in each of them . If the plugin does not have the function it is skipped . | 84 | 31 |
9,431 | def write_tsv ( headerfields , features , outfn ) : with open ( outfn , 'w' ) as fp : write_tsv_line_from_list ( headerfields , fp ) for line in features : write_tsv_line_from_list ( [ str ( line [ field ] ) for field in headerfields ] , fp ) | Writes header and generator of lines to tab separated file . | 80 | 12 |
9,432 | def write_tsv_line_from_list ( linelist , outfp ) : line = '\t' . join ( linelist ) outfp . write ( line ) outfp . write ( '\n' ) | Utility method to convert list to tsv line with carriage return | 48 | 13 |
9,433 | def replace_between_tags ( text , repl_ , start_tag , end_tag = None ) : new_lines = [ ] editing = False lines = text . split ( '\n' ) for line in lines : if not editing : new_lines . append ( line ) if line . strip ( ) . startswith ( start_tag ) : new_lines . append ( repl_ ) editing = True if end_tag is not None and ... | r Replaces text between sentinal lines in a block of text . | 141 | 14 |
9,434 | def theta_str ( theta , taustr = TAUSTR , fmtstr = '{coeff:,.1f}{taustr}' ) : coeff = theta / TAU theta_str = fmtstr . format ( coeff = coeff , taustr = taustr ) return theta_str | r Format theta so it is interpretable in base 10 | 73 | 12 |
9,435 | def bbox_str ( bbox , pad = 4 , sep = ', ' ) : if bbox is None : return 'None' fmtstr = sep . join ( [ '%' + six . text_type ( pad ) + 'd' ] * 4 ) return '(' + fmtstr % tuple ( bbox ) + ')' | r makes a string from an integer bounding box | 72 | 10 |
9,436 | def verts_str ( verts , pad = 1 ) : if verts is None : return 'None' fmtstr = ', ' . join ( [ '%' + six . text_type ( pad ) + 'd' + ', %' + six . text_type ( pad ) + 'd' ] * 1 ) return ', ' . join ( [ '(' + fmtstr % vert + ')' for vert in verts ] ) | r makes a string from a list of integer verticies | 94 | 12 |
9,437 | def remove_chars ( str_ , char_list ) : outstr = str_ [ : ] for char in char_list : outstr = outstr . replace ( char , '' ) return outstr | removes all chars in char_list from str_ | 44 | 11 |
9,438 | def get_minimum_indentation ( text ) : 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 ) | r returns the number of preceding spaces | 71 | 7 |
9,439 | def indentjoin ( strlist , indent = '\n ' , suffix = '' ) : indent_ = indent strlist = list ( strlist ) if len ( strlist ) == 0 : return '' return indent_ + indent_ . join ( [ six . text_type ( str_ ) + suffix for str_ in strlist ] ) | r Convineince indentjoin | 71 | 6 |
9,440 | def truncate_str ( str_ , maxlen = 110 , truncmsg = ' ~~~TRUNCATED~~~ ' ) : if NO_TRUNCATE : return str_ if maxlen is None or maxlen == - 1 or len ( str_ ) < maxlen : return str_ else : maxlen_ = maxlen - len ( truncmsg ) lowerb = int ( maxlen_ * .8 ) upperb = maxlen_ - lowerb tup = ( str_ [ : lowerb ] , truncmsg , str... | Removes the middle part of any string over maxlen characters . | 132 | 13 |
9,441 | def packstr ( instr , textwidth = 160 , breakchars = ' ' , break_words = True , newline_prefix = '' , indentation = '' , nlprefix = None , wordsep = ' ' , remove_newlines = True ) : if not isinstance ( instr , six . string_types ) : instr = repr ( instr ) if nlprefix is not None : newline_prefix = nlprefix str_ = pack_... | alias for pack_into . has more up to date kwargs | 147 | 14 |
9,442 | def byte_str ( nBytes , unit = 'bytes' , precision = 2 ) : #return (nBytes * ureg.byte).to(unit.upper()) if unit . lower ( ) . startswith ( 'b' ) : nUnit = nBytes elif unit . lower ( ) . startswith ( 'k' ) : nUnit = nBytes / ( 2.0 ** 10 ) elif unit . lower ( ) . startswith ( 'm' ) : nUnit = nBytes / ( 2.0 ** 20 ) elif ... | representing the number of bytes with the chosen unit | 222 | 10 |
9,443 | def func_str ( func , args = [ ] , kwargs = { } , type_aliases = [ ] , packed = False , packkw = None , truncate = False ) : import utool as ut # if truncate: # truncatekw = {'maxlen': 20} # else: truncatekw = { } argrepr_list = ( [ ] if args is None else ut . get_itemstr_list ( args , nl = False , truncate = truncate ... | string representation of function definition | 299 | 5 |
9,444 | def func_defsig ( func , with_name = True ) : import inspect argspec = inspect . getargspec ( func ) ( args , varargs , varkw , defaults ) = argspec defsig = inspect . formatargspec ( * argspec ) if with_name : defsig = get_callable_name ( func ) + defsig return defsig | String of function definition signature | 84 | 5 |
9,445 | 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 | String of function call signature | 85 | 5 |
9,446 | def numpy_str ( arr , strvals = False , precision = None , pr = None , force_dtype = False , with_dtype = None , suppress_small = None , max_line_width = None , threshold = None , * * kwargs ) : # strvals = kwargs.get('strvals', False) itemsep = kwargs . get ( 'itemsep' , ' ' ) # precision = kwargs.get('precision', Non... | suppress_small = False turns off scientific representation | 572 | 10 |
9,447 | def list_str_summarized ( list_ , list_name , maxlen = 5 ) : if len ( list_ ) > maxlen : return 'len(%s)=%d' % ( list_name , len ( list_ ) ) else : return '%s=%r' % ( list_name , list_ ) | prints the list members when the list is small and the length when it is large | 73 | 16 |
9,448 | def _rectify_countdown_or_bool ( count_or_bool ) : if count_or_bool is True or count_or_bool is False : count_or_bool_ = count_or_bool elif isinstance ( count_or_bool , int ) : if count_or_bool == 0 : return 0 sign_ = math . copysign ( 1 , count_or_bool ) count_or_bool_ = int ( count_or_bool - sign_ ) #if count_or_bool... | used by recrusive functions to specify which level to turn a bool on in counting down yeilds True True ... False conting up yeilds False False False ... True | 142 | 35 |
9,449 | def repr2 ( obj_ , * * kwargs ) : kwargs [ 'nl' ] = kwargs . pop ( 'nl' , kwargs . pop ( 'newlines' , False ) ) val_str = _make_valstr ( * * kwargs ) return val_str ( obj_ ) | Attempt to replace repr more configurable pretty version that works the same in both 2 and 3 | 71 | 18 |
9,450 | def repr2_json ( obj_ , * * kwargs ) : import utool as ut kwargs [ 'trailing_sep' ] = False json_str = ut . repr2 ( obj_ , * * kwargs ) json_str = str ( json_str . replace ( '\'' , '"' ) ) json_str = json_str . replace ( '(' , '[' ) json_str = json_str . replace ( ')' , ']' ) json_str = json_str . replace ( 'None' , 'n... | hack for json reprs | 127 | 5 |
9,451 | def list_str ( list_ , * * listkw ) : import utool as ut newlines = listkw . pop ( 'nl' , listkw . pop ( 'newlines' , 1 ) ) packed = listkw . pop ( 'packed' , False ) truncate = listkw . pop ( 'truncate' , False ) listkw [ 'nl' ] = _rectify_countdown_or_bool ( newlines ) listkw [ 'truncate' ] = _rectify_countdown_or_bo... | r Makes a pretty list string | 750 | 6 |
9,452 | def horiz_string ( * args , * * kwargs ) : import unicodedata precision = kwargs . get ( 'precision' , None ) sep = kwargs . get ( 'sep' , '' ) if len ( args ) == 1 and not isinstance ( args [ 0 ] , six . string_types ) : val_list = args [ 0 ] else : val_list = args val_list = [ unicodedata . normalize ( 'NFC' , ensure... | Horizontally concatenates strings reprs preserving indentation | 448 | 12 |
9,453 | def str_between ( str_ , startstr , endstr ) : if startstr is None : startpos = 0 else : startpos = str_ . find ( startstr ) + len ( startstr ) if endstr is None : endpos = None else : endpos = str_ . find ( endstr ) if endpos == - 1 : endpos = None newstr = str_ [ startpos : endpos ] return newstr | r gets substring between two sentianl strings | 93 | 10 |
9,454 | 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 : raise NotImplementedError ( ( 'cannot... | Works on must functionlike objects including str which has no func_name | 129 | 14 |
9,455 | def multi_replace ( str_ , search_list , repl_list ) : if isinstance ( repl_list , six . string_types ) : repl_list_ = [ repl_list ] * len ( search_list ) else : repl_list_ = repl_list newstr = str_ assert len ( search_list ) == len ( repl_list_ ) , 'bad lens' for search , repl in zip ( search_list , repl_list_ ) : new... | r Performs multiple replace functions foreach item in search_list and repl_list . | 116 | 18 |
9,456 | def pluralize ( wordtext , num = 2 , plural_suffix = 's' ) : if num == 1 : return wordtext else : if wordtext . endswith ( '\'s' ) : return wordtext [ : - 2 ] + 's\'' else : return wordtext + plural_suffix return ( wordtext + plural_suffix ) if num != 1 else wordtext | r Heuristically changes a word to its plural form if num is not 1 | 85 | 16 |
9,457 | def quantstr ( typestr , num , plural_suffix = 's' ) : return six . text_type ( num ) + ' ' + pluralize ( typestr , num , plural_suffix ) | r Heuristically generates an english phrase relating to the quantity of something . This is useful for writing user messages . | 47 | 23 |
9,458 | def msgblock ( key , text , side = '|' ) : blocked_text = '' . join ( [ ' + --- ' , key , ' ---\n' ] + [ ' ' + side + ' ' + line + '\n' for line in text . split ( '\n' ) ] + [ ' L ___ ' , key , ' ___\n' ] ) return blocked_text | puts text inside a visual ascii block | 86 | 10 |
9,459 | def get_textdiff ( text1 , text2 , num_context_lines = 0 , ignore_whitespace = False ) : import difflib text1 = ensure_unicode ( text1 ) text2 = ensure_unicode ( text2 ) text1_lines = text1 . splitlines ( ) text2_lines = text2 . splitlines ( ) if ignore_whitespace : text1_lines = [ t . rstrip ( ) for t in text1_lines ]... | r Uses difflib to return a difference string between two similar texts | 540 | 13 |
9,460 | def conj_phrase ( list_ , cond = 'or' ) : if len ( list_ ) == 0 : return '' elif len ( list_ ) == 1 : return list_ [ 0 ] elif len ( list_ ) == 2 : return ' ' . join ( ( list_ [ 0 ] , cond , list_ [ 1 ] ) ) else : condstr = '' . join ( ( ', ' + cond , ' ' ) ) return ', ' . join ( ( ', ' . join ( list_ [ : - 2 ] ) , cond... | Joins a list of words using English conjunction rules | 129 | 10 |
9,461 | def bubbletext ( text , font = 'cybermedium' ) : 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 | r Uses pyfiglet to create bubble text . | 87 | 10 |
9,462 | def is_url ( str_ ) : return any ( [ str_ . startswith ( 'http://' ) , str_ . startswith ( 'https://' ) , str_ . startswith ( 'www.' ) , '.org/' in str_ , '.com/' in str_ , ] ) | heuristic check if str is url formatted | 69 | 8 |
9,463 | def chr_range ( * args , * * kw ) : if len ( args ) == 1 : stop , = args start , step = 0 , 1 elif len ( args ) == 2 : start , stop = args step = 1 elif len ( args ) == 3 : start , stop , step = args else : raise ValueError ( 'incorrect args' ) chr_ = six . unichr base = ord ( kw . get ( 'base' , 'a' ) ) if isinstance ... | r Like range but returns characters | 213 | 6 |
9,464 | def highlight_regex ( str_ , pat , reflags = 0 , color = 'red' ) : #import colorama # from colorama import Fore, Style #color = Fore.MAGENTA # color = Fore.RED #match = re.search(pat, str_, flags=reflags) matches = list ( re . finditer ( pat , str_ , flags = reflags ) ) colored = str_ for match in reversed ( matches ) ... | FIXME Use pygments instead | 210 | 6 |
9,465 | def highlight_multi_regex ( str_ , pat_to_color , reflags = 0 ) : #import colorama # from colorama import Fore, Style #color = Fore.MAGENTA # color = Fore.RED #match = re.search(pat, str_, flags=reflags) colored = str_ to_replace = [ ] for pat , color in pat_to_color . items ( ) : matches = list ( re . finditer ( pat ,... | FIXME Use pygments instead . must be mututally exclusive | 204 | 13 |
9,466 | def find_block_end ( row , line_list , sentinal , direction = 1 ) : import re row_ = row line_ = line_list [ row_ ] flag1 = row_ == 0 or row_ == len ( line_list ) - 1 flag2 = re . match ( sentinal , line_ ) if not ( flag1 or flag2 ) : while True : if ( row_ == 0 or row_ == len ( line_list ) - 1 ) : break line_ = line_l... | Searches up and down until it finds the endpoints of a block Rectify with find_paragraph_end in pyvim_funcs | 133 | 29 |
9,467 | def compress_pdf ( pdf_fpath , output_fname = None ) : import utool as ut ut . assertpath ( pdf_fpath ) suffix = '_' + ut . get_datestamp ( False ) + '_compressed' print ( 'pdf_fpath = %r' % ( pdf_fpath , ) ) output_pdf_fpath = ut . augpath ( pdf_fpath , suffix , newfname = output_fname ) print ( 'output_pdf_fpath = %r... | uses ghostscript to write a pdf | 227 | 7 |
9,468 | def make_full_document ( text , title = None , preamp_decl = { } , preamb_extra = None ) : import utool as ut doc_preamb = ut . codeblock ( ''' %\\documentclass{article} \\documentclass[10pt,twocolumn,letterpaper]{article} % \\usepackage[utf8]{inputenc} \\usepackage[T1]{fontenc} \\usepackage{times} \\usepackage{epsfig}... | r dummy preamble and document to wrap around latex fragment | 433 | 12 |
9,469 | def render_latex_text ( input_text , nest_in_doc = False , preamb_extra = None , appname = 'utool' , verbose = None ) : import utool as ut if verbose is None : verbose = ut . VERBOSE dpath = ut . ensure_app_resource_dir ( appname , 'latex_tmp' ) # put a latex framgent in a full document # print(input_text) fname = 'tem... | compiles latex and shows the result | 172 | 7 |
9,470 | def render_latex ( input_text , dpath = None , fname = None , preamb_extra = None , verbose = 1 , * * kwargs ) : import utool as ut import vtool as vt # turn off page numbers input_text_ = '\pagenumbering{gobble}\n' + input_text # fname, _ = splitext(fname) img_fname = ut . ensure_ext ( fname , [ '.jpg' ] + list ( ut .... | Renders latex text into a jpeg . | 276 | 9 |
9,471 | def get_latex_figure_str2 ( fpath_list , cmdname , * * kwargs ) : import utool as ut from os . path import relpath # Make relative paths if kwargs . pop ( 'relpath' , True ) : start = ut . truepath ( '~/latex/crall-candidacy-2015' ) fpath_list = [ relpath ( fpath , start ) for fpath in fpath_list ] cmdname = ut . latex... | hack for candidacy | 197 | 3 |
9,472 | def add ( self , data , value = None , timestamp = None , namespace = None , debug = False ) : if value is not None : return self . add ( ( ( data , value ) , ) , timestamp = timestamp , namespace = namespace , debug = debug ) writer = self . writer if writer is None : raise GaugedUseAfterFreeError if timestamp is None... | Queue a gauge or gauges to be written | 737 | 9 |
9,473 | def flush ( self ) : writer = self . writer if writer is None : raise GaugedUseAfterFreeError self . flush_writer_position ( ) keys = self . translate_keys ( ) blocks = [ ] current_block = self . current_block statistics = self . statistics driver = self . driver flags = 0 # for future extensions, e.g. block compressio... | Flush all pending gauges | 271 | 6 |
9,474 | def resume_from ( self ) : position = self . driver . get_writer_position ( self . config . writer_name ) return position + self . config . resolution if position else 0 | Get a timestamp representing the position just after the last written gauge | 40 | 12 |
9,475 | def clear_from ( self , timestamp ) : block_size = self . config . block_size offset , remainder = timestamp // block_size , timestamp % block_size if remainder : raise ValueError ( 'Timestamp must be on a block boundary' ) self . driver . clear_from ( offset , timestamp ) | Clear all data from timestamp onwards . Note that the timestamp is rounded down to the nearest block boundary | 66 | 19 |
9,476 | def clear_key_before ( self , key , namespace = None , timestamp = None ) : block_size = self . config . block_size if namespace is None : namespace = self . config . namespace if timestamp is not None : offset , remainder = divmod ( timestamp , block_size ) if remainder : raise ValueError ( 'timestamp must be on a blo... | Clear all data before timestamp for a given key . Note that the timestamp is rounded down to the nearest block boundary | 135 | 22 |
9,477 | def _to_ctfile_counts_line ( self , key ) : counter = OrderedCounter ( self . counts_line_format ) self [ key ] [ 'number_of_atoms' ] = str ( len ( self . atoms ) ) self [ key ] [ 'number_of_bonds' ] = str ( len ( self . bonds ) ) counts_line = '' . join ( [ str ( value ) . rjust ( spacing ) for value , spacing in zip ... | Create counts line in CTfile format . | 135 | 8 |
9,478 | def _to_ctfile_atom_block ( self , key ) : counter = OrderedCounter ( Atom . atom_block_format ) ctab_atom_block = '\n' . join ( [ '' . join ( [ str ( value ) . rjust ( spacing ) for value , spacing in zip ( atom . _ctab_data . values ( ) , counter . values ( ) ) ] ) for atom in self [ key ] ] ) return '{}\n' . format ... | Create atom block in CTfile format . | 112 | 8 |
9,479 | def _to_ctfile_bond_block ( self , key ) : counter = OrderedCounter ( Bond . bond_block_format ) ctab_bond_block = '\n' . join ( [ '' . join ( [ str ( value ) . rjust ( spacing ) for value , spacing in zip ( bond . _ctab_data . values ( ) , counter . values ( ) ) ] ) for bond in self [ key ] ] ) return '{}\n' . format ... | Create bond block in CTfile format . | 115 | 8 |
9,480 | def _to_ctfile_property_block ( self ) : ctab_properties_data = defaultdict ( list ) for atom in self . atoms : for ctab_property_key , ctab_property_value in atom . _ctab_property_data . items ( ) : ctab_properties_data [ ctab_property_key ] . append ( OrderedDict ( zip ( self . ctab_conf [ self . version ] [ ctab_pro... | Create ctab properties block in CTfile format from atom - specific properties . | 294 | 15 |
9,481 | def delete_atom ( self , * atom_numbers ) : for atom_number in atom_numbers : deletion_atom = self . atom_by_number ( atom_number = atom_number ) # update atom numbers for atom in self . atoms : if int ( atom . atom_number ) > int ( atom_number ) : atom . atom_number = str ( int ( atom . atom_number ) - 1 ) # find inde... | Delete atoms by atom number . | 205 | 6 |
9,482 | def from_molfile ( cls , molfile , data = None ) : if not data : data = OrderedDict ( ) if not isinstance ( molfile , Molfile ) : raise ValueError ( 'Not a Molfile type: "{}"' . format ( type ( molfile ) ) ) if not isinstance ( data , dict ) : raise ValueError ( 'Not a dict type: "{}"' . format ( type ( data ) ) ) sdfi... | Construct new SDfile object from Molfile object . | 164 | 11 |
9,483 | def add_data ( self , id , key , value ) : self [ str ( id ) ] [ 'data' ] . setdefault ( key , [ ] ) self [ str ( id ) ] [ 'data' ] [ key ] . append ( value ) | Add new data item . | 55 | 5 |
9,484 | def add_molfile ( self , molfile , data ) : if not isinstance ( molfile , Molfile ) : raise ValueError ( 'Not a Molfile type: "{}"' . format ( type ( molfile ) ) ) if not isinstance ( data , dict ) : raise ValueError ( 'Not a dict type: "{}"' . format ( type ( data ) ) ) entry_ids = sorted ( self . keys ( ) , key = lam... | Add Molfile and data to SDfile object . | 210 | 11 |
9,485 | def add_sdfile ( self , sdfile ) : if not isinstance ( sdfile , SDfile ) : raise ValueError ( 'Not a SDfile type: "{}"' . format ( type ( sdfile ) ) ) for entry_id in sdfile : self . add_molfile ( molfile = sdfile [ entry_id ] [ 'molfile' ] , data = sdfile [ entry_id ] [ 'data' ] ) | Add new SDfile to current SDfile . | 105 | 9 |
9,486 | def neighbor_atoms ( self , atom_symbol = None ) : if not atom_symbol : return self . neighbors else : return [ atom for atom in self . neighbors if atom [ 'atom_symbol' ] == atom_symbol ] | Access neighbor atoms . | 54 | 4 |
9,487 | def update_atom_numbers ( self ) : self . _ctab_data [ 'first_atom_number' ] = self . first_atom . atom_number self . _ctab_data [ 'second_atom_number' ] = self . second_atom . atom_number | Update links first_atom_number - > second_atom_number | 63 | 14 |
9,488 | def default ( self , o ) : if isinstance ( o , Atom ) or isinstance ( o , Bond ) : return o . _ctab_data else : return o . __dict__ | Default encoder . | 41 | 4 |
9,489 | def get ( self , server ) : server_config = self . config . get ( server ) try : while server_config is None : new_config = self . _read_next_config ( ) server_config = new_config . get ( server ) new_config . update ( self . config ) self . config = new_config except StopIteration : return _default_server_configuratio... | Returns ServerConfig instance with configuration given server . | 147 | 9 |
9,490 | def free ( self ) : if self . _ptr is None : return Gauged . array_free ( self . ptr ) FloatArray . ALLOCATIONS -= 1 self . _ptr = None | Free the underlying C array | 40 | 5 |
9,491 | def generate_psms_quanted ( quantdb , tsvfn , isob_header , oldheader , isobaric = False , precursor = False ) : allquants , sqlfields = quantdb . select_all_psm_quants ( isobaric , precursor ) quant = next ( allquants ) for rownr , psm in enumerate ( readers . generate_tsv_psms ( tsvfn , oldheader ) ) : outpsm = { x :... | Takes dbfn and connects gets quants for each line in tsvfn sorts them in line by using keys in quantheader list . | 344 | 29 |
9,492 | def t_escaped_BACKSPACE_CHAR ( self , t ) : # 'b' t . lexer . pop_state ( ) t . value = unichr ( 0x0008 ) return t | r \ x62 | 46 | 4 |
9,493 | def t_escaped_FORM_FEED_CHAR ( self , t ) : # 'f' t . lexer . pop_state ( ) t . value = unichr ( 0x000c ) return t | r \ x66 | 47 | 4 |
9,494 | def t_escaped_CARRIAGE_RETURN_CHAR ( self , t ) : # 'r' t . lexer . pop_state ( ) t . value = unichr ( 0x000d ) return t | r \ x72 | 50 | 4 |
9,495 | def t_escaped_LINE_FEED_CHAR ( self , t ) : # 'n' t . lexer . pop_state ( ) t . value = unichr ( 0x000a ) return t | r \ x6E | 47 | 5 |
9,496 | def t_escaped_TAB_CHAR ( self , t ) : # 't' t . lexer . pop_state ( ) t . value = unichr ( 0x0009 ) return t | r \ x74 | 45 | 4 |
9,497 | def get_mzid_specfile_ids ( mzidfn , namespace ) : sid_fn = { } for specdata in mzid_specdata_generator ( mzidfn , namespace ) : sid_fn [ specdata . attrib [ 'id' ] ] = specdata . attrib [ 'name' ] return sid_fn | Returns mzid spectra data filenames and their IDs used in the mzIdentML file as a dict . Keys == IDs values == fns | 78 | 32 |
9,498 | def get_specidentitem_percolator_data ( item , xmlns ) : percomap = { '{0}userParam' . format ( xmlns ) : PERCO_HEADERMAP , } percodata = { } for child in item : try : percoscore = percomap [ child . tag ] [ child . attrib [ 'name' ] ] except KeyError : continue else : percodata [ percoscore ] = child . attrib [ 'value... | Loop through SpecIdentificationItem children . Find percolator data by matching to a dict lookup . Return a dict containing percolator data | 169 | 28 |
9,499 | def locate_path ( dname , recurse_down = True ) : tried_fpaths = [ ] root_dir = os . getcwd ( ) while root_dir is not None : dpath = join ( root_dir , dname ) if exists ( dpath ) : return dpath else : tried_fpaths . append ( dpath ) _new_root = dirname ( root_dir ) if _new_root == root_dir : root_dir = None break else ... | Search for a path | 176 | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.