idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
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 | 67 | 12 |
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 | 201 | 9 |
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 . | 57 | 7 |
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 . | 49 | 12 |
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 | 64 | 8 |
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 | 60 | 11 |
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 . | 68 | 25 |
207 | def get_from_postcode ( self , postcode , distance , skip_cache = False ) : distance = float ( distance ) if distance < 0 : raise IllegalDistanceException ( "Distance must not be negative" ) # remove spaces and change case here due to caching postcode = postcode . lower ( ) . replace ( ' ' , '' ) return self . _lookup ... | Calls postcodes . get_from_postcode but checks correctness of distance and by default utilises a local cache . | 99 | 25 |
208 | def get_from_geo ( self , lat , lng , distance , skip_cache = False ) : # remove spaces and change case here due to caching lat , lng , distance = float ( lat ) , float ( lng ) , float ( distance ) if distance < 0 : raise IllegalDistanceException ( "Distance must not be negative" ) self . _check_point ( lat , lng ) ret... | Calls postcodes . get_from_geo but checks the correctness of all arguments and by default utilises a local cache . | 111 | 27 |
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 | 101 | 10 |
210 | def seq_info ( names , id2names , insertions , sequences ) : seqs = { } # seqs[id] = [gene, model, [[i-gene_pos, i-model_pos, i-length, iseq, [orfs], [introns]], ...]] for name in names : id = id2names [ name ] gene = name . split ( 'fromHMM::' , 1 ) [ 0 ] . rsplit ( ' ' , 1 ) [ 1 ] model = name . split ( 'fromHMM::' ,... | get insertion information from header | 454 | 5 |
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 # print float(ol) / float(feat_len) if float ( ol ) / float ( feat_len ) >= thresh : return True return False | make sure thresh % feature is contained within insertion | 88 | 10 |
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 | 97 | 4 |
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 | 187 | 4 |
214 | def setup_markers ( seqs ) : family2marker = { } # family2marker[family] = [marker, size] 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 ... | setup unique marker for every orf annotation - change size if necessary | 181 | 13 |
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 | 94 | 8 |
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 | 141 | 7 |
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 | 351 | 14 |
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 | 97 | 16 |
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 | 650 | 17 |
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 ) # get [fasta, description, length] for ORF id id2desc = self_compare ( fastas , id2desc , algorithm ) # get best possible bit score for... | make and split a rbh network | 627 | 7 |
221 | def _parse_raster_info ( self , prop = RASTER_INFO ) : raster_info = { } . fromkeys ( _iso_definitions [ prop ] , u'' ) # Ensure conversion of lists to newlines is in place raster_info [ 'dimensions' ] = get_default_for_complex_sub ( prop = prop , subprop = 'dimensions' , value = parse_property ( self . _xml_tree , Non... | Collapses multiple dimensions into a single raster_info complex struct | 411 | 13 |
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' ) # Update number of dimensions at raster_info root (applies to all dimensions below) xroot , xpath = None , self . _data_map [ '_ri_num_dims' ] ... | Derives multiple dimensions from a single raster_info complex struct | 571 | 13 |
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 | 105 | 9 |
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 | 126 | 62 |
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 . | 88 | 5 |
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 . | 57 | 6 |
227 | def start ( self ) : # invoke the appropriate sub-command as requested from command-line 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" ) # set ex... | Starts execution of the script | 153 | 6 |
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 . | 319 | 12 |
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 . | 42 | 26 |
230 | def get_default_for ( prop , value ) : prop = prop . strip ( '_' ) # Handle alternate props (leading underscores) val = reduce_value ( value ) # Filtering of value happens here 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 v... | Ensures complex property types have the correct default values | 90 | 11 |
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'' # Remove alternate elements: write values only to primary location else : values = get_default_for ( prop , values ) # Enforce... | Either update the tree the default way or call the custom updater | 187 | 13 |
232 | def _update_property ( tree_to_update , xpath_root , xpaths , values ) : # Inner function to update a specific XPATH with the values provided def update_element ( elem , idx , root , path , vals ) : """ Internal helper function to encapsulate single item update """ has_root = bool ( root and len ( path ) > len ( root )... | 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 . | 548 | 50 |
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 | 171 | 7 |
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 | 303 | 8 |
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 | 456 | 7 |
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 | 289 | 7 |
237 | def validate_type ( prop , value , expected ) : # Validate on expected type(s), but ignore None: defaults handled elsewhere if value is not None and not isinstance ( value , expected ) : _validation_error ( prop , type ( value ) . __name__ , None , expected ) | Default validation for all types | 64 | 5 |
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 | 127 | 5 |
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 | 57 | 12 |
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 ( ) # TODO: support multi commands if name not in multi_capable_commands : return False if name != next_command . get_name ( ) : return False # if th... | Returns a boolean representing whether these commands can be grouped together or not . | 189 | 14 |
241 | def find_databases ( databases ) : # 16 ribosomal proteins in their expected order proteins = [ 'L15' , 'L18' , 'L6' , 'S8' , 'L5' , 'L24' , 'L14' , 'S17' , 'L16' , 'S3' , 'L22' , 'S19' , 'L2' , 'L4' , 'L3' , 'S10' ] # curated databases protein_databases = { 'L14' : 'rpL14_JGI_MDM.filtered.faa' , 'L15' : 'rpL15_JGI_MDM... | define ribosomal proteins and location of curated databases | 540 | 10 |
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? | 201 | 16 |
243 | def find_ribosomal ( rps , scaffolds , s2rp , min_hits , max_hits_rp , max_errors ) : for scaffold , proteins in list ( s2rp . items ( ) ) : # for each scaffold, get best hits for each rp hits = { p : [ i for i in sorted ( hits , key = itemgetter ( 10 ) ) ] [ 0 : max_hits_rp ] for p , hits in list ( proteins . items ( ... | 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 | 232 | 39 |
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 . | 57 | 17 |
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' el... | Update the text for each element at the configured path if attribute matches | 320 | 13 |
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 . | 62 | 11 |
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 | 63 | 4 |
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 . | 36 | 12 |
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 | 90 | 23 |
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 . | 46 | 49 |
251 | def emptylineless ( parser , token ) : nodelist = parser . parse ( ( 'endemptylineless' , ) ) parser . delete_first_token ( ) return EmptylinelessNode ( nodelist ) | Removes empty line . | 49 | 5 |
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 | 146 | 33 |
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 ( getatt... | Non - threaded batch command runner returning output results | 134 | 9 |
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 | 51 | 7 |
255 | def add_javascripts ( self , * js_files ) : # create the script tag if don't exists 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 | 101 | 7 |
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 | 62 | 6 |
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' ) # include jquery & mermaid.js only if there are Mermaid gr... | convert Markdown text as html . return the html file as string | 276 | 14 |
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 | 68 | 6 |
259 | def _text_to_graphiz ( self , text ) : dot = Source ( text , format = 'svg' ) return dot . pipe ( ) . decode ( 'utf-8' ) | create a graphviz graph from text | 42 | 8 |
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 | 133 | 13 |
261 | def getCharacterSet ( self ) : chars = u'' c = None cnt = 1 start = 0 while True : escaped_slash = False c = self . next ( ) # print "pattern : ", self.pattern # print "C : ", c # print "Slash : ", c == u'\\' # print 'chars : ', chars # print 'index : ', self.index # print 'last : ', self.last() # print 'lookahead : ',... | Get a character set with individual members or ranges . | 394 | 10 |
262 | def getLiteral ( self ) : # we are on the first non-special character 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_ch... | Get a sequence of non - special characters . | 119 | 9 |
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 . | 627 | 6 |
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 ) # this doesn't work anymore in p3 # print("Random method provider class: %s" % randint.im_class.__name__) self . se... | Print the parse tree and then call render for an example . | 113 | 12 |
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 . | 184 | 7 |
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 . | 92 | 12 |
267 | def connect_cloudfront ( self ) : 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 . | 58 | 14 |
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 . | 77 | 7 |
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 . | 113 | 9 |
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 # setting the path (key) of file in the container if source == "filename" : # grabs t... | Copy a file to s3 . | 373 | 7 |
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 . | 371 | 11 |
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 . | 69 | 7 |
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 ) # only try to upload things if the origin cropduster file exists (so it is not already uploaded to the CDN) if os . path . exis... | 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 . | 301 | 42 |
274 | def chmod ( self , target_file , acl = 'public-read' ) : self . k . key = target_file # setting the path (key) of file in the container self . k . set_acl ( acl ) # setting the file permissions self . k . close ( ) | sets permissions for a file on S3 | 64 | 8 |
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 . | 78 | 11 |
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 . | 42 | 12 |
277 | def run ( self ) : # Try to create the directory if not os . path . exists ( self . output ) : try : os . mkdir ( self . output ) except : print 'failed to create output directory %s' % self . output # Be sure it is a directory if not os . path . isdir ( self . output ) : print 'invalid output directory %s' % self . ou... | Reads data from disk and generates CSV files . | 227 | 10 |
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 . | 91 | 16 |
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 filt... | Firms search in rubric | 163 | 6 |
280 | def refresh ( self ) : self . _screen . force_update ( ) self . _screen . refresh ( ) self . _update ( 1 ) | Refresh the list and the screen | 31 | 7 |
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 | 60 | 5 |
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 | 76 | 5 |
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 | 126 | 6 |
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 | 67 | 6 |
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 | 67 | 10 |
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 ( ar... | Recreate the class based in your args multiple uses | 186 | 11 |
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 | 117 | 12 |
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 | 211 | 8 |
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 | 37 | 9 |
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 | 51 | 12 |
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 | 98 | 10 |
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 | 149 | 5 |
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 | 359 | 4 |
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 . | 344 | 7 |
295 | def _prepare_defaults ( self ) : for name , field in self . __fields__ . items ( ) : if field . assign : getattr ( self , name ) | Trigger assignment of default values . | 38 | 6 |
296 | def from_mongo ( cls , doc ) : if doc is None : # To support simplified iterative use, None should return None. return None if isinstance ( doc , Document ) : # No need to perform processing on existing Document instances. return doc if cls . __type_store__ and cls . __type_store__ in doc : # Instantiate specific class... | Convert data coming in from the MongoDB wire driver into a Document instance . | 212 | 16 |
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 . | 47 | 15 |
298 | def _op ( self , operation , other , * allowed ) : f = self . _field if self . _combining : # We are a field-compound query fragment, e.g. (Foo.bar & Foo.baz). return reduce ( self . _combining , ( q . _op ( operation , other , * allowed ) for q in f ) ) # pylint:disable=protected-access # Optimize this away in product... | A basic operation operating on a single value . | 207 | 9 |
299 | def _iop ( self , operation , other , * allowed ) : f = self . _field if self . _combining : # We are a field-compound query fragment, e.g. (Foo.bar & Foo.baz). return reduce ( self . _combining , ( q . _iop ( operation , other , * allowed ) for q in f ) ) # pylint:disable=protected-access # Optimize this away in produ... | An iterative operation operating on multiple values . Consumes iterators to construct a concrete list at time of execution . | 243 | 23 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.