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,300
def pop ( self ) : if self . stack : val = self . stack [ 0 ] self . stack = self . stack [ 1 : ] return val else : raise StackError ( 'Stack empty' )
Pops a value off the top of the stack .
43
11
9,301
def create_spectra_lookup ( lookup , fn_spectra ) : to_store = [ ] mzmlmap = lookup . get_mzmlfile_map ( ) for fn , spectrum in fn_spectra : spec_id = '{}_{}' . format ( mzmlmap [ fn ] , spectrum [ 'scan' ] ) mzml_rt = round ( float ( spectrum [ 'rt' ] ) , 12 ) mzml_iit = round ( float ( spectrum [ 'iit' ] ) , 12 ) mz ...
Stores all spectra rt injection time and scan nr in db
242
15
9,302
def assert_raises ( ex_type , func , * args , * * kwargs ) : try : func ( * args , * * kwargs ) except Exception as ex : assert isinstance ( ex , ex_type ) , ( 'Raised %r but type should have been %r' % ( ex , ex_type ) ) return True else : raise AssertionError ( 'No error was raised' )
r Checks that a function raises an error when given specific arguments .
91
13
9,303
def command_for_all_connections ( self , cb ) : for connection in self . __master . connections : cb ( connection . command )
Invoke the callback with a command - object for each connection .
33
13
9,304
def dump_autogen_code ( fpath , autogen_text , codetype = 'python' , fullprint = None , show_diff = None , dowrite = None ) : import utool as ut if dowrite is None : dowrite = ut . get_argflag ( ( '-w' , '--write' ) ) if show_diff is None : show_diff = ut . get_argflag ( '--diff' ) num_context_lines = ut . get_argval (...
Helper that write a file if - w is given on command line otherwise it just prints it out . It has the opption of comparing a diff to the file .
479
33
9,305
def autofix_codeblock ( codeblock , max_line_len = 80 , aggressive = False , very_aggressive = False , experimental = False ) : # FIXME idk how to remove the blank line following the function with # autopep8. It seems to not be supported by them, but it looks bad. import autopep8 arglist = [ '--max-line-length' , '80' ...
r Uses autopep8 to format a block of code
197
11
9,306
def auto_docstr ( modname , funcname , verbose = True , moddir = None , modpath = None , * * kwargs ) : #import utool as ut func , module , error_str = load_func_from_module ( modname , funcname , verbose = verbose , moddir = moddir , modpath = modpath ) if error_str is None : try : docstr = make_default_docstr ( func ...
r called from vim . Uses strings of filename and modnames to build docstr
262
16
9,307
def make_args_docstr ( argname_list , argtype_list , argdesc_list , ismethod , va_name = None , kw_name = None , kw_keys = [ ] ) : import utool as ut if ismethod : # Remove self from the list argname_list = argname_list [ 1 : ] argtype_list = argtype_list [ 1 : ] argdesc_list = argdesc_list [ 1 : ] argdoc_list = [ arg ...
r Builds the argument docstring
401
7
9,308
def remove_codeblock_syntax_sentinals ( code_text ) : flags = re . MULTILINE | re . DOTALL code_text_ = code_text code_text_ = re . sub ( r'^ *# *REM [^\n]*$\n?' , '' , code_text_ , flags = flags ) code_text_ = re . sub ( r'^ *# STARTBLOCK *$\n' , '' , code_text_ , flags = flags ) code_text_ = re . sub ( r'^ *# ENDBLOC...
r Removes template comments and vim sentinals
163
9
9,309
def sort_protein_group ( pgroup , sortfunctions , sortfunc_index ) : pgroup_out = [ ] subgroups = sortfunctions [ sortfunc_index ] ( pgroup ) sortfunc_index += 1 for subgroup in subgroups : if len ( subgroup ) > 1 and sortfunc_index < len ( sortfunctions ) : pgroup_out . extend ( sort_protein_group ( subgroup , sortfun...
Recursive function that sorts protein group by a number of sorting functions .
120
14
9,310
def sort_amounts ( proteins , sort_index ) : amounts = { } for protein in proteins : amount_x_for_protein = protein [ sort_index ] try : amounts [ amount_x_for_protein ] . append ( protein ) except KeyError : amounts [ amount_x_for_protein ] = [ protein ] return [ v for k , v in sorted ( amounts . items ( ) , reverse =...
Generic function for sorting peptides and psms . Assumes a higher number is better for what is passed at sort_index position in protein .
92
29
9,311
def free ( self ) : if self . _ptr is None : return Gauged . map_free ( self . ptr ) SparseMap . ALLOCATIONS -= 1 self . _ptr = None
Free the map
41
3
9,312
def append ( self , position , array ) : if not Gauged . map_append ( self . ptr , position , array . ptr ) : raise MemoryError
Append an array to the end of the map . The position must be greater than any positions in the map
33
22
9,313
def slice ( self , start = 0 , end = 0 ) : tmp = Gauged . map_new ( ) if tmp is None : raise MemoryError if not Gauged . map_concat ( tmp , self . ptr , start , end , 0 ) : Gauged . map_free ( tmp ) # pragma: no cover raise MemoryError return SparseMap ( tmp )
Slice the map from [ start end )
80
9
9,314
def concat ( self , operand , start = 0 , end = 0 , offset = 0 ) : if not Gauged . map_concat ( self . ptr , operand . ptr , start , end , offset ) : raise MemoryError
Concat a map . You can also optionally slice the operand map and apply an offset to each position before concatting
51
25
9,315
def buffer ( self , byte_offset = 0 ) : contents = self . ptr . contents ptr = addressof ( contents . buffer . contents ) + byte_offset length = contents . length * 4 - byte_offset return buffer ( ( c_char * length ) . from_address ( ptr ) . raw ) if length else None
Get a copy of the map buffer
70
7
9,316
def matches ( target , entry ) : # It must match all the non-empty entries. for t , e in itertools . zip_longest ( target , entry ) : if e and t != e : return False # ...and the provider and user can't be empty. return entry [ 0 ] and entry [ 1 ]
Does the target match the whitelist entry?
69
9
9,317
def check_entry ( * entry ) : whitelist = read_whitelist ( ) if not check_allow_prompt ( entry , whitelist ) : whitelist . append ( entry ) write_whitelist ( whitelist )
Throws an exception if the entry isn t on the whitelist .
50
14
9,318
def load_uncached ( location , use_json = None ) : if not whitelist . is_file ( location ) : r = requests . get ( raw . raw ( location ) ) if not r . ok : raise ValueError ( 'Couldn\'t read %s with code %s:\n%s' % ( location , r . status_code , r . text ) ) data = r . text else : try : f = os . path . realpath ( os . p...
Return data at either a file location or at the raw version of a URL or raise an exception .
232
20
9,319
def find_group_differences ( groups1 , groups2 ) : import utool as ut # For each group, build mapping from each item to the members the group item_to_others1 = { item : set ( _group ) - { item } for _group in groups1 for item in _group } item_to_others2 = { item : set ( _group ) - { item } for _group in groups2 for ite...
r Returns a measure of how disimilar two groupings are
279
12
9,320
def find_group_consistencies ( groups1 , groups2 ) : group1_list = { tuple ( sorted ( _group ) ) for _group in groups1 } group2_list = { tuple ( sorted ( _group ) ) for _group in groups2 } common_groups = list ( group1_list . intersection ( group2_list ) ) return common_groups
r Returns a measure of group consistency
81
7
9,321
def compare_groups ( true_groups , pred_groups ) : import utool as ut true = { frozenset ( _group ) for _group in true_groups } pred = { frozenset ( _group ) for _group in pred_groups } # Find the groups that are exactly the same common = true . intersection ( pred ) true_sets = true . difference ( common ) pred_sets =...
r Finds how predictions need to be modified to match the true grouping .
579
15
9,322
def grouping_delta_stats ( old , new ) : import pandas as pd import utool as ut group_delta = ut . grouping_delta ( old , new ) stats = ut . odict ( ) unchanged = group_delta [ 'unchanged' ] splits = group_delta [ 'splits' ] merges = group_delta [ 'merges' ] hybrid = group_delta [ 'hybrid' ] statsmap = ut . partial ( l...
Returns statistics about grouping changes
315
5
9,323
def upper_diag_self_prodx ( list_ ) : return [ ( item1 , item2 ) for n1 , item1 in enumerate ( list_ ) for n2 , item2 in enumerate ( list_ ) if n1 < n2 ]
upper diagnoal of cartesian product of self and self . Weird name . fixme
57
18
9,324
def colwise_diag_idxs ( size , num = 2 ) : # diag_idxs = list(diagonalized_iter(size)) # upper_diag_idxs = [(r, c) for r, c in diag_idxs if r < c] # # diag_idxs = list(diagonalized_iter(size)) import utool as ut diag_idxs = ut . iprod ( * [ range ( size ) for _ in range ( num ) ] ) #diag_idxs = list(ut.iprod(range(size...
r dont trust this implementation or this function name
285
9
9,325
def product_nonsame ( list1 , list2 ) : for item1 , item2 in itertools . product ( list1 , list2 ) : if item1 != item2 : yield ( item1 , item2 )
product of list1 and list2 where items are non equal
49
12
9,326
def greedy_max_inden_setcover ( candidate_sets_dict , items , max_covers = None ) : uncovered_set = set ( items ) rejected_keys = set ( ) accepted_keys = set ( ) covered_items_list = [ ] while True : # Break if we have enough covers if max_covers is not None and len ( covered_items_list ) >= max_covers : break maxkey =...
greedy algorithm for maximum independent set cover
327
8
9,327
def setcover_greedy ( candidate_sets_dict , items = None , set_weights = None , item_values = None , max_weight = None ) : import utool as ut solution_cover = { } # If candset_weights or item_values not given use the length as defaults if items is None : items = ut . flatten ( candidate_sets_dict . values ( ) ) if set_...
r Greedy algorithm for various covering problems . approximation gaurentees depending on specifications like set_weights and item values
440
24
9,328
def item_hist ( list_ ) : dict_hist = { } # Insert each item into the correct group for item in list_ : if item not in dict_hist : dict_hist [ item ] = 0 dict_hist [ item ] += 1 return dict_hist
counts the number of times each item appears in the dictionary
57
12
9,329
def get_nth_prime ( n , max_prime = 4100 , safe = True ) : if n <= 100 : first_100_primes = ( 2 , 3 , 5 , 7 , 11 , 13 , 17 , 19 , 23 , 29 , 31 , 37 , 41 , 43 , 47 , 53 , 59 , 61 , 67 , 71 , 73 , 79 , 83 , 89 , 97 , 101 , 103 , 107 , 109 , 113 , 127 , 131 , 137 , 139 , 149 , 151 , 157 , 163 , 167 , 173 , 179 , 181 , 191...
hacky but still brute force algorithm for finding nth prime for small tests
356
15
9,330
def knapsack ( items , maxweight , method = 'recursive' ) : if method == 'recursive' : return knapsack_recursive ( items , maxweight ) elif method == 'iterative' : return knapsack_iterative ( items , maxweight ) elif method == 'ilp' : return knapsack_ilp ( items , maxweight ) else : raise NotImplementedError ( '[util_a...
r Solve the knapsack problem by finding the most valuable subsequence of items subject that weighs no more than maxweight .
111
26
9,331
def knapsack_ilp ( items , maxweight , verbose = False ) : import pulp # Given Input values = [ t [ 0 ] for t in items ] weights = [ t [ 1 ] for t in items ] indices = [ t [ 2 ] for t in items ] # Formulate integer program prob = pulp . LpProblem ( "Knapsack" , pulp . LpMaximize ) # Solution variables x = pulp . LpVari...
solves knapsack using an integer linear program
386
10
9,332
def knapsack_iterative ( items , maxweight ) : # Knapsack requires integral weights weights = [ t [ 1 ] for t in items ] max_exp = max ( [ number_of_decimals ( w_ ) for w_ in weights ] ) coeff = 10 ** max_exp # Adjust weights to be integral int_maxweight = int ( maxweight * coeff ) int_items = [ ( v , int ( w * coeff )...
items = int_items maxweight = int_maxweight
133
12
9,333
def knapsack_iterative_int ( items , maxweight ) : values = [ t [ 0 ] for t in items ] weights = [ t [ 1 ] for t in items ] maxsize = maxweight + 1 # Sparse representation seems better dpmat = defaultdict ( lambda : defaultdict ( lambda : np . inf ) ) kmat = defaultdict ( lambda : defaultdict ( lambda : False ) ) idx_s...
r Iterative knapsack method
458
7
9,334
def knapsack_iterative_numpy ( items , maxweight ) : #import numpy as np items = np . array ( items ) weights = items . T [ 1 ] # Find maximum decimal place (this problem is in NP) max_exp = max ( [ number_of_decimals ( w_ ) for w_ in weights ] ) coeff = 10 ** max_exp # Adjust weights to be integral weights = ( weights...
Iterative knapsack method
497
6
9,335
def knapsack_greedy ( items , maxweight ) : items_subset = [ ] total_weight = 0 total_value = 0 for item in items : value , weight = item [ 0 : 2 ] if total_weight + weight > maxweight : continue else : items_subset . append ( item ) total_weight += weight total_value += value return total_value , items_subset
r non - optimal greedy version of knapsack algorithm does not sort input . Sort the input by largest value first if desired .
87
26
9,336
def choose ( n , k ) : import scipy . misc return scipy . misc . comb ( n , k , exact = True , repetition = False )
N choose k
35
3
9,337
def almost_eq ( arr1 , arr2 , thresh = 1E-11 , ret_error = False ) : error = np . abs ( arr1 - arr2 ) passed = error < thresh if ret_error : return passed , error return passed
checks if floating point number are equal to a threshold
55
10
9,338
def norm_zero_one ( array , dim = None ) : if not util_type . is_float ( array ) : array = array . astype ( np . float32 ) array_max = array . max ( dim ) array_min = array . min ( dim ) array_exnt = np . subtract ( array_max , array_min ) array_norm = np . divide ( np . subtract ( array , array_min ) , array_exnt ) re...
normalizes a numpy array from 0 to 1 based in its extent
104
14
9,339
def group_indices ( groupid_list ) : item_list = range ( len ( groupid_list ) ) grouped_dict = util_dict . group_items ( item_list , groupid_list ) # Sort by groupid for cache efficiency keys_ = list ( grouped_dict . keys ( ) ) try : keys = sorted ( keys_ ) except TypeError : # Python 3 does not allow sorting mixed typ...
groups indicies of each item in groupid_list
128
11
9,340
def ungroup_gen ( grouped_items , groupxs , fill = None ) : import utool as ut # Determine the number of items if unknown #maxpergroup = [max(xs) if len(xs) else 0 for xs in groupxs] #maxval = max(maxpergroup) if len(maxpergroup) else 0 minpergroup = [ min ( xs ) if len ( xs ) else 0 for xs in groupxs ] minval = min ( ...
Ungroups items returning a generator . Note that this is much slower than the list version and is not gaurenteed to have better memory usage .
522
31
9,341
def ungroup_unique ( unique_items , groupxs , maxval = None ) : if maxval is None : maxpergroup = [ max ( xs ) if len ( xs ) else 0 for xs in groupxs ] maxval = max ( maxpergroup ) if len ( maxpergroup ) else 0 ungrouped_items = [ None ] * ( maxval + 1 ) for item , xs in zip ( unique_items , groupxs ) : for x in xs : u...
Ungroups unique items to correspond to original non - unique list
122
13
9,342
def edit_distance ( string1 , string2 ) : import utool as ut try : import Levenshtein except ImportError as ex : ut . printex ( ex , 'pip install python-Levenshtein' ) raise #np.vectorize(Levenshtein.distance, [np.int]) #vec_lev = np.frompyfunc(Levenshtein.distance, 2, 1) #return vec_lev(string1, string2) import utool ...
Edit distance algorithm . String1 and string2 can be either strings or lists of strings
236
17
9,343
def standardize_boolexpr ( boolexpr_ , parens = False ) : import utool as ut import re onlyvars = boolexpr_ onlyvars = re . sub ( '\\bnot\\b' , '' , onlyvars ) onlyvars = re . sub ( '\\band\\b' , '' , onlyvars ) onlyvars = re . sub ( '\\bor\\b' , '' , onlyvars ) onlyvars = re . sub ( '\\(' , '' , onlyvars ) onlyvars = ...
r Standardizes a boolean expression into an or - ing of and - ed variables
753
16
9,344
def expensive_task_gen ( num = 8700 ) : import utool as ut #time_list = [] for x in range ( 0 , num ) : with ut . Timer ( verbose = False ) as t : ut . is_prime ( x ) yield t . ellapsed
r Runs a task that takes some time
61
8
9,345
def factors ( n ) : return set ( reduce ( list . __add__ , ( [ i , n // i ] for i in range ( 1 , int ( n ** 0.5 ) + 1 ) if n % i == 0 ) ) )
Computes all the integer factors of the number n
52
10
9,346
def add_protein_data ( proteins , pgdb , headerfields , genecentric = False , pool_to_output = False ) : proteindata = create_featuredata_map ( pgdb , genecentric = genecentric , psm_fill_fun = add_psms_to_proteindata , pgene_fill_fun = add_protgene_to_protdata , count_fun = count_peps_psms , pool_to_output = pool_to_o...
First creates a map with all master proteins with data then outputs protein data dicts for rows of a tsv . If a pool is given then only output for that pool will be shown in the protein table .
289
42
9,347
def get_protein_data_pgrouped ( proteindata , p_acc , headerfields ) : report = get_protein_data_base ( proteindata , p_acc , headerfields ) return get_cov_protnumbers ( proteindata , p_acc , report )
Parses protein data for a certain protein into tsv output dictionary
64
14
9,348
def keys ( self , namespace , prefix = None , limit = None , offset = None ) : params = [ namespace ] query = 'SELECT key FROM gauged_keys WHERE namespace = %s' if prefix is not None : query += ' AND key LIKE %s' params . append ( prefix + '%' ) if limit is not None : query += ' LIMIT %s' params . append ( limit ) if o...
Get keys from a namespace
129
5
9,349
def get_block ( self , namespace , offset , key ) : cursor = self . cursor cursor . execute ( 'SELECT data, flags FROM gauged_data ' 'WHERE namespace = %s AND "offset" = %s AND key = %s' , ( namespace , offset , key ) ) row = cursor . fetchone ( ) return ( None , None ) if row is None else row
Get the block identified by namespace offset key and value
82
10
9,350
def block_offset_bounds ( self , namespace ) : cursor = self . cursor cursor . execute ( 'SELECT MIN("offset"), MAX("offset") ' 'FROM gauged_statistics WHERE namespace = %s' , ( namespace , ) ) return cursor . fetchone ( )
Get the minimum and maximum block offset for the specified namespace
60
11
9,351
def set_writer_position ( self , name , timestamp ) : execute = self . cursor . execute execute ( 'DELETE FROM gauged_writer_history WHERE id = %s' , ( name , ) ) execute ( 'INSERT INTO gauged_writer_history (id, timestamp) ' 'VALUES (%s, %s)' , ( name , timestamp , ) )
Insert a timestamp to keep track of the current writer position
81
11
9,352
def add_cache ( self , namespace , key , query_hash , length , cache ) : start = 0 bulk_insert = self . bulk_insert cache_len = len ( cache ) row = '(%s,%s,%s,%s,%s,%s)' query = 'INSERT INTO gauged_cache ' '(namespace, key, "hash", length, start, value) VALUES ' execute = self . cursor . execute query_hash = self . psy...
Add cached values for the specified date range and query
203
10
9,353
def get_environment_vars ( filename ) : if sys . platform == "linux" or sys . platform == "linux2" : return { 'LD_PRELOAD' : path . join ( LIBFAKETIME_DIR , "libfaketime.so.1" ) , 'FAKETIME_SKIP_CMDS' : 'nodejs' , # node doesn't seem to work in the current version. 'FAKETIME_TIMESTAMP_FILE' : filename , } elif sys . pl...
Return a dict of environment variables required to run a service under faketime .
227
16
9,354
def change_time ( filename , newtime ) : with open ( filename , "w" ) as faketimetxt_handle : faketimetxt_handle . write ( "@" + newtime . strftime ( "%Y-%m-%d %H:%M:%S" ) )
Change the time of a process or group of processes by writing a new time to the time file .
67
20
9,355
def filter_unique_peptides ( peptides , score , ns ) : scores = { 'q' : 'q_value' , 'pep' : 'pep' , 'p' : 'p_value' , 'svm' : 'svm_score' } highest = { } for el in peptides : featscore = float ( el . xpath ( 'xmlns:%s' % scores [ score ] , namespaces = ns ) [ 0 ] . text ) seq = reader . get_peptide_seq ( el , ns ) if s...
Filters unique peptides from multiple Percolator output XML files . Takes a dir with a set of XMLs a score to filter on and a namespace . Outputs an ElementTree .
324
38
9,356
def import_symbol ( name = None , path = None , typename = None , base_path = None ) : _ , symbol = _import ( name or typename , path or base_path ) return symbol
Import a module or a typename within a module from its name .
46
14
9,357
def add_to_win32_PATH ( script_fpath , * add_path_list ) : import utool as ut write_dir = dirname ( script_fpath ) key = '[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment]' rtype = 'REG_EXPAND_SZ' # Read current PATH values win_pathlist = list ( os . environ [ 'PATH' ] . split ( os . pat...
r Writes a registery script to update the PATH variable into the sync registry
283
16
9,358
def dzip ( list1 , list2 ) : try : len ( list1 ) except TypeError : list1 = list ( list1 ) try : len ( list2 ) except TypeError : list2 = list ( list2 ) if len ( list1 ) == 0 and len ( list2 ) == 1 : # Corner case: # allow the first list to be empty and the second list to broadcast a # value. This means that the equali...
r Zips elementwise pairs between list1 and list2 into a dictionary . Values from list2 can be broadcast onto list1 .
218
27
9,359
def dict_stack ( dict_list , key_prefix = '' ) : dict_stacked_ = defaultdict ( list ) for dict_ in dict_list : for key , val in six . iteritems ( dict_ ) : dict_stacked_ [ key_prefix + key ] . append ( val ) dict_stacked = dict ( dict_stacked_ ) return dict_stacked
r stacks values from two dicts into a new dict where the values are list of the input values . the keys are the same .
84
27
9,360
def dict_stack2 ( dict_list , key_suffix = None , default = None ) : if len ( dict_list ) > 0 : dict_list_ = [ map_dict_vals ( lambda x : [ x ] , kw ) for kw in dict_list ] # Reduce does not handle default quite correctly default1 = [ ] default2 = [ default ] accum_ = dict_list_ [ 0 ] for dict_ in dict_list_ [ 1 : ] : ...
Stacks vals from a list of dicts into a dict of lists . Inserts Nones in place of empty items to preserve order .
220
29
9,361
def invert_dict ( dict_ , unique_vals = True ) : if unique_vals : inverted_items = [ ( val , key ) for key , val in six . iteritems ( dict_ ) ] inverted_dict = type ( dict_ ) ( inverted_items ) else : inverted_dict = group_items ( dict_ . keys ( ) , dict_ . values ( ) ) return inverted_dict
Reverses the keys and values in a dictionary . Set unique_vals to False if the values in the dict are not unique .
87
27
9,362
def iter_all_dict_combinations_ordered ( varied_dict ) : tups_list = [ [ ( key , val ) for val in val_list ] for ( key , val_list ) in six . iteritems ( varied_dict ) ] dict_iter = ( OrderedDict ( tups ) for tups in it . product ( * tups_list ) ) return dict_iter
Same as all_dict_combinations but preserves order
87
11
9,363
def all_dict_combinations_lbls ( varied_dict , remove_singles = True , allow_lone_singles = False ) : is_lone_single = all ( [ isinstance ( val_list , ( list , tuple ) ) and len ( val_list ) == 1 for key , val_list in iteritems_sorted ( varied_dict ) ] ) if not remove_singles or ( allow_lone_singles and is_lone_single ...
returns a label for each variation in a varydict .
364
12
9,364
def build_conflict_dict ( key_list , val_list ) : key_to_vals = defaultdict ( list ) for key , val in zip ( key_list , val_list ) : key_to_vals [ key ] . append ( val ) return key_to_vals
Builds dict where a list of values is associated with more than one key
63
15
9,365
def update_existing ( dict1 , dict2 , copy = False , assert_exists = False , iswarning = False , alias_dict = None ) : if assert_exists : try : assert_keys_are_subset ( dict1 , dict2 ) except AssertionError as ex : from utool import util_dbg util_dbg . printex ( ex , iswarning = iswarning , N = 1 ) if not iswarning : r...
r updates vals in dict1 using vals from dict2 only if the key is already in dict1 .
165
23
9,366
def dict_update_newkeys ( dict_ , dict2 ) : for key , val in six . iteritems ( dict2 ) : if key not in dict_ : dict_ [ key ] = val
Like dict . update but does not overwrite items
43
9
9,367
def is_dicteq ( dict1_ , dict2_ , almosteq_ok = True , verbose_err = True ) : import utool as ut assert len ( dict1_ ) == len ( dict2_ ) , 'dicts are not of same length' try : for ( key1 , val1 ) , ( key2 , val2 ) in zip ( dict1_ . items ( ) , dict2_ . items ( ) ) : assert key1 == key2 , 'key mismatch' assert type ( va...
Checks to see if dicts are the same . Performs recursion . Handles numpy
316
20
9,368
def dict_setdiff ( dict_ , negative_keys ) : keys = [ key for key in six . iterkeys ( dict_ ) if key not in set ( negative_keys ) ] subdict_ = dict_subset ( dict_ , keys ) return subdict_
r returns a copy of dict_ without keys in the negative_keys list
58
15
9,369
def delete_dict_keys ( dict_ , key_list ) : invalid_keys = set ( key_list ) - set ( dict_ . keys ( ) ) valid_keys = set ( key_list ) - invalid_keys for key in valid_keys : del dict_ [ key ] return dict_
r Removes items from a dictionary inplace . Keys that do not exist are ignored .
65
18
9,370
def dict_take_gen ( dict_ , keys , * d ) : if isinstance ( keys , six . string_types ) : # hack for string keys that makes copy-past easier keys = keys . split ( ', ' ) if len ( d ) == 0 : # no default given throws key error dictget = dict_ . __getitem__ elif len ( d ) == 1 : # default given does not throw key erro dic...
r generate multiple values from a dictionary
173
7
9,371
def dict_take ( dict_ , keys , * d ) : try : return list ( dict_take_gen ( dict_ , keys , * d ) ) except TypeError : return list ( dict_take_gen ( dict_ , keys , * d ) ) [ 0 ]
get multiple values from a dictionary
59
6
9,372
def dict_take_pop ( dict_ , keys , * d ) : if len ( d ) == 0 : return [ dict_ . pop ( key ) for key in keys ] elif len ( d ) == 1 : default = d [ 0 ] return [ dict_ . pop ( key , default ) for key in keys ] else : raise ValueError ( 'len(d) must be 1 or 0' )
like dict_take but pops values off
87
8
9,373
def dict_assign ( dict_ , keys , vals ) : for key , val in zip ( keys , vals ) : dict_ [ key ] = val
simple method for assigning or setting values with a similar interface to dict_take
35
15
9,374
def dict_where_len0 ( dict_ ) : keys = np . array ( dict_ . keys ( ) ) flags = np . array ( list ( map ( len , dict_ . values ( ) ) ) ) == 0 indices = np . where ( flags ) [ 0 ] return keys [ indices ]
Accepts a dict of lists . Returns keys that have vals with no length
64
16
9,375
def dict_hist ( item_list , weight_list = None , ordered = False , labels = None ) : if labels is None : # hist_ = defaultdict(lambda: 0) hist_ = defaultdict ( int ) else : hist_ = { k : 0 for k in labels } if weight_list is None : # weight_list = it.repeat(1) for item in item_list : hist_ [ item ] += 1 else : for item...
r Builds a histogram of items in item_list
220
12
9,376
def dict_isect_combine ( dict1 , dict2 , combine_op = op . add ) : keys3 = set ( dict1 . keys ( ) ) . intersection ( set ( dict2 . keys ( ) ) ) dict3 = { key : combine_op ( dict1 [ key ] , dict2 [ key ] ) for key in keys3 } return dict3
Intersection of dict keys and combination of dict values
80
10
9,377
def dict_union_combine ( dict1 , dict2 , combine_op = op . add , default = util_const . NoParam , default2 = util_const . NoParam ) : keys3 = set ( dict1 . keys ( ) ) . union ( set ( dict2 . keys ( ) ) ) if default is util_const . NoParam : dict3 = { key : combine_op ( dict1 [ key ] , dict2 [ key ] ) for key in keys3 }...
Combine of dict keys and uses dfault value when key does not exist
162
15
9,378
def dict_filter_nones ( dict_ ) : dict2_ = { key : val for key , val in six . iteritems ( dict_ ) if val is not None } return dict2_
r Removes None values
43
5
9,379
def groupby_tags ( item_list , tags_list ) : groupid_to_items = defaultdict ( list ) for tags , item in zip ( tags_list , item_list ) : for tag in tags : groupid_to_items [ tag ] . append ( item ) return groupid_to_items
r case where an item can belong to multiple groups
69
10
9,380
def group_pairs ( pair_list ) : # Initialize dict of lists groupid_to_items = defaultdict ( list ) # Insert each item into the correct group for item , groupid in pair_list : groupid_to_items [ groupid ] . append ( item ) return groupid_to_items
Groups a list of items using the first element in each pair as the item and the second element as the groupid .
69
25
9,381
def group_items ( items , by = None , sorted_ = True ) : if by is not None : pairs = list ( zip ( by , items ) ) if sorted_ : # Sort by groupid for cache efficiency (does this even do anything?) # I forgot why this is needed? Determenism? try : pairs = sorted ( pairs , key = op . itemgetter ( 0 ) ) except TypeError : #...
Groups a list of items by group id .
180
10
9,382
def hierarchical_group_items ( item_list , groupids_list ) : # Construct a defaultdict type with the appropriate number of levels num_groups = len ( groupids_list ) leaf_type = partial ( defaultdict , list ) if num_groups > 1 : node_type = leaf_type for _ in range ( len ( groupids_list ) - 2 ) : node_type = partial ( d...
Generalization of group_item . Convert a flast list of ids into a heirarchical dictionary .
209
22
9,383
def hierarchical_map_vals ( func , node , max_depth = None , depth = 0 ) : #if not isinstance(node, dict): if not hasattr ( node , 'items' ) : return func ( node ) elif max_depth is not None and depth >= max_depth : #return func(node) return map_dict_vals ( func , node ) #return {key: func(val) for key, val in six.iter...
node is a dict tree like structure with leaves of type list
253
12
9,384
def sort_dict ( dict_ , part = 'keys' , key = None , reverse = False ) : if part == 'keys' : index = 0 elif part in { 'vals' , 'values' } : index = 1 else : raise ValueError ( 'Unknown method part=%r' % ( part , ) ) if key is None : _key = op . itemgetter ( index ) else : def _key ( item ) : return key ( item [ index ]...
sorts a dictionary by its values or its keys
144
10
9,385
def order_dict_by ( dict_ , key_order ) : dict_keys = set ( dict_ . keys ( ) ) other_keys = dict_keys - set ( key_order ) key_order = it . chain ( key_order , other_keys ) sorted_dict = OrderedDict ( ( key , dict_ [ key ] ) for key in key_order if key in dict_keys ) return sorted_dict
r Reorders items in a dictionary according to a custom key order
93
13
9,386
def iteritems_sorted ( dict_ ) : if isinstance ( dict_ , OrderedDict ) : return six . iteritems ( dict_ ) else : return iter ( sorted ( six . iteritems ( dict_ ) ) )
change to iteritems ordered
50
5
9,387
def flatten_dict_vals ( dict_ ) : if isinstance ( dict_ , dict ) : return dict ( [ ( ( key , augkey ) , augval ) for key , val in dict_ . items ( ) for augkey , augval in flatten_dict_vals ( val ) . items ( ) ] ) else : return { None : dict_ }
Flattens only values in a heirarchical dictionary keys are nested .
79
15
9,388
def depth_atleast ( list_ , depth ) : if depth == 0 : return True else : try : return all ( [ depth_atleast ( item , depth - 1 ) for item in list_ ] ) except TypeError : return False
r Returns if depth of list is at least depth
53
10
9,389
def get_splitcolnr ( header , bioset , splitcol ) : if bioset : return header . index ( mzidtsvdata . HEADER_SETNAME ) elif splitcol is not None : return splitcol - 1 else : raise RuntimeError ( 'Must specify either --bioset or --splitcol' )
Returns column nr on which to split PSM table . Chooses from flags given via bioset and splitcol
71
23
9,390
def generate_psms_split ( fn , oldheader , bioset , splitcol ) : try : splitcolnr = get_splitcolnr ( oldheader , bioset , splitcol ) except IndexError : raise RuntimeError ( 'Cannot find bioset header column in ' 'input file {}, though --bioset has ' 'been passed' . format ( fn ) ) for psm in tsvreader . generate_tsv_p...
Loops PSMs and outputs dictionaries passed to writer . Dictionaries contain the PSMs and info to which split pool the respective PSM belongs
131
30
9,391
def rnumlistwithoutreplacement ( min , max ) : if checkquota ( ) < 1 : raise Exception ( "Your www.random.org quota has already run out." ) requestparam = build_request_parameterNR ( min , max ) request = urllib . request . Request ( requestparam ) request . add_header ( 'User-Agent' , 'randomwrapy/0.1 very alpha' ) op...
Returns a randomly ordered list of the integers between min and max
125
12
9,392
def rnumlistwithreplacement ( howmany , max , min = 0 ) : if checkquota ( ) < 1 : raise Exception ( "Your www.random.org quota has already run out." ) requestparam = build_request_parameterWR ( howmany , min , max ) request = urllib . request . Request ( requestparam ) request . add_header ( 'User-Agent' , 'randomwrapy...
Returns a list of howmany integers with a maximum value = max . The minimum value defaults to zero .
133
21
9,393
def num_fmt ( num , max_digits = None ) : if num is None : return 'None' def num_in_mag ( num , mag ) : return mag > num and num > ( - 1 * mag ) if max_digits is None : # TODO: generalize if num_in_mag ( num , 1 ) : if num_in_mag ( num , .1 ) : max_digits = 4 else : max_digits = 3 else : max_digits = 1 if util_type . i...
r Weird function . Not very well written . Very special case - y
258
14
9,394
def load_feature_lists ( self , feature_lists ) : column_names = [ ] feature_ranges = [ ] running_feature_count = 0 for list_id in feature_lists : feature_list_names = load_lines ( self . features_dir + 'X_train_{}.names' . format ( list_id ) ) column_names . extend ( feature_list_names ) start_index = running_feature_...
Load pickled features for train and test sets assuming they are saved in the features folder along with their column names .
294
23
9,395
def save_features ( self , train_features , test_features , feature_names , feature_list_id ) : self . save_feature_names ( feature_names , feature_list_id ) self . save_feature_list ( train_features , 'train' , feature_list_id ) self . save_feature_list ( test_features , 'test' , feature_list_id )
Save features for the training and test sets to disk along with their metadata .
88
15
9,396
def discover ( ) : # Try ../data: we're most likely running a Jupyter notebook from the 'notebooks' directory candidate_path = os . path . abspath ( os . path . join ( os . curdir , os . pardir , 'data' ) ) if os . path . exists ( candidate_path ) : return Project ( os . path . abspath ( os . path . join ( candidate_pa...
Automatically discover the paths to various data folders in this project and compose a Project instance .
272
18
9,397
def init ( ) : project = Project ( os . path . abspath ( os . getcwd ( ) ) ) paths_to_create = [ project . data_dir , project . notebooks_dir , project . aux_dir , project . features_dir , project . preprocessed_data_dir , project . submissions_dir , project . trained_model_dir , project . temp_dir , ] for path in path...
Creates the project infrastructure assuming the current directory is the project root . Typically used as a command - line entry point called by pygoose init .
110
30
9,398
def unique_justseen ( iterable , key = None ) : # unique_justseen('AAAABBBCCDAABBB') --> A B C D A B # unique_justseen('ABBCcAD', str.lower) --> A B C A D return imap ( next , imap ( operator . itemgetter ( 1 ) , groupby ( iterable , key ) ) )
List unique elements preserving order . Remember only the element just seen .
84
13
9,399
def _get_module ( module_name = None , module = None , register = True ) : if module is None and module_name is not None : try : module = sys . modules [ module_name ] except KeyError as ex : print ( ex ) raise KeyError ( ( 'module_name=%r must be loaded before ' + 'receiving injections' ) % module_name ) elif module i...
finds module in sys . modules based on module name unless the module has already been found and is passed in
134
22