idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
30,200
def handle_update ( self , options ) : username = options [ "username" ] try : user = User . objects . get ( username = username ) except User . DoesNotExist : raise CommandError ( "User %s does not exist" % username ) if options [ "email" ] : user . email = options [ "email" ] if options [ "active" ] in [ True , False...
Update existing user
30,201
def handle_details ( self , username ) : try : user = User . objects . get ( username = username ) except User . DoesNotExist : raise CommandError ( "Unable to find user '%s'" % username ) self . stdout . write ( "username : %s" % username ) self . stdout . write ( "is_active : %s" % user . is_active ) self . stdo...
Print user details
30,202
def apply_plugins ( plugin_names ) : if plugin_names is None : return for p in plugin_names : try : plugin = get_plugin_instance ( p ) yield ( plugin ) except PluginNotFound : pass
This function should be used by code in the SQUAD core to trigger functionality from plugins .
30,203
def metadata ( self ) : if self . __metadata__ is None : metadata = { } for test_run in self . test_runs . defer ( None ) . all ( ) : for key , value in test_run . metadata . items ( ) : metadata . setdefault ( key , [ ] ) if value not in metadata [ key ] : metadata [ key ] . append ( value ) for key in metadata . keys...
The build metadata is the union of the metadata in its test runs . Common keys with different values are transformed into a list with each of the different values .
30,204
def builds ( self , request , pk = None ) : builds = self . get_object ( ) . builds . prefetch_related ( 'test_runs' ) . order_by ( '-datetime' ) page = self . paginate_queryset ( builds ) serializer = BuildSerializer ( page , many = True , context = { 'request' : request } ) return self . get_paginated_response ( seri...
List of builds for the current project .
30,205
def suites ( self , request , pk = None ) : suites_names = self . get_object ( ) . suites . values_list ( 'slug' ) suites_metadata = SuiteMetadata . objects . filter ( kind = 'suite' , suite__in = suites_names ) page = self . paginate_queryset ( suites_metadata ) serializer = SuiteMetadataSerializer ( page , many = Tru...
List of test suite names available in this project
30,206
def main ( source , repo_source_files , requirements_file , local_source_file , work_dir ) : scm_source = fsutil . parse_path_or_url ( source ) paths = fsutil . decide_paths ( scm_source , work_dir ) if requirements_file : with open ( os . devnull , 'w' ) as devnull : docker_retcode = subprocess . call ( [ 'docker' , '...
Bundle up a deployment package for AWS Lambda .
30,207
def _default_ising_beta_range ( h , J ) : abs_h = [ abs ( hh ) for hh in h . values ( ) if hh != 0 ] abs_J = [ abs ( jj ) for jj in J . values ( ) if jj != 0 ] abs_biases = abs_h + abs_J if not abs_biases : return [ 0.1 , 1.0 ] min_delta_energy = min ( abs_biases ) abs_bias_dict = { k : abs ( v ) for k , v in h . items...
Determine the starting and ending beta from h J
30,208
def _getMultiClassMap ( self ) : mcmap = dict ( ) for i in range ( self . _datalen ) : if ( self . _y [ i ] not in mcmap ) : mcmap [ self . _y [ i ] ] = 0 else : mcmap [ self . _y [ i ] ] += 1 for each in self . _label_list : mcmap [ each ] = mcmap [ each ] / float ( self . _datalen ) return mcmap
Relief algorithms handle the scoring updates a little differently for data with multiclass outcomes . In ReBATE we implement multiclass scoring in line with the strategy described by Kononenko 1994 within the RELIEF - F variant which was suggested to outperform the RELIEF - E multiclass variant . This strategy weights ...
30,209
def _distarray_missing ( self , xc , xd , cdiffs ) : cindices = [ ] dindices = [ ] for i in range ( self . _datalen ) : cindices . append ( np . where ( np . isnan ( xc [ i ] ) ) [ 0 ] ) dindices . append ( np . where ( np . isnan ( xd [ i ] ) ) [ 0 ] ) if self . n_jobs != 1 : dist_array = Parallel ( n_jobs = self . n_...
Distance array calculation for data with missing values
30,210
def _find_neighbors ( self , inst , avg_dist ) : NN_near = [ ] NN_far = [ ] min_indices = [ ] max_indices = [ ] for i in range ( self . _datalen ) : if inst != i : locator = [ inst , i ] if i > inst : locator . reverse ( ) d = self . _distance_array [ locator [ 0 ] ] [ locator [ 1 ] ] if d < avg_dist : min_indices . ap...
Identify nearest as well as farthest hits and misses within radius defined by average distance over whole distance array . This works the same regardless of endpoint type .
30,211
def get_row_missing ( xc , xd , cdiffs , index , cindices , dindices ) : row = np . empty ( 0 , dtype = np . double ) cinst1 = xc [ index ] dinst1 = xd [ index ] can = cindices [ index ] dan = dindices [ index ] tf = len ( cinst1 ) + len ( dinst1 ) for j in range ( index ) : dist = 0 dinst2 = xd [ j ] cinst2 = xc [ j ]...
Calculate distance between index instance and all other instances .
30,212
def ramp_function ( data_type , attr , fname , xinstfeature , xNNifeature ) : diff = 0 mmdiff = attr [ fname ] [ 3 ] rawfd = abs ( xinstfeature - xNNifeature ) if data_type == 'mixed' : standDev = attr [ fname ] [ 4 ] if rawfd > standDev : diff = 1 else : diff = abs ( xinstfeature - xNNifeature ) / mmdiff else : diff =...
Our own user simplified variation of the ramp function suggested by Hong 1994 1997 . Hong s method requires the user to specifiy two thresholds that indicate the max difference before a score of 1 is given as well a min difference before a score of 0 is given and any in the middle get a score that is the normalized dif...
30,213
def ReliefF_compute_scores ( inst , attr , nan_entries , num_attributes , mcmap , NN , headers , class_type , X , y , labels_std , data_type ) : scores = np . zeros ( num_attributes ) for feature_num in range ( num_attributes ) : scores [ feature_num ] += compute_score ( attr , mcmap , NN , feature_num , inst , nan_ent...
Unique scoring procedure for ReliefF algorithm . Scoring based on k nearest hits and misses of current target instance .
30,214
def SURFstar_compute_scores ( inst , attr , nan_entries , num_attributes , mcmap , NN_near , NN_far , headers , class_type , X , y , labels_std , data_type ) : scores = np . zeros ( num_attributes ) for feature_num in range ( num_attributes ) : if len ( NN_near ) > 0 : scores [ feature_num ] += compute_score ( attr , m...
Unique scoring procedure for SURFstar algorithm . Scoring based on nearest neighbors within defined radius as well as anti - scoring of far instances outside of radius of current target instance
30,215
def _find_neighbors ( self , inst ) : dist_vect = [ ] for j in range ( self . _datalen ) : if inst != j : locator = [ inst , j ] if inst < j : locator . reverse ( ) dist_vect . append ( self . _distance_array [ locator [ 0 ] ] [ locator [ 1 ] ] ) dist_vect = np . array ( dist_vect ) inst_avg_dist = np . average ( dist_...
Identify nearest as well as farthest hits and misses within radius defined by average distance and standard deviation of distances from target instanace . This works the same regardless of endpoint type .
30,216
def _find_neighbors ( self , inst , avg_dist ) : NN = [ ] min_indicies = [ ] for i in range ( self . _datalen ) : if inst != i : locator = [ inst , i ] if i > inst : locator . reverse ( ) d = self . _distance_array [ locator [ 0 ] ] [ locator [ 1 ] ] if d < avg_dist : min_indicies . append ( i ) for i in range ( len ( ...
Identify nearest hits and misses within radius defined by average distance over whole distance array . This works the same regardless of endpoint type .
30,217
def leave_module ( self , node ) : for triple_quote in self . _tokenized_triple_quotes . values ( ) : self . _check_triple_quotes ( triple_quote ) self . _tokenized_triple_quotes = { }
Leave module and check remaining triple quotes .
30,218
def _process_for_docstring ( self , node , node_type ) : if node . doc is not None : if node_type == 'module' : if not node . body : for key in list ( self . _tokenized_triple_quotes . keys ( ) ) : quote_record = self . _tokenized_triple_quotes . get ( key ) if quote_record : self . _check_docstring_quotes ( quote_reco...
Check for docstring quote consistency .
30,219
def _find_docstring_line_for_no_body ( self , start ) : tracked = sorted ( list ( self . _tokenized_triple_quotes . keys ( ) ) ) for i in tracked : if min ( start , i ) == start : return i return None
Find the docstring associated with a definition with no body in the node .
30,220
def _find_docstring_line ( self , start , end ) : for i in range ( start , end + 1 ) : if i in self . _tokenized_triple_quotes : return i return None
Find the row where a docstring starts in a function or class .
30,221
def process_tokens ( self , tokens ) : for tok_type , token , ( start_row , start_col ) , _ , _ in tokens : if tok_type == tokenize . STRING : self . _process_string_token ( token , start_row , start_col )
Process the token stream .
30,222
def _process_string_token ( self , token , start_row , start_col ) : for i , char in enumerate ( token ) : if char in QUOTES : break norm_quote = token [ i : ] if len ( norm_quote ) >= 3 and norm_quote [ : 3 ] in TRIPLE_QUOTE_OPTS . values ( ) : self . _tokenized_triple_quotes [ start_row ] = ( token , norm_quote [ : 3...
Internal method for identifying and checking string tokens from the token stream .
30,223
def _check_triple_quotes ( self , quote_record ) : _ , triple , row , col = quote_record if triple != TRIPLE_QUOTE_OPTS . get ( self . config . triple_quote ) : self . _invalid_triple_quote ( triple , row , col )
Check if the triple quote from tokenization is valid .
30,224
def _check_docstring_quotes ( self , quote_record ) : _ , triple , row , col = quote_record if triple != TRIPLE_QUOTE_OPTS . get ( self . config . docstring_quote ) : self . _invalid_docstring_quote ( triple , row , col )
Check if the docstring quote from tokenization is valid .
30,225
def _invalid_string_quote ( self , quote , row , correct_quote = None , col = None ) : if not correct_quote : correct_quote = SMART_QUOTE_OPTS . get ( self . config . string_quote ) self . add_message ( 'invalid-string-quote' , line = row , args = ( quote , correct_quote ) , ** self . get_offset ( col ) )
Add a message for an invalid string literal quote .
30,226
def _invalid_triple_quote ( self , quote , row , col = None ) : self . add_message ( 'invalid-triple-quote' , line = row , args = ( quote , TRIPLE_QUOTE_OPTS . get ( self . config . triple_quote ) ) , ** self . get_offset ( col ) )
Add a message for an invalid triple quote .
30,227
def _invalid_docstring_quote ( self , quote , row , col = None ) : self . add_message ( 'invalid-docstring-quote' , line = row , args = ( quote , TRIPLE_QUOTE_OPTS . get ( self . config . docstring_quote ) ) , ** self . get_offset ( col ) )
Add a message for an invalid docstring quote .
30,228
def get_live_data_dir ( ) : if sys . platform == 'darwin' : data_dir = os . path . expanduser ( os . path . join ( "~" , "Library" , "Ethereum" , ) ) elif sys . platform in { 'linux' , 'linux2' , 'linux3' } : data_dir = os . path . expanduser ( os . path . join ( "~" , ".ethereum" , ) ) elif sys . platform == 'win32' :...
pygeth needs a base directory to store it s chain data . By default this is the directory that geth uses as it s datadir .
30,229
def get_accounts ( data_dir , ** geth_kwargs ) : command , proc = spawn_geth ( dict ( data_dir = data_dir , suffix_args = [ 'account' , 'list' ] , ** geth_kwargs ) ) stdoutdata , stderrdata = proc . communicate ( ) if proc . returncode : if "no keys in store" in stderrdata . decode ( "utf-8" ) : return tuple ( ) else :...
Returns all geth accounts as tuple of hex encoded strings
30,230
def create_new_account ( data_dir , password , ** geth_kwargs ) : if os . path . exists ( password ) : geth_kwargs [ 'password' ] = password command , proc = spawn_geth ( dict ( data_dir = data_dir , suffix_args = [ 'account' , 'new' ] , ** geth_kwargs ) ) if os . path . exists ( password ) : stdoutdata , stderrdata = ...
Creates a new Ethereum account on geth .
30,231
def compare ( left , right ) : with open_zip ( left ) as l : with open_zip ( right ) as r : return compare_zips ( l , r )
yields EVENT ENTRY pairs describing the differences between left and right which are filenames for a pair of zip files
30,232
def compare_zips ( left , right ) : ll = set ( left . namelist ( ) ) rl = set ( right . namelist ( ) ) for f in ll : if f in rl : rl . remove ( f ) if f [ - 1 ] == '/' : pass elif _different ( left , right , f ) : yield DIFF , f else : yield SAME , f else : yield LEFT , f for f in rl : yield RIGHT , f
yields EVENT ENTRY pairs describing the differences between left and right ZipFile instances
30,233
def _different ( left , right , f ) : l = left . getinfo ( f ) r = right . getinfo ( f ) if ( l . file_size == r . file_size ) and ( l . CRC == r . CRC ) : return _deep_different ( left , right , f ) else : return True
true if entry f is different between left and right ZipFile instances
30,234
def _deep_different ( left , right , entry ) : left = chunk_zip_entry ( left , entry ) right = chunk_zip_entry ( right , entry ) for ldata , rdata in zip_longest ( left , right ) : if ldata != rdata : return True return False
checks that entry is identical between ZipFile instances left and right
30,235
def collect_compare_into ( left , right , added , removed , altered , same ) : with open_zip ( left ) as l : with open_zip ( right ) as r : return collect_compare_zips_into ( l , r , added , removed , altered , same )
collects the differences between left and right which are filenames for valid zip files into the lists added removed altered and same . Returns a tuple of added removed altered same
30,236
def collect_compare_zips_into ( left , right , added , removed , altered , same ) : for event , filename in compare_zips ( left , right ) : if event == LEFT : group = removed elif event == RIGHT : group = added elif event == DIFF : group = altered elif event == SAME : group = same else : assert False if group is not No...
collects the differences between left and right ZipFile instances into the lists added removed altered and same . Returns a tuple of added removed altered same
30,237
def is_zipstream ( data ) : if isinstance ( data , ( str , buffer ) ) : data = BytesIO ( data ) if hasattr ( data , "read" ) : tell = 0 if hasattr ( data , "tell" ) : tell = data . tell ( ) try : result = bool ( _EndRecData ( data ) ) except IOError : result = False if hasattr ( data , "seek" ) : data . seek ( tell ) e...
just like zipfile . is_zipfile but works upon buffers and streams rather than filenames .
30,238
def file_crc32 ( filename , chunksize = _CHUNKSIZE ) : check = 0 with open ( filename , 'rb' ) as fd : for data in iter ( lambda : fd . read ( chunksize ) , "" ) : check = crc32 ( data , check ) return check
calculate the CRC32 of the contents of filename
30,239
def _collect_infos ( dirname ) : for r , _ds , fs in walk ( dirname ) : if not islink ( r ) and r != dirname : i = ZipInfo ( ) i . filename = join ( relpath ( r , dirname ) , "" ) i . file_size = 0 i . compress_size = 0 i . CRC = 0 yield i . filename , i for f in fs : df = join ( r , f ) relfn = relpath ( join ( r , f ...
Utility function used by ExplodedZipFile to generate ZipInfo entries for all of the files and directories under dirname
30,240
def zip_file ( fn , mode = "r" ) : if isdir ( fn ) : return ExplodedZipFile ( fn ) elif is_zipfile ( fn ) : return ZipFile ( fn , mode ) else : raise Exception ( "cannot treat as an archive: %r" % fn )
returns either a zipfile . ZipFile instance or an ExplodedZipFile instance depending on whether fn is the name of a valid zip file or a directory .
30,241
def chunk_zip_entry ( zipfile , name , chunksize = _CHUNKSIZE ) : with open_zip_entry ( zipfile , name , mode = 'r' ) as stream : data = stream . read ( chunksize ) while data : yield data data = stream . read ( chunksize )
opens an entry from an openex zip file archive and yields sequential chunks of data from the resulting stream .
30,242
def collect_by_typename ( obj_sequence , cache = None ) : if cache is None : cache = { } for val in obj_sequence : key = type ( val ) . __name__ bucket = cache . get ( key , None ) if bucket is not None : bucket . append ( val ) else : cache [ key ] = [ val ] return cache
collects objects from obj_sequence and stores them into buckets by type name . cache is an optional dict into which we collect the results .
30,243
def collect_by_type ( obj_sequence , cache = None ) : if cache is None : cache = { } for val in obj_sequence : key = type ( val ) bucket = cache . get ( key , None ) if bucket is not None : bucket . append ( val ) else : cache [ key ] = [ val ] return cache
collects objects from obj_sequence and stores them into buckets by type . cache is an optional dict into which we collect the results .
30,244
def yield_sorted_by_type ( * typelist ) : def decorate ( fun ) : @ wraps ( fun ) def decorated ( * args , ** kwds ) : return iterate_by_type ( fun ( * args , ** kwds ) , typelist ) return decorated return decorate
a useful decorator for the collect_impl method of SuperChange subclasses . Caches the yielded changes and re - emits them collected by their type . The order of the types can be specified by listing the types as arguments to this decorator . Unlisted types will be yielded last in no guaranteed order .
30,245
def simplify ( self , options = None ) : simple = { "class" : type ( self ) . __name__ , "is_change" : self . is_change ( ) , "description" : self . get_description ( ) , "label" : self . label , } if options : simple [ "is_ignored" ] = self . is_ignored ( options ) if isinstance ( self , Addition ) : simple [ "is_addi...
returns a dict describing a simple snapshot of this change and its children if any .
30,246
def simplify ( self , options = None ) : simple = super ( GenericChange , self ) . simplify ( options ) ld = self . pretty_ldata ( ) if ld is not None : simple [ "old_data" ] = ld rd = self . pretty_rdata ( ) if rd is not None : simple [ "new_data" ] = rd return simple
provide a simple representation of this change as a dictionary
30,247
def clear ( self ) : super ( SuperChange , self ) . clear ( ) for c in self . changes : c . clear ( ) self . changes = tuple ( )
clears all child changes and drops the reference to them
30,248
def collect_impl ( self ) : ldata = self . get_ldata ( ) rdata = self . get_rdata ( ) for change_type in self . change_types : yield change_type ( ldata , rdata )
instantiates each of the entries in in the overriden change_types field with the left and right data
30,249
def collect ( self , force = False ) : if force or not self . changes : self . changes = tuple ( self . collect_impl ( ) ) return self . changes
calls collect_impl and stores the results as the child changes of this super - change . Returns a tuple of the data generated from collect_impl . Caches the result rather than re - computing each time unless force is True
30,250
def check_impl ( self ) : c = False for change in self . collect ( ) : change . check ( ) c = c or change . is_change ( ) return c , None
sets self . changes to the result of self . changes_impl then if any member of those checks shows as a change will return True None
30,251
def is_ignored ( self , options ) : if not self . is_change ( ) : return False changes = self . collect ( ) if not changes : return False for change in changes : if change . is_change ( ) and not change . is_ignored ( options ) : return False return True
If we have changed children and all the children which are changes are ignored then we are ignored . Otherwise we are not ignored
30,252
def squash_children ( self , options ) : oldsubs = self . collect ( ) self . changes = tuple ( squash ( c , options = options ) for c in oldsubs ) for change in oldsubs : change . clear ( )
reduces the memory footprint of this super - change by converting all child changes into squashed changes
30,253
def add_jardiff_optgroup ( parser ) : og = parser . add_argument_group ( "JAR Checking Options" ) og . add_argument ( "--ignore-jar-entry" , action = "append" , default = [ ] ) og . add_argument ( "--ignore-jar-signature" , action = "store_true" , default = False , help = "Ignore JAR signing changes" ) og . add_argumen...
option group specific to the tests in jardiff
30,254
def default_jardiff_options ( updates = None ) : parser = create_optparser ( ) options , _args = parser . parse_args ( list ( ) ) if updates : options . _update_careful ( updates ) return options
generate an options object with the appropriate default values in place for API usage of jardiff features . overrides is an optional dictionary which will be used to update fields on the options object .
30,255
def main ( args = sys . argv ) : parser = create_optparser ( args [ 0 ] ) return cli ( parser . parse_args ( args [ 1 : ] ) )
main entry point for the jardiff CLI
30,256
def add_general_report_optgroup ( parser ) : g = parser . add_argument_group ( "Reporting Options" ) g . add_argument ( "--report-dir" , action = "store" , default = None ) g . add_argument ( "--report" , action = _opt_cb_report , help = "comma-separated list of report formats" )
General Reporting Options
30,257
def add_json_report_optgroup ( parser ) : g = parser . add_argument_group ( "JSON Report Options" ) g . add_argument ( "--json-indent" , action = "store" , default = 2 , type = int )
Option group for the JSON report format
30,258
def _indent_change ( change , out , options , indent ) : show_unchanged = getattr ( options , "show_unchanged" , False ) show_ignored = getattr ( options , "show_ignored" , False ) show = False desc = change . get_description ( ) if change . is_change ( ) : if change . is_ignored ( options ) : if show_ignored : show = ...
recursive function to print indented change descriptions
30,259
def _indent ( stream , indent , * msgs ) : for x in range ( 0 , indent ) : stream . write ( " " ) for x in msgs : stream . write ( x . encode ( "ascii" , "backslashreplace" ) . decode ( "ascii" ) ) stream . write ( "\n" )
write a message to a text stream with indentation . Also ensures that the output encoding of the messages is safe for writing .
30,260
def _compose_cheetah_template_map ( cache ) : from . cheetah import get_templates import javatools for template_type in get_templates ( ) : if "_" not in template_type . __name__ : continue tn = template_type . __name__ pn , cn = tn . split ( "_" , 1 ) pk = getattr ( javatools , pn , None ) if pk is None : __import__ (...
does the work of composing the cheetah template map into the given cache
30,261
def resolve_cheetah_template ( change_type ) : tm = cheetah_template_map ( ) for t in change_type . mro ( ) : tmpl = tm . get ( t ) if tmpl : return tmpl raise Exception ( "No template for class %s" % change_type . __name__ )
return the appropriate cheetah template class for the given change type using the method - resolution - order of the change type .
30,262
def add_html_report_optgroup ( parser ) : g = parser . add_argument_group ( "HTML Report Options" ) g . add_argument ( "--html-stylesheet" , action = "append" , dest = "html_stylesheets" , default = list ( ) ) g . add_argument ( "--html-javascript" , action = "append" , dest = "html_javascripts" , default = list ( ) ) ...
Option group for the HTML report format
30,263
def quick_report ( report_type , change , options ) : report = report_type ( None , options ) if options . output : with open ( options . output , "w" ) as out : report . run ( change , None , out ) else : report . run ( change , None , sys . stdout )
writes a change report via report_type to options . output or sys . stdout
30,264
def get_relative_breadcrumbs ( self ) : basedir = self . basedir crumbs = self . breadcrumbs return [ ( relpath ( b , basedir ) , e ) for b , e in crumbs ]
get the breadcrumbs as relative to the basedir
30,265
def add_formats_by_name ( self , rfmt_list ) : for fmt in rfmt_list : if fmt == "json" : self . add_report_format ( JSONReportFormat ) elif fmt in ( "txt" , "text" ) : self . add_report_format ( TextReportFormat ) elif fmt in ( "htm" , "html" ) : self . add_report_format ( CheetahReportFormat )
adds formats by short label descriptors such as txt json or html
30,266
def subreporter ( self , subpath , entry ) : newbase = join ( self . basedir , subpath ) r = Reporter ( newbase , entry , self . options ) crumbs = list ( self . breadcrumbs ) crumbs . append ( ( self . basedir , self . entry ) ) r . breadcrumbs = crumbs r . formats = set ( self . formats ) return r
create a reporter for a sub - report with updated breadcrumbs and the same output formats
30,267
def setup ( self ) : if self . _formats : return basedir = self . basedir options = self . options crumbs = self . get_relative_breadcrumbs ( ) fmts = list ( ) for fmt_class in self . formats : fmt = fmt_class ( basedir , options , crumbs ) fmt . setup ( ) fmts . append ( fmt ) self . _formats = fmts
instantiates all report formats that have been added to this reporter and calls their setup methods .
30,268
def run ( self , change ) : if self . _formats is None : self . setup ( ) entry = self . entry for fmt in self . _formats : fmt . run ( change , entry ) self . clear ( )
runs the report format instances in this reporter . Will call setup if it hasn t been called already
30,269
def clear ( self ) : if self . _formats : for fmt in self . _formats : fmt . clear ( ) self . _formats = None
calls clear on any report format instances created during setup and drops the cache
30,270
def _relative ( self , uri ) : if uri . startswith ( "http:" ) or uri . startswith ( "https:" ) or uri . startswith ( "file:" ) or uri . startswith ( "/" ) : return uri elif exists ( uri ) : return relpath ( uri , self . basedir ) else : return uri
if uri is relative re - relate it to our basedir
30,271
def _relative_uris ( self , uri_list ) : return [ u for u in ( self . _relative ( uri ) for uri in uri_list ) if u ]
if uris in list are relative re - relate them to our basedir
30,272
def setup ( self ) : from javatools import cheetah options = self . options datadir = getattr ( options , "html_copy_data" , None ) if getattr ( options , "html_data_copied" , False ) or not datadir : return datasrc = join ( cheetah . __path__ [ 0 ] , "data" ) javascripts = list ( ) stylesheets = list ( ) for _orig , c...
copies default stylesheets and javascript files if necessary and appends them to the options
30,273
def run_impl ( self , change , entry , out ) : options = self . options javascripts = self . _relative_uris ( options . html_javascripts ) stylesheets = self . _relative_uris ( options . html_stylesheets ) template_class = resolve_cheetah_template ( type ( change ) ) template = template_class ( ) template . transaction...
sets up the report directory for an HTML report . Obtains the top - level Cheetah template that is appropriate for the change instance and runs it .
30,274
def get_requires ( self , ignored = tuple ( ) ) : if self . _requires is None : self . _collect_requires_provides ( ) d = self . _requires if ignored : d = dict ( ( k , v ) for k , v in d . items ( ) if not fnmatches ( k , * ignored ) ) return d
a map of requirements to what requires it . ignored is an optional list of globbed patterns indicating packages classes etc that shouldn t be included in the provides map
30,275
def get_provides ( self , ignored = tuple ( ) ) : if self . _provides is None : self . _collect_requires_provides ( ) d = self . _provides if ignored : d = dict ( ( k , v ) for k , v in d . items ( ) if not fnmatches ( k , * ignored ) ) return d
a map of provided classes and class members and what provides them . ignored is an optional list of globbed patterns indicating packages classes etc that shouldn t be included in the provides map
30,276
def close ( self ) : if self . tmpdir : rmtree ( self . tmpdir ) self . tmpdir = None self . _contents = None
if this was a zip d distribution any introspection may have resulted in opening or creating temporary files . Call close in order to clean up .
30,277
def _unpack ( struct , bc , offset = 0 ) : return struct . unpack_from ( bc , offset ) , offset + struct . size
returns the unpacked data tuple and the next offset past the unpacked data
30,278
def _unpack_lookupswitch ( bc , offset ) : jump = ( offset % 4 ) if jump : offset += ( 4 - jump ) ( default , npairs ) , offset = _unpack ( _struct_ii , bc , offset ) switches = list ( ) for _index in range ( npairs ) : pair , offset = _unpack ( _struct_ii , bc , offset ) switches . append ( pair ) return ( default , s...
function for unpacking the lookupswitch op arguments
30,279
def _unpack_tableswitch ( bc , offset ) : jump = ( offset % 4 ) if jump : offset += ( 4 - jump ) ( default , low , high ) , offset = _unpack ( _struct_iii , bc , offset ) joffs = list ( ) for _index in range ( ( high - low ) + 1 ) : j , offset = _unpack ( _struct_i , bc , offset ) joffs . append ( j ) return ( default ...
function for unpacking the tableswitch op arguments
30,280
def _unpack_wide ( bc , offset ) : code = ord ( bc [ offset ] ) if code == OP_iinc : return _unpack ( _struct_BHh , bc , offset ) elif code in ( OP_iload , OP_fload , OP_aload , OP_lload , OP_dload , OP_istore , OP_fstore , OP_astore , OP_lstore , OP_dstore , OP_ret ) : return _unpack ( _struct_BH , bc , offset ) else ...
unpacker for wide ops
30,281
def _mp_run_check ( tasks , results , options ) : try : for index , change in iter ( tasks . get , None ) : change . check ( ) squashed = squash ( change , options = options ) change . clear ( ) results . put ( ( index , squashed ) ) except KeyboardInterrupt : return
a helper function for multiprocessing with DistReport .
30,282
def add_distdiff_optgroup ( parser ) : cpus = cpu_count ( ) og = parser . add_argument_group ( "Distribution Checking Options" ) og . add_argument ( "--processes" , type = int , default = cpus , help = "Number of child processes to spawn to handle" " sub-reports. Set to 0 to disable multi-processing." " Defaults to the...
Option group relating to the use of a DistChange or DistReport
30,283
def create_optparser ( progname = None ) : from . import report parser = ArgumentParser ( prog = progname ) parser . add_argument ( "dist" , nargs = 2 , help = "distributions to compare" ) add_general_optgroup ( parser ) add_distdiff_optgroup ( parser ) add_jardiff_optgroup ( parser ) add_classdiff_optgroup ( parser ) ...
an OptionParser instance filled with options and groups appropriate for use with the distdiff command
30,284
def default_distdiff_options ( updates = None ) : parser = create_optparser ( ) options = parser . parse_args ( list ( ) ) if updates : options . _update_careful ( updates ) return options
generate an options object with the appropriate default values in place for API usage of distdiff features . overrides is an optional dictionary which will be used to update fields on the options object .
30,285
def collect_impl ( self ) : ld = self . ldata rd = self . rdata deep = not self . shallow for event , entry in compare ( ld , rd ) : if deep and fnmatches ( entry , * JAR_PATTERNS ) : if event == LEFT : yield DistJarRemoved ( ld , rd , entry ) elif event == RIGHT : yield DistJarAdded ( ld , rd , entry ) elif event == D...
emits change instances based on the delta of the two distribution directories
30,286
def collect_impl ( self ) : for c in DistChange . collect_impl ( self ) : if isinstance ( c , DistJarChange ) : if c . is_change ( ) : ln = DistJarReport . report_name nr = self . reporter . subreporter ( c . entry , ln ) c = DistJarReport ( c . ldata , c . rdata , c . entry , nr ) elif isinstance ( c , DistClassChange...
overrides DistJarChange and DistClassChange from the underlying DistChange with DistJarReport and DistClassReport instances
30,287
def mp_check_impl ( self , process_count ) : from multiprocessing import Process , Queue options = self . reporter . options func = _mp_run_check self . reporter . setup ( ) changes = list ( self . collect_impl ( ) ) task_count = 0 tasks = Queue ( ) results = Queue ( ) try : for index in range ( 0 , len ( changes ) ) :...
a multiprocessing - enabled check implementation . Will create up to process_count helper processes and use them to perform the DistJarReport and DistClassReport actions .
30,288
def compile_struct ( fmt , cache = None ) : if cache is None : cache = _struct_cache sfmt = cache . get ( fmt , None ) if not sfmt : sfmt = Struct ( fmt ) cache [ fmt ] = sfmt return sfmt
returns a struct . Struct instance compiled from fmt . If fmt has already been compiled it will return the previously compiled Struct instance from the cache .
30,289
def unpack ( self , fmt ) : sfmt = compile_struct ( fmt ) size = sfmt . size offset = self . offset if self . data : avail = len ( self . data ) - offset else : avail = 0 if avail < size : raise UnpackException ( fmt , size , avail ) self . offset = offset + size return sfmt . unpack_from ( self . data , offset )
unpacks the given fmt from the underlying buffer and returns the results . Will raise an UnpackException if there is not enough data to satisfy the fmt
30,290
def unpack_struct ( self , struct ) : size = struct . size offset = self . offset if self . data : avail = len ( self . data ) - offset else : avail = 0 if avail < size : raise UnpackException ( struct . format , size , avail ) self . offset = offset + size return struct . unpack_from ( self . data , offset )
unpacks the given struct from the underlying buffer and returns the results . Will raise an UnpackException if there is not enough data to satisfy the format of the structure
30,291
def read ( self , count ) : offset = self . offset if self . data : avail = len ( self . data ) - offset else : avail = 0 if avail < count : raise UnpackException ( None , count , avail ) self . offset = offset + count return self . data [ offset : self . offset ]
read count bytes from the underlying buffer and return them as a str . Raises an UnpackException if there is not enough data in the underlying buffer .
30,292
def unpack ( self , fmt ) : sfmt = compile_struct ( fmt ) size = sfmt . size if not self . data : raise UnpackException ( fmt , size , 0 ) buff = self . data . read ( size ) if len ( buff ) < size : raise UnpackException ( fmt , size , len ( buff ) ) return sfmt . unpack ( buff )
unpacks the given fmt from the underlying stream and returns the results . Will raise an UnpackException if there is not enough data to satisfy the fmt
30,293
def unpack_struct ( self , struct ) : size = struct . size if not self . data : raise UnpackException ( struct . format , size , 0 ) buff = self . data . read ( size ) if len ( buff ) < size : raise UnpackException ( struct . format , size , len ( buff ) ) return struct . unpack ( buff )
unpacks the given struct from the underlying stream and returns the results . Will raise an UnpackException if there is not enough data to satisfy the format of the structure
30,294
def read ( self , count ) : if not self . data : raise UnpackException ( None , count , 0 ) buff = self . data . read ( count ) if len ( buff ) < count : raise UnpackException ( None , count , len ( buff ) ) return buff
read count bytes from the unpacker and return it . Raises an UnpackException if there is not enough data in the underlying stream .
30,295
def close ( self ) : data = self . data self . data = None if hasattr ( data , "close" ) : data . close ( )
close this unpacker and the underlying stream if it supports such
30,296
def build_template ( self , template , template_file , package ) : try : from Cheetah . Compiler import Compiler except ImportError : self . announce ( "unable to import Cheetah.Compiler, build failed" ) raise else : comp = Compiler ( file = template_file , moduleName = template ) conf_fn = DEFAULT_CONFIG if exists ( c...
Compile the cheetah template in src into a python file in build
30,297
def add_classdiff_optgroup ( parser ) : g = parser . add_argument_group ( "Class Checking Options" ) g . add_argument ( "--ignore-version-up" , action = "store_true" , default = False ) g . add_argument ( "--ignore-version-down" , action = "store_true" , default = False ) g . add_argument ( "--ignore-platform-up" , act...
option group specific to class checking
30,298
def add_general_optgroup ( parser ) : g = parser . add_argument_group ( "General Options" ) g . add_argument ( "-q" , "--quiet" , dest = "silent" , action = "store_true" , default = False ) g . add_argument ( "-v" , "--verbose" , nargs = 0 , action = _opt_cb_verbose ) g . add_argument ( "-o" , "--output" , dest = "outp...
option group for general - use features of all javatool CLIs
30,299
def _iter_templates ( ) : import javatools . cheetah from Cheetah . Template import Template for _ , name , _ in iter_modules ( __path__ ) : __import__ ( "javatools.cheetah." + name ) found = getattr ( getattr ( javatools . cheetah , name ) , name ) if issubclass ( found , Template ) : yield found
uses reflection to yield the Cheetah templates under this module