idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
13,100 | def do_retry ( self , arg ) : prev_line = self . curframe . f_lineno - 1 # Make sure not to jump to the middle of the previous statement while True : try : self . curframe . f_lineno = prev_line break except ValueError : prev_line -= 1 self . do_jump ( prev_line ) self . do_continue ( arg ) return 1 | Rerun the previous command . | 87 | 7 |
13,101 | def dispatch_line ( self , frame ) : callback = TerminalPdb . dispatch_line ( self , frame ) # If the ipdb session ended, don't return a callback for the next line if self . stoplineno == - 1 : return None return callback | Handle line action and return the next line callback . | 55 | 10 |
13,102 | def wrap_with_try ( self , node ) : handlers = [ ] if self . ignore_exceptions is None : handlers . append ( ast . ExceptHandler ( type = None , name = None , body = [ ast . Raise ( ) ] ) ) else : ignores_nodes = self . ignore_exceptions handlers . append ( ast . ExceptHandler ( type = ast . Tuple ( ignores_nodes , ast . Load ( ) ) , name = None , body = [ ast . Raise ( ) ] ) ) if self . catch_exception is None or get_node_value ( self . catch_exception ) not in ( get_node_value ( ast_node ) for ast_node in self . ignore_exceptions ) : call_extra_parameters = [ ] if IS_PYTHON_3 else [ None , None ] start_debug_cmd = ast . Expr ( value = ast . Call ( ast . Name ( "start_debugging" , ast . Load ( ) ) , [ ] , [ ] , * call_extra_parameters ) ) catch_exception_type = None if self . catch_exception is not None : catch_exception_type = self . catch_exception handlers . append ( ast . ExceptHandler ( type = catch_exception_type , name = None , body = [ start_debug_cmd ] ) ) try_except_extra_params = { "finalbody" : [ ] } if IS_PYTHON_3 else { } new_node = self . ast_try_except ( orelse = [ ] , body = [ node ] , handlers = handlers , * * try_except_extra_params ) return ast . copy_location ( new_node , node ) | Wrap an ast node in a try node to enter debug on exception . | 379 | 15 |
13,103 | def try_except_handler ( self , node ) : # List all excepted exception's names excepted_types = [ ] for handler in node . handlers : if handler . type is None : excepted_types = None break if isinstance ( handler . type , ast . Tuple ) : excepted_types . extend ( [ exception_type for exception_type in handler . type . elts ] ) else : excepted_types . append ( handler . type ) new_exception_list = self . ignore_exceptions if self . ignore_exceptions is not None : if excepted_types is None : new_exception_list = None else : new_exception_list = list ( set ( excepted_types + self . ignore_exceptions ) ) # Set the new ignore list, and save the old one old_exception_handlers , self . ignore_exceptions = self . ignore_exceptions , new_exception_list # Run recursively on all sub nodes with the new ignore list node . body = [ self . visit ( node_item ) for node_item in node . body ] # Revert changes from ignore list self . ignore_exceptions = old_exception_handlers | Handler for try except statement to ignore excepted exceptions . | 262 | 11 |
13,104 | def visit_Call ( self , node ) : if self . depth == 0 : return node if self . ignore_exceptions is None : ignore_exceptions = ast . Name ( "None" , ast . Load ( ) ) else : ignore_exceptions = ast . List ( self . ignore_exceptions , ast . Load ( ) ) catch_exception_type = self . catch_exception if self . catch_exception else "None" catch_exception = ast . Name ( catch_exception_type , ast . Load ( ) ) depth = ast . Num ( self . depth - 1 if self . depth > 0 else - 1 ) debug_node_name = ast . Name ( "debug" , ast . Load ( ) ) call_extra_parameters = [ ] if IS_PYTHON_3 else [ None , None ] node . func = ast . Call ( debug_node_name , [ node . func , ignore_exceptions , catch_exception , depth ] , [ ] , * call_extra_parameters ) return node | Propagate debug wrapper into inner function calls if needed . | 228 | 11 |
13,105 | def get_qtls_from_rqtl_data ( matrix , lod_threshold ) : t_matrix = list ( zip ( * matrix ) ) qtls = [ [ 'Trait' , 'Linkage Group' , 'Position' , 'Exact marker' , 'LOD' ] ] # row 0: markers # row 1: chr # row 2: pos for row in t_matrix [ 3 : ] : lgroup = None max_lod = None peak = None cnt = 1 while cnt < len ( row ) : if lgroup is None : lgroup = t_matrix [ 1 ] [ cnt ] if lgroup == t_matrix [ 1 ] [ cnt ] : if max_lod is None : max_lod = float ( row [ cnt ] ) if float ( row [ cnt ] ) > float ( max_lod ) : max_lod = float ( row [ cnt ] ) peak = cnt else : if max_lod and float ( max_lod ) > float ( lod_threshold ) and peak : qtl = [ row [ 0 ] , # trait t_matrix [ 1 ] [ peak ] , # LG t_matrix [ 2 ] [ peak ] , # pos t_matrix [ 0 ] [ peak ] , # marker max_lod , # LOD value ] qtls . append ( qtl ) lgroup = None max_lod = None peak = cnt cnt = cnt + 1 return qtls | Retrieve the list of significants QTLs for the given input matrix and using the specified LOD threshold . This assumes one QTL per linkage group . | 333 | 32 |
13,106 | def save_session ( self , * args , * * kwargs ) : # do not send session cookie if g . get ( 'stateless_sessions' ) : return # send cookie return super ( BoilerSessionInterface , self ) . save_session ( * args , * * kwargs ) | Save session Skip setting session cookie if requested via g . stateless_sessions | 65 | 16 |
13,107 | def prune_old ( self ) : path = self . pubdir dirmask = self . dirmask expire = self . expire expire_limit = int ( time . time ( ) ) - ( 86400 * expire ) logger . info ( 'Pruning directories older than %d days' , expire ) if not os . path . isdir ( path ) : logger . warning ( 'Dir %r not found -- skipping pruning' , path ) return for entry in os . listdir ( path ) : logger . debug ( 'Found: %r' , entry ) if os . path . isdir ( os . path . join ( path , entry ) ) : try : stamp = time . mktime ( time . strptime ( entry , dirmask ) ) except ValueError as e : logger . info ( 'Dir %r did not match dirmask %r: %r' , entry , dirmask , e ) logger . info ( 'Skipping %r' , entry ) continue if stamp < expire_limit : shutil . rmtree ( os . path . join ( path , entry ) ) logger . info ( 'File Publisher: Pruned old dir: %r' , entry ) else : logger . info ( '%r is still active' , entry ) else : logger . info ( '%r is not a directory. Skipping.' , entry ) logger . info ( 'Finished with pruning' ) | Removes the directories that are older than a certain date . | 306 | 12 |
13,108 | def send_report ( self , report_parts ) : logger . info ( 'Checking and creating the report directory' ) report_parts = sorted ( filter ( lambda x : x . fmt in self . formats , report_parts ) , key = lambda x : self . formats . index ( x . fmt ) ) workdir = os . path . join ( self . pubdir , self . dirname ) if not os . path . isdir ( workdir ) : try : os . makedirs ( workdir ) except OSError as e : logger . error ( 'Error creating directory "{0}": {0}' . format ( workdir , e ) ) return fmtname = '{0}-{1}-{2}.{3}' if len ( report_parts ) > 1 else '{0}-{2}.{3}' for i , text_part in enumerate ( filter ( lambda x : x . fmt in self . formats , report_parts ) ) : filename = fmtname . format ( self . filename , i , socket . gethostname ( ) , text_part . ext ) repfile = os . path . join ( workdir , filename ) logger . info ( 'Dumping the report part %d into %r' , i , repfile ) fh = open ( repfile , 'w' ) fh . write ( text_part . text ) fh . close ( ) print ( 'Report part saved in: %r' % repfile ) if self . notify : logger . info ( 'Creating an email message' ) email_address = self . config . get ( 'main' , 'email_address' ) smtp_server = self . config . get ( 'main' , 'smtp_server' ) publoc = os . path . join ( self . pubroot , self . dirname ) eml = MIMEText ( 'New lograptor report is available at:\r\n{0}' . format ( publoc ) ) eml [ 'Subject' ] = '{0} system events: {1} (report notification)' . format ( socket . gethostname ( ) , time . strftime ( '%c' , time . localtime ( ) ) ) eml [ 'Date' ] = formatdate ( ) eml [ 'From' ] = email_address eml [ 'To' ] = ', ' . join ( self . notify ) eml [ 'X-Mailer' ] = u'{0}-{1}' . format ( package_name , __version__ ) mail_message ( smtp_server , eml . as_string ( ) , email_address , self . notify ) print ( 'Notification mailed to: {0}' . format ( ',' . join ( self . notify ) ) ) if self . rawlogs : logfilename = '{0}.log' . format ( self . filename ) logfile = os . path . join ( workdir , '{0}.gz' . format ( logfilename ) ) logger . info ( 'Gzipping logs and writing them to %r' , logfilename ) outfh = open ( logfile , 'w+b' ) do_chunked_gzip ( self . rawfh , outfh , logfilename ) outfh . close ( ) print ( 'Gzipped logs saved in: {0}' . format ( logfile ) ) # Purge old reports self . prune_old ( ) | Publish the report parts to local files . Each report part is a text with a title and specific extension . For html and plaintext sending the report part is unique for csv send also the stats and unparsed string are plain text and report items are csv texts . | 751 | 56 |
13,109 | def parse ( self ) : self . _parse ( self . method ) return list ( set ( [ deco for deco in self . decos if deco ] ) ) | Return the list of string of all the decorators found | 37 | 11 |
13,110 | def filter_304_headers ( headers ) : return [ ( k , v ) for k , v in headers if k . lower ( ) not in _filter_from_304 ] | Filter a list of headers to include in a 304 Not Modified response . | 38 | 14 |
13,111 | def response ( code , body = '' , etag = None , last_modified = None , expires = None , * * kw ) : if etag is not None : if not ( etag [ 0 ] == '"' and etag [ - 1 ] == '"' ) : etag = '"%s"' % etag kw [ 'etag' ] = etag if last_modified is not None : kw [ 'last_modified' ] = datetime_to_httpdate ( last_modified ) if expires is not None : if isinstance ( expires , datetime ) : kw [ 'expires' ] = datetime_to_httpdate ( expires ) else : kw [ 'expires' ] = timedelta_to_httpdate ( expires ) headers = [ ( k . replace ( '_' , '-' ) . title ( ) , v ) for k , v in sorted ( kw . items ( ) ) ] return Response ( code , headers , body ) | Helper to build an HTTP response . | 214 | 7 |
13,112 | def body ( self ) : if self . _body is None : raw_body = self . _raw_body if self . _body_writer is None : self . _body = raw_body ( ) if callable ( raw_body ) else raw_body else : self . _body = self . _body_writer ( raw_body ) return self . _body | Seralizes and returns the response body . | 79 | 9 |
13,113 | def set_cookie ( self , key , value = '' , max_age = None , path = '/' , domain = None , secure = False , httponly = False , expires = None ) : key , value = key . encode ( 'utf-8' ) , value . encode ( 'utf-8' ) cookie = SimpleCookie ( { key : value } ) m = cookie [ key ] if max_age is not None : if isinstance ( max_age , timedelta ) : m [ 'max-age' ] = int ( total_seconds ( max_age ) ) else : m [ 'max-age' ] = int ( max_age ) if path is not None : m [ 'path' ] = path . encode ( 'utf-8' ) if domain is not None : m [ 'domain' ] = domain . encode ( 'utf-8' ) if secure : m [ 'secure' ] = True if httponly : m [ 'httponly' ] = True if expires is not None : # 'expires' expects an offset in seconds, like max-age if isinstance ( expires , datetime ) : expires = total_seconds ( expires - datetime . utcnow ( ) ) elif isinstance ( expires , timedelta ) : expires = total_seconds ( expires ) m [ 'expires' ] = int ( expires ) self . headers . add_header ( 'Set-Cookie' , m . OutputString ( ) ) | Set a response cookie . | 313 | 5 |
13,114 | def conditional_to ( self , request ) : if not self . code == 200 : return self request_headers = request . headers response_headers = self . headers if_none_match = request_headers . get ( 'If-None-Match' ) if_modified_since = request_headers . get ( 'If-Modified-Since' ) etag_ok , date_ok = False , False if if_none_match : etag = response_headers . get ( 'ETag' ) if etag and match_etag ( etag , if_none_match , weak = True ) : etag_ok = True if if_modified_since : last_modified = response_headers . get ( 'Last-Modified' ) if last_modified : try : modified_ts = httpdate_to_timestamp ( last_modified ) last_valid_ts = httpdate_to_timestamp ( if_modified_since ) if modified_ts <= last_valid_ts : date_ok = True except : pass # Ignore invalid dates if if_none_match and not etag_ok : return self elif if_modified_since and not date_ok : return self elif etag_ok or date_ok : headers = filter_304_headers ( self . headers . items ( ) ) if 'Date' not in self . headers : headers . append ( ( 'Date' , datetime_to_httpdate ( time . time ( ) ) ) ) return Response ( status = 304 , headers = headers , body = '' ) return self | Return a response that is conditional to a given request . | 336 | 11 |
13,115 | def _get_ukko_report ( ) : with urllib . request . urlopen ( URL_UKKO_REPORT ) as response : ret = str ( response . read ( ) ) return ret | Get Ukko s report from the fixed URL . | 44 | 10 |
13,116 | def get_nodes ( n = 8 , exclude = [ ] , loop = None ) : report = _get_ukko_report ( ) nodes = _parse_ukko_report ( report ) ret = [ ] while len ( ret ) < n and len ( nodes ) > 0 : node = nodes [ 0 ] if node not in exclude : reachable = True if loop is not None : reachable = loop . run_until_complete ( _test_node ( node ) ) if reachable : ret . append ( node ) nodes = nodes [ 1 : ] return ret | Get Ukko nodes with the least amount of load . | 122 | 11 |
13,117 | def get_unix_ioctl_terminal_size ( ) : def ioctl_gwinsz ( fd ) : try : import fcntl import termios import struct return struct . unpack ( 'hh' , fcntl . ioctl ( fd , termios . TIOCGWINSZ , '1234' ) ) except ( IOError , OSError ) : return None cr = ioctl_gwinsz ( 0 ) or ioctl_gwinsz ( 1 ) or ioctl_gwinsz ( 2 ) if not cr : try : f = open ( os . ctermid ( ) ) cr = ioctl_gwinsz ( f . fileno ( ) ) f . close ( ) except ( IOError , OSError ) : pass if not cr : try : cr = ( os . environ [ 'LINES' ] , os . environ [ 'COLUMNS' ] ) except KeyError : return None return int ( cr [ 1 ] ) , int ( cr [ 0 ] ) | Get the terminal size of a UNIX terminal using the ioctl UNIX command . | 230 | 17 |
13,118 | def add_marker_to_qtl ( qtl , map_list ) : closest = '' diff = None for marker in map_list : if qtl [ 1 ] == marker [ 1 ] : tmp_diff = float ( qtl [ 2 ] ) - float ( marker [ 2 ] ) if diff is None or abs ( diff ) > abs ( tmp_diff ) : diff = tmp_diff closest = marker if closest != '' : closest = closest [ 0 ] return closest | Add the closest marker to the given QTL . | 102 | 10 |
13,119 | def add_marker_to_qtls ( qtlfile , mapfile , outputfile = 'qtls_with_mk.csv' ) : qtl_list = read_input_file ( qtlfile , ',' ) map_list = read_input_file ( mapfile , ',' ) if not qtl_list or not map_list : # pragma: no cover return qtl_list [ 0 ] . append ( 'Closest marker' ) qtls = [ ] qtls . append ( qtl_list [ 0 ] ) for qtl in qtl_list [ 1 : ] : qtl . append ( add_marker_to_qtl ( qtl , map_list ) ) qtls . append ( qtl ) LOG . info ( '- %s QTLs processed in %s' % ( len ( qtls ) , qtlfile ) ) write_matrix ( outputfile , qtls ) | This function adds to a list of QTLs the closest marker to the QTL peak . | 213 | 19 |
13,120 | def addFilter ( self , filterMethod = FILTER_METHOD_AND , * * kwargs ) : filterMethod = filterMethod . upper ( ) if filterMethod not in FILTER_METHODS : raise ValueError ( 'Unknown filter method, %s. Must be one of: %s' % ( str ( filterMethod ) , repr ( FILTER_METHODS ) ) ) self . filters . append ( ( filterMethod , kwargs ) ) | addFilter - Add a filter to this query . | 96 | 10 |
13,121 | def execute ( self , lst ) : from . import QueryableListMixed if not issubclass ( lst . __class__ , QueryableListBase ) : lst = QueryableListMixed ( lst ) filters = copy . copy ( self . filters ) nextFilter = filters . popleft ( ) while nextFilter : ( filterMethod , filterArgs ) = nextFilter lst = self . _applyFilter ( lst , filterMethod , filterArgs ) if len ( lst ) == 0 : return lst try : nextFilter = filters . popleft ( ) except : break return lst | execute - Execute the series of filters in order on the provided list . | 130 | 15 |
13,122 | def copy ( self ) : ret = QueryBuilder ( ) ret . filters = copy . copy ( self . filters ) return ret | copy - Create a copy of this query . | 26 | 9 |
13,123 | def _applyFilter ( lst , filterMethod , filterArgs ) : if filterMethod == FILTER_METHOD_AND : return lst . filterAnd ( * * filterArgs ) else : # ALready validated in addFIlter that type is AND or OR return lst . filterOr ( * * filterArgs ) | _applyFilter - Applies the given filter method on a set of args | 67 | 15 |
13,124 | def _raise_corsair_error ( self , error = None , message = "" ) : if error is None : error = self . last_error ( ) raise error ( message ) | Raise error message based on the last reported error from the SDK | 40 | 13 |
13,125 | def device_count ( self ) : device_count = get_device_count ( self . corsair_sdk ) if device_count == - 1 : self . _raise_corsair_error ( ) return device_count | Find amount of CUE devices | 51 | 6 |
13,126 | def led_id_from_char ( self , char ) : led_id = get_led_id_for_key_name ( self . corsair_sdk , bytes ( char ) ) if led_id == 0 : self . _raise_corsair_error ( ) return led_id | Get id of a led by the letter Only between A - Z | 67 | 13 |
13,127 | def set_led ( self , led_id , color ) : if not set_leds_color ( self . corsair_sdk , LedColor ( led_id , * color ) ) : self . _raise_corsair_error ( ) return True | Set color of an led | 58 | 5 |
13,128 | def request_control ( self , device_id , access_mode = True ) : if access_mode : if not request_control ( self . corsair_sdk , device_id ) : self . _raise_corsair_error ( ) return True else : self . reload ( ) | Request exclusive control of device | 64 | 5 |
13,129 | def device ( self , device_id , * args , * * kwargs ) : return Device ( device_id , self . corsair_sdk , self . _corsair_sdk_path , * args , * * kwargs ) | Return a Device object based on id | 56 | 7 |
13,130 | def device_info ( self , device_id = None ) : if device_id is None : device_id = self . device_id return get_device_info ( self . corsair_sdk , device_id ) | Return device information if device_id is not specified return for this device | 50 | 14 |
13,131 | def get_obsolete_acc_to_uniparc ( acc ) : contents = http_get ( 'www.uniprot.org/uniparc/?query={0}' . format ( acc ) ) mtchs = re . findall ( r'"UPI[A-Z0-9]+?"' , contents , re . DOTALL ) uniparc_id = set ( [ m [ 1 : - 1 ] for m in mtchs ] ) if len ( uniparc_id ) == 1 : return uniparc_id . pop ( ) elif len ( uniparc_id ) > 1 : raise Exception ( 'Multiple UPI identifiers found.' ) return None | Tries to determine the UniParc ID for obsolete ACCs which are not returned using uniprot_map . | 150 | 24 |
13,132 | def get_common_PDB_IDs ( pdb_id , cache_dir = None , exception_on_failure = True ) : m = pdb_to_uniparc ( [ pdb_id ] , cache_dir = cache_dir ) UniProtACs = [ ] if pdb_id in m : for entry in m [ pdb_id ] : if entry . UniProtACs : UniProtACs . extend ( entry . UniProtACs ) elif exception_on_failure : raise Exception ( 'No UniProtAC for one entry.Lookup failed.' ) elif exception_on_failure : raise Exception ( 'Lookup failed.' ) if not UniProtACs : if exception_on_failure : raise Exception ( 'Lookup failed.' ) else : return None common_set = set ( uniprot_map ( 'ACC' , 'PDB_ID' , [ UniProtACs [ 0 ] ] , cache_dir = cache_dir ) . get ( UniProtACs [ 0 ] , [ ] ) ) for acc in UniProtACs [ 1 : ] : common_set = common_set . intersection ( set ( uniprot_map ( 'ACC' , 'PDB_ID' , [ acc ] , cache_dir = cache_dir ) . get ( acc , [ ] ) ) ) return sorted ( common_set ) | This function takes a PDB ID maps it to UniProt ACCs then returns the common set of PDB IDs related to those ACCs . The purpose is to find any PDB files related to pdb_id particularly for complexes such that the other PDB files contain identical sequences or mutant complexes . | 303 | 61 |
13,133 | def _parse_sequence_tag ( self ) : #main_tags = self._dom.getElementsByTagName("uniprot") #assert(len(main_tags) == 1) #entry_tags = main_tags[0].getElementsByTagName("entry") #assert(len(entry_tags) == 1) #entry_tags[0] entry_tag = self . entry_tag # only get sequence tags that are direct children of the entry tag (sequence tags can also be children of entry.comment.conflict) sequence_tags = [ child for child in entry_tag . childNodes if child . nodeType == child . ELEMENT_NODE and child . tagName == 'sequence' ] assert ( len ( sequence_tags ) == 1 ) sequence_tag = sequence_tags [ 0 ] # atomic mass, sequence, CRC64 digest self . atomic_mass = float ( sequence_tag . getAttribute ( "mass" ) ) self . sequence = "" . join ( sequence_tag . firstChild . nodeValue . strip ( ) . split ( "\n" ) ) self . sequence_length = int ( sequence_tag . getAttribute ( "length" ) ) self . CRC64Digest = sequence_tag . getAttribute ( "checksum" ) | Parses the sequence and atomic mass . | 276 | 9 |
13,134 | def cool_paginate ( context , * * kwargs ) -> dict : names = ( 'size' , 'next_name' , 'previous_name' , 'elastic' , 'page_obj' , ) return_dict = { name : value for name , value in zip ( names , map ( kwargs . get , names ) ) } if context . get ( 'request' ) : return_dict [ 'request' ] = context [ 'request' ] else : raise RequestNotExists ( 'Unable to find request in your template context,' 'please make sure that you have the request context processor enabled' ) if not return_dict . get ( 'page_obj' ) : if context . get ( 'page_obj' ) : return_dict [ 'page_obj' ] = context [ 'page_obj' ] else : raise PageNotSpecified ( 'You customized paginator standard name, ' "but haven't specified it in {% cool_paginate %} tag." ) if not return_dict . get ( 'elastic' ) : return_dict [ 'elastic' ] = getattr ( settings , 'COOL_PAGINATOR_ELASTIC' , 10 ) return return_dict | Main function for pagination process . | 268 | 7 |
13,135 | def time_restarts ( data_path ) : path = os . path . join ( data_path , 'last_restarted' ) if not os . path . isfile ( path ) : with open ( path , 'a' ) : os . utime ( path , None ) last_modified = os . stat ( path ) . st_mtime with open ( path , 'a' ) : os . utime ( path , None ) now = os . stat ( path ) . st_mtime dif = round ( now - last_modified , 2 ) last_restart = datetime . fromtimestamp ( now ) . strftime ( '%H:%M:%S' ) result = 'LAST RESTART WAS {} SECONDS AGO at {}' . format ( dif , last_restart ) print ( style ( fg = 'green' , bg = 'red' , text = result ) ) | When called will create a file and measure its mtime on restarts | 201 | 14 |
13,136 | def from_stmt ( stmt , engine , * * kwargs ) : result_proxy = engine . execute ( stmt , * * kwargs ) return from_db_cursor ( result_proxy . cursor ) | Execute a query in form of texture clause return the result in form of | 49 | 15 |
13,137 | def compute_stability_classification ( self , predicted_data , record , dataframe_record ) : stability_classification , stability_classication_x_cutoff , stability_classication_y_cutoff = None , self . stability_classication_x_cutoff , self . stability_classication_y_cutoff if record [ 'DDG' ] != None : stability_classification = fraction_correct ( [ record [ 'DDG' ] ] , [ predicted_data [ self . ddg_analysis_type ] ] , x_cutoff = stability_classication_x_cutoff , y_cutoff = stability_classication_y_cutoff ) stability_classification = int ( stability_classification ) assert ( stability_classification == 0 or stability_classification == 1 ) dataframe_record [ 'StabilityClassification' ] = stability_classification | Calculate the stability classification for this case . | 194 | 10 |
13,138 | def compute_absolute_error ( self , predicted_data , record , dataframe_record ) : absolute_error = abs ( record [ 'DDG' ] - predicted_data [ self . ddg_analysis_type ] ) dataframe_record [ 'AbsoluteError' ] = absolute_error | Calculate the absolute error for this case . | 64 | 10 |
13,139 | def count_residues ( self , record , pdb_record ) : mutations = self . get_record_mutations ( record ) pdb_chains = set ( [ m [ 'Chain' ] for m in mutations ] ) assert ( len ( pdb_chains ) == 1 ) # we expect monomeric cases pdb_chain = pdb_chains . pop ( ) return len ( pdb_record . get ( 'Chains' , { } ) . get ( pdb_chain , { } ) . get ( 'Sequence' , '' ) ) | Count the number of residues in the chains for the case . | 122 | 12 |
13,140 | def full_analysis ( self , analysis_set , output_directory , verbose = True , compile_pdf = True , quick_plots = False ) : if not os . path . isdir ( output_directory ) : os . makedirs ( output_directory ) self . analysis_directory = output_directory self . calculate_metrics ( analysis_set = analysis_set , analysis_directory = output_directory , verbose = verbose ) self . write_dataframe_to_csv ( os . path . join ( output_directory , 'data.csv' ) ) # Return latex_report return self . plot ( analysis_set = analysis_set , analysis_directory = output_directory , matplotlib_plots = True , verbose = verbose , compile_pdf = compile_pdf , quick_plots = quick_plots ) | Combines calculate_metrics write_dataframe_to_csv and plot | 183 | 16 |
13,141 | def get_unique_ajps ( benchmark_runs ) : br_ajps = { } for br in benchmark_runs : for ajp in br . additional_join_parameters : if ajp not in br_ajps : br_ajps [ ajp ] = set ( ) br_ajps [ ajp ] . add ( br . additional_join_parameters [ ajp ] [ 'short_name' ] ) unique_ajps = [ ] for ajp in br_ajps : if len ( br_ajps [ ajp ] ) > 1 : unique_ajps . append ( ajp ) return unique_ajps | Determines which join parameters are unique | 139 | 8 |
13,142 | def get_experimental_ddg_values ( self , record , dataframe_record ) : new_idxs = [ ] for analysis_set in self . get_analysis_sets ( record ) : ddg_details = record [ 'DDG' ] [ analysis_set ] exp_ddg_fieldname = BenchmarkRun . get_analysis_set_fieldname ( 'Experimental' , analysis_set ) new_idxs . append ( exp_ddg_fieldname ) dataframe_record [ exp_ddg_fieldname ] = None if ddg_details : dataframe_record [ exp_ddg_fieldname ] = ddg_details [ 'MeanDDG' ] # Update the CSV headers try : idx = self . csv_headers . index ( 'Experimental' ) self . csv_headers = self . csv_headers [ : idx ] + new_idxs + self . csv_headers [ idx + 1 : ] except ValueError , e : pass | Adds the mean experimental value associated with each analysis set to the dataframe row . | 221 | 16 |
13,143 | def compute_stability_classification ( self , predicted_data , record , dataframe_record ) : new_idxs = [ ] stability_classication_x_cutoff , stability_classication_y_cutoff = self . stability_classication_x_cutoff , self . stability_classication_y_cutoff for analysis_set in self . get_analysis_sets ( record ) : ddg_details = record [ 'DDG' ] [ analysis_set ] exp_ddg_fieldname = BenchmarkRun . get_analysis_set_fieldname ( 'Experimental' , analysis_set ) stability_classification_fieldname = BenchmarkRun . get_analysis_set_fieldname ( 'StabilityClassification' , analysis_set ) new_idxs . append ( stability_classification_fieldname ) dataframe_record [ stability_classification_fieldname ] = None if ddg_details : stability_classification = None if dataframe_record [ exp_ddg_fieldname ] != None : stability_classification = fraction_correct ( [ dataframe_record [ exp_ddg_fieldname ] ] , [ predicted_data [ self . ddg_analysis_type ] ] , x_cutoff = stability_classication_x_cutoff , y_cutoff = stability_classication_y_cutoff ) stability_classification = int ( stability_classification ) assert ( stability_classification == 0 or stability_classification == 1 ) dataframe_record [ stability_classification_fieldname ] = stability_classification # Update the CSV headers try : idx = self . csv_headers . index ( 'StabilityClassification' ) self . csv_headers = self . csv_headers [ : idx ] + new_idxs + self . csv_headers [ idx + 1 : ] except ValueError , e : pass | Calculate the stability classification for the analysis cases . Must be called after get_experimental_ddg_values . | 414 | 25 |
13,144 | def compute_absolute_error ( self , predicted_data , record , dataframe_record ) : new_idxs = [ ] for analysis_set in self . get_analysis_sets ( record ) : ddg_details = record [ 'DDG' ] [ analysis_set ] exp_ddg_fieldname = BenchmarkRun . get_analysis_set_fieldname ( 'Experimental' , analysis_set ) absolute_error_fieldname = BenchmarkRun . get_analysis_set_fieldname ( 'AbsoluteError' , analysis_set ) new_idxs . append ( absolute_error_fieldname ) dataframe_record [ absolute_error_fieldname ] = None if ddg_details and predicted_data [ self . ddg_analysis_type ] != None : absolute_error = abs ( dataframe_record [ exp_ddg_fieldname ] - predicted_data [ self . ddg_analysis_type ] ) dataframe_record [ absolute_error_fieldname ] = absolute_error # Update the CSV headers try : idx = self . csv_headers . index ( 'AbsoluteError' ) self . csv_headers = self . csv_headers [ : idx ] + new_idxs + self . csv_headers [ idx + 1 : ] except ValueError , e : pass | Calculate the absolute error for the analysis cases . Must be called after get_experimental_ddg_values . | 290 | 25 |
13,145 | def add_result ( self , values ) : idx = [ values [ 'host' ] ] for gid in self . key_gids [ 1 : ] : idx . append ( values [ gid ] ) idx = tuple ( idx ) try : self . results [ idx ] += 1 except KeyError : self . results [ idx ] = 1 self . _last_idx = idx | Add a tuple or increment the value of an existing one in the rule results dictionary . | 89 | 17 |
13,146 | def increase_last ( self , k ) : idx = self . _last_idx if idx is not None : self . results [ idx ] += k | Increase the last result by k . | 36 | 7 |
13,147 | def parse_rules ( self ) : # Load patterns: an app is removed when has no defined patterns. try : rule_options = self . config . items ( 'rules' ) except configparser . NoSectionError : raise LogRaptorConfigError ( "the app %r has no defined rules!" % self . name ) rules = [ ] for option , value in rule_options : pattern = value . replace ( '\n' , '' ) # Strip newlines for multi-line declarations if not self . args . filters : # No filters case: substitute the filter fields with the corresponding patterns. pattern = string . Template ( pattern ) . safe_substitute ( self . fields ) rules . append ( AppRule ( option , pattern , self . args ) ) continue for filter_group in self . args . filters : _pattern , filter_keys = exact_sub ( pattern , filter_group ) _pattern = string . Template ( _pattern ) . safe_substitute ( self . fields ) if len ( filter_keys ) >= len ( filter_group ) : rules . append ( AppRule ( option , _pattern , self . args , filter_keys ) ) elif self . _thread : rules . append ( AppRule ( option , _pattern , self . args ) ) return rules | Add a set of rules to the app dividing between filter and other rule set | 273 | 15 |
13,148 | def increase_last ( self , k ) : rule = self . _last_rule if rule is not None : rule . increase_last ( k ) | Increase the counter of the last matched rule by k . | 32 | 11 |
13,149 | def get_sections_by_delegate_and_term ( person , term , future_terms = 0 , include_secondaries = True , transcriptable_course = 'yes' , delete_flag = [ 'active' ] ) : data = _get_sections_by_person_and_term ( person , term , "GradeSubmissionDelegate" , include_secondaries , future_terms , transcriptable_course , delete_flag ) return _json_to_sectionref ( data ) | Returns a list of uw_sws . models . SectionReference objects for the passed grade submission delegate and term . | 107 | 24 |
13,150 | def get_sections_by_curriculum_and_term ( curriculum , term ) : url = "{}?{}" . format ( section_res_url_prefix , urlencode ( [ ( "curriculum_abbreviation" , curriculum . label , ) , ( "quarter" , term . quarter . lower ( ) , ) , ( "year" , term . year , ) , ] ) ) return _json_to_sectionref ( get_resource ( url ) ) | Returns a list of uw_sws . models . SectionReference objects for the passed curriculum and term . | 105 | 22 |
13,151 | def get_sections_by_building_and_term ( building , term ) : url = "{}?{}" . format ( section_res_url_prefix , urlencode ( [ ( "quarter" , term . quarter . lower ( ) , ) , ( "facility_code" , building , ) , ( "year" , term . year , ) , ] ) ) return _json_to_sectionref ( get_resource ( url ) ) | Returns a list of uw_sws . models . SectionReference objects for the passed building and term . | 98 | 22 |
13,152 | def _json_to_sectionref ( data ) : section_term = None sections = [ ] for section_data in data . get ( "Sections" , [ ] ) : if ( section_term is None or section_data [ "Year" ] != section_term . year or section_data [ "Quarter" ] != section_term . quarter ) : section_term = get_term_by_year_and_quarter ( section_data [ "Year" ] , section_data [ "Quarter" ] ) section = SectionReference ( term = section_term , curriculum_abbr = section_data [ "CurriculumAbbreviation" ] , course_number = section_data [ "CourseNumber" ] , section_id = section_data [ "SectionID" ] , url = section_data [ "Href" ] ) sections . append ( section ) return sections | Returns a list of SectionReference object created from the passed json data . | 193 | 14 |
13,153 | def get_section_by_url ( url , include_instructor_not_on_time_schedule = True ) : if not course_url_pattern . match ( url ) : raise InvalidSectionURL ( url ) return _json_to_section ( get_resource ( url ) , include_instructor_not_on_time_schedule = ( include_instructor_not_on_time_schedule ) ) | Returns a uw_sws . models . Section object for the passed section url . | 96 | 18 |
13,154 | def get_section_by_label ( label , include_instructor_not_on_time_schedule = True ) : validate_section_label ( label ) url = "{}/{}.json" . format ( course_res_url_prefix , encode_section_label ( label ) ) return get_section_by_url ( url , include_instructor_not_on_time_schedule ) | Returns a uw_sws . models . Section object for the passed section label . | 92 | 18 |
13,155 | def get_linked_sections ( section , include_instructor_not_on_time_schedule = True ) : linked_sections = [ ] for url in section . linked_section_urls : section = get_section_by_url ( url , include_instructor_not_on_time_schedule ) linked_sections . append ( section ) return linked_sections | Returns a list of uw_sws . models . Section objects representing linked sections for the passed section . | 84 | 22 |
13,156 | def get_joint_sections ( section , include_instructor_not_on_time_schedule = True ) : joint_sections = [ ] for url in section . joint_section_urls : section = get_section_by_url ( url , include_instructor_not_on_time_schedule ) joint_sections . append ( section ) return joint_sections | Returns a list of uw_sws . models . Section objects representing joint sections for the passed section . | 85 | 22 |
13,157 | def get_chain_details_by_related_pdb_chains ( self , pdb_id , chain_id , pfam_accs ) : if not pfam_accs : return None associated_pdb_chains = set ( ) pfam_api = self . get_pfam_api ( ) for pfam_acc in pfam_accs : associated_pdb_chains = associated_pdb_chains . union ( pfam_api . get_pdb_chains_from_pfam_accession_number ( pfam_acc ) ) hits = [ ] #class_count = {} pfam_scop_mapping = { } for pdb_chain_pair in associated_pdb_chains : ass_pdb_id , ass_chain_id = pdb_chain_pair [ 0 ] , pdb_chain_pair [ 1 ] hit = self . get_chain_details ( ass_pdb_id , chain = ass_chain_id , internal_function_call = True , pfam_scop_mapping = pfam_scop_mapping ) if hit and hit . get ( 'chains' ) : assert ( len ( hit [ 'chains' ] ) == 1 ) hits . append ( hit [ 'chains' ] [ ass_chain_id ] ) #for k, v in hit.iteritems(): #class_count[v['sccs']] = class_count.get(v['sccs'], 0) #class_count[v['sccs']] += 1 #print(' %s, %s: %s' % (v['pdb_id'], k, v['sccs'])) #pprint.pprint(class_count) allowed_scop_domains = map ( int , map ( set . intersection , pfam_scop_mapping . values ( ) ) [ 0 ] ) allowed_scop_domains = list ( set ( ( allowed_scop_domains or [ ] ) + ( self . get_sunid_for_pfam_accs ( pfam_accs ) or [ ] ) ) ) filtered_hits = [ ] print ( pfam_accs ) print ( allowed_scop_domains ) print ( '%d hits' % len ( hits ) ) for hit in hits : domains_to_ignore = [ ] for k , v in hit [ 'domains' ] . iteritems ( ) : if v [ 'sunid' ] in allowed_scop_domains : filtered_hits . append ( v ) print ( '%d filtered_hits' % len ( filtered_hits ) ) if not filtered_hits : return None d = self . get_basic_pdb_chain_information ( pdb_id , chain_id ) d . update ( self . get_common_fields ( filtered_hits ) ) d . update ( dict ( SCOPe_sources = 'Pfam + SCOPe' , SCOPe_search_fields = 'Pfam + link_pdb.pdb_chain_id' , SCOPe_trust_level = 3 ) ) # Add the lowest common classification over all related Pfam families for k , v in sorted ( self . levels . iteritems ( ) ) : d [ v ] = None d . update ( dict ( self . get_common_hierarchy ( filtered_hits ) ) ) return d | Returns a dict of SCOPe details using info This returns Pfam - level information for a PDB chain i . e . no details on the protein species or domain will be returned . If there are SCOPe entries for the associated Pfam accession numbers which agree then this function returns pretty complete information . | 754 | 63 |
13,158 | def recall_service ( self , service ) : if not isinstance ( service , Service ) : raise TypeError ( "service must be of type Service." ) logger . warning ( "The deployment for {0} on {1} failed starting the rollback." . format ( service . alias , self . url . geturl ( ) ) ) def anonymous ( anonymous_service ) : if not isinstance ( anonymous_service , Service ) : raise TypeError ( "service must be an instance of Service." ) containers = self . find_previous_service_containers ( anonymous_service ) if containers : for name in list ( anonymous_service . containers . keys ( ) ) : del anonymous_service . containers [ name ] anonymous_service . cargo . delete ( ) for name , container in six . iteritems ( containers ) : # TODO: add function to container obj to see if its running. if container . state ( ) . get ( 'running' ) : logger . info ( "is already running... Might want to investigate." , extra = { 'formatter' : 'container' , 'container' : container . name } ) else : if container . start ( ) : logger . info ( "is restarted and healthy." , extra = { 'formatter' : 'container' , 'container' : container . name } ) else : logger . error ( "failed to start." , extra = { 'formatter' : 'container' , 'container' : container . name } ) container . dump_logs ( ) raise Exception ( "The deployment for {0} on {1} went horribly wrong" . format ( container . name , self . url . geturl ( ) ) ) self . _service_map ( service , anonymous , descending = False ) | This method assumes that its a roll back during a deployment . If not used during a deployment session | 371 | 19 |
13,159 | def clean_up_dangling_images ( self ) : cargoes = Image . all ( client = self . _client_session , filters = { 'dangling' : True } ) for id , cargo in six . iteritems ( cargoes ) : logger . info ( "Removing dangling image: {0}" . format ( id ) ) cargo . delete ( ) | Clean up all dangling images . | 80 | 6 |
13,160 | def offload_all_service_containers ( self , service ) : def anonymous ( anonymous_service ) : if not isinstance ( anonymous_service , Service ) : raise TypeError ( "service must be an instance of Service." ) containers = self . find_service_containers ( anonymous_service ) if containers : logger . info ( "Deleting service: {0} containers." . format ( anonymous_service . name ) ) for container in six . itervalues ( containers ) : container . delete ( ) self . _service_map ( service , anonymous , descending = True ) | Deletes all containers related to the service . | 126 | 9 |
13,161 | def _container_registration ( self , alias ) : containers = Container . find_by_name ( self . _client_session , alias ) def validate_name ( name ) : valid = True if name in containers : valid = False return valid count = 1 container_name = "{0}-0{1}" . format ( alias , count ) while not validate_name ( container_name ) : count += 1 container_index = count if count > 10 else "0{0}" . format ( count ) container_name = "{0}-{1}" . format ( alias , container_index ) return container_name | Check for an available name and return that to the caller . | 132 | 12 |
13,162 | def teardown_databases ( self , old_config , options ) : if len ( old_config ) > 1 : old_names , mirrors = old_config else : old_names = old_config for connection , old_name , destroy in old_names : if destroy : connection . creation . destroy_test_db ( old_name , options [ 'verbosity' ] ) | Destroys all the non - mirror databases . | 83 | 10 |
13,163 | def oembed ( url , class_ = "" ) : o = "<a href=\"{url}\" class=\"oembed {class_}\" ></a>" . format ( url = url , class_ = class_ ) return Markup ( o ) | Create OEmbed link | 54 | 5 |
13,164 | def img_src ( url , class_ = "" , responsive = False , lazy_load = False , id_ = "" ) : if not url . startswith ( "http://" ) and not url . startswith ( "https://" ) : url = static_url ( url ) data_src = "" if responsive : class_ += " responsive" if lazy_load : data_src = url # 1x1 image url = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNgYAAAAAMAASsJTYQAAAAASUVORK5CYII=" class_ += " lazy" img = "<img src=\"{src}\" class=\"{class_}\" id=\"{id_}\" data-src={data_src}>" . format ( src = url , class_ = class_ , id_ = id_ , data_src = data_src ) return Markup ( img ) | Create an image src | 230 | 4 |
13,165 | def give_dots_yield ( R , r , r_ , resolution = 2 * PI / 1000 , spins = 50 ) : def x ( theta ) : return ( R - r ) * math . cos ( theta ) + r_ * math . cos ( ( R - r ) / r * theta ) def y ( theta ) : return ( R - r ) * math . sin ( theta ) - r_ * math . sin ( ( R - r ) / r * theta ) theta = 0.0 while theta < 2 * PI * spins : yield ( x ( theta ) , y ( theta ) ) theta += resolution | Generate Spirograph dots without numpy using yield . | 143 | 13 |
13,166 | def give_dots ( R , r , r_ , resolution = 2 * PI / 1000 , spins = 50 ) : thetas = np . arange ( 0 , 2 * PI * spins , resolution ) Rr = R - r x = Rr * np . cos ( thetas ) + r_ * np . cos ( Rr / r * thetas ) y = Rr * np . sin ( thetas ) - r_ * np . sin ( Rr / r * thetas ) return x , y | Generate Spirograph dots with numpy . | 115 | 11 |
13,167 | def spiro_image ( R , r , r_ , resolution = 2 * PI / 1000 , spins = 50 , size = [ 32 , 32 ] ) : x , y = give_dots ( 200 , r , r_ , spins = 20 ) xy = np . array ( [ x , y ] ) . T xy = np . array ( np . around ( xy ) , dtype = np . int64 ) xy = xy [ ( xy [ : , 0 ] >= - 250 ) & ( xy [ : , 1 ] >= - 250 ) & ( xy [ : , 0 ] < 250 ) & ( xy [ : , 1 ] < 250 ) ] xy = xy + 250 img = np . ones ( [ 500 , 500 ] , dtype = np . uint8 ) img [ : ] = 255 img [ xy [ : , 0 ] , xy [ : , 1 ] ] = 0 img = misc . imresize ( img , size ) fimg = img / 255.0 return fimg | Create image with given Spirograph parameters using numpy and scipy . | 224 | 17 |
13,168 | def html ( text , lazy_images = False ) : extensions = [ 'markdown.extensions.nl2br' , 'markdown.extensions.sane_lists' , 'markdown.extensions.toc' , 'markdown.extensions.tables' , OEmbedExtension ( ) ] if lazy_images : extensions . append ( LazyImageExtension ( ) ) return markdown . markdown ( text , extensions = extensions ) | To render a markdown format text into HTML . | 99 | 10 |
13,169 | def run ( self , root ) : self . markdown . images = [ ] for image in root . getiterator ( "img" ) : self . markdown . images . append ( image . attrib [ "src" ] ) | Find all images and append to markdown . images . | 49 | 11 |
13,170 | def dict_map ( function , dictionary ) : return dict ( ( key , function ( value ) ) for key , value in dictionary . items ( ) ) | dict_map is much like the built - in function map . It takes a dictionary and applys a function to the values of that dictionary returning a new dictionary with the mapped values in the original keys . | 32 | 41 |
13,171 | def sorted_items ( d , key = __identity , reverse = False ) : # wrap the key func so it operates on the first element of each item def pairkey_key ( item ) : return key ( item [ 0 ] ) return sorted ( d . items ( ) , key = pairkey_key , reverse = reverse ) | Return the items of the dictionary sorted by the keys | 70 | 10 |
13,172 | def invert_map ( map ) : res = dict ( ( v , k ) for k , v in map . items ( ) ) if not len ( res ) == len ( map ) : raise ValueError ( 'Key conflict in inverted mapping' ) return res | Given a dictionary return another dictionary with keys and values switched . If any of the values resolve to the same key raises a ValueError . | 55 | 27 |
13,173 | def matching_key_for ( self , key ) : try : return next ( e_key for e_key in self . keys ( ) if e_key == key ) except StopIteration : raise KeyError ( key ) | Given a key return the actual key stored in self that matches . Raise KeyError if the key isn t found . | 48 | 23 |
13,174 | def backup ( backup_filename = None ) : timestamp = time . strftime ( "%Y-%m-%d-%H-%M-%S" , time . gmtime ( ) ) if not backup_filename : if not os . path . isdir ( BACKUPS_PATH ) : print 'Need to create {}' . format ( BACKUPS_PATH ) os . makedirs ( BACKUPS_PATH , 0700 ) backup_filename = '{backups_path}/cozy-{timestamp}.tgz' . format ( backups_path = BACKUPS_PATH , timestamp = timestamp ) elif os . path . exists ( backup_filename ) : print 'Backup file already exists: {}' . format ( backup_filename ) return couchdb_path = _get_couchdb_path ( ) cmd = 'tar cvzf {backup_filename}' cmd += ' --exclude stack.token' cmd += ' --exclude couchdb.login' cmd += ' --exclude self-hosting.json' cmd += ' /etc/cozy /usr/local/var/cozy {couchdb_path}/cozy.couch' cmd = cmd . format ( backup_filename = backup_filename , couchdb_path = couchdb_path ) helpers . cmd_exec ( cmd , show_output = True ) print 'Backup file: {}' . format ( backup_filename ) | Backup a Cozy | 315 | 5 |
13,175 | def get_config ( ) : from boiler . migrations . config import MigrationsConfig # used for errors map = dict ( path = 'MIGRATIONS_PATH' , db_url = 'SQLALCHEMY_DATABASE_URI' , metadata = 'SQLAlchemy metadata' ) app = bootstrap . get_app ( ) params = dict ( ) params [ 'path' ] = app . config . get ( map [ 'path' ] , 'migrations' ) params [ 'db_url' ] = app . config . get ( map [ 'db_url' ] ) params [ 'metadata' ] = db . metadata for param , value in params . items ( ) : if not value : msg = 'Configuration error: [{}] is undefined' raise Exception ( msg . format ( map [ param ] ) ) config = MigrationsConfig ( * * params ) return config | Prepare and return alembic config These configurations used to live in alembic config initialiser but that just tight coupling . Ideally we should move that to userspace and find a way to pass these into alembic commands . | 195 | 47 |
13,176 | def init ( ) : try : config = get_config ( ) print ( config . dir ) alembic_command . init ( config , config . dir , 'project' ) except CommandError as e : click . echo ( red ( str ( e ) ) ) | Initialize new migrations directory | 56 | 6 |
13,177 | def revision ( revision , path , branch_label , splice , head , sql , autogenerate , message ) : alembic_command . revision ( config = get_config ( ) , rev_id = revision , version_path = path , branch_label = branch_label , splice = splice , head = head , sql = sql , autogenerate = autogenerate , message = message ) | Create new revision file | 90 | 4 |
13,178 | def merge ( revision , branch_label , message , list_revisions = '' ) : alembic_command . merge ( config = get_config ( ) , revisions = list_revisions , message = message , branch_label = branch_label , rev_id = revision ) | Merge two revision together create new revision file | 60 | 9 |
13,179 | def up ( tag , sql , revision ) : alembic_command . upgrade ( config = get_config ( ) , revision = revision , sql = sql , tag = tag ) | Upgrade to revision | 38 | 3 |
13,180 | def down ( tag , sql , revision ) : alembic_command . downgrade ( config = get_config ( ) , revision = revision , sql = sql , tag = tag ) | Downgrade to revision | 38 | 4 |
13,181 | def history ( verbose , range ) : alembic_command . history ( config = get_config ( ) , rev_range = range , verbose = verbose ) | List revision changesets chronologically | 37 | 6 |
13,182 | def heads ( resolve , verbose ) : alembic_command . heads ( config = get_config ( ) , verbose = verbose , resolve_dependencies = resolve ) | Show available heads | 38 | 3 |
13,183 | def stamp ( revision , sql , tag ) : alembic_command . stamp ( config = get_config ( ) , revision = revision , sql = sql , tag = tag ) | Stamp db to given revision without migrating | 38 | 8 |
13,184 | def get_or_create_in_transaction ( tsession , model , values , missing_columns = [ ] , variable_columns = [ ] , updatable_columns = [ ] , only_use_supplied_columns = False , read_only = False ) : values = copy . deepcopy ( values ) # todo: this does not seem to be necessary since we do not seem to be writing fieldnames = [ c . name for c in list ( sqlalchemy_inspect ( model ) . columns ) ] for c in missing_columns : fieldnames . remove ( c ) for c in updatable_columns : fieldnames . remove ( c ) for c in variable_columns : if c in fieldnames : fieldnames . remove ( c ) if only_use_supplied_columns : fieldnames = sorted ( set ( fieldnames ) . intersection ( set ( values . keys ( ) ) ) ) else : unexpected_fields = set ( values . keys ( ) ) . difference ( set ( fieldnames ) ) . difference ( set ( variable_columns ) ) . difference ( set ( updatable_columns ) ) if unexpected_fields : raise Exception ( "The fields '{0}' were passed but not found in the schema for table {1}." . format ( "', '" . join ( sorted ( unexpected_fields ) ) , model . __dict__ [ '__tablename__' ] ) ) pruned_values = { } for k in set ( values . keys ( ) ) . intersection ( set ( fieldnames ) ) : v = values [ k ] pruned_values [ k ] = v instance = tsession . query ( model ) . filter_by ( * * pruned_values ) if instance . count ( ) > 1 : raise Exception ( 'Multiple records were found with the search criteria.' ) instance = instance . first ( ) if instance : if read_only == False : for c in updatable_columns : setattr ( instance , c , values [ c ] ) tsession . flush ( ) return instance else : if read_only == False : if sorted ( pruned_values . keys ( ) ) != sorted ( fieldnames ) : # When adding new records, we require that all necessary fields are present raise Exception ( 'Some required fields are missing: {0}. Either supply these fields or add them to the missing_columns list.' . format ( set ( fieldnames ) . difference ( pruned_values . keys ( ) ) ) ) instance = model ( * * pruned_values ) tsession . add ( instance ) tsession . flush ( ) return instance return None | Uses the SQLAlchemy model to retrieve an existing record based on the supplied field values or if there is no existing record to create a new database record . | 565 | 32 |
13,185 | def get_or_create_in_transaction_wrapper ( tsession , model , values , missing_columns = [ ] , variable_columns = [ ] , updatable_columns = [ ] , only_use_supplied_columns = False , read_only = False ) : return get_or_create_in_transaction ( tsession , model , values , missing_columns = missing_columns , variable_columns = variable_columns , updatable_columns = updatable_columns , only_use_supplied_columns = only_use_supplied_columns , read_only = read_only ) | This function can be used to determine which calling method is spending time in get_or_create_in_transaction when profiling the database API . Switch out calls to get_or_create_in_transaction to get_or_create_in_transaction_wrapper in the suspected functions to determine where the pain lies . | 144 | 68 |
13,186 | def get_weight ( self , rule ) : if not issubclass ( rule . __class__ , ( Rule , RuleLeaf ) ) : raise TypeError ( "Rule to get weight ({}) is not subclass " "of {} or {}." . format ( rule , Rule , RuleLeaf ) ) try : ind = self . _R . index ( rule ) return self . _W [ ind ] except : return None | Get weight for rule . | 89 | 5 |
13,187 | def evaluate ( self , artifact ) : s = 0 w = 0.0 if len ( self . R ) == 0 : return 0.0 , None for i in range ( len ( self . R ) ) : s += self . R [ i ] ( artifact ) * self . W [ i ] w += abs ( self . W [ i ] ) if w == 0.0 : return 0.0 , None return s / w , None | r Evaluate artifact with agent s current rules and weights . | 93 | 12 |
13,188 | def _init_dates ( self ) : if self . total_transactions == 0 : return None self . epoch_start = Result . select ( Result . epoch ) . order_by ( Result . epoch . asc ( ) ) . limit ( 1 ) . get ( ) . epoch self . epoch_finish = Result . select ( Result . epoch ) . order_by ( Result . epoch . desc ( ) ) . limit ( 1 ) . get ( ) . epoch self . start_datetime = time . strftime ( '%Y-%m-%d %H:%M:%S' , time . localtime ( self . epoch_start ) ) self . finish_datetime = time . strftime ( '%Y-%m-%d %H:%M:%S' , time . localtime ( self . epoch_finish ) ) | Initialize all dates properties | 185 | 5 |
13,189 | def _init_dataframes ( self ) : df = pd . read_sql_query ( "SELECT elapsed, epoch, scriptrun_time, custom_timers FROM result ORDER BY epoch ASC" , db . get_conn ( ) ) self . _get_all_timers ( df ) self . main_results = self . _get_processed_dataframe ( df ) # create all custom timers dataframes for key , value in six . iteritems ( self . _timers_values ) : df = pd . DataFrame ( value , columns = [ 'epoch' , 'scriptrun_time' ] ) df . index = pd . to_datetime ( df [ 'epoch' ] , unit = 's' ) timer_results = self . _get_processed_dataframe ( df ) self . timers_results [ key ] = timer_results # clear memory del self . _timers_values | Initialise the main dataframe for the results and the custom timers dataframes | 201 | 15 |
13,190 | def _get_all_timers ( self , dataframe ) : s = dataframe [ 'custom_timers' ] . apply ( json . loads ) s . index = dataframe [ 'epoch' ] for index , value in s . iteritems ( ) : if not value : continue for key , value in six . iteritems ( value ) : self . _timers_values [ key ] . append ( ( index , value ) ) self . total_timers += 1 del dataframe [ 'custom_timers' ] del s | Get all timers and set them in the _timers_values property | 116 | 14 |
13,191 | def _get_processed_dataframe ( self , dataframe ) : dataframe . index = pd . to_datetime ( dataframe [ 'epoch' ] , unit = 's' , utc = True ) del dataframe [ 'epoch' ] summary = dataframe . describe ( percentiles = [ .80 , .90 , .95 ] ) . transpose ( ) . loc [ 'scriptrun_time' ] df_grp = dataframe . groupby ( pd . TimeGrouper ( '{}S' . format ( self . interval ) ) ) df_final = df_grp . apply ( lambda x : x . describe ( percentiles = [ .80 , .90 , .95 ] ) [ 'scriptrun_time' ] ) return { "raw" : dataframe . round ( 2 ) , "compiled" : df_final . round ( 2 ) , "summary" : summary . round ( 2 ) } | Generate required dataframe for results from raw dataframe | 207 | 11 |
13,192 | def _init_turrets ( self ) : for turret in Turret . select ( ) : self . turrets . append ( turret . to_dict ( ) ) | Setup data from database | 34 | 4 |
13,193 | def compile_results ( self ) : self . _init_dataframes ( ) self . total_transactions = len ( self . main_results [ 'raw' ] ) self . _init_dates ( ) | Compile all results for the current test | 45 | 8 |
13,194 | def centroid ( X ) : C = np . sum ( X , axis = 0 ) / len ( X ) return C | Calculate the centroid from a matrix X | 26 | 10 |
13,195 | def is_valid ( self , instance ) : errors = self . errors ( instance ) if isinstance ( errors , list ) : return not any ( errors ) return not bool ( errors ) | Return True if no errors are raised when validating instance . | 39 | 12 |
13,196 | def _validate ( self , data ) : errors = { } # if the validator is not enabled, return the empty error dict if not self . _enabled : return errors for field in self . validators : field_errors = [ ] for validator in self . validators [ field ] : try : validator ( data . get ( field , None ) ) except ValidationError as e : field_errors += e . messages # if there were errors, cast to ErrorList for output convenience if field_errors : errors [ field ] = ErrorList ( field_errors ) return errors | Helper to run validators on the field data . | 123 | 10 |
13,197 | def errors ( self , instance ) : if isinstance ( instance , dict ) : return self . _validate ( instance ) elif isinstance ( instance , forms . BaseForm ) : if instance . is_bound and instance . is_valid ( ) : return self . _validate ( instance . cleaned_data ) return self . _validate ( dict ( [ ( f , instance . initial . get ( f , instance [ f ] . value ( ) ) ) for f in self . validators ] ) ) elif isinstance ( instance , formsets . BaseFormSet ) : if instance . can_delete : validate_forms = [ form for form in instance . initial_forms if not instance . _should_delete_form ( form ) ] + [ form for form in instance . extra_forms if ( form . has_changed ( ) and not instance . _should_delete_form ( form ) ) ] return [ self . errors ( f ) for f in validate_forms ] else : validate_forms = instance . initial_forms + [ form for form in instance . extra_forms if form . has_changed ( ) ] return [ self . errors ( f ) for f in validate_forms ] elif isinstance ( instance , models . Model ) : return self . _validate ( dict ( [ ( f , getattr ( instance , f ) ) for f in self . validators ] ) ) | Run all field validators and return a dict of errors . | 297 | 12 |
13,198 | def queryset_formatter ( queryset ) : return Markup ( base_list_formatter ( None , [ '<a href="{}">{}</a>' . format ( u . get_admin_url ( _external = True ) , u ) for u in queryset ] , ) ) | This is used for custom detail fields returning a QuerySet of admin objects . | 70 | 15 |
13,199 | def qs_field ( model_class , field , filters = None , formatter = queryset_formatter , manager_name = 'objects' , ) : if filters is None : filters = { } def _ ( view , context , _model , name ) : filters [ field ] = _model # e.g. students: user # e.g. User.objects, User.deleted_objects manager = getattr ( model_class , manager_name ) return formatter ( manager ( * * filters ) ) return _ | Show computed fields based on QuerySet s . | 114 | 9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.