idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
200
def append_index_id ( id , ids ) : index = 1 mod = '%s_%s' % ( id , index ) while mod in ids : index += 1 mod = '%s_%s' % ( id , index ) ids . append ( mod ) return mod , ids
add index to id to make it unique wrt ids
201
def de_rep ( fastas , append_index , return_original = False ) : ids = [ ] for fasta in fastas : for seq in parse_fasta ( fasta ) : header = seq [ 0 ] . split ( '>' ) [ 1 ] . split ( ) id = header [ 0 ] if id not in ids : ids . append ( id ) if return_original is True : yield [ header , seq ] else : yield seq elif appe...
de - replicate fastas based on sequence names
202
def get ( postcode ) : postcode = quote ( postcode . replace ( ' ' , '' ) ) url = '%s/postcode/%s.json' % ( END_POINT , postcode ) return _get_json_resp ( url )
Request data associated with postcode .
203
def get_from_postcode ( postcode , distance ) : postcode = quote ( postcode . replace ( ' ' , '' ) ) return _get_from ( distance , 'postcode=%s' % postcode )
Request all postcode data within distance miles of postcode .
204
def _check_point ( self , lat , lng ) : if abs ( lat ) > 90 or abs ( lng ) > 180 : msg = "Illegal lat and/or lng, (%s, %s) provided." % ( lat , lng ) raise IllegalPointException ( msg )
Checks if latitude and longitude correct
205
def _lookup ( self , skip_cache , fun , * args , ** kwargs ) : if args not in self . cache or skip_cache : self . cache [ args ] = fun ( * args , ** kwargs ) return self . cache [ args ]
Checks for cached responses before requesting from web - service
206
def get_nearest ( self , lat , lng , skip_cache = False ) : lat , lng = float ( lat ) , float ( lng ) self . _check_point ( lat , lng ) return self . _lookup ( skip_cache , get_nearest , lat , lng )
Calls postcodes . get_nearest but checks correctness of lat and long and by default utilises a local cache .
207
def get_from_postcode ( self , postcode , distance , skip_cache = False ) : distance = float ( distance ) if distance < 0 : raise IllegalDistanceException ( "Distance must not be negative" ) postcode = postcode . lower ( ) . replace ( ' ' , '' ) return self . _lookup ( skip_cache , get_from_postcode , postcode , float ...
Calls postcodes . get_from_postcode but checks correctness of distance and by default utilises a local cache .
208
def get_from_geo ( self , lat , lng , distance , skip_cache = False ) : lat , lng , distance = float ( lat ) , float ( lng ) , float ( distance ) if distance < 0 : raise IllegalDistanceException ( "Distance must not be negative" ) self . _check_point ( lat , lng ) return self . _lookup ( skip_cache , get_from_geo , lat...
Calls postcodes . get_from_geo but checks the correctness of all arguments and by default utilises a local cache .
209
def insertions_from_masked ( seq ) : insertions = [ ] prev = True for i , base in enumerate ( seq ) : if base . isupper ( ) and prev is True : insertions . append ( [ ] ) prev = False elif base . islower ( ) : insertions [ - 1 ] . append ( i ) prev = True return [ [ min ( i ) , max ( i ) ] for i in insertions if i != [...
get coordinates of insertions from insertion - masked sequence
210
def seq_info ( names , id2names , insertions , sequences ) : seqs = { } for name in names : id = id2names [ name ] gene = name . split ( 'fromHMM::' , 1 ) [ 0 ] . rsplit ( ' ' , 1 ) [ 1 ] model = name . split ( 'fromHMM::' , 1 ) [ 1 ] . split ( '=' , 1 ) [ 1 ] . split ( ) [ 0 ] i_gene_pos = insertions [ id ] i_model_po...
get insertion information from header
211
def check_overlap ( pos , ins , thresh ) : ins_pos = ins [ 0 ] ins_len = ins [ 2 ] ol = overlap ( ins_pos , pos ) feat_len = pos [ 1 ] - pos [ 0 ] + 1 if float ( ol ) / float ( feat_len ) >= thresh : return True return False
make sure thresh % feature is contained within insertion
212
def max_insertion ( seqs , gene , domain ) : seqs = [ i [ 2 ] for i in list ( seqs . values ( ) ) if i [ 2 ] != [ ] and i [ 0 ] == gene and i [ 1 ] == domain ] lengths = [ ] for seq in seqs : for ins in seq : lengths . append ( int ( ins [ 2 ] ) ) if lengths == [ ] : return 100 return max ( lengths )
length of largest insertion
213
def model_length ( gene , domain ) : if gene == '16S' : domain2max = { 'E_coli_K12' : int ( 1538 ) , 'bacteria' : int ( 1689 ) , 'archaea' : int ( 1563 ) , 'eukarya' : int ( 2652 ) } return domain2max [ domain ] elif gene == '23S' : domain2max = { 'E_coli_K12' : int ( 2903 ) , 'bacteria' : int ( 3146 ) , 'archaea' : in...
get length of model
214
def setup_markers ( seqs ) : family2marker = { } markers = cycle ( [ '^' , 'p' , '*' , '+' , 'x' , 'd' , '|' , 'v' , '>' , '<' , '8' ] ) size = 60 families = [ ] for seq in list ( seqs . values ( ) ) : for insertion in seq [ 2 ] : for family in list ( insertion [ - 1 ] . values ( ) ) : if family not in families : famil...
setup unique marker for every orf annotation - change size if necessary
215
def plot_by_gene_and_domain ( name , seqs , tax , id2name ) : for gene in set ( [ seq [ 0 ] for seq in list ( seqs . values ( ) ) ] ) : for domain in set ( [ seq [ 1 ] for seq in list ( seqs . values ( ) ) ] ) : plot_insertions ( name , seqs , gene , domain , tax , id2name )
plot insertions for each gene and domain
216
def get_descriptions ( fastas ) : id2desc = { } for fasta in fastas : for seq in parse_fasta ( fasta ) : header = seq [ 0 ] . split ( '>' ) [ 1 ] . split ( ' ' ) id = header [ 0 ] if len ( header ) > 1 : desc = ' ' . join ( header [ 1 : ] ) else : desc = 'n/a' length = float ( len ( [ i for i in seq [ 1 ] . strip ( ) i...
get the description for each ORF
217
def print_genome_matrix ( hits , fastas , id2desc , file_name ) : out = open ( file_name , 'w' ) fastas = sorted ( fastas ) print ( '## percent identity between genomes' , file = out ) print ( '# - \t %s' % ( '\t' . join ( fastas ) ) , file = out ) for fasta in fastas : line = [ fasta ] for other in fastas : if other =...
optimize later? slow ... should combine with calculate_threshold module
218
def self_compare ( fastas , id2desc , algorithm ) : for fasta in fastas : blast = open ( search ( fasta , fasta , method = algorithm , alignment = 'local' ) ) for hit in best_blast ( blast , 1 ) : id , bit = hit [ 0 ] . split ( ) [ 0 ] , float ( hit [ - 1 ] ) id2desc [ id ] . append ( bit ) return id2desc
compare genome to self to get the best possible bit score for each ORF
219
def calc_thresholds ( rbh , file_name , thresholds = [ False , False , False , False ] , stdevs = 2 ) : calc_threshold = thresholds [ - 1 ] norm_threshold = { } for pair in itertools . permutations ( [ i for i in rbh ] , 2 ) : if pair [ 0 ] not in norm_threshold : norm_threshold [ pair [ 0 ] ] = { } norm_threshold [ pa...
if thresholds are not specififed calculate based on the distribution of normalized bit scores
220
def neto ( fastas , algorithm = 'usearch' , e = 0.01 , bit = 40 , length = .65 , norm_bit = False ) : thresholds = [ e , bit , length , norm_bit ] id2desc = get_descriptions ( fastas ) id2desc = self_compare ( fastas , id2desc , algorithm ) hits = compare_genomes ( fastas , id2desc , algorithm ) calc_thresholds ( hits ...
make and split a rbh network
221
def _parse_raster_info ( self , prop = RASTER_INFO ) : raster_info = { } . fromkeys ( _iso_definitions [ prop ] , u'' ) raster_info [ 'dimensions' ] = get_default_for_complex_sub ( prop = prop , subprop = 'dimensions' , value = parse_property ( self . _xml_tree , None , self . _data_map , '_ri_num_dims' ) , xpath = sel...
Collapses multiple dimensions into a single raster_info complex struct
222
def _update_raster_info ( self , ** update_props ) : tree_to_update = update_props [ 'tree_to_update' ] prop = update_props [ 'prop' ] values = update_props . pop ( 'values' ) xroot , xpath = None , self . _data_map [ '_ri_num_dims' ] raster_info = [ update_property ( tree_to_update , xroot , xpath , prop , values . ge...
Derives multiple dimensions from a single raster_info complex struct
223
def _trim_xpath ( self , xpath , prop ) : xroot = self . _get_xroot_for ( prop ) if xroot is None and isinstance ( xpath , string_types ) : xtags = xpath . split ( XPATH_DELIM ) if xtags [ - 1 ] in _iso_tag_primitives : xroot = XPATH_DELIM . join ( xtags [ : - 1 ] ) return xroot
Removes primitive type tags from an XPATH
224
def shortcut_app_id ( shortcut ) : algorithm = Crc ( width = 32 , poly = 0x04C11DB7 , reflect_in = True , xor_in = 0xffffffff , reflect_out = True , xor_out = 0xffffffff ) crc_input = '' . join ( [ shortcut . exe , shortcut . name ] ) high_32 = algorithm . bit_by_bit ( crc_input ) | 0x80000000 full_64 = ( high_32 << 32...
Generates the app id for a given shortcut . Steam uses app ids as a unique identifier for games but since shortcuts dont have a canonical serverside representation they need to be generated on the fly . The important part about this function is that it will generate the same app id as Steam does for a given shortcut
225
def _config ( self ) : cfg_wr = self . repo . config_writer ( ) cfg_wr . add_section ( 'user' ) cfg_wr . set_value ( 'user' , 'name' , self . metadata . author ) cfg_wr . set_value ( 'user' , 'email' , self . metadata . email ) cfg_wr . release ( )
Execute git config .
226
def _remote_add ( self ) : self . repo . create_remote ( 'origin' , 'git@github.com:{username}/{repo}.git' . format ( username = self . metadata . username , repo = self . metadata . name ) )
Execute git remote add .
227
def start ( self ) : try : self . args . func ( ) except SystemExit as e : if e . code != 0 : raise except KeyboardInterrupt : self . log . warning ( "exited via keyboard interrupt" ) except : self . log . exception ( "exited start function" ) finally : self . _flush_metrics_q . put ( None , block = True ) self . _flus...
Starts execution of the script
228
def define_baseargs ( self , parser ) : parser . add_argument ( '--name' , default = sys . argv [ 0 ] , help = 'Name to identify this instance' ) parser . add_argument ( '--log-level' , default = None , help = 'Logging level as picked from the logging module' ) parser . add_argument ( '--log-format' , default = None , ...
Define basic command - line arguments required by the script .
229
def cleanup_payload ( self , payload ) : p = payload . replace ( '\n' , '' ) p = p . rstrip ( ) p = p . lstrip ( ) return p
Basically turns payload that looks like \\ n to . In the calling function if this function returns no object is added for that payload .
230
def get_default_for ( prop , value ) : prop = prop . strip ( '_' ) val = reduce_value ( value ) if prop in _COMPLEX_LISTS : return wrap_value ( val ) elif prop in _COMPLEX_STRUCTS : return val or { } else : return u'' if val is None else val
Ensures complex property types have the correct default values
231
def update_property ( tree_to_update , xpath_root , xpaths , prop , values , supported = None ) : if supported and prop . startswith ( '_' ) and prop . strip ( '_' ) in supported : values = u'' else : values = get_default_for ( prop , values ) if not xpaths : return [ ] elif not isinstance ( xpaths , ParserProperty ) :...
Either update the tree the default way or call the custom updater
232
def _update_property ( tree_to_update , xpath_root , xpaths , values ) : def update_element ( elem , idx , root , path , vals ) : has_root = bool ( root and len ( path ) > len ( root ) and path . startswith ( root ) ) path , attr = get_xpath_tuple ( path ) if attr : removed = [ get_element ( elem , path ) ] remove_elem...
Default update operation for a single parser property . If xpaths contains one xpath then one element per value will be inserted at that location in the tree_to_update ; otherwise the number of values must match the number of xpaths .
233
def validate_complex ( prop , value , xpath_map = None ) : if value is not None : validate_type ( prop , value , dict ) if prop in _complex_definitions : complex_keys = _complex_definitions [ prop ] else : complex_keys = { } if xpath_map is None else xpath_map for complex_prop , complex_val in iteritems ( value ) : com...
Default validation for single complex data structure
234
def validate_complex_list ( prop , value , xpath_map = None ) : if value is not None : validate_type ( prop , value , ( dict , list ) ) if prop in _complex_definitions : complex_keys = _complex_definitions [ prop ] else : complex_keys = { } if xpath_map is None else xpath_map for idx , complex_struct in enumerate ( wra...
Default validation for Attribute Details data structure
235
def validate_dates ( prop , value , xpath_map = None ) : if value is not None : validate_type ( prop , value , dict ) date_keys = set ( value ) if date_keys : if DATE_TYPE not in date_keys or DATE_VALUES not in date_keys : if prop in _complex_definitions : complex_keys = _complex_definitions [ prop ] else : complex_key...
Default validation for Date Types data structure
236
def validate_process_steps ( prop , value ) : if value is not None : validate_type ( prop , value , ( dict , list ) ) procstep_keys = set ( _complex_definitions [ prop ] ) for idx , procstep in enumerate ( wrap_value ( value ) ) : ps_idx = prop + '[' + str ( idx ) + ']' validate_type ( ps_idx , procstep , dict ) for ps...
Default validation for Process Steps data structure
237
def validate_type ( prop , value , expected ) : if value is not None and not isinstance ( value , expected ) : _validation_error ( prop , type ( value ) . __name__ , None , expected )
Default validation for all types
238
def _validation_error ( prop , prop_type , prop_value , expected ) : if prop_type is None : attrib = 'value' assigned = prop_value else : attrib = 'type' assigned = prop_type raise ValidationError ( 'Invalid property {attrib} for {prop}:\n\t{attrib}: {assigned}\n\texpected: {expected}' , attrib = attrib , prop = prop ,...
Default validation for updated properties
239
def get_prop ( self , prop ) : if self . _parser is None : raise ConfigurationError ( 'Cannot call ParserProperty."get_prop" with no parser configured' ) return self . _parser ( prop ) if prop else self . _parser ( )
Calls the getter with no arguments and returns its value
240
def can_group_commands ( command , next_command ) : multi_capable_commands = ( 'get' , 'set' , 'delete' ) if next_command is None : return False name = command . get_name ( ) if name not in multi_capable_commands : return False if name != next_command . get_name ( ) : return False if grouped_args_for_command ( command ...
Returns a boolean representing whether these commands can be grouped together or not .
241
def find_databases ( databases ) : proteins = [ 'L15' , 'L18' , 'L6' , 'S8' , 'L5' , 'L24' , 'L14' , 'S17' , 'L16' , 'S3' , 'L22' , 'S19' , 'L2' , 'L4' , 'L3' , 'S10' ] protein_databases = { 'L14' : 'rpL14_JGI_MDM.filtered.faa' , 'L15' : 'rpL15_JGI_MDM.filtered.faa' , 'L16' : 'rpL16_JGI_MDM.filtered.faa' , 'L18' : 'rpL...
define ribosomal proteins and location of curated databases
242
def find_next ( start , stop , i2hits ) : if start not in i2hits and stop in i2hits : index = stop elif stop not in i2hits and start in i2hits : index = start elif start not in i2hits and stop not in i2hits : index = choice ( [ start , stop ] ) i2hits [ index ] = [ [ False ] ] else : A , B = i2hits [ start ] [ 0 ] , i2...
which protein has the best hit the one to the right or to the left?
243
def find_ribosomal ( rps , scaffolds , s2rp , min_hits , max_hits_rp , max_errors ) : for scaffold , proteins in list ( s2rp . items ( ) ) : hits = { p : [ i for i in sorted ( hits , key = itemgetter ( 10 ) ) ] [ 0 : max_hits_rp ] for p , hits in list ( proteins . items ( ) ) if len ( hits ) > 0 } if len ( hits ) < min...
determine which hits represent real ribosomal proteins identify each in syntenic block max_hits_rp = maximum number of hits to consider per ribosomal protein per scaffold
244
def filter_rep_set ( inF , otuSet ) : seqs = [ ] for record in SeqIO . parse ( inF , "fasta" ) : if record . id in otuSet : seqs . append ( record ) return seqs
Parse the rep set file and remove all sequences not associated with unique OTUs .
245
def _update_report_item ( self , ** update_props ) : tree_to_update = update_props [ 'tree_to_update' ] prop = update_props [ 'prop' ] values = wrap_value ( update_props [ 'values' ] ) xroot = self . _get_xroot_for ( prop ) attr_key = 'type' attr_val = u'' if prop == 'attribute_accuracy' : attr_val = 'DQQuanAttAcc' eli...
Update the text for each element at the configured path if attribute matches
246
def _clear_interrupt ( self , intbit ) : int_status = self . _device . readU8 ( VCNL4010_INTSTAT ) int_status &= ~ intbit self . _device . write8 ( VCNL4010_INTSTAT , int_status )
Clear the specified interrupt bit in the interrupt status register .
247
def move ( self ) : a = random . randint ( 0 , len ( self . state ) - 1 ) b = random . randint ( 0 , len ( self . state ) - 1 ) self . state [ [ a , b ] ] = self . state [ [ b , a ] ]
Swaps two nodes
248
def self_signed ( self , value ) : self . _self_signed = bool ( value ) if self . _self_signed : self . _issuer = None
A bool - if the certificate should be self - signed .
249
def _get_crl_url ( self , distribution_points ) : if distribution_points is None : return None for distribution_point in distribution_points : name = distribution_point [ 'distribution_point' ] if name . name == 'full_name' and name . chosen [ 0 ] . name == 'uniform_resource_identifier' : return name . chosen [ 0 ] . c...
Grabs the first URL out of a asn1crypto . x509 . CRLDistributionPoints object
250
def ocsp_no_check ( self , value ) : if value is None : self . _ocsp_no_check = None else : self . _ocsp_no_check = bool ( value )
A bool - if the certificate should have the OCSP no check extension . Only applicable to certificates created for signing OCSP responses . Such certificates should normally be issued for a very short period of time since they are effectively whitelisted by clients .
251
def emptylineless ( parser , token ) : nodelist = parser . parse ( ( 'endemptylineless' , ) ) parser . delete_first_token ( ) return EmptylinelessNode ( nodelist )
Removes empty line .
252
def http_purge_url ( url ) : url = urlparse ( url ) connection = HTTPConnection ( url . hostname , url . port or 80 ) path = url . path or '/' connection . request ( 'PURGE' , '%s?%s' % ( path , url . query ) if url . query else path , '' , { 'Host' : '%s:%s' % ( url . hostname , url . port ) if url . port else url . h...
Do an HTTP PURGE of the given asset . The URL is run through urlparse and must point to the varnish instance not the varnishadm
253
def run ( addr , * commands , ** kwargs ) : results = [ ] handler = VarnishHandler ( addr , ** kwargs ) for cmd in commands : if isinstance ( cmd , tuple ) and len ( cmd ) > 1 : results . extend ( [ getattr ( handler , c [ 0 ] . replace ( '.' , '_' ) ) ( * c [ 1 : ] ) for c in cmd ] ) else : results . append ( getattr ...
Non - threaded batch command runner returning output results
254
def add_stylesheets ( self , * css_files ) : for css_file in css_files : self . main_soup . style . append ( self . _text_file ( css_file ) )
add stylesheet files in HTML head
255
def add_javascripts ( self , * js_files ) : if self . main_soup . script is None : script_tag = self . main_soup . new_tag ( 'script' ) self . main_soup . body . append ( script_tag ) for js_file in js_files : self . main_soup . script . append ( self . _text_file ( js_file ) )
add javascripts files in HTML body
256
def export ( self ) : with open ( self . export_url , 'w' , encoding = 'utf-8' ) as file : file . write ( self . build ( ) ) if self . open_browser : webbrowser . open_new_tab ( self . export_url )
return the object in a file
257
def build ( self ) : markdown_html = markdown . markdown ( self . markdown_text , extensions = [ TocExtension ( ) , 'fenced_code' , 'markdown_checklist.extension' , 'markdown.extensions.tables' ] ) markdown_soup = BeautifulSoup ( markdown_html , 'html.parser' ) if markdown_soup . find ( 'code' , attrs = { 'class' : 'me...
convert Markdown text as html . return the html file as string
258
def _text_file ( self , url ) : try : with open ( url , 'r' , encoding = 'utf-8' ) as file : return file . read ( ) except FileNotFoundError : print ( 'File `{}` not found' . format ( url ) ) sys . exit ( 0 )
return the content of a file
259
def _text_to_graphiz ( self , text ) : dot = Source ( text , format = 'svg' ) return dot . pipe ( ) . decode ( 'utf-8' )
create a graphviz graph from text
260
def _add_mermaid_js ( self ) : self . add_javascripts ( '{}/js/jquery-1.11.3.min.js' . format ( self . resources_path ) ) self . add_javascripts ( '{}/js/mermaid.min.js' . format ( self . resources_path ) ) self . add_stylesheets ( '{}/css/mermaid.css' . format ( self . resources_path ) ) self . main_soup . script . ap...
add js libraries and css files of mermaid js_file
261
def getCharacterSet ( self ) : chars = u'' c = None cnt = 1 start = 0 while True : escaped_slash = False c = self . next ( ) if self . lookahead ( ) == u'-' and not c == u'\\' : f = c self . next ( ) c = self . next ( ) if not c or ( c in self . meta_chars ) : raise StringGenerator . SyntaxError ( u"unexpected end of c...
Get a character set with individual members or ranges .
262
def getLiteral ( self ) : chars = u'' c = self . current ( ) while True : if c and c == u"\\" : c = self . next ( ) if c : chars += c continue elif not c or ( c in self . meta_chars ) : break else : chars += c if self . lookahead ( ) and self . lookahead ( ) in self . meta_chars : break c = self . next ( ) return Strin...
Get a sequence of non - special characters .
263
def getSequence ( self , level = 0 ) : seq = [ ] op = '' left_operand = None right_operand = None sequence_closed = False while True : c = self . next ( ) if not c : break if c and c not in self . meta_chars : seq . append ( self . getLiteral ( ) ) elif c and c == u'$' and self . lookahead ( ) == u'{' : seq . append ( ...
Get a sequence of nodes .
264
def dump ( self , ** kwargs ) : import sys if not self . seq : self . seq = self . getSequence ( ) print ( "StringGenerator version: %s" % ( __version__ ) ) print ( "Python version: %s" % sys . version ) self . seq . dump ( ) return self . render ( ** kwargs )
Print the parse tree and then call render for an example .
265
def render_list ( self , cnt , unique = False , progress_callback = None , ** kwargs ) : rendered_list = [ ] i = 0 total_attempts = 0 while True : if i >= cnt : break if total_attempts > cnt * self . unique_attempts_factor : raise StringGenerator . UniquenessError ( u"couldn't satisfy uniqueness" ) s = self . render ( ...
Return a list of generated strings .
266
def connect ( self ) : self . conn = boto . connect_s3 ( self . AWS_ACCESS_KEY_ID , self . AWS_SECRET_ACCESS_KEY , debug = self . S3UTILS_DEBUG_LEVEL ) self . bucket = self . conn . get_bucket ( self . AWS_STORAGE_BUCKET_NAME ) self . k = Key ( self . bucket )
Establish the connection . This is done automatically for you .
267
def connect_cloudfront ( self ) : "Connect to Cloud Front. This is done automatically for you when needed." self . conn_cloudfront = connect_cloudfront ( self . AWS_ACCESS_KEY_ID , self . AWS_SECRET_ACCESS_KEY , debug = self . S3UTILS_DEBUG_LEVEL )
Connect to Cloud Front . This is done automatically for you when needed .
268
def mkdir ( self , target_folder ) : self . printv ( "Making directory: %s" % target_folder ) self . k . key = re . sub ( r"^/|/$" , "" , target_folder ) + "/" self . k . set_contents_from_string ( '' ) self . k . close ( )
Create a folder on S3 .
269
def rm ( self , path ) : list_of_files = list ( self . ls ( path ) ) if list_of_files : if len ( list_of_files ) == 1 : self . bucket . delete_key ( list_of_files [ 0 ] ) else : self . bucket . delete_keys ( list_of_files ) self . printv ( "Deleted: %s" % list_of_files ) else : logger . error ( "There was nothing to re...
Delete the path and anything under the path .
270
def __put_key ( self , local_file , target_file , acl = 'public-read' , del_after_upload = False , overwrite = True , source = "filename" ) : action_word = "moving" if del_after_upload else "copying" try : self . k . key = target_file if source == "filename" : self . k . set_contents_from_filename ( local_file , self ....
Copy a file to s3 .
271
def cp ( self , local_path , target_path , acl = 'public-read' , del_after_upload = False , overwrite = True , invalidate = False ) : result = None if overwrite : list_of_files = [ ] else : list_of_files = self . ls ( folder = target_path , begin_from_file = "" , num = - 1 , get_grants = False , all_grant_data = False ...
Copy a file or folder from local to s3 .
272
def mv ( self , local_file , target_file , acl = 'public-read' , overwrite = True , invalidate = False ) : self . cp ( local_file , target_file , acl = acl , del_after_upload = True , overwrite = overwrite , invalidate = invalidate )
Similar to Linux mv command .
273
def cp_cropduster_image ( self , the_image_path , del_after_upload = False , overwrite = False , invalidate = False ) : local_file = os . path . join ( settings . MEDIA_ROOT , the_image_path ) if os . path . exists ( local_file ) : the_image_crops_path = os . path . splitext ( the_image_path ) [ 0 ] the_image_crops_pat...
Deal with saving cropduster images to S3 . Cropduster is a Django library for resizing editorial images . S3utils was originally written to put cropduster images on S3 bucket .
274
def chmod ( self , target_file , acl = 'public-read' ) : self . k . key = target_file self . k . set_acl ( acl ) self . k . close ( )
sets permissions for a file on S3
275
def ll ( self , folder = "" , begin_from_file = "" , num = - 1 , all_grant_data = False ) : return self . ls ( folder = folder , begin_from_file = begin_from_file , num = num , get_grants = True , all_grant_data = all_grant_data )
Get the list of files and permissions from S3 .
276
def get_path ( url ) : url = urlsplit ( url ) path = url . path if url . query : path += "?{}" . format ( url . query ) return path
Get the path from a given url including the querystring .
277
def run ( self ) : if not os . path . exists ( self . output ) : try : os . mkdir ( self . output ) except : print 'failed to create output directory %s' % self . output if not os . path . isdir ( self . output ) : print 'invalid output directory %s' % self . output sys . exit ( 1 ) visitors = [ _CompaniesCSV ( self . ...
Reads data from disk and generates CSV files .
278
def process_fields ( self , fields ) : result = [ ] strip = '' . join ( self . PREFIX_MAP ) for field in fields : direction = self . PREFIX_MAP [ '' ] if field [ 0 ] in self . PREFIX_MAP : direction = self . PREFIX_MAP [ field [ 0 ] ] field = field . lstrip ( strip ) result . append ( ( field , direction ) ) return res...
Process a list of simple string field definitions and assign their order based on prefix .
279
def search_in_rubric ( self , ** kwargs ) : point = kwargs . pop ( 'point' , False ) if point : kwargs [ 'point' ] = '%s,%s' % point bound = kwargs . pop ( 'bound' , False ) if bound : kwargs [ 'bound[point1]' ] = bound [ 0 ] kwargs [ 'bound[point2]' ] = bound [ 1 ] filters = kwargs . pop ( 'filters' , False ) if filte...
Firms search in rubric
280
def refresh ( self ) : self . _screen . force_update ( ) self . _screen . refresh ( ) self . _update ( 1 )
Refresh the list and the screen
281
def start ( self , activity , action ) : try : self . _start_action ( activity , action ) except ValueError : retox_log . debug ( "Could not find action %s in env %s" % ( activity , self . name ) ) self . refresh ( )
Mark an action as started
282
def stop ( self , activity , action ) : try : self . _remove_running_action ( activity , action ) except ValueError : retox_log . debug ( "Could not find action %s in env %s" % ( activity , self . name ) ) self . _mark_action_completed ( activity , action ) self . refresh ( )
Mark a task as completed
283
def finish ( self , status ) : retox_log . info ( "Completing %s with status %s" % ( self . name , status ) ) result = Screen . COLOUR_GREEN if not status else Screen . COLOUR_RED self . palette [ 'title' ] = ( Screen . COLOUR_WHITE , Screen . A_BOLD , result ) for item in list ( self . _task_view . options ) : self . ...
Move laggard tasks over
284
def reset ( self ) : self . palette [ 'title' ] = ( Screen . COLOUR_WHITE , Screen . A_BOLD , Screen . COLOUR_BLUE ) self . _completed_view . options = [ ] self . _task_view . options = [ ] self . refresh ( )
Reset the frame between jobs
285
def default_arguments ( cls ) : func = cls . __init__ args = func . __code__ . co_varnames defaults = func . __defaults__ index = - len ( defaults ) return { k : v for k , v in zip ( args [ index : ] , defaults ) }
Returns the available kwargs of the called class
286
def recreate ( cls , * args , ** kwargs ) : cls . check_arguments ( kwargs ) first_is_callable = True if any ( args ) and callable ( args [ 0 ] ) else False signature = cls . default_arguments ( ) allowed_arguments = { k : v for k , v in kwargs . items ( ) if k in signature } if ( any ( allowed_arguments ) or any ( arg...
Recreate the class based in your args multiple uses
287
def check_arguments ( cls , passed ) : defaults = list ( cls . default_arguments ( ) . keys ( ) ) template = ( "Pass arg {argument:!r} in {cname:!r}, can be a typo? " "Supported key arguments: {defaults}" ) fails = [ ] for arg in passed : if arg not in defaults : warn ( template . format ( argument = arg , cname = cls ...
Put warnings of arguments whose can t be handle by the class
288
def process ( self , data , type , history ) : if type in history : return if type . enum ( ) : return history . append ( type ) resolved = type . resolve ( ) value = None if type . multi_occurrence ( ) : value = [ ] else : if len ( resolved ) > 0 : if resolved . mixed ( ) : value = Factory . property ( resolved . name...
process the specified type then process its children
289
def skip_child ( self , child , ancestry ) : if child . any ( ) : return True for x in ancestry : if x . choice ( ) : return True return False
get whether or not to skip the specified child
290
def active_knocks ( obj ) : if not hasattr ( _thread_locals , 'knock_enabled' ) : return True return _thread_locals . knock_enabled . get ( obj . __class__ , True )
Checks whether knocks are enabled for the model given as argument
291
def pause_knocks ( obj ) : if not hasattr ( _thread_locals , 'knock_enabled' ) : _thread_locals . knock_enabled = { } obj . __class__ . _disconnect ( ) _thread_locals . knock_enabled [ obj . __class__ ] = False yield _thread_locals . knock_enabled [ obj . __class__ ] = True obj . __class__ . _connect ( )
Context manager to suspend sending knocks for the given model
292
def _loopreport ( self ) : while 1 : eventlet . sleep ( 0.2 ) ac2popenlist = { } for action in self . session . _actions : for popen in action . _popenlist : if popen . poll ( ) is None : lst = ac2popenlist . setdefault ( action . activity , [ ] ) lst . append ( popen ) if not action . _popenlist and action in self . _...
Loop over the report progress
293
def send ( email , subject = None , from_email = None , to_email = None , cc = None , bcc = None , reply_to = None , smtp = None ) : if is_string ( email ) : email = EmailContent ( email ) from_email = sanitize_email_address ( from_email or email . headers . get ( 'from' ) ) to_email = sanitize_email_address ( to_email...
Send markdown email
294
def _process_tz ( self , dt , naive , tz ) : def _tz ( t ) : if t in ( None , 'naive' ) : return t if t == 'local' : if __debug__ and not localtz : raise ValueError ( "Requested conversion to local timezone, but `localtz` not installed." ) t = localtz if not isinstance ( t , tzinfo ) : if __debug__ and not localtz : ra...
Process timezone casting and conversion .
295
def _prepare_defaults ( self ) : for name , field in self . __fields__ . items ( ) : if field . assign : getattr ( self , name )
Trigger assignment of default values .
296
def from_mongo ( cls , doc ) : if doc is None : return None if isinstance ( doc , Document ) : return doc if cls . __type_store__ and cls . __type_store__ in doc : cls = load ( doc [ cls . __type_store__ ] , 'marrow.mongo.document' ) instance = cls ( _prepare_defaults = False ) instance . __data__ = doc instance . _pre...
Convert data coming in from the MongoDB wire driver into a Document instance .
297
def pop ( self , name , default = SENTINEL ) : if default is SENTINEL : return self . __data__ . pop ( name ) return self . __data__ . pop ( name , default )
Retrieve and remove a value from the backing store optionally with a default .
298
def _op ( self , operation , other , * allowed ) : f = self . _field if self . _combining : return reduce ( self . _combining , ( q . _op ( operation , other , * allowed ) for q in f ) ) if __debug__ and _complex_safety_check ( f , { operation } | set ( allowed ) ) : raise NotImplementedError ( "{self!r} does not allow...
A basic operation operating on a single value .
299
def _iop ( self , operation , other , * allowed ) : f = self . _field if self . _combining : return reduce ( self . _combining , ( q . _iop ( operation , other , * allowed ) for q in f ) ) if __debug__ and _complex_safety_check ( f , { operation } | set ( allowed ) ) : raise NotImplementedError ( "{self!r} does not all...
An iterative operation operating on multiple values . Consumes iterators to construct a concrete list at time of execution .