idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
6,000 | def get ( self ) : ret_list = [ ] if hasattr ( self , "font" ) : ret_list . append ( self . font ) if hasattr ( self , "size" ) : ret_list . append ( self . size ) if hasattr ( self , "text" ) : ret_list . append ( self . text ) return ret_list | method to fetch all contents as a list | 79 | 8 |
6,001 | def extract_by_prefix_surfix ( text , prefix , surfix , minlen = None , maxlen = None , include = False ) : if minlen is None : minlen = 0 if maxlen is None : maxlen = 2 ** 30 pattern = r"""(?<=%s)[\s\S]{%s,%s}?(?=%s)""" % ( prefix , minlen , maxlen , surfix ) if include : return [ prefix + s + surfix for s in re . findall ( pattern , text ) ] else : return re . findall ( pattern , text ) | Extract the text in between a prefix and surfix . It use non - greedy match . | 134 | 19 |
6,002 | def extract_number ( text ) : result = list ( ) chunk = list ( ) valid_char = set ( ".1234567890" ) for char in text : if char in valid_char : chunk . append ( char ) else : result . append ( "" . join ( chunk ) ) chunk = list ( ) result . append ( "" . join ( chunk ) ) result_new = list ( ) for number in result : if "." in number : try : result_new . append ( float ( number ) ) except : pass else : try : result_new . append ( int ( number ) ) except : pass return result_new | Extract digit character from text . | 134 | 7 |
6,003 | def extract_email ( text ) : result = list ( ) for tp in re . findall ( _regex_extract_email , text . lower ( ) ) : for email in tp : if re . match ( _regex_validate_email , email ) : result . append ( email ) return result | Extract email from text . | 69 | 6 |
6,004 | def sign ( self , headers : Mapping , method = None , path = None ) : required_headers = self . header_list message = generate_message ( required_headers , headers , method , path ) signature = encode_string ( self . _signer . sign ( message ) , 'base64' ) ret_headers = multidict . CIMultiDict ( headers ) ret_headers [ 'Authorization' ] = self . _signature_tpl % signature . decode ( 'ascii' ) return ret_headers | Add Signature Authorization header to case - insensitive header dict . | 116 | 11 |
6,005 | async def verify ( self , headers : Mapping , method = None , path = None ) : if not 'authorization' in headers : return False auth_type , auth_params = parse_authorization_header ( headers [ 'authorization' ] ) if auth_type . lower ( ) != 'signature' : return False for param in ( 'algorithm' , 'keyId' , 'signature' ) : if param not in auth_params : raise VerifierException ( "Unsupported HTTP signature, missing '{}'" . format ( param ) ) auth_headers = ( auth_params . get ( 'headers' ) or 'date' ) . lower ( ) . strip ( ) . split ( ) missing_reqd = set ( self . _required_headers ) - set ( auth_headers ) if missing_reqd : error_headers = ', ' . join ( missing_reqd ) raise VerifierException ( 'One or more required headers not provided: {}' . format ( error_headers ) ) key_id , algo = auth_params [ 'keyId' ] , auth_params [ 'algorithm' ] if not self . _handlers . supports ( algo ) : raise VerifierException ( "Unsupported HTTP signature algorithm '{}'" . format ( algo ) ) pubkey = await self . _key_finder . find_key ( key_id , algo ) if not pubkey : raise VerifierException ( "Cannot locate public key for '{}'" . format ( key_id ) ) LOGGER . debug ( "Got %s public key for '%s': %s" , algo , key_id , pubkey ) handler = self . _handlers . create_verifier ( algo , pubkey ) message = generate_message ( auth_headers , headers , method , path ) signature = auth_params [ 'signature' ] raw_signature = decode_string ( signature , 'base64' ) if handler . verify ( message , raw_signature ) : return { 'verified' : True , 'algorithm' : algo , 'headers' : auth_headers , 'keyId' : key_id , 'key' : pubkey , 'signature' : signature } raise VerifierException ( "Signature could not be verified for keyId '{}'" . format ( key_id ) ) | Parse Signature Authorization header and verify signature | 510 | 8 |
6,006 | def docpie ( self , argv = None ) : token = self . _prepare_token ( argv ) # check first, raise after # so `-hwhatever` can trigger `-h` first self . check_flag_and_handler ( token ) if token . error is not None : # raise DocpieExit('%s\n\n%s' % (token.error, help_msg)) self . exception_handler ( token . error ) try : result , dashed = self . _match ( token ) except DocpieExit as e : self . exception_handler ( e ) # if error is not None: # self.exception_handler(error) value = result . get_value ( self . appeared_only , False ) self . clear ( ) self . update ( value ) if self . appeared_only : self . _drop_non_appeared ( ) logger . debug ( 'get all matched value %s' , self ) rest = list ( self . usages ) # a copy rest . remove ( result ) self . _add_rest_value ( rest ) logger . debug ( 'merged rest values, now %s' , self ) self . _add_option_value ( ) self . _dashes_value ( dashed ) return dict ( self ) | match the argv for each usages return dict . | 276 | 11 |
6,007 | def clone_exception ( error , args ) : new_error = error . __class__ ( * args ) new_error . __dict__ = error . __dict__ return new_error | return a new cloned error | 41 | 6 |
6,008 | def to_dict ( self ) : # cls, self): config = { 'stdopt' : self . stdopt , 'attachopt' : self . attachopt , 'attachvalue' : self . attachvalue , 'auto2dashes' : self . auto2dashes , 'case_sensitive' : self . case_sensitive , 'namedoptions' : self . namedoptions , 'appearedonly' : self . appeared_only , 'optionsfirst' : self . options_first , 'option_name' : self . option_name , 'usage_name' : self . usage_name , 'name' : self . name , 'help' : self . help , 'version' : self . version } text = { 'doc' : self . doc , 'usage_text' : self . usage_text , 'option_sections' : self . option_sections , } # option = [convert_2_dict(x) for x in self.options] option = { } for title , options in self . options . items ( ) : option [ title ] = [ convert_2_dict ( x ) for x in options ] usage = [ convert_2_dict ( x ) for x in self . usages ] return { '__version__' : self . _version , '__class__' : 'Docpie' , '__config__' : config , '__text__' : text , 'option' : option , 'usage' : usage , 'option_names' : [ list ( x ) for x in self . opt_names ] , 'opt_names_required_max_args' : self . opt_names_required_max_args } | Convert Docpie into a JSONlizable dict . | 362 | 11 |
6,009 | def from_dict ( cls , dic ) : if '__version__' not in dic : raise ValueError ( 'Not support old docpie data' ) data_version = int ( dic [ '__version__' ] . replace ( '.' , '' ) ) this_version = int ( cls . _version . replace ( '.' , '' ) ) logger . debug ( 'this: %s, old: %s' , this_version , data_version ) if data_version < this_version : raise ValueError ( 'Not support old docpie data' ) assert dic [ '__class__' ] == 'Docpie' config = dic [ '__config__' ] help = config . pop ( 'help' ) version = config . pop ( 'version' ) option_name = config . pop ( 'option_name' ) usage_name = config . pop ( 'usage_name' ) self = cls ( None , * * config ) self . option_name = option_name self . usage_name = usage_name text = dic [ '__text__' ] self . doc = text [ 'doc' ] self . usage_text = text [ 'usage_text' ] self . option_sections = text [ 'option_sections' ] self . opt_names = [ set ( x ) for x in dic [ 'option_names' ] ] self . opt_names_required_max_args = dic [ 'opt_names_required_max_args' ] self . set_config ( help = help , version = version ) self . options = o = { } for title , options in dic [ 'option' ] . items ( ) : opt_ins = [ convert_2_object ( x , { } , self . namedoptions ) for x in options ] o [ title ] = opt_ins self . usages = [ convert_2_object ( x , self . options , self . namedoptions ) for x in dic [ 'usage' ] ] return self | Convert dict generated by convert_2_dict into Docpie instance | 438 | 14 |
6,010 | def set_config ( self , * * config ) : reinit = False if 'stdopt' in config : stdopt = config . pop ( 'stdopt' ) reinit = ( stdopt != self . stdopt ) self . stdopt = stdopt if 'attachopt' in config : attachopt = config . pop ( 'attachopt' ) reinit = reinit or ( attachopt != self . attachopt ) self . attachopt = attachopt if 'attachvalue' in config : attachvalue = config . pop ( 'attachvalue' ) reinit = reinit or ( attachvalue != self . attachvalue ) self . attachvalue = attachvalue if 'auto2dashes' in config : self . auto2dashes = config . pop ( 'auto2dashes' ) if 'name' in config : name = config . pop ( 'name' ) reinit = reinit or ( name != self . name ) self . name = name if 'help' in config : self . help = config . pop ( 'help' ) self . _set_or_remove_extra_handler ( self . help , ( '--help' , '-h' ) , self . help_handler ) if 'version' in config : self . version = config . pop ( 'version' ) self . _set_or_remove_extra_handler ( self . version is not None , ( '--version' , '-v' ) , self . version_handler ) if 'case_sensitive' in config : case_sensitive = config . pop ( 'case_sensitive' ) reinit = reinit or ( case_sensitive != self . case_sensitive ) self . case_sensitive = case_sensitive if 'optionsfirst' in config : self . options_first = config . pop ( 'optionsfirst' ) if 'appearedonly' in config : self . appeared_only = config . pop ( 'appearedonly' ) if 'namedoptions' in config : namedoptions = config . pop ( 'namedoptions' ) reinit = reinit or ( namedoptions != self . namedoptions ) self . namedoptions = namedoptions if 'extra' in config : self . extra . update ( self . _formal_extra ( config . pop ( 'extra' ) ) ) if config : # should be empty raise ValueError ( '`%s` %s not accepted key argument%s' % ( '`, `' . join ( config ) , 'is' if len ( config ) == 1 else 'are' , '' if len ( config ) == 1 else 's' ) ) if self . doc is not None and reinit : logger . warning ( 'You changed the config that requires re-initialized' ' `Docpie` object. Create a new one instead' ) self . _init ( ) | Shadow all the current config . | 595 | 6 |
6,011 | def find_flag_alias ( self , flag ) : for each in self . opt_names : if flag in each : result = set ( each ) # a copy result . remove ( flag ) return result return None | Return alias set of a flag ; return None if flag is not defined in Options . | 45 | 17 |
6,012 | def set_auto_handler ( self , flag , handler ) : assert flag . startswith ( '-' ) and flag not in ( '-' , '--' ) alias = self . find_flag_alias ( flag ) or [ ] self . extra [ flag ] = handler for each in alias : self . extra [ each ] = handler | Set pre - auto - handler for a flag . | 72 | 10 |
6,013 | def preview ( self , stream = sys . stdout ) : write = stream . write write ( ( '[Quick preview of Docpie %s]' % self . _version ) . center ( 80 , '=' ) ) write ( '\n' ) write ( ' sections ' . center ( 80 , '-' ) ) write ( '\n' ) write ( self . usage_text ) write ( '\n' ) option_sections = self . option_sections if option_sections : write ( '\n' ) write ( '\n' . join ( option_sections . values ( ) ) ) write ( '\n' ) write ( ' str ' . center ( 80 , '-' ) ) write ( '\n[%s]\n' % self . usage_name ) for each in self . usages : write ( ' %s\n' % each ) write ( '\n[Options:]\n\n' ) for title , sections in self . options . items ( ) : if title : full_title = '%s %s' % ( title , self . option_name ) else : full_title = self . option_name write ( full_title ) write ( '\n' ) for each in sections : write ( ' %s\n' % each ) write ( '\n' ) write ( ' repr ' . center ( 80 , '-' ) ) write ( '\n[%s]\n' % self . usage_name ) for each in self . usages : write ( ' %r\n' % each ) write ( '\n[Options:]\n\n' ) for title , sections in self . options . items ( ) : if title : full_title = '%s %s' % ( title , self . option_name ) else : full_title = self . option_name write ( full_title ) write ( '\n' ) for each in sections : write ( ' %r\n' % each ) write ( '\n' ) write ( ' auto handlers ' . center ( 80 , '-' ) ) write ( '\n' ) for key , value in self . extra . items ( ) : write ( '%s %s\n' % ( key , value ) ) | A quick preview of docpie . Print all the parsed object | 484 | 12 |
6,014 | def refresh_core ( self ) : self . log . info ( 'Sending out mass query for all attributes' ) for key in ATTR_CORE : self . query ( key ) | Query device for all attributes that exist regardless of power state . | 40 | 12 |
6,015 | def poweron_refresh ( self ) : if self . _poweron_refresh_successful : return else : self . refresh_all ( ) self . _loop . call_later ( 2 , self . poweron_refresh ) | Keep requesting all attributes until it works . | 51 | 8 |
6,016 | def refresh_all ( self ) : self . log . info ( 'refresh_all' ) for key in LOOKUP : self . query ( key ) | Query device for all attributes that are known . | 33 | 9 |
6,017 | def connection_made ( self , transport ) : self . log . info ( 'Connection established to AVR' ) self . transport = transport #self.transport.set_write_buffer_limits(0) limit_low , limit_high = self . transport . get_write_buffer_limits ( ) self . log . debug ( 'Write buffer limits %d to %d' , limit_low , limit_high ) self . command ( 'ECH1' ) self . refresh_core ( ) | Called when asyncio . Protocol establishes the network connection . | 107 | 12 |
6,018 | def data_received ( self , data ) : self . buffer += data . decode ( ) self . log . debug ( 'Received %d bytes from AVR: %s' , len ( self . buffer ) , self . buffer ) self . _assemble_buffer ( ) | Called when asyncio . Protocol detects received data from network . | 59 | 13 |
6,019 | def connection_lost ( self , exc ) : if exc is None : self . log . warning ( 'eof from receiver?' ) else : self . log . warning ( 'Lost connection to receiver: %s' , exc ) self . transport = None if self . _connection_lost_callback : self . _loop . call_soon ( self . _connection_lost_callback ) | Called when asyncio . Protocol loses the network connection . | 81 | 12 |
6,020 | def _assemble_buffer ( self ) : self . transport . pause_reading ( ) for message in self . buffer . split ( ';' ) : if message != '' : self . log . debug ( 'assembled message ' + message ) self . _parse_message ( message ) self . buffer = "" self . transport . resume_reading ( ) return | Split up received data from device into individual commands . | 75 | 10 |
6,021 | def _populate_inputs ( self , total ) : total = total + 1 for input_number in range ( 1 , total ) : self . query ( 'ISN' + str ( input_number ) . zfill ( 2 ) ) | Request the names for all active configured inputs on the device . | 52 | 12 |
6,022 | def formatted_command ( self , command ) : command = command command = command . encode ( ) self . log . debug ( '> %s' , command ) try : self . transport . write ( command ) time . sleep ( 0.01 ) except : self . log . warning ( 'No transport found, unable to send command' ) | Issue a raw formatted command to the device . | 71 | 9 |
6,023 | def dump_rawdata ( self ) : if hasattr ( self , 'transport' ) : attrs = vars ( self . transport ) return ', ' . join ( "%s: %s" % item for item in attrs . items ( ) ) | Return contents of transport object for debugging forensics . | 55 | 10 |
6,024 | def add_upsert ( self , value , criteria ) : value = value . strip ( ) v = value . lower ( ) self . lower_val_to_val [ v ] = value criteria_array = self . upserts . get ( v ) if criteria_array is None : criteria_array = [ ] # start with # '{"value": "some_value", "criteria": []}, ' self . upserts_size [ v ] = 31 + len ( value ) criteria_array . append ( criteria . to_dict ( ) ) self . upserts [ v ] = criteria_array self . upserts_size [ v ] += criteria . json_size ( ) | Add a tag or populator to the batch by value and criteria | 149 | 13 |
6,025 | def add_delete ( self , value ) : value = value . strip ( ) v = value . lower ( ) self . lower_val_to_val [ v ] = value if len ( v ) == 0 : raise ValueError ( "Invalid value for delete. Value is empty." ) self . deletes . add ( v ) | Delete a tag or populator by value - these are processed before upserts | 70 | 16 |
6,026 | def parts ( self ) : parts = [ ] upserts = dict ( ) deletes = [ ] # we keep track of the batch size as we go (pretty close approximation!) so we can chunk it small enough # to limit the HTTP posts to under 700KB - server limits to 750KB, so play it safe max_upload_size = 700000 # loop upserts first - fit the deletes in afterward # '{"replace_all": true, "complete": false, "guid": "6659fbfc-3f08-42ee-998c-9109f650f4b7", "upserts": [], "deletes": []}' base_part_size = 118 if not self . replace_all : base_part_size += 1 # yeah, this is totally overkill :) part_size = base_part_size for value in self . upserts : if ( part_size + self . upserts_size [ value ] ) >= max_upload_size : # this record would put us over the limit - close out the batch part and start a new one parts . append ( BatchPart ( self . replace_all , upserts , deletes ) ) upserts = dict ( ) deletes = [ ] part_size = base_part_size # for the new upserts dict, drop the lower-casing of value upserts [ self . lower_val_to_val [ value ] ] = self . upserts [ value ] part_size += self . upserts_size [ value ] # updating the approximate size of the batch for value in self . deletes : # delete adds length of string plus quotes, comma and space if ( part_size + len ( value ) + 4 ) >= max_upload_size : parts . append ( BatchPart ( self . replace_all , upserts , deletes ) ) upserts = dict ( ) deletes = [ ] part_size = base_part_size # for the new deletes set, drop the lower-casing of value deletes . append ( { 'value' : self . lower_val_to_val [ value ] } ) part_size += len ( value ) + 4 if len ( upserts ) + len ( deletes ) > 0 : # finish the batch parts . append ( BatchPart ( self . replace_all , upserts , deletes ) ) if len ( parts ) == 0 : if not self . replace_all : raise ValueError ( "Batch has no data, and 'replace_all' is False" ) parts . append ( BatchPart ( self . replace_all , dict ( ) , [ ] ) ) # last part finishes the batch parts [ - 1 ] . set_last_part ( ) return parts | Return an array of batch parts to submit | 600 | 8 |
6,027 | def build_json ( self , guid ) : upserts = [ ] for value in self . upserts : upserts . append ( { "value" : value , "criteria" : self . upserts [ value ] } ) return json . dumps ( { 'replace_all' : self . replace_all , 'guid' : guid , 'complete' : self . complete , 'upserts' : upserts , 'deletes' : self . deletes } ) | Build JSON with the input guid | 107 | 6 |
6,028 | def _ensure_field ( self , key ) : if self . _has_field : self . _size += 2 # comma, space self . _has_field = True self . _size += len ( key ) + 4 | Ensure a non - array field | 49 | 7 |
6,029 | def _ensure_array ( self , key , value ) : if key not in self . _json_dict : self . _json_dict [ key ] = [ ] self . _size += 2 # brackets self . _ensure_field ( key ) if len ( self . _json_dict [ key ] ) > 0 : # this array already has an entry, so add comma and space self . _size += 2 if isinstance ( value , str ) : self . _size += 2 # quotes self . _size += len ( str ( value ) ) self . _json_dict [ key ] . append ( value ) | Ensure an array field | 133 | 5 |
6,030 | def add_tcp_flag ( self , tcp_flag ) : if tcp_flag not in [ 1 , 2 , 4 , 8 , 16 , 32 , 64 , 128 ] : raise ValueError ( "Invalid TCP flag. Valid: [1, 2, 4, 8, 16,32, 64, 128]" ) prev_size = 0 if self . _json_dict . get ( 'tcp_flags' ) is None : self . _json_dict [ 'tcp_flags' ] = 0 else : prev_size = len ( str ( self . _json_dict [ 'tcp_flags' ] ) ) + len ( 'tcp_flags' ) + 3 # str, key, key quotes, colon self . _json_dict [ 'tcp_flags' ] |= tcp_flag # update size new_size = len ( str ( self . _json_dict [ 'tcp_flags' ] ) ) + len ( 'tcp_flags' ) + 3 # str, key, key quotes, colon self . _size += new_size - prev_size if prev_size == 0 and self . _has_field : # add the comma and space self . _size += 2 self . _has_field = True | Add a single TCP flag - will be OR d into the existing bitmask | 269 | 15 |
6,031 | def set_tcp_flags ( self , tcp_flags ) : if tcp_flags < 0 or tcp_flags > 255 : raise ValueError ( "Invalid tcp_flags. Valid: 0-255." ) prev_size = 0 if self . _json_dict . get ( 'tcp_flags' ) is not None : prev_size = len ( str ( self . _json_dict [ 'tcp_flags' ] ) ) + len ( 'tcp_flags' ) + 3 # str, key, key quotes, colon self . _json_dict [ 'tcp_flags' ] = tcp_flags # update size new_size = len ( str ( self . _json_dict [ 'tcp_flags' ] ) ) + len ( 'tcp_flags' ) + 3 # str, key, key quotes, colon self . _size += new_size - prev_size if prev_size == 0 and self . _has_field : # add the comma and space self . _size += 2 self . _has_field = True | Set the complete tcp flag bitmask | 228 | 7 |
6,032 | def _submit_batch ( self , url , batch ) : # TODO: validate column_name batch_parts = batch . parts ( ) guid = "" headers = { 'User-Agent' : 'kentik-python-api/0.1' , 'Content-Type' : 'application/json' , 'X-CH-Auth-Email' : self . api_email , 'X-CH-Auth-API-Token' : self . api_token } # submit each part last_part = dict ( ) for batch_part in batch_parts : # submit resp = requests . post ( url , headers = headers , data = batch_part . build_json ( guid ) ) # print the HTTP response to help debug print ( resp . text ) # break out at first sign of trouble resp . raise_for_status ( ) last_part = resp . json ( ) guid = last_part [ 'guid' ] if guid is None or len ( guid ) == 0 : raise RuntimeError ( 'guid not found in batch response' ) return last_part | Submit the batch returning the JSON - > dict from the last HTTP response | 230 | 14 |
6,033 | def submit_populator_batch ( self , column_name , batch ) : if not set ( column_name ) . issubset ( _allowedCustomDimensionChars ) : raise ValueError ( 'Invalid custom dimension name "%s": must only contain letters, digits, and underscores' % column_name ) if len ( column_name ) < 3 or len ( column_name ) > 20 : raise ValueError ( 'Invalid value "%s": must be between 3-20 characters' % column_name ) url = '%s/api/v5/batch/customdimensions/%s/populators' % ( self . base_url , column_name ) resp_json_dict = self . _submit_batch ( url , batch ) if resp_json_dict . get ( 'error' ) is not None : raise RuntimeError ( 'Error received from server: %s' % resp_json_dict [ 'error' ] ) return resp_json_dict [ 'guid' ] | Submit a populator batch | 214 | 5 |
6,034 | def submit_tag_batch ( self , batch ) : url = '%s/api/v5/batch/tags' % self . base_url self . _submit_batch ( url , batch ) | Submit a tag batch | 44 | 4 |
6,035 | def fetch_batch_status ( self , guid ) : url = '%s/api/v5/batch/%s/status' % ( self . base_url , guid ) headers = { 'User-Agent' : 'kentik-python-api/0.1' , 'Content-Type' : 'application/json' , 'X-CH-Auth-Email' : self . api_email , 'X-CH-Auth-API-Token' : self . api_token } resp = requests . get ( url , headers = headers ) # break out at first sign of trouble resp . raise_for_status ( ) return BatchResponse ( guid , resp . json ( ) ) | Fetch the status of a batch given the guid | 151 | 10 |
6,036 | def predict_files ( self , files ) : imgs = [ 0 ] * len ( files ) for i , file in enumerate ( files ) : img = cv2 . imread ( file ) . astype ( 'float64' ) img = cv2 . resize ( img , ( 224 , 224 ) ) img = preprocess_input ( img ) if img is None : print ( 'failed to open: {}, continuing...' . format ( file ) ) imgs [ i ] = img return self . model . predict ( np . array ( imgs ) ) | reads files off disk resizes them and then predicts them files should be a list or itrerable of file paths that lead to images they are then loaded with opencv resized and predicted | 122 | 38 |
6,037 | def rename_genome ( genome_in , genome_out = None ) : if genome_out is None : genome_out = "{}_renamed.fa" . format ( genome_in . split ( "." ) [ 0 ] ) with open ( genome_out , "w" ) as output_handle : for record in SeqIO . parse ( genome_in , "fasta" ) : # Replace hyphens, tabs and whitespace with underscores new_record_id = record . id . replace ( " " , "_" ) new_record_id = new_record_id . replace ( "-" , "_" ) new_record_id = new_record_id . replace ( "\t" , "_" ) # Remove anything that's weird, i.e. not alphanumeric # or an underscore new_record_id = re . sub ( "[^_A-Za-z0-9]+" , "" , new_record_id ) header = ">{}\n" . format ( new_record_id ) output_handle . write ( header ) output_handle . write ( "{}\n" . format ( str ( record . seq ) ) ) | Rename genome and slugify headers | 255 | 7 |
6,038 | def filter_genome ( genome_in , threshold = 500 , list_records = None ) : if list_records is None : def truth ( * args ) : del args return True is_a_record_to_keep = truth else : try : with open ( list_records ) as records_handle : records_to_keep = records_handle . readlines ( ) except OSError : if not hasattr ( list_records , "__contains__" ) : raise else : records_to_keep = list_records is_a_record_to_keep = records_to_keep . __contains__ records_to_write = ( record for record in SeqIO . parse ( genome_in , "fasta" ) if ( len ( record . seq ) >= threshold and is_a_record_to_keep ( record . id ) ) ) return records_to_write | Filter fasta file according to various parameters . | 199 | 9 |
6,039 | def rename_proteins ( prot_in , prot_out = None , chunk_size = DEFAULT_CHUNK_SIZE ) : if prot_out is None : prot_out = "{}_renamed.fa" . format ( prot_in . split ( "." ) [ 0 ] ) with open ( prot_out , "w" ) as prot_out_handle : for record in SeqIO . parse ( prot_in , "fasta" ) : header = record . description name , pos_start , _ , _ , _ = header . split ( "#" ) chunk_start = int ( pos_start ) // chunk_size name_split = name . split ( "_" ) contig_name = "_" . join ( name_split [ : - 1 ] ) gene_id = name_split [ - 1 ] new_record_id = "{}_{}__gene{}" . format ( contig_name , chunk_start , gene_id ) prot_out_handle . write ( ">{}\n" . format ( new_record_id ) ) prot_out_handle . write ( "{}\n" . format ( str ( record . seq ) ) ) | Rename prodigal output files | 260 | 7 |
6,040 | def write_records ( records , output_file , split = False ) : if split : for record in records : with open ( "{}{}.fa" . format ( output_file , record . id ) , "w" ) as record_handle : SeqIO . write ( record , record_handle , "fasta" ) else : SeqIO . write ( records , output_file , "fasta" ) | Write FASTA records | 90 | 5 |
6,041 | def add_sample ( self , * * data ) : missing_dimensions = set ( data ) . difference ( self . dimensions ) if missing_dimensions : raise KeyError ( 'Dimensions not defined in this series: %s' % ', ' . join ( missing_dimensions ) ) for dim in self . dimensions : getattr ( self , dim ) . append ( data . get ( dim ) ) | Add a sample to this series . | 86 | 7 |
6,042 | def samples ( self ) : names = self . series . dimensions for values in zip ( * ( getattr ( self . series , name ) for name in names ) ) : yield dict ( zip ( names , values ) ) | Yield the samples as dicts keyed by dimensions . | 46 | 12 |
6,043 | def write_binary ( filename , data ) : dir = os . path . dirname ( filename ) if not os . path . exists ( dir ) : os . makedirs ( dir ) with open ( filename , 'wb' ) as f : f . write ( data ) | Create path to filename and saves binary data | 58 | 8 |
6,044 | def files_with_exts ( root = '.' , suffix = '' ) : return ( os . path . join ( rootdir , filename ) for rootdir , dirnames , filenames in os . walk ( root ) for filename in filenames if filename . endswith ( suffix ) ) | Returns generator that contains filenames from root directory and ends with suffix | 64 | 14 |
6,045 | def find_apikey ( ) : env_keys = [ 'TINYPNG_APIKEY' , 'TINYPNG_API_KEY' ] paths = [ ] paths . append ( os . path . join ( os . path . abspath ( "." ) , "tinypng.key" ) ) # local directory paths . append ( os . path . expanduser ( "~/.tinypng.key" ) ) # home directory for env_key in env_keys : if os . environ . get ( env_key ) : return os . environ . get ( env_key ) for path in paths : if os . path . exists ( path ) : return open ( path , 'rt' ) . read ( ) . strip ( ) return None | Finds TinyPNG API key | 163 | 7 |
6,046 | def compare_packages ( rpm_str_a , rpm_str_b , arch_provided = True ) : logger . debug ( 'resolve_versions(%s, %s)' , rpm_str_a , rpm_str_b ) evr_a = parse_package ( rpm_str_a , arch_provided ) [ 'EVR' ] evr_b = parse_package ( rpm_str_b , arch_provided ) [ 'EVR' ] return labelCompare ( evr_a , evr_b ) | Compare two RPM strings to determine which is newer | 117 | 9 |
6,047 | def compare_evrs ( evr_a , evr_b ) : a_epoch , a_ver , a_rel = evr_a b_epoch , b_ver , b_rel = evr_b if a_epoch != b_epoch : return a_newer if a_epoch > b_epoch else b_newer ver_comp = compare_versions ( a_ver , b_ver ) if ver_comp != a_eq_b : return ver_comp rel_comp = compare_versions ( a_rel , b_rel ) return rel_comp | Compare two EVR tuples to determine which is newer | 133 | 11 |
6,048 | def compare_versions ( version_a , version_b ) : logger . debug ( 'compare_versions(%s, %s)' , version_a , version_b ) if version_a == version_b : return a_eq_b try : chars_a , chars_b = list ( version_a ) , list ( version_b ) except TypeError : raise RpmError ( 'Could not compare {0} to ' '{1}' . format ( version_a , version_b ) ) while len ( chars_a ) != 0 and len ( chars_b ) != 0 : logger . debug ( 'starting loop comparing %s ' 'to %s' , chars_a , chars_b ) _check_leading ( chars_a , chars_b ) if chars_a [ 0 ] == '~' and chars_b [ 0 ] == '~' : map ( lambda x : x . pop ( 0 ) , ( chars_a , chars_b ) ) elif chars_a [ 0 ] == '~' : return b_newer elif chars_b [ 0 ] == '~' : return a_newer if len ( chars_a ) == 0 or len ( chars_b ) == 0 : break block_res = _get_block_result ( chars_a , chars_b ) if block_res != a_eq_b : return block_res if len ( chars_a ) == len ( chars_b ) : logger . debug ( 'versions are equal' ) return a_eq_b else : logger . debug ( 'versions not equal' ) return a_newer if len ( chars_a ) > len ( chars_b ) else b_newer | Compare two RPM version strings | 371 | 5 |
6,049 | def package ( package_string , arch_included = True ) : logger . debug ( 'package(%s, %s)' , package_string , arch_included ) pkg_info = parse_package ( package_string , arch_included ) pkg = Package ( pkg_info [ 'name' ] , pkg_info [ 'EVR' ] [ 0 ] , pkg_info [ 'EVR' ] [ 1 ] , pkg_info [ 'EVR' ] [ 2 ] , pkg_info [ 'arch' ] , package_str = package_string ) return pkg | Parse an RPM version string | 134 | 6 |
6,050 | def parse_package ( package_string , arch_included = True ) : # Yum sets epoch values to 0 if they are not specified logger . debug ( 'parse_package(%s, %s)' , package_string , arch_included ) default_epoch = '0' arch = None if arch_included : char_list = list ( package_string ) arch = _pop_arch ( char_list ) package_string = '' . join ( char_list ) logger . debug ( 'updated version_string: %s' , package_string ) try : name , epoch , version , release = _rpm_re . match ( package_string ) . groups ( ) except AttributeError : raise RpmError ( 'Could not parse package string: %s' % package_string ) if epoch == '' or epoch is None : epoch = default_epoch info = { 'name' : name , 'EVR' : ( epoch , version , release ) , 'arch' : arch } logger . debug ( 'parsed information: %s' , info ) return info | Parse an RPM version string to get name version and arch | 234 | 12 |
6,051 | def _pop_arch ( char_list ) : logger . debug ( '_pop_arch(%s)' , char_list ) arch_list = [ ] char = char_list . pop ( ) while char != '.' : arch_list . insert ( 0 , char ) try : char = char_list . pop ( ) except IndexError : # Raised for a string with no periods raise RpmError ( 'Could not parse an architecture. Did you mean to ' 'set the arch_included flag to False?' ) logger . debug ( 'arch chars: %s' , arch_list ) return '' . join ( arch_list ) | Pop the architecture from a version string and return it | 138 | 10 |
6,052 | def _check_leading ( * char_lists ) : logger . debug ( '_check_leading(%s)' , char_lists ) for char_list in char_lists : while ( len ( char_list ) != 0 and not char_list [ 0 ] . isalnum ( ) and not char_list [ 0 ] == '~' ) : char_list . pop ( 0 ) logger . debug ( 'updated list: %s' , char_list ) | Remove any non - alphanumeric or non - ~ leading characters | 101 | 13 |
6,053 | def _trim_zeros ( * char_lists ) : logger . debug ( '_trim_zeros(%s)' , char_lists ) for char_list in char_lists : while len ( char_list ) != 0 and char_list [ 0 ] == '0' : char_list . pop ( 0 ) logger . debug ( 'updated block: %s' , char_list ) | Trim any zeros from provided character lists | 88 | 9 |
6,054 | def _pop_digits ( char_list ) : logger . debug ( '_pop_digits(%s)' , char_list ) digits = [ ] while len ( char_list ) != 0 and char_list [ 0 ] . isdigit ( ) : digits . append ( char_list . pop ( 0 ) ) logger . debug ( 'got digits: %s' , digits ) logger . debug ( 'updated char list: %s' , char_list ) return digits | Pop consecutive digits from the front of list and return them | 103 | 11 |
6,055 | def _pop_letters ( char_list ) : logger . debug ( '_pop_letters(%s)' , char_list ) letters = [ ] while len ( char_list ) != 0 and char_list [ 0 ] . isalpha ( ) : letters . append ( char_list . pop ( 0 ) ) logger . debug ( 'got letters: %s' , letters ) logger . debug ( 'updated char list: %s' , char_list ) return letters | Pop consecutive letters from the front of a list and return them | 101 | 12 |
6,056 | def _compare_blocks ( block_a , block_b ) : logger . debug ( '_compare_blocks(%s, %s)' , block_a , block_b ) if block_a [ 0 ] . isdigit ( ) : _trim_zeros ( block_a , block_b ) if len ( block_a ) != len ( block_b ) : logger . debug ( 'block lengths are not equal' ) return a_newer if len ( block_a ) > len ( block_b ) else b_newer if block_a == block_b : logger . debug ( 'blocks are equal' ) return a_eq_b else : logger . debug ( 'blocks are not equal' ) return a_newer if block_a > block_b else b_newer | Compare two blocks of characters | 177 | 5 |
6,057 | def _get_block_result ( chars_a , chars_b ) : logger . debug ( '_get_block_result(%s, %s)' , chars_a , chars_b ) first_is_digit = chars_a [ 0 ] . isdigit ( ) pop_func = _pop_digits if first_is_digit else _pop_letters return_if_no_b = a_newer if first_is_digit else b_newer block_a , block_b = pop_func ( chars_a ) , pop_func ( chars_b ) if len ( block_b ) == 0 : logger . debug ( 'blocks are equal' ) return return_if_no_b return _compare_blocks ( block_a , block_b ) | Get the first block from two character lists and compare | 172 | 10 |
6,058 | def list_ ( * , cursor : str = None , exclude_archived : bool = None , exclude_members : bool = None , limit : int = None ) -> snug . Query [ Page [ t . List [ Channel ] ] ] : kwargs = { 'exclude_archived' : exclude_archived , 'exclude_members' : exclude_members , 'limit' : limit } response = yield { 'cursor' : cursor , * * kwargs } try : next_cursor = response [ 'response_metadata' ] [ 'next_cursor' ] except KeyError : next_query = None else : next_query = list_ ( * * kwargs , cursor = next_cursor ) return Page ( load_channel_list ( response [ 'channels' ] ) , next_query = next_query , ) | list all channels | 184 | 3 |
6,059 | def create ( name : str , * , validate : bool = None ) -> snug . Query [ Channel ] : return { 'name' : name , 'validate' : validate } | create a new channel | 38 | 4 |
6,060 | def tube ( self , name ) : if name in self . _tubes : return self . _tubes [ name ] assert name , 'Tube name must be specified' t = self . _tube_cls ( self , name ) self . _tubes [ name ] = t return t | Returns tube by its name | 62 | 5 |
6,061 | def device_measurement ( device , ts = None , part = None , result = None , code = None , * * kwargs ) : if ts is None : ts = local_now ( ) payload = MeasurementPayload ( device = device , part = part ) m = Measurement ( ts , result , code , list ( kwargs ) ) payload . measurements . append ( m ) m . add_sample ( ts , * * kwargs ) return dumps ( payload ) | Returns a JSON MeasurementPayload ready to be send through a transport . | 104 | 15 |
6,062 | def add_sample ( self , ts , * * kwargs ) : if not self . series . offsets : self . ts = ts offset = 0 else : dt = ts - self . ts offset = ( dt . days * 24 * 60 * 60 * 1000 + dt . seconds * 1000 + dt . microseconds // 1000 ) self . series . add_sample ( offset , * * kwargs ) | Add a sample to this measurements . | 89 | 7 |
6,063 | def samples ( self ) : names = self . series . dimensions for n , offset in enumerate ( self . series . offsets ) : dt = datetime . timedelta ( microseconds = offset * 1000 ) d = { "ts" : self . ts + dt } for name in names : d [ name ] = getattr ( self . series , name ) [ n ] yield d | Yield samples as dictionaries keyed by dimensions . | 82 | 11 |
6,064 | def determine_format ( data , extension = None ) : if isinstance ( data , ( os . PathLike , str ) ) : data = open ( data , 'rb' ) data_reader = DataReader ( data ) data_reader . seek ( 0 , os . SEEK_SET ) d = data_reader . read ( 4 ) if d . startswith ( ( b'ID3' , b'\xFF\xFB' ) ) : # TODO: Catch all MP3 possibilities. if extension is None or extension . endswith ( '.mp3' ) : return MP3 if d . startswith ( ( b'fLaC' , b'ID3' ) ) : if extension is None or extension . endswith ( '.flac' ) : return FLAC if d . startswith ( b'RIFF' ) : if extension is None or extension . endswith ( '.wav' ) : return WAV return None | Determine the format of an audio file . | 206 | 10 |
6,065 | def load ( f ) : if isinstance ( f , ( os . PathLike , str ) ) : fileobj = open ( f , 'rb' ) else : try : f . read ( 0 ) except AttributeError : raise ValueError ( "Not a valid file-like object." ) except Exception : raise ValueError ( "Can't read from file-like object." ) fileobj = f parser_cls = determine_format ( fileobj , os . path . splitext ( fileobj . name ) [ 1 ] ) if parser_cls is None : raise UnsupportedFormat ( "Supported format signature not found." ) else : fileobj . seek ( 0 , os . SEEK_SET ) return parser_cls . load ( fileobj ) | Load audio metadata from filepath or file - like object . | 161 | 12 |
6,066 | def loads ( b ) : parser_cls = determine_format ( b ) if parser_cls is None : raise UnsupportedFormat ( "Supported format signature not found." ) return parser_cls . load ( b ) | Load audio metadata from a bytes - like object . | 48 | 10 |
6,067 | def Find ( self , node_type , item_type ) : if node_type == OtherNodes . DirectionNode : child = self . GetChild ( len ( self . children ) - 1 ) while child is not None and not isinstance ( child . GetItem ( ) , item_type ) : if child . GetItem ( ) . __class__ . __name__ == item_type . __name__ : return True child = child . GetChild ( 0 ) if node_type == OtherNodes . ExpressionNode : child = self . GetChild ( len ( self . children ) - 2 ) while child is not None and not isinstance ( child . GetItem ( ) , item_type ) : if child . GetItem ( ) . __class__ . __name__ == item_type . __name__ : return True child = child . GetChild ( 0 ) | method for finding specific types of notation from nodes . will currently return the first one it encounters because this method s only really intended for some types of notation for which the exact value doesn t really matter . | 184 | 40 |
6,068 | def count_lines ( abspath ) : with open ( abspath , "rb" ) as f : i = 0 for line in f : i += 1 pass return i | Count how many lines in a pure text file . | 36 | 10 |
6,069 | def lines_stats ( dir_path , file_filter ) : n_files = 0 n_lines = 0 for p in Path ( dir_path ) . select_file ( file_filter ) : n_files += 1 n_lines += count_lines ( p . abspath ) return n_files , n_lines | Lines count of selected files under a directory . | 69 | 10 |
6,070 | def parse_content ( self , text ) : match = re . search ( self . usage_re_str . format ( self . usage_name ) , text , flags = ( re . DOTALL if self . case_sensitive else ( re . DOTALL | re . IGNORECASE ) ) ) if match is None : return dic = match . groupdict ( ) logger . debug ( dic ) self . raw_content = dic [ 'raw' ] if dic [ 'sep' ] in ( '\n' , '\r\n' ) : self . formal_content = dic [ 'section' ] return reallen = len ( dic [ 'name' ] ) replace = '' . ljust ( reallen ) drop_name = match . expand ( '%s\\g<sep>\\g<section>' % replace ) self . formal_content = self . drop_started_empty_lines ( drop_name ) . rstrip ( ) | get Usage section and set to raw_content formal_content of no title and empty - line version | 213 | 20 |
6,071 | def spaceless_pdf_plot_maker ( array , filename , vmax = None , dpi = DEFAULT_DPI ) : if vmax is None : vmax = np . percentile ( array , DEFAULT_SATURATION_THRESHOLD ) plt . gca ( ) . set_axis_off ( ) plt . subplots_adjust ( top = 1 , bottom = 0 , right = 1 , left = 0 , hspace = 0 , wspace = 0 ) plt . margins ( 0 , 0 ) plt . gca ( ) . xaxis . set_major_locator ( plt . NullLocator ( ) ) plt . gca ( ) . yaxis . set_major_locator ( plt . NullLocator ( ) ) plt . figure ( ) if SEABORN : sns . heatmap ( array , vmax = vmax , cmap = "Reds" ) else : plt . imshow ( array , vmax = vmax , cmap = "Reds" , interpolation = "none" ) plt . colorbar ( ) plt . savefig ( filename , bbox_inches = "tight" , pad_inches = 0.0 , dpi = dpi ) plt . close ( ) | Draw a pretty plot from an array | 278 | 7 |
6,072 | def draw_sparse_matrix ( array_filename , output_image , vmax = DEFAULT_SATURATION_THRESHOLD , max_size_matrix = DEFAULT_MAX_SIZE_MATRIX , ) : matrix = np . loadtxt ( array_filename , dtype = np . int32 , skiprows = 1 ) try : row , col , data = matrix . T except ValueError : row , col , data = matrix size = max ( np . amax ( row ) , np . amax ( col ) ) + 1 S = sparse . coo_matrix ( ( data , ( row , col ) ) , shape = ( size , size ) ) if max_size_matrix <= 0 : binning = 1 else : binning = ( size // max_size_matrix ) + 1 binned_S = hcs . bin_sparse ( S , subsampling_factor = binning ) dense_S = binned_S . todense ( ) dense_S = dense_S + dense_S . T - np . diag ( np . diag ( dense_S ) ) normed_S = hcs . normalize_dense ( dense_S ) spaceless_pdf_plot_maker ( normed_S , output_image , vmax = vmax ) | Draw a quick preview of a sparse matrix with automated binning and normalization . | 289 | 16 |
6,073 | def nth ( iterable , n , default = None ) : return next ( itertools . islice ( iterable , n , None ) , default ) | Returns the nth item or a default value . | 35 | 10 |
6,074 | def pull ( iterable , n ) : fifo = collections . deque ( maxlen = n ) for i in iterable : fifo . append ( i ) return list ( fifo ) | Return last n items of the iterable as a list . | 41 | 12 |
6,075 | def running_window ( iterable , size ) : if size > len ( iterable ) : raise ValueError ( "size can not be greater than length of iterable." ) fifo = collections . deque ( maxlen = size ) for i in iterable : fifo . append ( i ) if len ( fifo ) == size : yield list ( fifo ) | Generate n - size running window . | 78 | 8 |
6,076 | def cycle_running_window ( iterable , size ) : if size > len ( iterable ) : raise ValueError ( "size can not be greater than length of iterable." ) fifo = collections . deque ( maxlen = size ) cycle = itertools . cycle ( iterable ) counter = itertools . count ( 1 ) length = len ( iterable ) for i in cycle : fifo . append ( i ) if len ( fifo ) == size : yield list ( fifo ) if next ( counter ) == length : break | Generate n - size cycle running window . | 116 | 9 |
6,077 | def shift_and_trim ( array , dist ) : length = len ( array ) if length == 0 : return [ ] if ( dist >= length ) or ( dist <= - length ) : return [ ] elif dist < 0 : return array [ - dist : ] elif dist > 0 : return array [ : - dist ] else : return list ( array ) | Shift and trim unneeded item . | 77 | 7 |
6,078 | def shift_and_pad ( array , dist , pad = "__null__" ) : length = len ( array ) if length == 0 : return [ ] if pad == "__null__" : if dist > 0 : padding_item = array [ 0 ] elif dist < 0 : padding_item = array [ - 1 ] else : padding_item = None else : padding_item = pad if abs ( dist ) >= length : return length * [ padding_item , ] elif dist == 0 : return list ( array ) elif dist > 0 : return [ padding_item , ] * dist + array [ : - dist ] elif dist < 0 : return array [ - dist : ] + [ padding_item , ] * - dist else : # Never get in this logic raise Exception | Shift and pad with item . | 168 | 6 |
6,079 | def size_of_generator ( generator , memory_efficient = True ) : if memory_efficient : counter = 0 for _ in generator : counter += 1 return counter else : return len ( list ( generator ) ) | Get number of items in a generator function . | 45 | 9 |
6,080 | def validate ( self , value ) : errors = [ ] self . _used_validator = [ ] for val in self . _validators : try : val . validate ( value ) self . _used_validator . append ( val ) except ValidatorException as e : errors . append ( e ) except Exception as e : errors . append ( ValidatorException ( "Unknown Error" , e ) ) if len ( errors ) > 0 : raise ValidatorException . from_list ( errors ) return value | validate function form OrValidator | 106 | 7 |
6,081 | def GetTotalValue ( self ) : value = "" if hasattr ( self , "meter" ) : top_value = self . meter . beats bottom = self . meter . type fraction = top_value / bottom if fraction == 1 : value = "1" else : if fraction > 1 : value = "1." if fraction < 1 : if fraction >= 0.5 : fraction -= 0.5 value = "2" if fraction == 0.25 : value += "." return value | Gets the total value of the bar according to it s time signature | 102 | 14 |
6,082 | def GetLastKey ( self , voice = 1 ) : voice_obj = self . GetChild ( voice ) if voice_obj is not None : key = BackwardSearch ( KeyNode , voice_obj , 1 ) if key is not None : return key else : if hasattr ( self , "key" ) : return self . key else : if hasattr ( self , "key" ) : return self . key | key as in musical key not index | 88 | 7 |
6,083 | def SplitString ( value ) : string_length = len ( value ) chunks = int ( string_length / 10 ) string_list = list ( value ) lstring = "" if chunks > 1 : lstring = "\\markup { \n\r \column { " for i in range ( int ( chunks ) ) : lstring += "\n\r\r \\line { \"" index = i * 10 for i in range ( index ) : lstring += string_list [ i ] lstring += "\" \r\r}" lstring += "\n\r } \n }" if lstring == "" : indexes = [ i for i in range ( len ( string_list ) ) if string_list [ i ] == "\r" or string_list [ i ] == "\n" ] lstring = "\\markup { \n\r \column { " if len ( indexes ) == 0 : lstring += "\n\r\r \\line { \"" + "" . join ( string_list ) + "\" \n\r\r } \n\r } \n }" else : rows = [ ] row_1 = string_list [ : indexes [ 0 ] ] rows . append ( row_1 ) for i in range ( len ( indexes ) ) : start = indexes [ i ] if i != len ( indexes ) - 1 : end = indexes [ i + 1 ] else : end = len ( string_list ) row = string_list [ start : end ] rows . append ( row ) for row in rows : lstring += "\n\r\r \\line { \"" lstring += "" . join ( row ) lstring += "\" \r\r}" lstring += "\n\r } \n }" return lstring | simple method that puts in spaces every 10 characters | 380 | 9 |
6,084 | def NumbersToWords ( number ) : units = [ 'one' , 'two' , 'three' , 'four' , 'five' , 'six' , 'seven' , 'eight' , 'nine' ] tens = [ 'ten' , 'twenty' , 'thirty' , 'forty' , 'fifty' , 'sixty' , 'seventy' , 'eighty' , 'ninety' ] output = "" if number != 0 : str_val = str ( number ) if 4 > len ( str_val ) > 2 : output += units [ int ( str_val [ 0 ] ) - 1 ] output += "hundred" if str_val [ 1 ] != 0 : output += "and" + tens [ int ( str_val [ 1 ] ) - 1 ] if str_val [ 2 ] != 0 : output += units [ int ( str_val [ 2 ] ) - 1 ] if 3 > len ( str_val ) > 1 : output += tens [ int ( str_val [ 0 ] ) - 1 ] if str_val [ 1 ] != 0 : output += units [ int ( str_val [ 1 ] ) - 1 ] if 2 > len ( str_val ) == 1 : output += units [ int ( str_val [ 0 ] ) - 1 ] else : output = "zero" return output | little function that converts numbers to words . This could be more efficient and won t work if the number is bigger than 999 but it s for stave names and I doubt any part would have more than 10 staves let alone 999 . | 292 | 47 |
6,085 | def CheckTotals ( self ) : staves = self . GetChildrenIndexes ( ) for staff in staves : child = self . getStaff ( staff ) child . CheckTotals ( ) | method to calculate the maximum total lilypond value for a measure without a time signature | 43 | 18 |
6,086 | def CheckPreviousBarline ( self , staff ) : measure_before_last = self . getMeasureAtPosition ( - 2 , staff ) last_measure = self . getMeasureAtPosition ( - 1 , staff ) if last_measure is not None and measure_before_last is not None : bline1 = measure_before_last . GetBarline ( "right" ) bline2 = last_measure . GetBarline ( "left" ) if bline1 is not None : if hasattr ( bline1 , "ending" ) : if bline2 is not None : if not hasattr ( bline2 , "ending" ) : bline1 . ending . type = "discontinue" else : bline1 . ending . type = "discontinue" | method which checks the bar before the current for changes we need to make to it s barlines | 172 | 19 |
6,087 | def __parse ( self ) -> object : char = self . data [ self . idx : self . idx + 1 ] if char in [ b'1' , b'2' , b'3' , b'4' , b'5' , b'6' , b'7' , b'8' , b'9' , b'0' ] : str_len = int ( self . __read_to ( b':' ) ) return self . __read ( str_len ) elif char == b'i' : self . idx += 1 return int ( self . __read_to ( b'e' ) ) elif char == b'd' : return self . __parse_dict ( ) elif char == b'l' : return self . __parse_list ( ) elif char == b'' : raise bencodepy . DecodingError ( 'Unexpected End of File at index position of {0}.' . format ( str ( self . idx ) ) ) else : raise bencodepy . DecodingError ( 'Invalid token character ({0}) at position {1}.' . format ( str ( char ) , str ( self . idx ) ) ) | Selects the appropriate method to decode next bencode element and returns the result . | 261 | 16 |
6,088 | def decode ( self ) -> Iterable : if self . data [ 0 : 1 ] not in ( b'd' , b'l' ) : return self . __wrap_with_tuple ( ) return self . __parse ( ) | Start of decode process . Returns final results . | 50 | 9 |
6,089 | def __wrap_with_tuple ( self ) -> tuple : l = list ( ) length = len ( self . data ) while self . idx < length : l . append ( self . __parse ( ) ) return tuple ( l ) | Returns a tuple of all nested bencode elements . | 51 | 10 |
6,090 | def __parse_dict ( self ) -> OrderedDict : self . idx += 1 d = OrderedDict ( ) key_name = None while self . data [ self . idx : self . idx + 1 ] != b'e' : if key_name is None : key_name = self . __parse ( ) else : d [ key_name ] = self . __parse ( ) key_name = None self . idx += 1 return d | Returns an Ordered Dictionary of nested bencode elements . | 101 | 11 |
6,091 | def __parse_list ( self ) -> list : self . idx += 1 l = [ ] while self . data [ self . idx : self . idx + 1 ] != b'e' : l . append ( self . __parse ( ) ) self . idx += 1 return l | Returns an list of nested bencode elements . | 63 | 9 |
6,092 | def PopAllChildren ( self ) : indexes = self . GetChildrenIndexes ( ) children = [ ] for c in indexes : child = self . PopChild ( c ) children . append ( child ) return children | Method to remove and return all children of current node | 44 | 10 |
6,093 | def _process_file ( input_file , output_file , apikey ) : bytes_ = read_binary ( input_file ) compressed = shrink ( bytes_ , apikey ) if compressed . success and compressed . bytes : write_binary ( output_file , compressed . bytes ) else : if compressed . errno in FATAL_ERRORS : raise StopProcessing ( compressed ) elif compressed . errno == TinyPNGError . InternalServerError : raise RetryProcessing ( compressed ) return compressed | Shrinks input_file to output_file . | 110 | 11 |
6,094 | def process_directory ( source , target , apikey , handler , overwrite = False ) : handler . on_start ( ) attempts = defaultdict ( lambda : 0 ) input_files = files_with_exts ( source , suffix = '.png' ) next_ = lambda : next ( input_files , None ) current_file = next_ ( ) response = None last_processed = None while current_file : output_file = target_path ( source , target , current_file ) if os . path . exists ( output_file ) and not overwrite : handler . on_skip ( current_file , source = source ) current_file = next_ ( ) continue try : handler . on_pre_item ( current_file ) last_processed = current_file response = _process_file ( current_file , output_file , apikey ) current_file = next_ ( ) except StopProcessing as e : # Unauthorized or exceed number of allowed monthly calls response = e . response handler . on_stop ( response . errmsg ) break except RetryProcessing as e : # handle InternalServerError on tinypng side response = e . response if attempts [ current_file ] < 9 : handler . on_retry ( current_file ) time . sleep ( TINYPNG_SLEEP_SEC ) attempts [ current_file ] += 1 else : current_file = next_ ( ) finally : handler . on_post_item ( response , input_file = last_processed , source = source ) handler . on_finish ( output_dir = target ) | Optimize and save png files form source to target directory . | 341 | 13 |
6,095 | def _main ( args ) : if not args . apikey : print ( "\nPlease provide TinyPNG API key" ) print ( "To obtain key visit https://api.tinypng.com/developers\n" ) sys . exit ( 1 ) input_dir = realpath ( args . input ) if not args . output : output_dir = input_dir + "-output" else : output_dir = realpath ( args . output ) if input_dir == output_dir : print ( "\nPlease specify different output directory\n" ) sys . exit ( 1 ) handler = ScreenHandler ( ) try : process_directory ( input_dir , output_dir , args . apikey , handler ) except KeyboardInterrupt : handler . on_finish ( output_dir = output_dir ) | Batch compression . | 173 | 4 |
6,096 | def task ( self , task_name ) : return Task ( uri = ':' . join ( ( self . _engine_name , task_name ) ) , cwd = self . _cwd ) | Returns an ENVI Py Engine Task object . See ENVI Py Engine Task for examples . | 44 | 18 |
6,097 | def tasks ( self ) : task_input = { 'taskName' : 'QueryTaskCatalog' } output = taskengine . execute ( task_input , self . _engine_name , cwd = self . _cwd ) return output [ 'outputParameters' ] [ 'TASKS' ] | Returns a list of all tasks known to the engine . | 64 | 11 |
6,098 | def execute ( query , auth = None , client = urllib_request . build_opener ( ) ) : exec_fn = getattr ( type ( query ) , '__execute__' , _default_execute_method ) return exec_fn ( query , client , _make_auth ( auth ) ) | Execute a query returning its result | 67 | 7 |
6,099 | def execute_async ( query , auth = None , client = event_loop ) : exc_fn = getattr ( type ( query ) , '__execute_async__' , Query . __execute_async__ ) return exc_fn ( query , client , _make_auth ( auth ) ) | Execute a query asynchronously returning its result | 66 | 10 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.