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 = float ( spectrum [ 'mz' ] ) to_store . append ( ( spec_id , mzmlmap [ fn ] , spectrum [ 'scan' ] , spectrum [ 'charge' ] , mz , mzml_rt , mzml_iit ) ) if len ( to_store ) == DB_STORE_CHUNK : lookup . store_mzmls ( to_store ) to_store = [ ] lookup . store_mzmls ( to_store ) lookup . index_mzml ( ) | 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 ( '--diff' , type_ = int , default = None ) show_diff = show_diff or num_context_lines is not None num_context_lines = ut . get_argval ( '--diff' , type_ = int , default = None ) if fullprint is None : fullprint = True if fullprint is False : fullprint = ut . get_argflag ( '--print' ) print ( '[autogen] Autogenerated %s...\n+---\n' % ( fpath , ) ) if not dowrite : if fullprint : ut . print_code ( autogen_text , lexer_name = codetype ) print ( '\nL___' ) else : print ( 'specify --print to write to stdout' ) pass print ( 'specify -w to write, or --diff to compare' ) print ( '...would write to: %s' % fpath ) if show_diff : if ut . checkpath ( fpath , verbose = True ) : prev_text = ut . read_from ( fpath ) textdiff = ut . get_textdiff ( prev_text , autogen_text , num_context_lines = num_context_lines ) try : ut . print_difftext ( textdiff ) except UnicodeDecodeError : import unicodedata textdiff = unicodedata . normalize ( 'NFKD' , textdiff ) . encode ( 'ascii' , 'ignore' ) ut . print_difftext ( textdiff ) if dowrite : print ( 'WARNING: Not writing. Remove --diff from command line' ) elif dowrite : ut . write_to ( fpath , autogen_text ) | 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' ] if aggressive : arglist . extend ( [ '-a' ] ) if very_aggressive : arglist . extend ( [ '-a' , '-a' ] ) if experimental : arglist . extend ( [ '--experimental' ] ) arglist . extend ( [ '' ] ) autopep8_options = autopep8 . parse_args ( arglist ) fixed_codeblock = autopep8 . fix_code ( codeblock , options = autopep8_options ) return fixed_codeblock | 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 , * * kwargs ) except Exception as ex : import utool as ut error_str = ut . formatex ( ex , 'Caught Error in parsing docstr' , tb = True ) #ut.printex(ex) error_str += ( '\n\nReplicateCommand:\n ' 'python -m utool --tf auto_docstr ' '--modname={modname} --funcname={funcname} --moddir={moddir}' ) . format ( modname = modname , funcname = funcname , moddir = moddir ) error_str += '\n kwargs=' + ut . repr4 ( kwargs ) return error_str else : docstr = error_str return docstr | 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 + ' (%s): %s' % ( _type , desc ) for arg , _type , desc in zip ( argname_list , argtype_list , argdesc_list ) ] # Add in varargs and kwargs # References: # http://www.sphinx-doc.org/en/stable/ext/example_google.html#example-google if va_name is not None : argdoc_list . append ( '*' + va_name + ':' ) if kw_name is not None : import textwrap prefix = '**' + kw_name + ': ' wrapped_lines = textwrap . wrap ( ', ' . join ( kw_keys ) , width = 70 - len ( prefix ) ) sep = '\n' + ( ' ' * len ( prefix ) ) kw_keystr = sep . join ( wrapped_lines ) argdoc_list . append ( ( prefix + kw_keystr ) . strip ( ) ) # align? align_args = False if align_args : argdoc_aligned_list = ut . align_lines ( argdoc_list , character = '(' ) arg_docstr = '\n' . join ( argdoc_aligned_list ) else : arg_docstr = '\n' . join ( argdoc_list ) return arg_docstr | 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'^ *# ENDBLOCK *$\n?' , '' , code_text_ , flags = flags ) code_text_ = code_text_ . rstrip ( ) return code_text_ | 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 , sortfunctions , sortfunc_index ) ) else : pgroup_out . extend ( subgroup ) return pgroup_out | 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 = True ) ] | 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 . path . abspath ( os . path . expanduser ( location ) ) ) data = open ( f ) . read ( ) except Exception as e : e . args = ( 'There was an error reading the file' , location , f ) + e . args raise if use_json is None : use_json = any ( location . endswith ( s ) for s in SUFFIXES ) if not use_json : return data try : return yaml . load ( data ) except Exception as e : e . args = ( 'There was a JSON error in the file' , location ) + e . args raise | 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 item in _group } flat_items1 = ut . flatten ( groups1 ) flat_items2 = ut . flatten ( groups2 ) flat_items = list ( set ( flat_items1 + flat_items2 ) ) errors = [ ] item_to_error = { } for item in flat_items : # Determine the number of unshared members in each group others1 = item_to_others1 . get ( item , set ( [ ] ) ) others2 = item_to_others2 . get ( item , set ( [ ] ) ) missing1 = others1 - others2 missing2 = others2 - others1 error = len ( missing1 ) + len ( missing2 ) if error > 0 : item_to_error [ item ] = error errors . append ( error ) total_error = sum ( errors ) return total_error | 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 = pred . difference ( common ) # connected compoment lookups pred_conn = { p : frozenset ( ps ) for ps in pred for p in ps } true_conn = { t : frozenset ( ts ) for ts in true for t in ts } # How many predictions can be merged into perfect pieces? # For each true sets, find if it can be made via merging pred sets pred_merges = [ ] true_merges = [ ] for ts in true_sets : ccs = set ( [ pred_conn . get ( t , frozenset ( ) ) for t in ts ] ) if frozenset . union ( * ccs ) == ts : # This is a pure merge pred_merges . append ( ccs ) true_merges . append ( ts ) # How many predictions can be split into perfect pieces? true_splits = [ ] pred_splits = [ ] for ps in pred_sets : ccs = set ( [ true_conn . get ( p , frozenset ( ) ) for p in ps ] ) if frozenset . union ( * ccs ) == ps : # This is a pure merge true_splits . append ( ccs ) pred_splits . append ( ps ) pred_merges_flat = ut . flatten ( pred_merges ) true_splits_flat = ut . flatten ( true_splits ) pred_hybrid = frozenset ( map ( frozenset , pred_sets ) ) . difference ( set ( pred_splits + pred_merges_flat ) ) true_hybrid = frozenset ( map ( frozenset , true_sets ) ) . difference ( set ( true_merges + true_splits_flat ) ) comparisons = { 'common' : common , # 'true_splits_flat': true_splits_flat, 'true_splits' : true_splits , 'true_merges' : true_merges , 'true_hybrid' : true_hybrid , 'pred_splits' : pred_splits , 'pred_merges' : pred_merges , # 'pred_merges_flat': pred_merges_flat, 'pred_hybrid' : pred_hybrid , } return comparisons | 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 ( lambda x : ut . stats_dict ( map ( len , x ) , size = True ) ) stats [ 'unchanged' ] = statsmap ( unchanged ) stats [ 'old_split' ] = statsmap ( splits [ 'old' ] ) stats [ 'new_split' ] = statsmap ( ut . flatten ( splits [ 'new' ] ) ) stats [ 'old_merge' ] = statsmap ( ut . flatten ( merges [ 'old' ] ) ) stats [ 'new_merge' ] = statsmap ( merges [ 'new' ] ) stats [ 'old_hybrid' ] = statsmap ( hybrid [ 'old' ] ) stats [ 'new_hybrid' ] = statsmap ( hybrid [ 'new' ] ) df = pd . DataFrame . from_dict ( stats , orient = 'index' ) df = df . loc [ list ( stats . keys ( ) ) ] return df | 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), range(size))) # this is pretty much a simple c ordering upper_diag_idxs = [ tup [ : : - 1 ] for tup in diag_idxs if all ( [ a > b for a , b in ut . itertwo ( tup ) ] ) #if all([a > b for a, b in ut.itertwo(tup[:2])]) ] #upper_diag_idxs = [(c, r) for r, c in diag_idxs if r > c] # # upper_diag_idxs = [(r, c) for r, c in diag_idxs if r > c] return upper_diag_idxs | 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 = None maxlen = - 1 # Loop over candidates to find the biggested unadded cover set for key , candidate_items in six . iteritems ( candidate_sets_dict ) : if key in rejected_keys or key in accepted_keys : continue #print('Checking %r' % (key,)) lenval = len ( candidate_items ) # len(uncovered_set.intersection(candidate_items)) == lenval: if uncovered_set . issuperset ( candidate_items ) : if lenval > maxlen : maxkey = key maxlen = lenval else : rejected_keys . add ( key ) # Add the set to the cover if maxkey is None : break maxval = candidate_sets_dict [ maxkey ] accepted_keys . add ( maxkey ) covered_items_list . append ( list ( maxval ) ) # Add values in this key to the cover uncovered_set . difference_update ( maxval ) uncovered_items = list ( uncovered_set ) covertup = uncovered_items , covered_items_list , accepted_keys return covertup | 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_weights is None : get_weight = len else : def get_weight ( solution_cover ) : sum ( [ set_weights [ key ] for key in solution_cover . keys ( ) ] ) if item_values is None : get_value = len else : def get_value ( vals ) : sum ( [ item_values [ v ] for v in vals ] ) if max_weight is None : max_weight = get_weight ( candidate_sets_dict ) avail_covers = { key : set ( val ) for key , val in candidate_sets_dict . items ( ) } # While we still need covers while get_weight ( solution_cover ) < max_weight and len ( avail_covers ) > 0 : # Find candiate set with the most uncovered items avail_covers . values ( ) uncovered_values = list ( map ( get_value , avail_covers . values ( ) ) ) chosen_idx = ut . argmax ( uncovered_values ) if uncovered_values [ chosen_idx ] <= 0 : # needlessly adding value-less items break chosen_key = list ( avail_covers . keys ( ) ) [ chosen_idx ] # Add values in this key to the cover chosen_set = avail_covers [ chosen_key ] solution_cover [ chosen_key ] = candidate_sets_dict [ chosen_key ] # Remove chosen set from available options and covered items # from remaining available sets del avail_covers [ chosen_key ] for vals in avail_covers . values ( ) : vals . difference_update ( chosen_set ) return solution_cover | 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 , 193 , 197 , 199 , 211 , 223 , 227 , 229 , 233 , 239 , 241 , 251 , 257 , 263 , 269 , 271 , 277 , 281 , 283 , 293 , 307 , 311 , 313 , 317 , 331 , 337 , 347 , 349 , 353 , 359 , 367 , 373 , 379 , 383 , 389 , 397 , 401 , 409 , 419 , 421 , 431 , 433 , 439 , 443 , 449 , 457 , 461 , 463 , 467 , 479 , 487 , 491 , 499 , 503 , 509 , 521 , 523 , 541 , ) #print(len(first_100_primes)) nth_prime = first_100_primes [ n - 1 ] else : if safe : primes = [ num for num in range ( 2 , max_prime ) if is_prime ( num ) ] nth_prime = primes [ n ] else : # This can run for a while... get it? while? nth_prime = get_nth_prime_bruteforce ( n ) return nth_prime | 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_alg] knapsack method=%r' % ( method , ) ) | 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 . LpVariable . dicts ( name = 'x' , indexs = indices , lowBound = 0 , upBound = 1 , cat = pulp . LpInteger ) # maximize objective function prob . objective = sum ( v * x [ i ] for v , i in zip ( values , indices ) ) # subject to prob . add ( sum ( w * x [ i ] for w , i in zip ( weights , indices ) ) <= maxweight ) # Solve using with solver like CPLEX, GLPK, or SCIP. #pulp.CPLEX().solve(prob) pulp . PULP_CBC_CMD ( ) . solve ( prob ) # Read solution flags = [ x [ i ] . varValue for i in indices ] total_value = sum ( [ val for val , flag in zip ( values , flags ) if flag ] ) items_subset = [ item for item , flag in zip ( items , flags ) if flag ] # Print summary if verbose : print ( prob ) print ( 'OPT:' ) print ( '\n' . join ( [ ' %s = %s' % ( x [ i ] . name , x [ i ] . varValue ) for i in indices ] ) ) print ( 'total_value = %r' % ( total_value , ) ) return total_value , items_subset | 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 ) , idx ) for v , w , idx in items ] return knapsack_iterative_int ( int_items , int_maxweight ) | 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_subset = [ ] # NOQA for w in range ( maxsize ) : dpmat [ 0 ] [ w ] = 0 # For each item consider to include it or not for idx in range ( len ( items ) ) : item_val = values [ idx ] item_weight = weights [ idx ] # consider at each possible bag size for w in range ( maxsize ) : valid_item = item_weight <= w if idx > 0 : prev_val = dpmat [ idx - 1 ] [ w ] prev_noitem_val = dpmat [ idx - 1 ] [ w - item_weight ] else : prev_val = 0 prev_noitem_val = 0 withitem_val = item_val + prev_noitem_val more_valuable = withitem_val > prev_val if valid_item and more_valuable : dpmat [ idx ] [ w ] = withitem_val kmat [ idx ] [ w ] = True else : dpmat [ idx ] [ w ] = prev_val kmat [ idx ] [ w ] = False # Trace backwards to get the items used in the solution K = maxweight for idx in reversed ( range ( len ( items ) ) ) : if kmat [ idx ] [ K ] : idx_subset . append ( idx ) K = K - weights [ idx ] idx_subset = sorted ( idx_subset ) items_subset = [ items [ i ] for i in idx_subset ] total_value = dpmat [ len ( items ) - 1 ] [ maxweight ] return total_value , items_subset | 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 * coeff ) . astype ( np . int ) values = items . T [ 0 ] MAXWEIGHT = int ( maxweight * coeff ) W_SIZE = MAXWEIGHT + 1 dpmat = np . full ( ( len ( items ) , W_SIZE ) , np . inf ) kmat = np . full ( ( len ( items ) , W_SIZE ) , 0 , dtype = np . bool ) idx_subset = [ ] for w in range ( W_SIZE ) : dpmat [ 0 ] [ w ] = 0 for idx in range ( 1 , len ( items ) ) : item_val = values [ idx ] item_weight = weights [ idx ] for w in range ( W_SIZE ) : valid_item = item_weight <= w prev_val = dpmat [ idx - 1 ] [ w ] if valid_item : prev_noitem_val = dpmat [ idx - 1 ] [ w - item_weight ] withitem_val = item_val + prev_noitem_val more_valuable = withitem_val > prev_val else : more_valuable = False dpmat [ idx ] [ w ] = withitem_val if more_valuable else prev_val kmat [ idx ] [ w ] = more_valuable K = MAXWEIGHT for idx in reversed ( range ( 1 , len ( items ) ) ) : if kmat [ idx , K ] : idx_subset . append ( idx ) K = K - weights [ idx ] idx_subset = sorted ( idx_subset ) items_subset = [ items [ i ] for i in idx_subset ] total_value = dpmat [ len ( items ) - 1 ] [ MAXWEIGHT ] return total_value , items_subset | 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 ) return array_norm | 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 types keys = util_list . sortedby2 ( keys_ , keys_ ) groupxs = util_dict . dict_take ( grouped_dict , keys ) return keys , groupxs | 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 ( minpergroup ) if len ( minpergroup ) else 0 flat_groupx = ut . flatten ( groupxs ) sortx = ut . argsort ( flat_groupx ) # Indicates the index being yeilded groupx_sorted = ut . take ( flat_groupx , sortx ) flat_items = ut . iflatten ( grouped_items ) # Storage for data weiting to be yeilded toyeild = { } items_yeilded = 0 # Indicates the index we are curently yeilding current_index = 0 # Determine where fills need to happen num_fills_before = [ minval ] + ( np . diff ( groupx_sorted ) - 1 ) . tolist ( ) + [ 0 ] # Check if there are fills before the first item fills = num_fills_before [ items_yeilded ] if fills > 0 : for _ in range ( fills ) : yield None current_index += 1 # Yield items as possible for yeild_at , item in zip ( flat_groupx , flat_items ) : if yeild_at > current_index : toyeild [ yeild_at ] = item elif yeild_at == current_index : # When we find the next element to yeild yield item current_index += 1 items_yeilded += 1 # Check if there are fills before the next item fills = num_fills_before [ items_yeilded ] if fills > 0 : for _ in range ( fills ) : yield None current_index += 1 # Now yield everything that came before this while current_index in toyeild : item = toyeild . pop ( current_index ) yield item current_index += 1 items_yeilded += 1 # Check if there are fills before the next item fills = num_fills_before [ items_yeilded ] if fills > 0 : for _ in range ( fills ) : yield None current_index += 1 | 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 : ungrouped_items [ x ] = item return ungrouped_items | 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 as ut isiter1 = ut . isiterable ( string1 ) isiter2 = ut . isiterable ( string2 ) strs1 = string1 if isiter1 else [ string1 ] strs2 = string2 if isiter2 else [ string2 ] distmat = [ [ Levenshtein . distance ( str1 , str2 ) for str2 in strs2 ] for str1 in strs1 ] # broadcast if not isiter2 : distmat = ut . take_column ( distmat , 0 ) if not isiter1 : distmat = distmat [ 0 ] return distmat | 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 = re . sub ( '\\)' , '' , onlyvars ) varnames = ut . remove_doublspaces ( onlyvars ) . strip ( ) . split ( ' ' ) varied_dict = { var : [ True , False ] for var in varnames } bool_states = ut . all_dict_combinations ( varied_dict ) outputs = [ eval ( boolexpr_ , state . copy ( ) , state . copy ( ) ) for state in bool_states ] true_states = ut . compress ( bool_states , outputs ) true_tuples = ut . take_column ( true_states , varnames ) true_cases = [ str ( '' . join ( [ str ( int ( t ) ) for t in tup ] ) ) for tup in true_tuples ] # Convert to binary ones_bin = [ int ( x , 2 ) for x in true_cases ] #ones_str = [str(x) for x in true_cases] from quine_mccluskey . qm import QuineMcCluskey qm = QuineMcCluskey ( ) result = qm . simplify ( ones = ones_bin , num_bits = len ( varnames ) ) #result = qm.simplify_los(ones=ones_str, num_bits=len(varnames)) grouped_terms = [ dict ( ut . group_items ( varnames , rs ) ) for rs in result ] def parenjoin ( char , list_ ) : if len ( list_ ) == 0 : return '' else : if parens : return '(' + char . join ( list_ ) + ')' else : return char . join ( list_ ) if parens : expanded_terms = [ ( term . get ( '1' , [ ] ) + [ '(not ' + b + ')' for b in term . get ( '0' , [ ] ) ] + [ parenjoin ( ' ^ ' , term . get ( '^' , [ ] ) ) , parenjoin ( ' ~ ' , term . get ( '~' , [ ] ) ) , ] ) for term in grouped_terms ] else : expanded_terms = [ ( term . get ( '1' , [ ] ) + [ 'not ' + b for b in term . get ( '0' , [ ] ) ] + [ parenjoin ( ' ^ ' , term . get ( '^' , [ ] ) ) , parenjoin ( ' ~ ' , term . get ( '~' , [ ] ) ) , ] ) for term in grouped_terms ] final_terms = [ [ t for t in term if t ] for term in expanded_terms ] products = [ parenjoin ( ' and ' , [ f for f in form if f ] ) for form in final_terms ] final_expr = ' or ' . join ( products ) return final_expr | 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_output , get_uniques = True ) dataget_fun = { True : get_protein_data_genecentric , False : get_protein_data_pgrouped } [ genecentric is not False ] firstfield = prottabledata . ACCESSIONS [ genecentric ] for protein in proteins : outprotein = { k : v for k , v in protein . items ( ) } outprotein [ firstfield ] = outprotein . pop ( prottabledata . HEADER_PROTEIN ) protein_acc = protein [ prottabledata . HEADER_PROTEIN ] outprotein . update ( dataget_fun ( proteindata , protein_acc , headerfields ) ) outprotein = { k : str ( v ) for k , v in outprotein . items ( ) } yield outprotein | 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 offset is not None : query += ' OFFSET %s' params . append ( offset ) cursor = self . cursor cursor . execute ( query , params ) return [ key for key , in cursor ] | 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 . psycopg2 . Binary ( query_hash ) while start < cache_len : rows = cache [ start : start + bulk_insert ] params = [ ] for timestamp , value in rows : params . extend ( ( namespace , key , query_hash , length , timestamp , value ) ) insert = ( row + ',' ) * ( len ( rows ) - 1 ) + row execute ( query + insert , params ) start += bulk_insert self . db . commit ( ) | 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 . platform == "darwin" : return { 'DYLD_INSERT_LIBRARIES' : path . join ( LIBFAKETIME_DIR , "libfaketime.1.dylib" ) , 'DYLD_FORCE_FLAT_NAMESPACE' : '1' , 'FAKETIME_TIMESTAMP_FILE' : filename , } else : raise RuntimeError ( "libfaketime does not support '{}' platform" . format ( sys . platform ) ) | 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 seq not in highest : highest [ seq ] = { 'pep_el' : formatting . stringify_strip_namespace_declaration ( el , ns ) , 'score' : featscore } if score == 'svm' : # greater than score is accepted if featscore > highest [ seq ] [ 'score' ] : highest [ seq ] = { 'pep_el' : formatting . stringify_strip_namespace_declaration ( el , ns ) , 'score' : featscore } else : # lower than score is accepted if featscore < highest [ seq ] [ 'score' ] : highest [ seq ] = { 'pep_el' : formatting . stringify_strip_namespace_declaration ( el , ns ) , 'score' : featscore } formatting . clear_el ( el ) for pep in list ( highest . values ( ) ) : yield pep [ 'pep_el' ] | 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 . path . pathsep ) ) new_path_list = ut . unique_ordered ( win_pathlist + list ( add_path_list ) ) #new_path_list = unique_ordered(win_pathlist, rob_pathlist) print ( '\n' . join ( new_path_list ) ) pathtxt = pathsep . join ( new_path_list ) varval_list = [ ( 'Path' , pathtxt ) ] regfile_str = make_regfile_str ( key , varval_list , rtype ) ut . view_directory ( write_dir ) print ( regfile_str ) ut . writeto ( script_fpath , regfile_str , mode = 'wb' ) print ( 'Please have an admin run the script. You may need to restart' ) | 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 equality check wont work for the case # where list1 and list2 are supposed to correspond, but the length of # list2 is 1. list2 = [ ] if len ( list2 ) == 1 and len ( list1 ) > 1 : list2 = list2 * len ( list1 ) if len ( list1 ) != len ( list2 ) : raise ValueError ( 'out of alignment len(list1)=%r, len(list2)=%r' % ( len ( list1 ) , len ( list2 ) ) ) return dict ( zip ( list1 , list2 ) ) | 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 : ] : default1 . append ( default ) accum_ = dict_union_combine ( accum_ , dict_ , default = default1 , default2 = default2 ) stacked_dict = accum_ # stacked_dict = reduce(partial(dict_union_combine, default=[default]), dict_list_) else : stacked_dict = { } # Augment keys if requested if key_suffix is not None : stacked_dict = map_dict_keys ( lambda x : x + key_suffix , stacked_dict ) return stacked_dict | 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 ) : # all entries have one length multitups_list = [ [ ( key , val ) for val in val_list ] for key , val_list in iteritems_sorted ( varied_dict ) ] else : multitups_list = [ [ ( key , val ) for val in val_list ] for key , val_list in iteritems_sorted ( varied_dict ) if isinstance ( val_list , ( list , tuple ) ) and len ( val_list ) > 1 ] combtup_list = list ( it . product ( * multitups_list ) ) combtup_list2 = [ [ ( key , val ) if isinstance ( val , six . string_types ) else ( key , repr ( val ) ) for ( key , val ) in combtup ] for combtup in combtup_list ] comb_lbls = [ ',' . join ( [ '%s=%s' % ( key , val ) for ( key , val ) in combtup ] ) for combtup in combtup_list2 ] #comb_lbls = list(map(str, comb_pairs)) return comb_lbls | 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 : raise if copy : dict1 = dict ( dict1 ) if alias_dict is None : alias_dict = { } for key , val in six . iteritems ( dict2 ) : key = alias_dict . get ( key , key ) if key in dict1 : dict1 [ key ] = val return dict1 | 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 ( val1 ) == type ( val2 ) , 'vals are not same type' if HAVE_NUMPY and np . iterable ( val1 ) : if almosteq_ok and ut . is_float ( val1 ) : assert np . all ( ut . almost_eq ( val1 , val2 ) ) , 'float vals are not within thresh' else : assert all ( [ np . all ( x1 == x2 ) for ( x1 , x2 ) in zip ( val1 , val2 ) ] ) , 'np vals are different' elif isinstance ( val1 , dict ) : is_dicteq ( val1 , val2 , almosteq_ok = almosteq_ok , verbose_err = verbose_err ) else : assert val1 == val2 , 'vals are different' except AssertionError as ex : if verbose_err : ut . printex ( ex ) return False return True | 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 dictget = dict_ . get else : raise ValueError ( 'len(d) must be 1 or 0' ) for key in keys : if HAVE_NUMPY and isinstance ( key , np . ndarray ) : # recursive call yield list ( dict_take_gen ( dict_ , key , * d ) ) else : yield dictget ( key , * d ) | 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 , weight in zip ( item_list , weight_list ) : hist_ [ item ] += weight # hist_ = dict(hist_) if ordered : # import utool as ut # key_order = ut.sortedby(list(hist_.keys()), list(hist_.values())) getval = op . itemgetter ( 1 ) key_order = [ key for ( key , value ) in sorted ( hist_ . items ( ) , key = getval ) ] hist_ = order_dict_by ( hist_ , key_order ) return hist_ | 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 } else : if default2 is util_const . NoParam : default2 = default dict3 = { key : combine_op ( dict1 . get ( key , default ) , dict2 . get ( key , default2 ) ) for key in keys3 } return dict3 | 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 : # Python 3 does not allow sorting mixed types pairs = sorted ( pairs , key = lambda tup : str ( tup [ 0 ] ) ) else : pairs = items # Initialize a dict of lists groupid_to_items = defaultdict ( list ) # Insert each item into the correct group for groupid , item in pairs : groupid_to_items [ groupid ] . append ( item ) return groupid_to_items | 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 ( defaultdict , node_type ) root_type = node_type elif num_groups == 1 : root_type = list else : raise ValueError ( 'must suply groupids' ) tree = defaultdict ( root_type ) # groupid_tuple_list = list ( zip ( * groupids_list ) ) for groupid_tuple , item in zip ( groupid_tuple_list , item_list ) : node = tree for groupid in groupid_tuple : node = node [ groupid ] node . append ( item ) return tree | 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.iteritems(node)} else : # recursion #return {key: hierarchical_map_vals(func, val, max_depth, depth + 1) for key, val in six.iteritems(node)} #keyval_list = [(key, hierarchical_map_vals(func, val, max_depth, depth + 1)) for key, val in six.iteritems(node)] keyval_list = [ ( key , hierarchical_map_vals ( func , val , max_depth , depth + 1 ) ) for key , val in node . items ( ) ] if isinstance ( node , OrderedDict ) : return OrderedDict ( keyval_list ) else : return dict ( keyval_list ) | 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 ] ) sorted_items = sorted ( six . iteritems ( dict_ ) , key = _key , reverse = reverse ) sorted_dict = OrderedDict ( sorted_items ) return sorted_dict | 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_psms ( fn , oldheader ) : yield { 'psm' : psm , 'split_pool' : psm [ oldheader [ splitcolnr ] ] } | 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' ) opener = urllib . request . build_opener ( ) numlist = opener . open ( request ) . read ( ) return numlist . split ( ) | 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/0.1 very alpha' ) opener = urllib . request . build_opener ( ) numlist = opener . open ( request ) . read ( ) return numlist . split ( ) | 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 . is_float ( num ) : num_str = ( '%.' + str ( max_digits ) + 'f' ) % num # Handle trailing and leading zeros num_str = num_str . rstrip ( '0' ) . lstrip ( '0' ) if num_str . startswith ( '.' ) : num_str = '0' + num_str if num_str . endswith ( '.' ) : num_str = num_str + '0' return num_str elif util_type . is_int ( num ) : return int_comma_str ( num ) else : return '%r' | 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_count end_index = running_feature_count + len ( feature_list_names ) - 1 running_feature_count += len ( feature_list_names ) feature_ranges . append ( [ list_id , start_index , end_index ] ) X_train = np . hstack ( [ load ( self . features_dir + 'X_train_{}.pickle' . format ( list_id ) ) for list_id in feature_lists ] ) X_test = np . hstack ( [ load ( self . features_dir + 'X_test_{}.pickle' . format ( list_id ) ) for list_id in feature_lists ] ) df_train = pd . DataFrame ( X_train , columns = column_names ) df_test = pd . DataFrame ( X_test , columns = column_names ) return df_train , df_test , feature_ranges | 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_path , os . pardir ) ) ) # Try ./data candidate_path = os . path . abspath ( os . path . join ( os . curdir , 'data' ) ) if os . path . exists ( candidate_path ) : return Project ( os . path . abspath ( os . curdir ) ) # Try ../../data 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_path , os . pardir , os . pardir ) ) ) # Out of ideas at this point. raise ValueError ( 'Cannot discover the structure of the project. Make sure that the data directory exists' ) | 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 paths_to_create : os . makedirs ( path , exist_ok = True ) | 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 is not None and module_name is None : pass else : raise ValueError ( 'module_name or module must be exclusively specified' ) if register is True : _add_injected_module ( module ) return module | finds module in sys . modules based on module name unless the module has already been found and is passed in | 134 | 22 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.