idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
22,500
def get_sdk_dir ( self ) : try : return self . _sdk_dir except AttributeError : sdk_dir = self . find_sdk_dir ( ) self . _sdk_dir = sdk_dir return sdk_dir
Return the MSSSDK given the version string .
58
11
22,501
def get_sdk_vc_script ( self , host_arch , target_arch ) : if ( host_arch == 'amd64' and target_arch == 'x86' ) : # No cross tools needed compiling 32 bits on 64 bit machine host_arch = target_arch arch_string = target_arch if ( host_arch != target_arch ) : arch_string = '%s_%s' % ( host_arch , target_arch ) debug ( "sdk.py: get_sdk_vc_script():arch_string:%s host_arch:%s target_arch:%s" % ( arch_string , host_arch , target_arch ) ) file = self . vc_setup_scripts . get ( arch_string , None ) debug ( "sdk.py: get_sdk_vc_script():file:%s" % file ) return file
Return the script to initialize the VC compiler installed by SDK
197
11
22,502
def format_rpc ( data ) : address , rpc_id , args , resp , _status = data name = rpc_name ( rpc_id ) if isinstance ( args , ( bytes , bytearray ) ) : arg_str = hexlify ( args ) else : arg_str = repr ( args ) if isinstance ( resp , ( bytes , bytearray ) ) : resp_str = hexlify ( resp ) else : resp_str = repr ( resp ) #FIXME: Check and print status as well return "%s called on address %d, payload=%s, response=%s" % ( name , address , arg_str , resp_str )
Format an RPC call and response .
151
7
22,503
async def start ( self ) : self . _command_task . start ( ) try : await self . _cleanup_old_connections ( ) except Exception : await self . stop ( ) raise #FIXME: This is a temporary hack, get the actual device we are serving. iotile_id = next ( iter ( self . adapter . devices ) ) self . device = self . adapter . devices [ iotile_id ] self . _logger . info ( "Serving device 0x%04X over BLED112" , iotile_id ) await self . _update_advertisement ( ) self . setup_client ( self . CLIENT_ID , scan = False , broadcast = True )
Start serving access to devices over bluetooth .
152
9
22,504
async def stop ( self ) : await self . _command_task . future_command ( [ '_set_mode' , 0 , 0 ] ) # Disable advertising await self . _cleanup_old_connections ( ) self . _command_task . stop ( ) self . _stream . stop ( ) self . _serial_port . close ( ) await super ( BLED112Server , self ) . stop ( )
Safely shut down this interface
91
6
22,505
async def _call_rpc ( self , header ) : length , _ , cmd , feature , address = struct . unpack ( "<BBBBB" , bytes ( header ) ) rpc_id = ( feature << 8 ) | cmd payload = self . rpc_payload [ : length ] self . _logger . debug ( "Calling RPC %d:%04X with %s" , address , rpc_id , binascii . hexlify ( payload ) ) exception = None response = None try : response = await self . send_rpc ( self . CLIENT_ID , str ( self . device . iotile_id ) , address , rpc_id , bytes ( payload ) , timeout = 30.0 ) except VALID_RPC_EXCEPTIONS as err : exception = err except Exception as err : self . _logger . exception ( "Error calling RPC %d:%04X" , address , rpc_id ) exception = err status , response = pack_rpc_response ( response , exception ) resp_header = struct . pack ( "<BBBB" , status , 0 , 0 , len ( response ) ) await self . _send_notification ( self . ReceiveHeaderHandle , resp_header ) if len ( response ) > 0 : await self . _send_notification ( self . ReceivePayloadHandle , response )
Call an RPC given a header and possibly a previously sent payload
298
12
22,506
def format_script ( sensor_graph ) : records = [ ] records . append ( SetGraphOnlineRecord ( False , address = 8 ) ) records . append ( ClearDataRecord ( address = 8 ) ) records . append ( ResetGraphRecord ( address = 8 ) ) for node in sensor_graph . nodes : records . append ( AddNodeRecord ( str ( node ) , address = 8 ) ) for streamer in sensor_graph . streamers : records . append ( AddStreamerRecord ( streamer , address = 8 ) ) for stream , value in sorted ( sensor_graph . constant_database . items ( ) , key = lambda x : x [ 0 ] . encode ( ) ) : records . append ( SetConstantRecord ( stream , value , address = 8 ) ) records . append ( PersistGraphRecord ( address = 8 ) ) records . append ( ClearConfigVariablesRecord ( ) ) for slot in sorted ( sensor_graph . config_database , key = lambda x : x . encode ( ) ) : for config_id in sorted ( sensor_graph . config_database [ slot ] ) : config_type , value = sensor_graph . config_database [ slot ] [ config_id ] byte_value = _convert_to_bytes ( config_type , value ) records . append ( SetConfigRecord ( slot , config_id , byte_value ) ) # If we have an app tag and version set program them in app_tag = sensor_graph . metadata_database . get ( 'app_tag' ) app_version = sensor_graph . metadata_database . get ( 'app_version' ) if app_tag is not None : records . append ( SetDeviceTagRecord ( app_tag = app_tag , app_version = app_version ) ) script = UpdateScript ( records ) return script . encode ( )
Create a binary script containing this sensor graph .
390
9
22,507
def dump ( self ) : walkers = { } walkers . update ( { str ( walker . selector ) : walker . dump ( ) for walker in self . _queue_walkers } ) walkers . update ( { str ( walker . selector ) : walker . dump ( ) for walker in self . _virtual_walkers } ) return { u'engine' : self . _engine . dump ( ) , u'rollover_storage' : self . _rollover_storage , u'rollover_streaming' : self . _rollover_streaming , u'last_values' : { str ( stream ) : reading . asdict ( ) for stream , reading in self . _last_values . items ( ) } , u'walkers' : walkers }
Dump the state of this SensorLog .
172
9
22,508
def set_rollover ( self , area , enabled ) : if area == u'streaming' : self . _rollover_streaming = enabled elif area == u'storage' : self . _rollover_storage = enabled else : raise ArgumentError ( "You must pass one of 'storage' or 'streaming' to set_rollover" , area = area )
Configure whether rollover is enabled for streaming or storage streams .
83
13
22,509
def watch ( self , selector , callback ) : if selector not in self . _monitors : self . _monitors [ selector ] = set ( ) self . _monitors [ selector ] . add ( callback )
Call a function whenever a stream changes .
45
8
22,510
def create_walker ( self , selector , skip_all = True ) : if selector . buffered : walker = BufferedStreamWalker ( selector , self . _engine , skip_all = skip_all ) self . _queue_walkers . append ( walker ) return walker if selector . match_type == DataStream . CounterType : walker = CounterStreamWalker ( selector ) else : walker = VirtualStreamWalker ( selector ) self . _virtual_walkers . append ( walker ) return walker
Create a stream walker based on the given selector .
110
11
22,511
def destroy_walker ( self , walker ) : if walker . buffered : self . _queue_walkers . remove ( walker ) else : self . _virtual_walkers . remove ( walker )
Destroy a previously created stream walker .
46
8
22,512
def restore_walker ( self , dumped_state ) : selector_string = dumped_state . get ( u'selector' ) if selector_string is None : raise ArgumentError ( "Invalid stream walker state in restore_walker, missing 'selector' key" , state = dumped_state ) selector = DataStreamSelector . FromString ( selector_string ) walker = self . create_walker ( selector ) walker . restore ( dumped_state ) return walker
Restore a stream walker that was previously serialized .
101
12
22,513
def clear ( self ) : for walker in self . _virtual_walkers : walker . skip_all ( ) self . _engine . clear ( ) for walker in self . _queue_walkers : walker . skip_all ( ) self . _last_values = { }
Clear all data from this sensor_log .
63
9
22,514
def push ( self , stream , reading ) : # Make sure the stream is correct reading = copy . copy ( reading ) reading . stream = stream . encode ( ) if stream . buffered : output_buffer = stream . output if self . id_assigner is not None : reading . reading_id = self . id_assigner ( stream , reading ) try : self . _engine . push ( reading ) except StorageFullError : # If we are in fill-stop mode, don't auto erase old data. if ( stream . output and not self . _rollover_streaming ) or ( not stream . output and not self . _rollover_storage ) : raise self . _erase_buffer ( stream . output ) self . _engine . push ( reading ) for walker in self . _queue_walkers : # Only notify the walkers that are on this queue if walker . selector . output == output_buffer : walker . notify_added ( stream ) # Activate any monitors we have for this stream for selector in self . _monitors : if selector is None or selector . matches ( stream ) : for callback in self . _monitors [ selector ] : callback ( stream , reading ) # Virtual streams live only in their walkers, so update each walker # that contains this stream. for walker in self . _virtual_walkers : if walker . matches ( stream ) : walker . push ( stream , reading ) self . _last_values [ stream ] = reading
Push a reading into a stream updating any associated stream walkers .
319
13
22,515
def _erase_buffer ( self , output_buffer ) : erase_size = self . _model . get ( u'buffer_erase_size' ) buffer_type = u'storage' if output_buffer : buffer_type = u'streaming' old_readings = self . _engine . popn ( buffer_type , erase_size ) # Now go through all of our walkers that could match and # update their availability counts and data buffer pointers for reading in old_readings : stream = DataStream . FromEncoded ( reading . stream ) for walker in self . _queue_walkers : # Only notify the walkers that are on this queue if walker . selector . output == output_buffer : walker . notify_rollover ( stream )
Erase readings in the specified buffer to make space .
168
11
22,516
def inspect_last ( self , stream , only_allocated = False ) : if only_allocated : found = False for walker in self . _virtual_walkers : if walker . matches ( stream ) : found = True break if not found : raise UnresolvedIdentifierError ( "inspect_last could not find an allocated virtual streamer for the desired stream" , stream = stream ) if stream in self . _last_values : return self . _last_values [ stream ] raise StreamEmptyError ( u"inspect_last called on stream that has never been written to" , stream = stream )
Return the last value pushed into a stream .
132
9
22,517
def _run_exitfuncs ( ) : while _exithandlers : func , targs , kargs = _exithandlers . pop ( ) func ( * targs , * * kargs )
run any registered exit functions
45
5
22,518
def _windowsLdmodTargets ( target , source , env , for_signature ) : return _dllTargets ( target , source , env , for_signature , 'LDMODULE' )
Get targets for loadable modules .
46
7
22,519
def _windowsLdmodSources ( target , source , env , for_signature ) : return _dllSources ( target , source , env , for_signature , 'LDMODULE' )
Get sources for loadable modules .
42
7
22,520
def _dllEmitter ( target , source , env , paramtp ) : SCons . Tool . msvc . validate_vars ( env ) extratargets = [ ] extrasources = [ ] dll = env . FindIxes ( target , '%sPREFIX' % paramtp , '%sSUFFIX' % paramtp ) no_import_lib = env . get ( 'no_import_lib' , 0 ) if not dll : raise SCons . Errors . UserError ( 'A shared library should have exactly one target with the suffix: %s' % env . subst ( '$%sSUFFIX' % paramtp ) ) insert_def = env . subst ( "$WINDOWS_INSERT_DEF" ) if not insert_def in [ '' , '0' , 0 ] and not env . FindIxes ( source , "WINDOWSDEFPREFIX" , "WINDOWSDEFSUFFIX" ) : # append a def file to the list of sources extrasources . append ( env . ReplaceIxes ( dll , '%sPREFIX' % paramtp , '%sSUFFIX' % paramtp , "WINDOWSDEFPREFIX" , "WINDOWSDEFSUFFIX" ) ) version_num , suite = SCons . Tool . msvs . msvs_parse_version ( env . get ( 'MSVS_VERSION' , '6.0' ) ) if version_num >= 8.0 and ( env . get ( 'WINDOWS_INSERT_MANIFEST' , 0 ) or env . get ( 'WINDOWS_EMBED_MANIFEST' , 0 ) ) : # MSVC 8 and above automatically generate .manifest files that must be installed extratargets . append ( env . ReplaceIxes ( dll , '%sPREFIX' % paramtp , '%sSUFFIX' % paramtp , "WINDOWSSHLIBMANIFESTPREFIX" , "WINDOWSSHLIBMANIFESTSUFFIX" ) ) if 'PDB' in env and env [ 'PDB' ] : pdb = env . arg2nodes ( '$PDB' , target = target , source = source ) [ 0 ] extratargets . append ( pdb ) target [ 0 ] . attributes . pdb = pdb if version_num >= 11.0 and env . get ( 'PCH' , 0 ) : # MSVC 11 and above need the PCH object file to be added to the link line, # otherwise you get link error LNK2011. pchobj = SCons . Util . splitext ( str ( env [ 'PCH' ] ) ) [ 0 ] + '.obj' # print "prog_emitter, version %s, appending pchobj %s"%(version_num, pchobj) if pchobj not in extrasources : extrasources . append ( pchobj ) if not no_import_lib and not env . FindIxes ( target , "LIBPREFIX" , "LIBSUFFIX" ) : # Append an import library to the list of targets. extratargets . append ( env . ReplaceIxes ( dll , '%sPREFIX' % paramtp , '%sSUFFIX' % paramtp , "LIBPREFIX" , "LIBSUFFIX" ) ) # and .exp file is created if there are exports from a DLL extratargets . append ( env . ReplaceIxes ( dll , '%sPREFIX' % paramtp , '%sSUFFIX' % paramtp , "WINDOWSEXPPREFIX" , "WINDOWSEXPSUFFIX" ) ) return ( target + extratargets , source + extrasources )
Common implementation of dll emitter .
818
8
22,521
def embedManifestDllCheck ( target , source , env ) : if env . get ( 'WINDOWS_EMBED_MANIFEST' , 0 ) : manifestSrc = target [ 0 ] . get_abspath ( ) + '.manifest' if os . path . exists ( manifestSrc ) : ret = ( embedManifestDllAction ) ( [ target [ 0 ] ] , None , env ) if ret : raise SCons . Errors . UserError ( "Unable to embed manifest into %s" % ( target [ 0 ] ) ) return ret else : print ( '(embed: no %s.manifest found; not embedding.)' % str ( target [ 0 ] ) ) return 0
Function run by embedManifestDllCheckAction to check for existence of manifest and other conditions and embed the manifest by calling embedManifestDllAction if so .
153
34
22,522
def embedManifestExeCheck ( target , source , env ) : if env . get ( 'WINDOWS_EMBED_MANIFEST' , 0 ) : manifestSrc = target [ 0 ] . get_abspath ( ) + '.manifest' if os . path . exists ( manifestSrc ) : ret = ( embedManifestExeAction ) ( [ target [ 0 ] ] , None , env ) if ret : raise SCons . Errors . UserError ( "Unable to embed manifest into %s" % ( target [ 0 ] ) ) return ret else : print ( '(embed: no %s.manifest found; not embedding.)' % str ( target [ 0 ] ) ) return 0
Function run by embedManifestExeCheckAction to check for existence of manifest and other conditions and embed the manifest by calling embedManifestExeAction if so .
153
34
22,523
def generate ( env ) : global PSAction if PSAction is None : PSAction = SCons . Action . Action ( '$PSCOM' , '$PSCOMSTR' ) global DVIPSAction if DVIPSAction is None : DVIPSAction = SCons . Action . Action ( DviPsFunction , strfunction = DviPsStrFunction ) global PSBuilder if PSBuilder is None : PSBuilder = SCons . Builder . Builder ( action = PSAction , prefix = '$PSPREFIX' , suffix = '$PSSUFFIX' , src_suffix = '.dvi' , src_builder = 'DVI' , single_source = True ) env [ 'BUILDERS' ] [ 'PostScript' ] = PSBuilder env [ 'DVIPS' ] = 'dvips' env [ 'DVIPSFLAGS' ] = SCons . Util . CLVar ( '' ) # I'm not quite sure I got the directories and filenames right for variant_dir # We need to be in the correct directory for the sake of latex \includegraphics eps included files. env [ 'PSCOM' ] = 'cd ${TARGET.dir} && $DVIPS $DVIPSFLAGS -o ${TARGET.file} ${SOURCE.file}' env [ 'PSPREFIX' ] = '' env [ 'PSSUFFIX' ] = '.ps'
Add Builders and construction variables for dvips to an Environment .
311
14
22,524
def build_library ( tile , libname , chip ) : dirs = chip . build_dirs ( ) output_name = '%s_%s.a' % ( libname , chip . arch_name ( ) ) # Support both firmware/src and just src locations for source code if os . path . exists ( 'firmware' ) : VariantDir ( dirs [ 'build' ] , os . path . join ( 'firmware' , 'src' ) , duplicate = 0 ) else : VariantDir ( dirs [ 'build' ] , 'src' , duplicate = 0 ) library_env = setup_environment ( chip ) library_env [ 'OUTPUT' ] = output_name library_env [ 'OUTPUT_PATH' ] = os . path . join ( dirs [ 'build' ] , output_name ) library_env [ 'BUILD_DIR' ] = dirs [ 'build' ] # Check for any dependencies this library has tilebus_defs = setup_dependencies ( tile , library_env ) # Create header files for all tilebus config variables and commands that are defined in ourselves # or in our dependencies tilebus_defs += tile . find_products ( 'tilebus_definitions' ) compile_tilebus ( tilebus_defs , library_env , header_only = True ) SConscript ( os . path . join ( dirs [ 'build' ] , 'SConscript' ) , exports = 'library_env' ) library_env . InstallAs ( os . path . join ( dirs [ 'output' ] , output_name ) , os . path . join ( dirs [ 'build' ] , output_name ) ) # See if we should copy any files over to the output: for src , dst in chip . property ( 'copy_files' , [ ] ) : srcpath = os . path . join ( * src ) destpath = os . path . join ( dirs [ 'output' ] , dst ) library_env . InstallAs ( destpath , srcpath ) return os . path . join ( dirs [ 'output' ] , output_name )
Build a static ARM cortex library
465
6
22,525
def setup_environment ( chip , args_file = None ) : config = ConfigManager ( ) # Make sure we never get MSVC settings for windows since that has the wrong command line flags for gcc if platform . system ( ) == 'Windows' : env = Environment ( tools = [ 'mingw' ] , ENV = os . environ ) else : env = Environment ( tools = [ 'default' ] , ENV = os . environ ) env [ 'INCPREFIX' ] = '-I"' env [ 'INCSUFFIX' ] = '"' env [ 'CPPDEFPREFIX' ] = '' env [ 'CPPDEFSUFFIX' ] = '' env [ 'CPPPATH' ] = chip . includes ( ) env [ 'ARCH' ] = chip # Setup Cross Compiler env [ 'CC' ] = 'arm-none-eabi-gcc' env [ 'AS' ] = 'arm-none-eabi-gcc' env [ 'LINK' ] = 'arm-none-eabi-gcc' env [ 'AR' ] = 'arm-none-eabi-ar' env [ 'RANLIB' ] = 'arm-none-eabi-ranlib' # AS command line is by default setup for call as directly so we need # to modify it to call via *-gcc to allow for preprocessing env [ 'ASCOM' ] = "$AS $ASFLAGS -o $TARGET -c $SOURCES" # Setup nice display strings unless we're asked to show raw commands if not config . get ( 'build:show-commands' ) : env [ 'CCCOMSTR' ] = "Compiling $TARGET" env [ 'ARCOMSTR' ] = "Building static library $TARGET" env [ 'RANLIBCOMSTR' ] = "Indexing static library $TARGET" env [ 'LINKCOMSTR' ] = "Linking $TARGET" # Setup Compiler Flags env [ 'CCFLAGS' ] = chip . combined_properties ( 'cflags' ) env [ 'LINKFLAGS' ] = chip . combined_properties ( 'ldflags' ) env [ 'ARFLAGS' ] . append ( chip . combined_properties ( 'arflags' ) ) # There are default ARFLAGS that are necessary to keep env [ 'ASFLAGS' ] . append ( chip . combined_properties ( 'asflags' ) ) # Add in compile tile definitions defines = utilities . build_defines ( chip . property ( 'defines' , { } ) ) env [ 'CPPDEFINES' ] = defines if args_file is not None : env [ 'CCCOM' ] = "$CC $CCFLAGS $CPPFLAGS @{} -c -o $TARGET $SOURCES" . format ( args_file ) # Setup Target Architecture env [ 'CCFLAGS' ] . append ( '-mcpu=%s' % chip . property ( 'cpu' ) ) env [ 'ASFLAGS' ] . append ( '-mcpu=%s' % chip . property ( 'cpu' ) ) env [ 'LINKFLAGS' ] . append ( '-mcpu=%s' % chip . property ( 'cpu' ) ) # Initialize library paths (all libraries are added via dependencies) env [ 'LIBPATH' ] = [ ] env [ 'LIBS' ] = [ ] return env
Setup the SCons environment for compiling arm cortex code .
745
11
22,526
def tb_h_file_creation ( target , source , env ) : files = [ str ( x ) for x in source ] try : desc = TBDescriptor ( files ) except pyparsing . ParseException as e : raise BuildError ( "Could not parse tilebus file" , parsing_exception = e ) block = desc . get_block ( config_only = True ) block . render_template ( block . CommandHeaderTemplate , out_path = str ( target [ 0 ] ) ) block . render_template ( block . ConfigHeaderTemplate , out_path = str ( target [ 1 ] ) )
Compile tilebus file into only . h files corresponding to config variables for inclusion in a library
134
19
22,527
def checksum_creation_action ( target , source , env ) : # Important Notes: # There are apparently many ways to calculate a CRC-32 checksum, we use the following options # Initial seed value prepended to the input: 0xFFFFFFFF # Whether the input is fed into the shift register least-significant bit or most-significant bit first: LSB # Whether each data word is inverted: No # Whether the final CRC value is inverted: No # *These settings must agree between the executive and this function* import crcmod crc32_func = crcmod . mkCrcFun ( 0x104C11DB7 , initCrc = 0xFFFFFFFF , rev = False , xorOut = 0 ) with open ( str ( source [ 0 ] ) , 'rb' ) as f : data = f . read ( ) # Ignore the last four bytes of the file since that is where the checksum will go data = data [ : - 4 ] # Make sure the magic number is correct so that we're dealing with an actual firmware image magicbin = data [ - 4 : ] magic , = struct . unpack ( '<L' , magicbin ) if magic != 0xBAADDAAD : raise BuildError ( "Attempting to patch a file that is not a CDB binary or has the wrong size" , reason = "invalid magic number found" , actual_magic = magic , desired_magic = 0xBAADDAAD ) # Calculate CRC32 in the same way as its done in the target microcontroller checksum = crc32_func ( data ) & 0xFFFFFFFF with open ( str ( target [ 0 ] ) , 'w' ) as f : # hex strings end with L on windows and possibly some other systems checkhex = hex ( checksum ) if checkhex [ - 1 ] == 'L' : checkhex = checkhex [ : - 1 ] f . write ( "--defsym=__image_checksum=%s\n" % checkhex )
Create a linker command file for patching an application checksum into a firmware image
428
17
22,528
def create_arg_file ( target , source , env ) : output_name = str ( target [ 0 ] ) with open ( output_name , "w" ) as outfile : for define in env . get ( 'CPPDEFINES' , [ ] ) : outfile . write ( define + '\n' ) include_folders = target [ 0 ] . RDirs ( tuple ( env . get ( 'CPPPATH' , [ ] ) ) ) include_folders . append ( '.' ) for include_folder in include_folders : include_folder = str ( include_folder ) if not include_folder . startswith ( 'build' ) : include_folder = os . path . join ( 'firmware' , 'src' , include_folder ) outfile . write ( '"-I{}"\n' . format ( include_folder . replace ( '\\' , '\\\\' ) ) )
Create an argument file containing - I and - D arguments to gcc .
202
14
22,529
def merge_hex_executables ( target , source , env ) : output_name = str ( target [ 0 ] ) hex_final = IntelHex ( ) for image in source : file = str ( image ) root , ext = os . path . splitext ( file ) file_format = ext [ 1 : ] if file_format == 'elf' : file = root + '.hex' hex_data = IntelHex ( file ) # merge will throw errors on mismatched Start Segment Addresses, which we don't need # See <https://stackoverflow.com/questions/26295776/what-are-the-intel-hex-records-type-03-or-05-doing-in-ihex-program-for-arm> hex_data . start_addr = None hex_final . merge ( hex_data , overlap = 'error' ) with open ( output_name , 'w' ) as outfile : hex_final . write_hex_file ( outfile )
Combine all hex files into a singular executable file .
220
11
22,530
def ensure_image_is_hex ( input_path ) : family = utilities . get_family ( 'module_settings.json' ) target = family . platform_independent_target ( ) build_dir = target . build_dirs ( ) [ 'build' ] if platform . system ( ) == 'Windows' : env = Environment ( tools = [ 'mingw' ] , ENV = os . environ ) else : env = Environment ( tools = [ 'default' ] , ENV = os . environ ) input_path = str ( input_path ) image_name = os . path . basename ( input_path ) root , ext = os . path . splitext ( image_name ) if len ( ext ) == 0 : raise BuildError ( "Unknown file format or missing file extension in ensure_image_is_hex" , file_name = input_path ) file_format = ext [ 1 : ] if file_format == 'hex' : return input_path if file_format == 'elf' : new_file = os . path . join ( build_dir , root + '.hex' ) if new_file not in CONVERTED_HEX_FILES : env . Command ( new_file , input_path , action = Action ( "arm-none-eabi-objcopy -O ihex $SOURCE $TARGET" , "Creating intel hex file from: $SOURCE" ) ) CONVERTED_HEX_FILES . add ( new_file ) return new_file raise BuildError ( "Unknown file format extension in ensure_image_is_hex" , file_name = input_path , extension = file_format )
Return a path to a hex version of a firmware image .
360
12
22,531
def _dispatch_rpc ( self , address , rpc_id , arg_payload ) : if self . emulator . is_tile_busy ( address ) : self . _track_change ( 'device.rpc_busy_response' , ( address , rpc_id , arg_payload , None , None ) , formatter = format_rpc ) raise BusyRPCResponse ( ) try : # Send the RPC immediately and wait for the response resp = super ( EmulatedDevice , self ) . call_rpc ( address , rpc_id , arg_payload ) self . _track_change ( 'device.rpc_sent' , ( address , rpc_id , arg_payload , resp , None ) , formatter = format_rpc ) return resp except AsynchronousRPCResponse : self . _track_change ( 'device.rpc_started' , ( address , rpc_id , arg_payload , None , None ) , formatter = format_rpc ) raise except Exception as exc : self . _track_change ( 'device.rpc_exception' , ( address , rpc_id , arg_payload , None , exc ) , formatter = format_rpc ) raise
Background work queue handler to dispatch RPCs .
274
9
22,532
def rpc ( self , address , rpc_id , * args , * * kwargs ) : if isinstance ( rpc_id , RPCDeclaration ) : arg_format = rpc_id . arg_format resp_format = rpc_id . resp_format rpc_id = rpc_id . rpc_id else : arg_format = kwargs . get ( 'arg_format' , None ) resp_format = kwargs . get ( 'resp_format' , None ) arg_payload = b'' if arg_format is not None : arg_payload = pack_rpc_payload ( arg_format , args ) self . _logger . debug ( "Sending rpc to %d:%04X, payload=%s" , address , rpc_id , args ) resp_payload = self . call_rpc ( address , rpc_id , arg_payload ) if resp_format is None : return [ ] resp = unpack_rpc_payload ( resp_format , resp_payload ) return resp
Immediately dispatch an RPC inside this EmulatedDevice .
239
11
22,533
def trace_sync ( self , data , timeout = 5.0 ) : done = AwaitableResponse ( ) self . trace ( data , callback = done . set_result ) return done . wait ( timeout )
Send tracing data and wait for it to finish .
45
10
22,534
def stream_sync ( self , report , timeout = 120.0 ) : done = AwaitableResponse ( ) self . stream ( report , callback = done . set_result ) return done . wait ( timeout )
Send a report and wait for it to finish .
45
10
22,535
def synchronize_task ( self , func , * args , * * kwargs ) : async def _runner ( ) : return func ( * args , * * kwargs ) return self . emulator . run_task_external ( _runner ( ) )
Run callable in the rpc thread and wait for it to finish .
55
15
22,536
def load_metascenario ( self , scenario_list ) : for scenario in scenario_list : name = scenario . get ( 'name' ) if name is None : raise DataError ( "Scenario in scenario list is missing a name parameter" , scenario = scenario ) tile_address = scenario . get ( 'tile' ) args = scenario . get ( 'args' , { } ) dest = self if tile_address is not None : dest = self . _tiles . get ( tile_address ) if dest is None : raise DataError ( "Attempted to load a scenario into a tile address that does not exist" , address = tile_address , valid_addresses = list ( self . _tiles ) ) dest . load_scenario ( name , * * args )
Load one or more scenarios from a list .
166
9
22,537
def associated_stream ( self ) : if not self . important : raise InternalError ( "You may only call autocopied_stream on when DataStream.important is True" , stream = self ) if self . stream_id >= DataStream . ImportantSystemStorageStart : stream_type = DataStream . BufferedType else : stream_type = DataStream . OutputType return DataStream ( stream_type , self . stream_id , True )
Return the corresponding output or storage stream for an important system input .
95
13
22,538
def FromString ( cls , string_rep ) : rep = str ( string_rep ) parts = rep . split ( ) if len ( parts ) > 3 : raise ArgumentError ( "Too many whitespace separated parts of stream designator" , input_string = string_rep ) elif len ( parts ) == 3 and parts [ 0 ] != u'system' : raise ArgumentError ( "Too many whitespace separated parts of stream designator" , input_string = string_rep ) elif len ( parts ) < 2 : raise ArgumentError ( "Too few components in stream designator" , input_string = string_rep ) # Now actually parse the string if len ( parts ) == 3 : system = True stream_type = parts [ 1 ] stream_id = parts [ 2 ] else : system = False stream_type = parts [ 0 ] stream_id = parts [ 1 ] try : stream_id = int ( stream_id , 0 ) except ValueError as exc : raise ArgumentError ( "Could not convert stream id to integer" , error_string = str ( exc ) , stream_id = stream_id ) try : stream_type = cls . StringToType [ stream_type ] except KeyError : raise ArgumentError ( "Invalid stream type given" , stream_type = stream_type , known_types = cls . StringToType . keys ( ) ) return DataStream ( stream_type , stream_id , system )
Create a DataStream from a string representation .
309
9
22,539
def FromEncoded ( self , encoded ) : stream_type = ( encoded >> 12 ) & 0b1111 stream_system = bool ( encoded & ( 1 << 11 ) ) stream_id = ( encoded & ( ( 1 << 11 ) - 1 ) ) return DataStream ( stream_type , stream_id , stream_system )
Create a DataStream from an encoded 16 - bit unsigned integer .
70
13
22,540
def as_stream ( self ) : if not self . singular : raise ArgumentError ( "Attempted to convert a non-singular selector to a data stream, it matches multiple" , selector = self ) return DataStream ( self . match_type , self . match_id , self . match_spec == DataStreamSelector . MatchSystemOnly )
Convert this selector to a DataStream .
74
9
22,541
def FromStream ( cls , stream ) : if stream . system : specifier = DataStreamSelector . MatchSystemOnly else : specifier = DataStreamSelector . MatchUserOnly return DataStreamSelector ( stream . stream_type , stream . stream_id , specifier )
Create a DataStreamSelector from a DataStream .
60
11
22,542
def FromEncoded ( cls , encoded ) : match_spec = encoded & ( ( 1 << 11 ) | ( 1 << 15 ) ) match_type = ( encoded & ( 0b111 << 12 ) ) >> 12 match_id = encoded & ( ( 1 << 11 ) - 1 ) if match_spec not in cls . SpecifierEncodingMap : raise ArgumentError ( "Unknown encoded match specifier" , match_spec = match_spec , known_specifiers = cls . SpecifierEncodingMap . keys ( ) ) spec_name = cls . SpecifierEncodingMap [ match_spec ] # Handle wildcard matches if match_id == cls . MatchAllCode : match_id = None return DataStreamSelector ( match_type , match_id , spec_name )
Create a DataStreamSelector from an encoded 16 - bit value .
172
14
22,543
def FromString ( cls , string_rep ) : rep = str ( string_rep ) rep = rep . replace ( u'node' , '' ) rep = rep . replace ( u'nodes' , '' ) if rep . startswith ( u'all' ) : parts = rep . split ( ) spec_string = u'' if len ( parts ) == 3 : spec_string = parts [ 1 ] stream_type = parts [ 2 ] elif len ( parts ) == 2 : stream_type = parts [ 1 ] else : raise ArgumentError ( "Invalid wildcard stream selector" , string_rep = string_rep ) try : # Remove pluralization that can come with e.g. 'all system outputs' if stream_type . endswith ( u's' ) : stream_type = stream_type [ : - 1 ] stream_type = DataStream . StringToType [ stream_type ] except KeyError : raise ArgumentError ( "Invalid stream type given" , stream_type = stream_type , known_types = DataStream . StringToType . keys ( ) ) stream_spec = DataStreamSelector . SpecifierNames . get ( spec_string , None ) if stream_spec is None : raise ArgumentError ( "Invalid stream specifier given (should be system, user, combined or blank)" , string_rep = string_rep , spec_string = spec_string ) return DataStreamSelector ( stream_type , None , stream_spec ) # If we're not matching a wildcard stream type, then the match is exactly # the same as a DataStream identifier, so use that to match it. stream = DataStream . FromString ( rep ) return DataStreamSelector . FromStream ( stream )
Create a DataStreamSelector from a string .
370
10
22,544
def matches ( self , stream ) : if self . match_type != stream . stream_type : return False if self . match_id is not None : return self . match_id == stream . stream_id if self . match_spec == DataStreamSelector . MatchUserOnly : return not stream . system elif self . match_spec == DataStreamSelector . MatchSystemOnly : return stream . system elif self . match_spec == DataStreamSelector . MatchUserAndBreaks : return ( not stream . system ) or ( stream . system and ( stream . stream_id in DataStream . KnownBreakStreams ) ) # The other case is that match_spec is MatchCombined, which matches everything # regardless of system of user flag return True
Check if this selector matches the given stream
161
8
22,545
def encode ( self ) : match_id = self . match_id if match_id is None : match_id = ( 1 << 11 ) - 1 return ( self . match_type << 12 ) | DataStreamSelector . SpecifierEncodings [ self . match_spec ] | match_id
Encode this stream as a packed 16 - bit unsigned integer .
65
13
22,546
def generate ( env ) : M4Action = SCons . Action . Action ( '$M4COM' , '$M4COMSTR' ) bld = SCons . Builder . Builder ( action = M4Action , src_suffix = '.m4' ) env [ 'BUILDERS' ] [ 'M4' ] = bld # .m4 files might include other files, and it would be pretty hard # to write a scanner for it, so let's just cd to the dir of the m4 # file and run from there. # The src_suffix setup is like so: file.c.m4 -> file.c, # file.cpp.m4 -> file.cpp etc. env [ 'M4' ] = 'm4' env [ 'M4FLAGS' ] = SCons . Util . CLVar ( '-E' ) env [ 'M4COM' ] = 'cd ${SOURCE.rsrcdir} && $M4 $M4FLAGS < ${SOURCE.file} > ${TARGET.abspath}'
Add Builders and construction variables for m4 to an Environment .
232
13
22,547
def generate ( env ) : env . AppendUnique ( LATEXSUFFIXES = SCons . Tool . LaTeXSuffixes ) from . import dvi dvi . generate ( env ) from . import pdf pdf . generate ( env ) bld = env [ 'BUILDERS' ] [ 'DVI' ] bld . add_action ( '.ltx' , LaTeXAuxAction ) bld . add_action ( '.latex' , LaTeXAuxAction ) bld . add_emitter ( '.ltx' , SCons . Tool . tex . tex_eps_emitter ) bld . add_emitter ( '.latex' , SCons . Tool . tex . tex_eps_emitter ) SCons . Tool . tex . generate_common ( env )
Add Builders and construction variables for LaTeX to an Environment .
174
13
22,548
def encode_priority ( self , facility , priority ) : return ( facility << 3 ) | self . priority_map . get ( priority , self . LOG_WARNING )
Encode the facility and priority . You can pass in strings or integers - if strings are passed the facility_names and priority_names mapping dictionaries are used to convert them to integers .
35
38
22,549
def close ( self ) : self . acquire ( ) try : if self . transport is not None : self . transport . close ( ) super ( Rfc5424SysLogHandler , self ) . close ( ) finally : self . release ( )
Closes the socket .
51
5
22,550
def sonTraceRootPath ( ) : import sonLib . bioio i = os . path . abspath ( sonLib . bioio . __file__ ) return os . path . split ( os . path . split ( os . path . split ( i ) [ 0 ] ) [ 0 ] ) [ 0 ]
function for finding external location
66
5
22,551
def linOriginRegression ( points ) : j = sum ( [ i [ 0 ] for i in points ] ) k = sum ( [ i [ 1 ] for i in points ] ) if j != 0 : return k / j , j , k return 1 , j , k
computes a linear regression starting at zero
58
8
22,552
def close ( i , j , tolerance ) : return i <= j + tolerance and i >= j - tolerance
check two float values are within a bound of one another
22
11
22,553
def filterOverlappingAlignments ( alignments ) : l = [ ] alignments = alignments [ : ] sortAlignments ( alignments ) alignments . reverse ( ) for pA1 in alignments : for pA2 in l : if pA1 . contig1 == pA2 . contig1 and getPositiveCoordinateRangeOverlap ( pA1 . start1 + 1 , pA1 . end1 , pA2 . start1 + 1 , pA2 . end1 ) is not None : #One offset, inclusive coordinates break if pA1 . contig2 == pA2 . contig2 and getPositiveCoordinateRangeOverlap ( pA1 . start2 + 1 , pA1 . end2 , pA2 . start2 + 1 , pA2 . end2 ) is not None : #One offset, inclusive coordinates break if pA1 . contig2 == pA2 . contig1 and getPositiveCoordinateRangeOverlap ( pA1 . start2 + 1 , pA1 . end2 , pA2 . start1 + 1 , pA2 . end1 ) is not None : #One offset, inclusive coordinates break if pA1 . contig1 == pA2 . contig2 and getPositiveCoordinateRangeOverlap ( pA1 . start1 + 1 , pA1 . end1 , pA2 . start2 + 1 , pA2 . end2 ) is not None : #One offset, inclusive coordinates break else : l . append ( pA1 ) l . reverse ( ) return l
Filter alignments to be non - overlapping .
347
9
22,554
def binaryTree_depthFirstNumbers ( binaryTree , labelTree = True , dontStopAtID = True ) : traversalIDs = { } def traverse ( binaryTree , mid = 0 , leafNo = 0 ) : if binaryTree . internal and ( dontStopAtID or binaryTree . iD is None ) : midStart = mid j , leafNo = traverse ( binaryTree . left , mid , leafNo ) mid = j j , leafNo = traverse ( binaryTree . right , j + 1 , leafNo ) traversalIDs [ binaryTree ] = TraversalID ( midStart , mid , j ) return j , leafNo traversalID = TraversalID ( mid , mid , mid + 1 ) traversalID . leafNo = leafNo #thus nodes must be unique traversalIDs [ binaryTree ] = traversalID return mid + 1 , leafNo + 1 traverse ( binaryTree ) if labelTree : for binaryTree in traversalIDs . keys ( ) : binaryTree . traversalID = traversalIDs [ binaryTree ] return traversalIDs
get mid - order depth first tree numbers
226
8
22,555
def binaryTree_nodeNames ( binaryTree ) : def fn ( binaryTree , labels ) : if binaryTree . internal : fn ( binaryTree . left , labels ) fn ( binaryTree . right , labels ) labels [ binaryTree . traversalID . mid ] = labels [ binaryTree . left . traversalID . mid ] + "_" + labels [ binaryTree . right . traversalID . mid ] return labels [ binaryTree . traversalID . mid ] else : labels [ binaryTree . traversalID . mid ] = str ( binaryTree . iD ) return labels [ binaryTree . traversalID . mid ] labels = [ None ] * binaryTree . traversalID . midEnd fn ( binaryTree , labels ) return labels
creates names for the leave and internal nodes of the newick tree from the leaf labels
156
18
22,556
def makeRandomBinaryTree ( leafNodeNumber = None ) : while True : nodeNo = [ - 1 ] def fn ( ) : nodeNo [ 0 ] += 1 if random . random ( ) > 0.6 : i = str ( nodeNo [ 0 ] ) return BinaryTree ( 0.00001 + random . random ( ) * 0.8 , True , fn ( ) , fn ( ) , i ) else : return BinaryTree ( 0.00001 + random . random ( ) * 0.8 , False , None , None , str ( nodeNo [ 0 ] ) ) tree = fn ( ) def fn2 ( tree ) : if tree . internal : return fn2 ( tree . left ) + fn2 ( tree . right ) return 1 if leafNodeNumber is None or fn2 ( tree ) == leafNodeNumber : return tree
Creates a random binary tree .
178
7
22,557
def getRandomBinaryTreeLeafNode ( binaryTree ) : if binaryTree . internal == True : if random . random ( ) > 0.5 : return getRandomBinaryTreeLeafNode ( binaryTree . left ) else : return getRandomBinaryTreeLeafNode ( binaryTree . right ) else : return binaryTree
Get random binary tree node .
70
6
22,558
def transformByDistance ( wV , subModel , alphabetSize = 4 ) : nc = [ 0.0 ] * alphabetSize for i in xrange ( 0 , alphabetSize ) : j = wV [ i ] k = subModel [ i ] for l in xrange ( 0 , alphabetSize ) : nc [ l ] += j * k [ l ] return nc
transform wV by given substitution matrix
81
7
22,559
def normaliseWV ( wV , normFac = 1.0 ) : f = sum ( wV ) / normFac return [ i / f for i in wV ]
make char probs divisible by one
38
8
22,560
def felsensteins ( binaryTree , subMatrices , ancestorProbs , leaves , alphabetSize ) : l = { } def upPass ( binaryTree ) : if binaryTree . internal : #is internal binaryTree i = branchUp ( binaryTree . left ) j = branchUp ( binaryTree . right ) k = multiplyWV ( i , j , alphabetSize ) l [ binaryTree . traversalID . mid ] = ( k , i , j ) return k l [ binaryTree . traversalID . mid ] = leaves [ binaryTree . traversalID . leafNo ] return leaves [ binaryTree . traversalID . leafNo ] def downPass ( binaryTree , ancestorProbs ) : if binaryTree . internal : #is internal binaryTree i = l [ binaryTree . traversalID . mid ] l [ binaryTree . traversalID . mid ] = multiplyWV ( ancestorProbs , i [ 0 ] , alphabetSize ) branchDown ( binaryTree . left , multiplyWV ( ancestorProbs , i [ 2 ] , alphabetSize ) ) branchDown ( binaryTree . right , multiplyWV ( ancestorProbs , i [ 1 ] , alphabetSize ) ) def branchUp ( binaryTree ) : return transformByDistance ( upPass ( binaryTree ) , subMatrices [ binaryTree . traversalID . mid ] , alphabetSize ) def branchDown ( binaryTree , ancestorProbs ) : downPass ( binaryTree , transformByDistance ( ancestorProbs , subMatrices [ binaryTree . traversalID . mid ] , alphabetSize ) ) upPass ( binaryTree ) downPass ( binaryTree , ancestorProbs ) return l
calculates the un - normalised probabilties of each non - gap residue position
350
19
22,561
def annotateTree ( bT , fn ) : l = [ None ] * bT . traversalID . midEnd def fn2 ( bT ) : l [ bT . traversalID . mid ] = fn ( bT ) if bT . internal : fn2 ( bT . left ) fn2 ( bT . right ) fn2 ( bT ) return l
annotate a tree in an external array using the given function
81
12
22,562
def remodelTreeRemovingRoot ( root , node ) : import bioio assert root . traversalID . mid != node hash = { } def fn ( bT ) : if bT . traversalID . mid == node : assert bT . internal == False return [ bT ] elif bT . internal : i = fn ( bT . left ) if i is None : i = fn ( bT . right ) if i is not None : hash [ i [ - 1 ] ] = bT i . append ( bT ) return i return None l = fn ( root ) def fn2 ( i , j ) : if i . left == j : return i . right assert i . right == j return i . left def fn3 ( bT ) : if hash [ bT ] == root : s = '(' + bioio . printBinaryTree ( fn2 ( hash [ bT ] , bT ) , bT , True ) [ : - 1 ] + ')' else : s = '(' + bioio . printBinaryTree ( fn2 ( hash [ bT ] , bT ) , bT , True ) [ : - 1 ] + ',' + fn3 ( hash [ bT ] ) + ')' return s + ":" + str ( bT . distance ) s = fn3 ( l [ 0 ] ) + ';' t = bioio . newickTreeParser ( s ) return t
Node is mid order number
306
5
22,563
def moveRoot ( root , branch ) : import bioio if root . traversalID . mid == branch : return bioio . newickTreeParser ( bioio . printBinaryTree ( root , True ) ) def fn2 ( tree , seq ) : if seq is not None : return '(' + bioio . printBinaryTree ( tree , True ) [ : - 1 ] + ',' + seq + ')' return bioio . printBinaryTree ( tree , True ) [ : - 1 ] def fn ( tree , seq ) : if tree . traversalID . mid == branch : i = tree . distance tree . distance /= 2 seq = '(' + bioio . printBinaryTree ( tree , True ) [ : - 1 ] + ',(' + seq + ( '):%s' % tree . distance ) + ');' tree . distance = i return seq if tree . internal : if branch < tree . traversalID . mid : seq = fn2 ( tree . right , seq ) return fn ( tree . left , seq ) else : assert branch > tree . traversalID . mid seq = fn2 ( tree . left , seq ) return fn ( tree . right , seq ) else : return bioio . printBinaryTree ( tree , True ) [ : - 1 ] s = fn ( root , None ) return bioio . newickTreeParser ( s )
Removes the old root and places the new root at the mid point along the given branch
294
18
22,564
def checkGeneTreeMatchesSpeciesTree ( speciesTree , geneTree , processID ) : def fn ( tree , l ) : if tree . internal : fn ( tree . left , l ) fn ( tree . right , l ) else : l . append ( processID ( tree . iD ) ) l = [ ] fn ( speciesTree , l ) l2 = [ ] fn ( geneTree , l2 ) for i in l2 : #print "node", i, l assert i in l
Function to check ids in gene tree all match nodes in species tree
106
14
22,565
def calculateProbableRootOfGeneTree ( speciesTree , geneTree , processID = lambda x : x ) : #get all rooted trees #run dup calc on each tree #return tree with fewest number of dups if geneTree . traversalID . midEnd <= 3 : return ( 0 , 0 , geneTree ) checkGeneTreeMatchesSpeciesTree ( speciesTree , geneTree , processID ) l = [ ] def fn ( tree ) : if tree . traversalID . mid != geneTree . left . traversalID . mid and tree . traversalID . mid != geneTree . right . traversalID . mid : newGeneTree = moveRoot ( geneTree , tree . traversalID . mid ) binaryTree_depthFirstNumbers ( newGeneTree ) dupCount , lossCount = calculateDupsAndLossesByReconcilingTrees ( speciesTree , newGeneTree , processID ) l . append ( ( dupCount , lossCount , newGeneTree ) ) if tree . internal : fn ( tree . left ) fn ( tree . right ) fn ( geneTree ) l . sort ( ) return l [ 0 ] [ 2 ] , l [ 0 ] [ 0 ] , l [ 0 ] [ 1 ]
Goes through each root possible branch making it the root . Returns tree that requires the minimum number of duplications .
262
23
22,566
def redirectLoggerStreamHandlers ( oldStream , newStream ) : for handler in list ( logger . handlers ) : #Remove old handlers if handler . stream == oldStream : handler . close ( ) logger . removeHandler ( handler ) for handler in logger . handlers : #Do not add a duplicate handler if handler . stream == newStream : return logger . addHandler ( logging . StreamHandler ( newStream ) )
Redirect the stream of a stream handler to a different stream
86
12
22,567
def popen ( command , tempFile ) : fileHandle = open ( tempFile , 'w' ) logger . debug ( "Running the command: %s" % command ) sts = subprocess . call ( command , shell = True , stdout = fileHandle , bufsize = - 1 ) fileHandle . close ( ) if sts != 0 : raise RuntimeError ( "Command: %s exited with non-zero status %i" % ( command , sts ) ) return sts
Runs a command and captures standard out in the given temp file .
100
14
22,568
def popenCatch ( command , stdinString = None ) : logger . debug ( "Running the command: %s" % command ) if stdinString != None : process = subprocess . Popen ( command , shell = True , stdin = subprocess . PIPE , stdout = subprocess . PIPE , bufsize = - 1 ) output , nothing = process . communicate ( stdinString ) else : process = subprocess . Popen ( command , shell = True , stdout = subprocess . PIPE , stderr = sys . stderr , bufsize = - 1 ) output , nothing = process . communicate ( ) #process.stdout.read().strip() sts = process . wait ( ) if sts != 0 : raise RuntimeError ( "Command: %s with stdin string '%s' exited with non-zero status %i" % ( command , stdinString , sts ) ) return output
Runs a command and return standard out .
201
9
22,569
def getTotalCpuTimeAndMemoryUsage ( ) : me = resource . getrusage ( resource . RUSAGE_SELF ) childs = resource . getrusage ( resource . RUSAGE_CHILDREN ) totalCpuTime = me . ru_utime + me . ru_stime + childs . ru_utime + childs . ru_stime totalMemoryUsage = me . ru_maxrss + me . ru_maxrss return totalCpuTime , totalMemoryUsage
Gives the total cpu time and memory usage of itself and its children .
109
15
22,570
def saveInputs ( savedInputsDir , listOfFilesAndDirsToSave ) : logger . info ( "Saving the inputs: %s to the directory: %s" % ( " " . join ( listOfFilesAndDirsToSave ) , savedInputsDir ) ) assert os . path . isdir ( savedInputsDir ) #savedInputsDir = getTempDirectory(saveInputsDir) createdFiles = [ ] for fileName in listOfFilesAndDirsToSave : if os . path . isfile ( fileName ) : copiedFileName = os . path . join ( savedInputsDir , os . path . split ( fileName ) [ - 1 ] ) system ( "cp %s %s" % ( fileName , copiedFileName ) ) else : copiedFileName = os . path . join ( savedInputsDir , os . path . split ( fileName ) [ - 1 ] ) + ".tar" system ( "tar -cf %s %s" % ( copiedFileName , fileName ) ) createdFiles . append ( copiedFileName ) return createdFiles
Copies the list of files to a directory created in the save inputs dir and returns the name of this directory .
237
23
22,571
def nameValue ( name , value , valueType = str , quotes = False ) : if valueType == bool : if value : return "--%s" % name return "" if value is None : return "" if quotes : return "--%s '%s'" % ( name , valueType ( value ) ) return "--%s %s" % ( name , valueType ( value ) )
Little function to make it easier to make name value strings for commands .
84
14
22,572
def makeSubDir ( dirName ) : if not os . path . exists ( dirName ) : os . mkdir ( dirName ) os . chmod ( dirName , 0777 ) return dirName
Makes a given subdirectory if it doesn t already exist making sure it us public .
43
18
22,573
def getTempFile ( suffix = "" , rootDir = None ) : if rootDir is None : handle , tmpFile = tempfile . mkstemp ( suffix ) os . close ( handle ) return tmpFile else : tmpFile = os . path . join ( rootDir , "tmp_" + getRandomAlphaNumericString ( ) + suffix ) open ( tmpFile , 'w' ) . close ( ) os . chmod ( tmpFile , 0777 ) #Ensure everyone has access to the file. return tmpFile
Returns a string representing a temporary file that must be manually deleted
111
12
22,574
def getTempDirectory ( rootDir = None ) : if rootDir is None : return tempfile . mkdtemp ( ) else : if not os . path . exists ( rootDir ) : try : os . makedirs ( rootDir ) except OSError : # Maybe it got created between the test and the makedirs call? pass while True : # Keep trying names until we find one that doesn't exist. If one # does exist, don't nest inside it, because someone else may be # using it for something. tmpDir = os . path . join ( rootDir , "tmp_" + getRandomAlphaNumericString ( ) ) if not os . path . exists ( tmpDir ) : break os . mkdir ( tmpDir ) os . chmod ( tmpDir , 0777 ) #Ensure everyone has access to the file. return tmpDir
returns a temporary directory that must be manually deleted . rootDir will be created if it does not exist .
183
22
22,575
def catFiles ( filesToCat , catFile ) : if len ( filesToCat ) == 0 : #We must handle this case or the cat call will hang waiting for input open ( catFile , 'w' ) . close ( ) return maxCat = 25 system ( "cat %s > %s" % ( " " . join ( filesToCat [ : maxCat ] ) , catFile ) ) filesToCat = filesToCat [ maxCat : ] while len ( filesToCat ) > 0 : system ( "cat %s >> %s" % ( " " . join ( filesToCat [ : maxCat ] ) , catFile ) ) filesToCat = filesToCat [ maxCat : ]
Cats a bunch of files into one file . Ensures a no more than maxCat files are concatenated at each step .
151
27
22,576
def prettyXml ( elem ) : roughString = ET . tostring ( elem , "utf-8" ) reparsed = minidom . parseString ( roughString ) return reparsed . toprettyxml ( indent = " " )
Return a pretty - printed XML string for the ElementTree Element .
54
13
22,577
def fastaEncodeHeader ( attributes ) : for i in attributes : assert len ( str ( i ) . split ( ) ) == 1 return "|" . join ( [ str ( i ) for i in attributes ] )
Decodes the fasta header
47
6
22,578
def fastaWrite ( fileHandleOrFile , name , seq , mode = "w" ) : fileHandle = _getFileHandle ( fileHandleOrFile , mode ) valid_chars = { x for x in string . ascii_letters + "-" } try : assert any ( [ isinstance ( seq , unicode ) , isinstance ( seq , str ) ] ) except AssertionError : raise RuntimeError ( "Sequence is not unicode or string" ) try : assert all ( x in valid_chars for x in seq ) except AssertionError : bad_chars = { x for x in seq if x not in valid_chars } raise RuntimeError ( "Invalid FASTA character(s) see in fasta sequence: {}" . format ( bad_chars ) ) fileHandle . write ( ">%s\n" % name ) chunkSize = 100 for i in xrange ( 0 , len ( seq ) , chunkSize ) : fileHandle . write ( "%s\n" % seq [ i : i + chunkSize ] ) if isinstance ( fileHandleOrFile , "" . __class__ ) : fileHandle . close ( )
Writes out fasta file
253
6
22,579
def fastqRead ( fileHandleOrFile ) : fileHandle = _getFileHandle ( fileHandleOrFile ) line = fileHandle . readline ( ) while line != '' : if line [ 0 ] == '@' : name = line [ 1 : - 1 ] seq = fileHandle . readline ( ) [ : - 1 ] plus = fileHandle . readline ( ) if plus [ 0 ] != '+' : raise RuntimeError ( "Got unexpected line: %s" % plus ) qualValues = [ ord ( i ) for i in fileHandle . readline ( ) [ : - 1 ] ] if len ( seq ) != len ( qualValues ) : logger . critical ( "Got a mismatch between the number of sequence characters (%s) and number of qual values (%s) for sequence: %s, ignoring returning None" % ( len ( seq ) , len ( qualValues ) , name ) ) qualValues = None else : for i in qualValues : if i < 33 or i > 126 : raise RuntimeError ( "Got a qual value out of range %s (range is 33 to 126)" % i ) for i in seq : #For safety and sanity I only allows roman alphabet characters in fasta sequences. if not ( ( i >= 'A' and i <= 'Z' ) or ( i >= 'a' and i <= 'z' ) or i == '-' ) : raise RuntimeError ( "Invalid FASTQ character, ASCII code = \'%d\', found in input sequence %s" % ( ord ( i ) , name ) ) yield name , seq , qualValues line = fileHandle . readline ( ) if isinstance ( fileHandleOrFile , "" . __class__ ) : fileHandle . close ( )
Reads a fastq file iteratively
370
8
22,580
def _getMultiFastaOffsets ( fasta ) : f = open ( fasta , 'r' ) i = 0 j = f . read ( 1 ) l = [ ] while j != '' : i += 1 if j == '>' : i += 1 while f . read ( 1 ) != '\n' : i += 1 l . append ( i ) j = f . read ( 1 ) f . close ( ) return l
Reads in columns of multiple alignment and returns them iteratively
94
12
22,581
def fastaReadHeaders ( fasta ) : headers = [ ] fileHandle = open ( fasta , 'r' ) line = fileHandle . readline ( ) while line != '' : assert line [ - 1 ] == '\n' if line [ 0 ] == '>' : headers . append ( line [ 1 : - 1 ] ) line = fileHandle . readline ( ) fileHandle . close ( ) return headers
Returns a list of fasta header lines excluding
91
9
22,582
def fastaAlignmentRead ( fasta , mapFn = ( lambda x : x ) , l = None ) : if l is None : l = _getMultiFastaOffsets ( fasta ) else : l = l [ : ] seqNo = len ( l ) for i in xrange ( 0 , seqNo ) : j = open ( fasta , 'r' ) j . seek ( l [ i ] ) l [ i ] = j column = [ sys . maxint ] * seqNo if seqNo != 0 : while True : for j in xrange ( 0 , seqNo ) : i = l [ j ] . read ( 1 ) while i == '\n' : i = l [ j ] . read ( 1 ) column [ j ] = i if column [ 0 ] == '>' or column [ 0 ] == '' : for j in xrange ( 1 , seqNo ) : assert column [ j ] == '>' or column [ j ] == '' break for j in xrange ( 1 , seqNo ) : assert column [ j ] != '>' and column [ j ] != '' column [ j ] = mapFn ( column [ j ] ) yield column [ : ] for i in l : i . close ( )
reads in columns of multiple alignment and returns them iteratively
268
11
22,583
def fastaAlignmentWrite ( columnAlignment , names , seqNo , fastaFile , filter = lambda x : True ) : fastaFile = open ( fastaFile , 'w' ) columnAlignment = [ i for i in columnAlignment if filter ( i ) ] for seq in xrange ( 0 , seqNo ) : fastaFile . write ( ">%s\n" % names [ seq ] ) for column in columnAlignment : fastaFile . write ( column [ seq ] ) fastaFile . write ( "\n" ) fastaFile . close ( )
Writes out column alignment to given file multi - fasta format
126
13
22,584
def getRandomSequence ( length = 500 ) : fastaHeader = "" for i in xrange ( int ( random . random ( ) * 100 ) ) : fastaHeader = fastaHeader + random . choice ( [ 'A' , 'C' , '0' , '9' , ' ' , '\t' ] ) return ( fastaHeader , "" . join ( [ random . choice ( [ 'A' , 'C' , 'T' , 'G' , 'A' , 'C' , 'T' , 'G' , 'A' , 'C' , 'T' , 'G' , 'A' , 'C' , 'T' , 'G' , 'A' , 'C' , 'T' , 'G' , 'N' ] ) for i in xrange ( ( int ) ( random . random ( ) * length ) ) ] ) )
Generates a random name and sequence .
195
8
22,585
def mutateSequence ( seq , distance ) : subProb = distance inProb = 0.05 * distance deProb = 0.05 * distance contProb = 0.9 l = [ ] bases = [ 'A' , 'C' , 'T' , 'G' ] i = 0 while i < len ( seq ) : if random . random ( ) < subProb : l . append ( random . choice ( bases ) ) else : l . append ( seq [ i ] ) if random . random ( ) < inProb : l += getRandomSequence ( _expLength ( 0 , contProb ) ) [ 1 ] if random . random ( ) < deProb : i += int ( _expLength ( 0 , contProb ) ) i += 1 return "" . join ( l )
Mutates the DNA sequence for use in testing .
176
10
22,586
def newickTreeParser ( newickTree , defaultDistance = DEFAULT_DISTANCE , sortNonBinaryNodes = False , reportUnaryNodes = False ) : newickTree = newickTree . replace ( "(" , " ( " ) newickTree = newickTree . replace ( ")" , " ) " ) newickTree = newickTree . replace ( ":" , " : " ) newickTree = newickTree . replace ( ";" , "" ) newickTree = newickTree . replace ( "," , " , " ) newickTree = re . compile ( "[\s]*" ) . split ( newickTree ) while "" in newickTree : newickTree . remove ( "" ) def fn ( newickTree , i ) : if i [ 0 ] < len ( newickTree ) : if newickTree [ i [ 0 ] ] == ':' : d = float ( newickTree [ i [ 0 ] + 1 ] ) i [ 0 ] += 2 return d return defaultDistance def fn2 ( newickTree , i ) : if i [ 0 ] < len ( newickTree ) : j = newickTree [ i [ 0 ] ] if j != ':' and j != ')' and j != ',' : i [ 0 ] += 1 return j return None def fn3 ( newickTree , i ) : if newickTree [ i [ 0 ] ] == '(' : #subTree1 = None subTreeList = [ ] i [ 0 ] += 1 k = [ ] while newickTree [ i [ 0 ] ] != ')' : if newickTree [ i [ 0 ] ] == ',' : i [ 0 ] += 1 subTreeList . append ( fn3 ( newickTree , i ) ) i [ 0 ] += 1 def cmp ( i , j ) : if i . distance < j . distance : return - 1 if i . distance > j . distance : return 1 return 0 if sortNonBinaryNodes : subTreeList . sort ( cmp ) subTree1 = subTreeList [ 0 ] if len ( subTreeList ) > 1 : for subTree2 in subTreeList [ 1 : ] : subTree1 = BinaryTree ( 0.0 , True , subTree1 , subTree2 , None ) subTree1 . iD = fn2 ( newickTree , i ) subTree1 . distance += fn ( newickTree , i ) elif reportUnaryNodes : subTree1 = BinaryTree ( 0.0 , True , subTree1 , None , None ) subTree1 . iD = fn2 ( newickTree , i ) subTree1 . distance += fn ( newickTree , i ) else : fn2 ( newickTree , i ) subTree1 . distance += fn ( newickTree , i ) return subTree1 leafID = fn2 ( newickTree , i ) return BinaryTree ( fn ( newickTree , i ) , False , None , None , leafID ) return fn3 ( newickTree , [ 0 ] )
lax newick tree parser
657
6
22,587
def pWMRead ( fileHandle , alphabetSize = 4 ) : lines = fileHandle . readlines ( ) assert len ( lines ) == alphabetSize l = [ [ float ( i ) ] for i in lines [ 0 ] . split ( ) ] for line in lines [ 1 : ] : l2 = [ float ( i ) for i in line . split ( ) ] assert len ( l ) == len ( l2 ) for i in xrange ( 0 , len ( l ) ) : l [ i ] . append ( l2 [ i ] ) for i in xrange ( 0 , len ( l ) ) : j = sum ( l [ i ] ) + 0.0 l [ i ] = [ k / j for k in l [ i ] ] return l
reads in standard position weight matrix format rows are different types of base columns are individual residues
162
17
22,588
def pWMWrite ( fileHandle , pWM , alphabetSize = 4 ) : for i in xrange ( 0 , alphabetSize ) : fileHandle . write ( "%s\n" % ' ' . join ( [ str ( pWM [ j ] [ i ] ) for j in xrange ( 0 , len ( pWM ) ) ] ) )
Writes file in standard PWM format is reverse of pWMParser
75
15
22,589
def cigarRead ( fileHandleOrFile ) : fileHandle = _getFileHandle ( fileHandleOrFile ) #p = re.compile("cigar:\\s+(.+)\\s+([0-9]+)\\s+([0-9]+)\\s+([\\+\\-\\.])\\s+(.+)\\s+([0-9]+)\\s+([0-9]+)\\s+([\\+\\-\\.])\\s+(.+)\\s+(.*)\\s*)*") p = re . compile ( "cigar:\\s+(.+)\\s+([0-9]+)\\s+([0-9]+)\\s+([\\+\\-\\.])\\s+(.+)\\s+([0-9]+)\\s+([0-9]+)\\s+([\\+\\-\\.])\\s+([^\\s]+)(\\s+(.*)\\s*)*" ) line = fileHandle . readline ( ) while line != '' : pA = cigarReadFromString ( line ) if pA != None : yield pA line = fileHandle . readline ( ) if isinstance ( fileHandleOrFile , "" . __class__ ) : fileHandle . close ( )
Reads a list of pairwise alignments into a pairwise alignment structure .
279
16
22,590
def cigarWrite ( fileHandle , pairwiseAlignment , withProbs = True ) : if len ( pairwiseAlignment . operationList ) == 0 : logger . info ( "Writing zero length pairwiseAlignment to file!" ) strand1 = "+" if not pairwiseAlignment . strand1 : strand1 = "-" strand2 = "+" if not pairwiseAlignment . strand2 : strand2 = "-" fileHandle . write ( "cigar: %s %i %i %s %s %i %i %s %f" % ( pairwiseAlignment . contig2 , pairwiseAlignment . start2 , pairwiseAlignment . end2 , strand2 , pairwiseAlignment . contig1 , pairwiseAlignment . start1 , pairwiseAlignment . end1 , strand1 , pairwiseAlignment . score ) ) if withProbs == True : hashMap = { PairwiseAlignment . PAIRWISE_INDEL_Y : 'Z' , PairwiseAlignment . PAIRWISE_INDEL_X : 'Y' , PairwiseAlignment . PAIRWISE_MATCH : 'X' } for op in pairwiseAlignment . operationList : fileHandle . write ( ' %s %i %f' % ( hashMap [ op . type ] , op . length , op . score ) ) else : hashMap = { PairwiseAlignment . PAIRWISE_INDEL_Y : 'I' , PairwiseAlignment . PAIRWISE_INDEL_X : 'D' , PairwiseAlignment . PAIRWISE_MATCH : 'M' } for op in pairwiseAlignment . operationList : fileHandle . write ( ' %s %i' % ( hashMap [ op . type ] , op . length ) ) fileHandle . write ( "\n" )
Writes out the pairwiseAlignment to the file stream .
399
13
22,591
def getRandomPairwiseAlignment ( ) : i , j , k , l = _getRandomSegment ( ) m , n , o , p = _getRandomSegment ( ) score = random . choice ( xrange ( - 1000 , 1000 ) ) return PairwiseAlignment ( i , j , k , l , m , n , o , p , score , getRandomOperationList ( abs ( k - j ) , abs ( o - n ) ) )
Gets a random pairwiseAlignment .
100
9
22,592
def addEdgeToGraph ( parentNodeName , childNodeName , graphFileHandle , colour = "black" , length = "10" , weight = "1" , dir = "none" , label = "" , style = "" ) : graphFileHandle . write ( 'edge[color=%s,len=%s,weight=%s,dir=%s,label="%s",style=%s];\n' % ( colour , length , weight , dir , label , style ) ) graphFileHandle . write ( "%s -- %s;\n" % ( parentNodeName , childNodeName ) )
Links two nodes in the graph together .
134
8
22,593
def destroyTempFile ( self , tempFile ) : #Do basic assertions for goodness of the function assert os . path . isfile ( tempFile ) assert os . path . commonprefix ( ( self . rootDir , tempFile ) ) == self . rootDir #Checks file is part of tree #Update stats. self . tempFilesDestroyed += 1 #Do the actual removal os . remove ( tempFile ) self . __destroyFile ( tempFile )
Removes the temporary file in the temp file dir checking its in the temp file tree .
95
18
22,594
def destroyTempDir ( self , tempDir ) : #Do basic assertions for goodness of the function assert os . path . isdir ( tempDir ) assert os . path . commonprefix ( ( self . rootDir , tempDir ) ) == self . rootDir #Checks file is part of tree #Update stats. self . tempFilesDestroyed += 1 #Do the actual removal try : os . rmdir ( tempDir ) except OSError : shutil . rmtree ( tempDir ) #system("rm -rf %s" % tempDir) self . __destroyFile ( tempDir )
Removes a temporary directory in the temp file dir checking its in the temp file tree . The dir will be removed regardless of if it is empty .
128
30
22,595
def destroyTempFiles ( self ) : os . system ( "rm -rf %s" % self . rootDir ) logger . debug ( "Temp files created: %s, temp files actively destroyed: %s" % ( self . tempFilesCreated , self . tempFilesDestroyed ) )
Destroys all temp temp file hierarchy getting rid of all files .
61
14
22,596
def mutable_json_field ( # pylint: disable=keyword-arg-before-vararg enforce_string = False , # type: bool enforce_unicode = False , # type: bool json = json , # type: typing.Union[types.ModuleType, typing.Any] * args , # type: typing.Any * * kwargs # type: typing.Any ) : # type: (...) -> JSONField return sqlalchemy . ext . mutable . MutableDict . as_mutable ( JSONField ( enforce_string = enforce_string , enforce_unicode = enforce_unicode , json = json , * args , * * kwargs ) )
Mutable JSONField creator .
150
6
22,597
def load_dialect_impl ( self , dialect ) : # type: (DefaultDialect) -> TypeEngine if self . __use_json ( dialect ) : return dialect . type_descriptor ( self . __json_type ) return dialect . type_descriptor ( sqlalchemy . UnicodeText )
Select impl by dialect .
67
5
22,598
def process_bind_param ( self , value , dialect ) : # type: (typing.Any, DefaultDialect) -> typing.Union[str, typing.Any] if self . __use_json ( dialect ) or value is None : return value return self . __json_codec . dumps ( value , ensure_ascii = not self . __enforce_unicode )
Encode data if required .
84
6
22,599
def process_result_value ( self , value , # type: typing.Union[str, typing.Any] dialect # type: DefaultDialect ) : # type: (...) -> typing.Any if self . __use_json ( dialect ) or value is None : return value return self . __json_codec . loads ( value )
Decode data if required .
72
6