idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
42,100 | def strace_set_buffer_size ( self , size ) : size = ctypes . c_uint32 ( size ) res = self . _dll . JLINK_STRACE_Control ( enums . JLinkStraceCommand . SET_BUFFER_SIZE , size ) if res < 0 : raise errors . JLinkException ( 'Failed to set the STRACE buffer size.' ) return None | Sets the STRACE buffer size . |
42,101 | def trace_start ( self ) : cmd = enums . JLinkTraceCommand . START res = self . _dll . JLINKARM_TRACE_Control ( cmd , 0 ) if ( res == 1 ) : raise errors . JLinkException ( 'Failed to start trace.' ) return None | Starts collecting trace data . |
42,102 | def trace_stop ( self ) : cmd = enums . JLinkTraceCommand . STOP res = self . _dll . JLINKARM_TRACE_Control ( cmd , 0 ) if ( res == 1 ) : raise errors . JLinkException ( 'Failed to stop trace.' ) return None | Stops collecting trace data . |
42,103 | def trace_flush ( self ) : cmd = enums . JLinkTraceCommand . FLUSH res = self . _dll . JLINKARM_TRACE_Control ( cmd , 0 ) if ( res == 1 ) : raise errors . JLinkException ( 'Failed to flush the trace buffer.' ) return None | Flushes the trace buffer . |
42,104 | def trace_buffer_capacity ( self ) : cmd = enums . JLinkTraceCommand . GET_CONF_CAPACITY data = ctypes . c_uint32 ( 0 ) res = self . _dll . JLINKARM_TRACE_Control ( cmd , ctypes . byref ( data ) ) if ( res == 1 ) : raise errors . JLinkException ( 'Failed to get trace buffer size.' ) return data . value | Retrieves the trace buffer s current capacity . |
42,105 | def trace_set_buffer_capacity ( self , size ) : cmd = enums . JLinkTraceCommand . SET_CAPACITY data = ctypes . c_uint32 ( size ) res = self . _dll . JLINKARM_TRACE_Control ( cmd , ctypes . byref ( data ) ) if ( res == 1 ) : raise errors . JLinkException ( 'Failed to set trace buffer size.' ) return None | Sets the capacity for the trace buffer . |
42,106 | def trace_min_buffer_capacity ( self ) : cmd = enums . JLinkTraceCommand . GET_MIN_CAPACITY data = ctypes . c_uint32 ( 0 ) res = self . _dll . JLINKARM_TRACE_Control ( cmd , ctypes . byref ( data ) ) if ( res == 1 ) : raise errors . JLinkException ( 'Failed to get min trace buffer size.' ) return data . value | Retrieves the minimum capacity the trace buffer can be configured with . |
42,107 | def trace_max_buffer_capacity ( self ) : cmd = enums . JLinkTraceCommand . GET_MAX_CAPACITY data = ctypes . c_uint32 ( 0 ) res = self . _dll . JLINKARM_TRACE_Control ( cmd , ctypes . byref ( data ) ) if ( res == 1 ) : raise errors . JLinkException ( 'Failed to get max trace buffer size.' ) return data . value | Retrieves the maximum size the trace buffer can be configured with . |
42,108 | def trace_set_format ( self , fmt ) : cmd = enums . JLinkTraceCommand . SET_FORMAT data = ctypes . c_uint32 ( fmt ) res = self . _dll . JLINKARM_TRACE_Control ( cmd , ctypes . byref ( data ) ) if ( res == 1 ) : raise errors . JLinkException ( 'Failed to set trace format.' ) return None | Sets the format for the trace buffer to use . |
42,109 | def trace_format ( self ) : cmd = enums . JLinkTraceCommand . GET_FORMAT data = ctypes . c_uint32 ( 0 ) res = self . _dll . JLINKARM_TRACE_Control ( cmd , ctypes . byref ( data ) ) if ( res == 1 ) : raise errors . JLinkException ( 'Failed to get trace format.' ) return data . value | Retrieves the current format the trace buffer is using . |
42,110 | def trace_region_count ( self ) : cmd = enums . JLinkTraceCommand . GET_NUM_REGIONS data = ctypes . c_uint32 ( 0 ) res = self . _dll . JLINKARM_TRACE_Control ( cmd , ctypes . byref ( data ) ) if ( res == 1 ) : raise errors . JLinkException ( 'Failed to get trace region count.' ) return data . value | Retrieves a count of the number of available trace regions . |
42,111 | def trace_region ( self , region_index ) : cmd = enums . JLinkTraceCommand . GET_REGION_PROPS_EX region = structs . JLinkTraceRegion ( ) region . RegionIndex = int ( region_index ) res = self . _dll . JLINKARM_TRACE_Control ( cmd , ctypes . byref ( region ) ) if ( res == 1 ) : raise errors . JLinkException ( 'Failed to get trace region.' ) return region | Retrieves the properties of a trace region . |
42,112 | def trace_read ( self , offset , num_items ) : buf_size = ctypes . c_uint32 ( num_items ) buf = ( structs . JLinkTraceData * num_items ) ( ) res = self . _dll . JLINKARM_TRACE_Read ( buf , int ( offset ) , ctypes . byref ( buf_size ) ) if ( res == 1 ) : raise errors . JLinkException ( 'Failed to read from trace buffer.' ) return list ( buf ) [ : int ( buf_size . value ) ] | Reads data from the trace buffer and returns it . |
42,113 | def swo_start ( self , swo_speed = 9600 ) : if self . swo_enabled ( ) : self . swo_stop ( ) info = structs . JLinkSWOStartInfo ( ) info . Speed = swo_speed res = self . _dll . JLINKARM_SWO_Control ( enums . JLinkSWOCommands . START , ctypes . byref ( info ) ) if res < 0 : raise errors . JLinkException ( res ) self . _swo_enabled = True return None | Starts collecting SWO data . |
42,114 | def swo_stop ( self ) : res = self . _dll . JLINKARM_SWO_Control ( enums . JLinkSWOCommands . STOP , 0 ) if res < 0 : raise errors . JLinkException ( res ) return None | Stops collecting SWO data . |
42,115 | def swo_enable ( self , cpu_speed , swo_speed = 9600 , port_mask = 0x01 ) : if self . swo_enabled ( ) : self . swo_stop ( ) res = self . _dll . JLINKARM_SWO_EnableTarget ( cpu_speed , swo_speed , enums . JLinkSWOInterfaces . UART , port_mask ) if res != 0 : raise errors . JLinkException ( res ) self . _swo_enabled = True return None | Enables SWO output on the target device . |
42,116 | def swo_disable ( self , port_mask ) : res = self . _dll . JLINKARM_SWO_DisableTarget ( port_mask ) if res != 0 : raise errors . JLinkException ( res ) return None | Disables ITM & Stimulus ports . |
42,117 | def swo_flush ( self , num_bytes = None ) : if num_bytes is None : num_bytes = self . swo_num_bytes ( ) buf = ctypes . c_uint32 ( num_bytes ) res = self . _dll . JLINKARM_SWO_Control ( enums . JLinkSWOCommands . FLUSH , ctypes . byref ( buf ) ) if res < 0 : raise errors . JLinkException ( res ) return None | Flushes data from the SWO buffer . |
42,118 | def swo_speed_info ( self ) : info = structs . JLinkSWOSpeedInfo ( ) res = self . _dll . JLINKARM_SWO_Control ( enums . JLinkSWOCommands . GET_SPEED_INFO , ctypes . byref ( info ) ) if res < 0 : raise errors . JLinkException ( res ) return info | Retrieves information about the supported SWO speeds . |
42,119 | def swo_num_bytes ( self ) : res = self . _dll . JLINKARM_SWO_Control ( enums . JLinkSWOCommands . GET_NUM_BYTES , 0 ) if res < 0 : raise errors . JLinkException ( res ) return res | Retrives the number of bytes in the SWO buffer . |
42,120 | def swo_set_host_buffer_size ( self , buf_size ) : buf = ctypes . c_uint32 ( buf_size ) res = self . _dll . JLINKARM_SWO_Control ( enums . JLinkSWOCommands . SET_BUFFERSIZE_HOST , ctypes . byref ( buf ) ) if res < 0 : raise errors . JLinkException ( res ) return None | Sets the size of the buffer used by the host to collect SWO data . |
42,121 | def swo_set_emu_buffer_size ( self , buf_size ) : buf = ctypes . c_uint32 ( buf_size ) res = self . _dll . JLINKARM_SWO_Control ( enums . JLinkSWOCommands . SET_BUFFERSIZE_EMU , ctypes . byref ( buf ) ) if res < 0 : raise errors . JLinkException ( res ) return None | Sets the size of the buffer used by the J - Link to collect SWO data . |
42,122 | def swo_supported_speeds ( self , cpu_speed , num_speeds = 3 ) : buf_size = num_speeds buf = ( ctypes . c_uint32 * buf_size ) ( ) res = self . _dll . JLINKARM_SWO_GetCompatibleSpeeds ( cpu_speed , 0 , buf , buf_size ) if res < 0 : raise errors . JLinkException ( res ) return list ( buf ) [ : res ] | Retrives a list of SWO speeds supported by both the target and the connected J - Link . |
42,123 | def swo_read ( self , offset , num_bytes , remove = False ) : buf_size = ctypes . c_uint32 ( num_bytes ) buf = ( ctypes . c_uint8 * num_bytes ) ( 0 ) self . _dll . JLINKARM_SWO_Read ( buf , offset , ctypes . byref ( buf_size ) ) buf_size = buf_size . value if remove : self . swo_flush ( buf_size ) return list ( buf ) [ : buf_size ] | Reads data from the SWO buffer . |
42,124 | def swo_read_stimulus ( self , port , num_bytes ) : if port < 0 or port > 31 : raise ValueError ( 'Invalid port number: %s' % port ) buf_size = num_bytes buf = ( ctypes . c_uint8 * buf_size ) ( ) bytes_read = self . _dll . JLINKARM_SWO_ReadStimulus ( port , buf , buf_size ) return list ( buf ) [ : bytes_read ] | Reads the printable data via SWO . |
42,125 | def rtt_read ( self , buffer_index , num_bytes ) : buf = ( ctypes . c_ubyte * num_bytes ) ( ) bytes_read = self . _dll . JLINK_RTTERMINAL_Read ( buffer_index , buf , num_bytes ) if bytes_read < 0 : raise errors . JLinkRTTException ( bytes_read ) return list ( buf ) [ : bytes_read ] | Reads data from the RTT buffer . |
42,126 | def rtt_write ( self , buffer_index , data ) : buf_size = len ( data ) buf = ( ctypes . c_ubyte * buf_size ) ( * bytearray ( data ) ) bytes_written = self . _dll . JLINK_RTTERMINAL_Write ( buffer_index , buf , buf_size ) if bytes_written < 0 : raise errors . JLinkRTTException ( bytes_written ) return bytes_written | Writes data to the RTT buffer . |
42,127 | def rtt_control ( self , command , config ) : config_byref = ctypes . byref ( config ) if config is not None else None res = self . _dll . JLINK_RTTERMINAL_Control ( command , config_byref ) if res < 0 : raise errors . JLinkRTTException ( res ) return res | Issues an RTT Control command . |
42,128 | def main ( target_device ) : jlink = pylink . JLink ( ) print ( "connecting to JLink..." ) jlink . open ( ) print ( "connecting to %s..." % target_device ) jlink . set_tif ( pylink . enums . JLinkInterfaces . SWD ) jlink . connect ( target_device ) print ( "connected, starting RTT..." ) jlink . rtt_start ( ) while True : try : num_up = jlink . rtt_get_num_up_buffers ( ) num_down = jlink . rtt_get_num_down_buffers ( ) print ( "RTT started, %d up bufs, %d down bufs." % ( num_up , num_down ) ) break except pylink . errors . JLinkRTTException : time . sleep ( 0.1 ) try : thread . start_new_thread ( read_rtt , ( jlink , ) ) thread . start_new_thread ( write_rtt , ( jlink , ) ) while jlink . connected ( ) : time . sleep ( 1 ) print ( "JLink disconnected, exiting..." ) except KeyboardInterrupt : print ( "ctrl-c detected, exiting..." ) pass | Creates an interactive terminal to the target via RTT . |
42,129 | def run ( self ) : target = getattr ( self , '_Thread__target' , getattr ( self , '_target' , None ) ) args = getattr ( self , '_Thread__args' , getattr ( self , '_args' , None ) ) kwargs = getattr ( self , '_Thread__kwargs' , getattr ( self , '_kwargs' , None ) ) if target is not None : self . _return = target ( * args , ** kwargs ) return None | Runs the thread . |
42,130 | def join ( self , * args , ** kwargs ) : super ( ThreadReturn , self ) . join ( * args , ** kwargs ) return self . _return | Joins the thread . |
42,131 | def main ( ) : windows_libraries = list ( pylink . Library . find_library_windows ( ) ) latest_library = None for lib in windows_libraries : if os . path . dirname ( lib ) . endswith ( 'JLinkARM' ) : latest_library = lib break elif latest_library is None : latest_library = lib elif os . path . dirname ( lib ) > os . path . dirname ( latest_library ) : latest_library = lib if latest_library is None : raise OSError ( 'No J-Link library found.' ) library = pylink . Library ( latest_library ) jlink = pylink . JLink ( lib = library ) print ( 'Found version: %s' % jlink . version ) for emu in jlink . connected_emulators ( ) : jlink . disable_dialog_boxes ( ) jlink . open ( serial_no = emu . SerialNumber ) jlink . sync_firmware ( ) print ( 'Updated emulator with serial number %s' % emu . SerialNumber ) return None | Upgrades the firmware of the J - Links connected to a Windows device . |
42,132 | def async_decorator ( func ) : @ functools . wraps ( func ) def async_wrapper ( * args , ** kwargs ) : if 'callback' not in kwargs or not kwargs [ 'callback' ] : return func ( * args , ** kwargs ) callback = kwargs . pop ( 'callback' ) if not callable ( callback ) : raise TypeError ( 'Expected \'callback\' is not callable.' ) def thread_func ( * args , ** kwargs ) : exception , res = None , None try : res = func ( * args , ** kwargs ) except Exception as e : exception = e return callback ( exception , res ) thread = threads . ThreadReturn ( target = thread_func , args = args , kwargs = kwargs ) thread . daemon = True thread . start ( ) return thread return async_wrapper | Asynchronous function decorator . Interprets the function as being asynchronous so returns a function that will handle calling the Function asynchronously . |
42,133 | def strace ( device , trace_address , breakpoint_address ) : jlink = pylink . JLink ( ) jlink . open ( ) jlink . power_on ( ) jlink . set_tif ( pylink . JLinkInterfaces . SWD ) jlink . connect ( device ) jlink . reset ( ) jlink . breakpoint_clear_all ( ) op = pylink . JLinkStraceOperation . TRACE_START jlink . strace_clear_all ( ) jlink . strace_start ( ) bphandle = jlink . breakpoint_set ( breakpoint_address , thumb = True ) trhandle = jlink . strace_code_fetch_event ( op , address = trace_address ) jlink . restart ( ) time . sleep ( 1 ) while True : if jlink . halted ( ) : break while True : instructions = jlink . strace_read ( 1 ) if len ( instructions ) == 0 : break instruction = instructions [ 0 ] print ( jlink . disassemble_instruction ( instruction ) ) jlink . power_off ( ) jlink . close ( ) | Implements simple trace using the STrace API . |
42,134 | def create_parser ( ) : parser = argparse . ArgumentParser ( prog = pylink . __title__ , description = pylink . __description__ , epilog = pylink . __copyright__ ) parser . add_argument ( '--version' , action = 'version' , version = '%(prog)s ' + pylink . __version__ ) parser . add_argument ( '-v' , '--verbose' , action = 'count' , default = 0 , help = 'increase output verbosity' ) kwargs = { } kwargs [ 'title' ] = 'command' kwargs [ 'description' ] = 'specify subcommand to run' kwargs [ 'help' ] = 'subcommands' subparsers = parser . add_subparsers ( ** kwargs ) for command in commands ( ) : kwargs = { } kwargs [ 'name' ] = command . name kwargs [ 'description' ] = command . description kwargs [ 'help' ] = command . help subparser = subparsers . add_parser ( ** kwargs ) subparser . set_defaults ( command = command . run ) command . add_arguments ( subparser ) return parser | Builds the command parser . |
42,135 | def main ( args = None ) : if args is None : args = sys . argv [ 1 : ] parser = create_parser ( ) args = parser . parse_args ( args ) if args . verbose >= 2 : level = logging . DEBUG elif args . verbose >= 1 : level = logging . INFO else : level = logging . WARNING logging . basicConfig ( level = level ) try : args . command ( args ) except pylink . JLinkException as e : sys . stderr . write ( 'Error: %s%s' % ( str ( e ) , os . linesep ) ) return 1 return 0 | Main command - line interface entrypoint . |
42,136 | def create_jlink ( self , args ) : jlink = pylink . JLink ( ) jlink . open ( args . serial_no , args . ip_addr ) if hasattr ( args , 'tif' ) and args . tif is not None : if args . tif . lower ( ) == 'swd' : jlink . set_tif ( pylink . JLinkInterfaces . SWD ) else : jlink . set_tif ( pylink . JLinkInterfaces . JTAG ) if hasattr ( args , 'device' ) and args . device is not None : jlink . connect ( args . device ) return jlink | Creates an instance of a J - Link from the given arguments . |
42,137 | def add_common_arguments ( self , parser , has_device = False ) : if has_device : parser . add_argument ( '-t' , '--tif' , required = True , type = str . lower , choices = [ 'jtag' , 'swd' ] , help = 'target interface (JTAG | SWD)' ) parser . add_argument ( '-d' , '--device' , required = True , help = 'specify the target device name' ) group = parser . add_mutually_exclusive_group ( required = False ) group . add_argument ( '-s' , '--serial' , dest = 'serial_no' , help = 'specify the J-Link serial number' ) group . add_argument ( '-i' , '--ip_addr' , dest = 'ip_addr' , help = 'J-Link IP address' ) return None | Adds common arguments to the given parser . |
42,138 | def run ( self , args ) : jlink = self . create_jlink ( args ) erased = jlink . erase ( ) print ( 'Bytes Erased: %d' % erased ) | Erases the device connected to the J - Link . |
42,139 | def run ( self , args ) : kwargs = { } kwargs [ 'path' ] = args . file [ 0 ] kwargs [ 'addr' ] = args . addr kwargs [ 'on_progress' ] = pylink . util . flash_progress_callback jlink = self . create_jlink ( args ) _ = jlink . flash_file ( ** kwargs ) print ( 'Flashed device successfully.' ) | Flashes the device connected to the J - Link . |
42,140 | def add_arguments ( self , parser ) : parser . add_argument ( 'name' , nargs = 1 , choices = [ 'kinetis' ] , help = 'name of MCU to unlock' ) return self . add_common_arguments ( parser , True ) | Adds the unlock command arguments to the parser . |
42,141 | def run ( self , args ) : jlink = self . create_jlink ( args ) mcu = args . name [ 0 ] . lower ( ) if pylink . unlock ( jlink , mcu ) : print ( 'Successfully unlocked device!' ) else : print ( 'Failed to unlock device!' ) | Unlocks the target device . |
42,142 | def run ( self , args ) : jlink = self . create_jlink ( args ) if args . list : print ( 'Built-in Licenses: %s' % ', ' . join ( jlink . licenses . split ( ',' ) ) ) print ( 'Custom Licenses: %s' % ', ' . join ( jlink . custom_licenses . split ( ',' ) ) ) elif args . add is not None : if jlink . add_license ( args . add ) : print ( 'Successfully added license.' ) else : print ( 'License already exists.' ) elif args . erase : if jlink . erase_licenses ( ) : print ( 'Successfully erased all custom licenses.' ) else : print ( 'Failed to erase custom licenses.' ) | Runs the license command . |
42,143 | def add_arguments ( self , parser ) : parser . add_argument ( '-p' , '--product' , action = 'store_true' , help = 'print the production information' ) parser . add_argument ( '-j' , '--jtag' , action = 'store_true' , help = 'print the JTAG pin status' ) return self . add_common_arguments ( parser , False ) | Adds the information commands to the parser . |
42,144 | def run ( self , args ) : jlink = self . create_jlink ( args ) if args . product : print ( 'Product: %s' % jlink . product_name ) manufacturer = 'SEGGER' if jlink . oem is None else jlink . oem print ( 'Manufacturer: %s' % manufacturer ) print ( 'Hardware Version: %s' % jlink . hardware_version ) print ( 'Firmware: %s' % jlink . firmware_version ) print ( 'DLL Version: %s' % jlink . version ) print ( 'Features: %s' % ', ' . join ( jlink . features ) ) elif args . jtag : status = jlink . hardware_status print ( 'TCK Pin Status: %d' % status . tck ) print ( 'TDI Pin Status: %d' % status . tdi ) print ( 'TDO Pin Status: %d' % status . tdo ) print ( 'TMS Pin Status: %d' % status . tms ) print ( 'TRES Pin Status: %d' % status . tres ) print ( 'TRST Pin Status: %d' % status . trst ) | Runs the information command . |
42,145 | def add_arguments ( self , parser ) : group = parser . add_mutually_exclusive_group ( required = True ) group . add_argument ( '-l' , '--list' , nargs = '?' , type = str . lower , default = '_' , choices = [ 'usb' , 'ip' ] , help = 'list all the connected emulators' ) group . add_argument ( '-s' , '--supported' , nargs = 1 , help = 'query whether a device is supported' ) group . add_argument ( '-t' , '--test' , action = 'store_true' , help = 'perform a self-test' ) return None | Adds the arguments for the emulator command . |
42,146 | def run ( self , args ) : jlink = pylink . JLink ( ) if args . test : if jlink . test ( ) : print ( 'Self-test succeeded.' ) else : print ( 'Self-test failed.' ) elif args . list is None or args . list in [ 'usb' , 'ip' ] : host = pylink . JLinkHost . USB_OR_IP if args . list == 'usb' : host = pylink . JLinkHost . USB elif args . list == 'ip' : host = pylink . JLinkHost . IP emulators = jlink . connected_emulators ( host ) for ( index , emulator ) in enumerate ( emulators ) : if index > 0 : print ( '' ) print ( 'Product Name: %s' % emulator . acProduct . decode ( ) ) print ( 'Serial Number: %s' % emulator . SerialNumber ) usb = bool ( emulator . Connection ) if not usb : print ( 'Nickname: %s' % emulator . acNickname . decode ( ) ) print ( 'Firmware: %s' % emulator . acFWString . decode ( ) ) print ( 'Connection: %s' % ( 'USB' if usb else 'IP' ) ) if not usb : print ( 'IP Address: %s' % emulator . aIPAddr ) elif args . supported is not None : device = args . supported [ 0 ] num_supported_devices = jlink . num_supported_devices ( ) for i in range ( num_supported_devices ) : found_device = jlink . supported_device ( i ) if device . lower ( ) == found_device . name . lower ( ) : print ( 'Device Name: %s' % device ) print ( 'Core ID: %s' % found_device . CoreId ) print ( 'Flash Address: %s' % found_device . FlashAddr ) print ( 'Flash Size: %s bytes' % found_device . FlashSize ) print ( 'RAM Address: %s' % found_device . RAMAddr ) print ( 'RAM Size: %s bytes' % found_device . RAMSize ) print ( 'Manufacturer: %s' % found_device . manufacturer ) break else : print ( '%s is not supported :(' % device ) return None | Runs the emulator command . |
42,147 | def add_arguments ( self , parser ) : group = parser . add_mutually_exclusive_group ( required = True ) group . add_argument ( '-d' , '--downgrade' , action = 'store_true' , help = 'downgrade the J-Link firmware' ) group . add_argument ( '-u' , '--upgrade' , action = 'store_true' , help = 'upgrade the J-Link firmware' ) return self . add_common_arguments ( parser , False ) | Adds the arguments for the firmware command . |
42,148 | def run ( self , args ) : jlink = self . create_jlink ( args ) if args . downgrade : if not jlink . firmware_newer ( ) : print ( 'DLL firmware is not older than J-Link firmware.' ) else : jlink . invalidate_firmware ( ) try : jlink . update_firmware ( ) except pylink . JLinkException as e : jlink = self . create_jlink ( args ) print ( 'Firmware Downgraded: %s' % jlink . firmware_version ) elif args . upgrade : if not jlink . firmware_outdated ( ) : print ( 'DLL firmware is not newer than J-Link firmware.' ) else : try : jlink . update_firmware ( ) except pylink . JLinkException as e : jlink = self . create_jlink ( args ) print ( 'Firmware Updated: %s' % jlink . firmware_version ) return None | Runs the firmware command . |
42,149 | def name ( self ) : return ctypes . cast ( self . sName , ctypes . c_char_p ) . value . decode ( ) | Returns the name of the device . |
42,150 | def manufacturer ( self ) : buf = ctypes . cast ( self . sManu , ctypes . c_char_p ) . value return buf . decode ( ) if buf else None | Returns the name of the manufacturer of the device . |
42,151 | def software_breakpoint ( self ) : software_types = [ enums . JLinkBreakpoint . SW_RAM , enums . JLinkBreakpoint . SW_FLASH , enums . JLinkBreakpoint . SW ] return any ( self . Type & stype for stype in software_types ) | Returns whether this is a software breakpoint . |
42,152 | def find_library_windows ( cls ) : dll = cls . get_appropriate_windows_sdk_name ( ) + '.dll' root = 'C:\\' for d in os . listdir ( root ) : dir_path = os . path . join ( root , d ) if d . startswith ( 'Program Files' ) and os . path . isdir ( dir_path ) : dir_path = os . path . join ( dir_path , 'SEGGER' ) if not os . path . isdir ( dir_path ) : continue ds = filter ( lambda x : x . startswith ( 'JLink' ) , os . listdir ( dir_path ) ) for jlink_dir in ds : lib_path = os . path . join ( dir_path , jlink_dir , dll ) if os . path . isfile ( lib_path ) : yield lib_path | Loads the SEGGER DLL from the windows installation directory . |
42,153 | def find_library_linux ( cls ) : dll = Library . JLINK_SDK_NAME root = os . path . join ( '/' , 'opt' , 'SEGGER' ) for ( directory_name , subdirs , files ) in os . walk ( root ) : fnames = [ ] x86_found = False for f in files : path = os . path . join ( directory_name , f ) if os . path . isfile ( path ) and f . startswith ( dll ) : fnames . append ( f ) if '_x86' in path : x86_found = True for fname in fnames : fpath = os . path . join ( directory_name , fname ) if util . is_os_64bit ( ) : if '_x86' not in fname : yield fpath elif x86_found : if '_x86' in fname : yield fpath else : yield fpath | Loads the SEGGER DLL from the root directory . |
42,154 | def find_library_darwin ( cls ) : dll = Library . JLINK_SDK_NAME root = os . path . join ( '/' , 'Applications' , 'SEGGER' ) if not os . path . isdir ( root ) : return for d in os . listdir ( root ) : dir_path = os . path . join ( root , d ) if os . path . isdir ( dir_path ) and d . startswith ( 'JLink' ) : files = list ( f for f in os . listdir ( dir_path ) if os . path . isfile ( os . path . join ( dir_path , f ) ) ) if ( dll + '.dylib' ) in files : yield os . path . join ( dir_path , dll + '.dylib' ) for f in files : if f . startswith ( dll ) : yield os . path . join ( dir_path , f ) | Loads the SEGGER DLL from the installed applications . |
42,155 | def load_default ( self ) : path = ctypes_util . find_library ( self . _sdk ) if path is None : if self . _windows or self . _cygwin : path = next ( self . find_library_windows ( ) , None ) elif sys . platform . startswith ( 'linux' ) : path = next ( self . find_library_linux ( ) , None ) elif sys . platform . startswith ( 'darwin' ) : path = next ( self . find_library_darwin ( ) , None ) if path is not None : return self . load ( path ) return False | Loads the default J - Link SDK DLL . |
42,156 | def load ( self , path = None ) : self . unload ( ) self . _path = path or self . _path if self . _windows or self . _cygwin : suffix = '.dll' elif sys . platform . startswith ( 'darwin' ) : suffix = '.dylib' else : suffix = '.so' tf = tempfile . NamedTemporaryFile ( delete = False , suffix = suffix ) with open ( tf . name , 'wb' ) as outputfile : with open ( self . _path , 'rb' ) as inputfile : outputfile . write ( inputfile . read ( ) ) tf . close ( ) self . _temp = tf self . _lib = ctypes . cdll . LoadLibrary ( tf . name ) if self . _windows : self . _winlib = ctypes . windll . LoadLibrary ( tf . name ) for stdcall in self . _standard_calls_ : if hasattr ( self . _winlib , stdcall ) : setattr ( self . _lib , stdcall , getattr ( self . _winlib , stdcall ) ) return True | Loads the specified DLL if any otherwise re - loads the current DLL . |
42,157 | def unload ( self ) : unloaded = False if self . _lib is not None : if self . _winlib is not None : ctypes . windll . kernel32 . FreeLibrary . argtypes = ( ctypes . c_void_p , ) ctypes . windll . kernel32 . FreeLibrary ( self . _lib . _handle ) ctypes . windll . kernel32 . FreeLibrary ( self . _winlib . _handle ) self . _lib = None self . _winlib = None unloaded = True else : del self . _lib self . _lib = None unloaded = True if self . _temp is not None : os . remove ( self . _temp . name ) self . _temp = None return unloaded | Unloads the library s DLL if it has been loaded . |
42,158 | def _open ( filename = None , mode = 'r' ) : if not filename or filename == '-' : if not mode or 'r' in mode : file = sys . stdin elif 'w' in mode : file = sys . stdout else : raise ValueError ( 'Invalid mode for file: {}' . format ( mode ) ) else : file = open ( filename , mode ) try : yield file finally : if file not in ( sys . stdin , sys . stdout ) : file . close ( ) | Open a file or sys . stdout depending on the provided filename . |
42,159 | def get_pkg_names ( pkgs ) : result = set ( ) with open ( join ( "mapping" ) , "r" ) as f : data = dict ( x . strip ( ) . split ( ":" ) for x in f ) for pkg in pkgs : result . add ( data . get ( pkg , pkg ) ) return sorted ( result , key = lambda s : s . lower ( ) ) | Get PyPI package names from a list of imports . |
42,160 | def charmap ( prefixed_name ) : prefix , name = prefixed_name . split ( '.' ) return _instance ( ) . charmap [ prefix ] [ name ] | Return the character map used for a given font . |
42,161 | def set_global_defaults ( ** kwargs ) : valid_options = [ 'active' , 'selected' , 'disabled' , 'on' , 'off' , 'on_active' , 'on_selected' , 'on_disabled' , 'off_active' , 'off_selected' , 'off_disabled' , 'color' , 'color_on' , 'color_off' , 'color_active' , 'color_selected' , 'color_disabled' , 'color_on_selected' , 'color_on_active' , 'color_on_disabled' , 'color_off_selected' , 'color_off_active' , 'color_off_disabled' , 'animation' , 'offset' , 'scale_factor' , ] for kw in kwargs : if kw in valid_options : _default_options [ kw ] = kwargs [ kw ] else : error = "Invalid option '{0}'" . format ( kw ) raise KeyError ( error ) | Set global defaults for the options passed to the icon painter . |
42,162 | def paint ( self , iconic , painter , rect , mode , state , options ) : for opt in options : self . _paint_icon ( iconic , painter , rect , mode , state , opt ) | Main paint method . |
42,163 | def _paint_icon ( self , iconic , painter , rect , mode , state , options ) : painter . save ( ) color = options [ 'color' ] char = options [ 'char' ] color_options = { QIcon . On : { QIcon . Normal : ( options [ 'color_on' ] , options [ 'on' ] ) , QIcon . Disabled : ( options [ 'color_on_disabled' ] , options [ 'on_disabled' ] ) , QIcon . Active : ( options [ 'color_on_active' ] , options [ 'on_active' ] ) , QIcon . Selected : ( options [ 'color_on_selected' ] , options [ 'on_selected' ] ) } , QIcon . Off : { QIcon . Normal : ( options [ 'color_off' ] , options [ 'off' ] ) , QIcon . Disabled : ( options [ 'color_off_disabled' ] , options [ 'off_disabled' ] ) , QIcon . Active : ( options [ 'color_off_active' ] , options [ 'off_active' ] ) , QIcon . Selected : ( options [ 'color_off_selected' ] , options [ 'off_selected' ] ) } } color , char = color_options [ state ] [ mode ] painter . setPen ( QColor ( color ) ) draw_size = 0.875 * round ( rect . height ( ) * options [ 'scale_factor' ] ) prefix = options [ 'prefix' ] animation = options . get ( 'animation' ) if animation is not None : animation . setup ( self , painter , rect ) painter . setFont ( iconic . font ( prefix , draw_size ) ) if 'offset' in options : rect = QRect ( rect ) rect . translate ( options [ 'offset' ] [ 0 ] * rect . width ( ) , options [ 'offset' ] [ 1 ] * rect . height ( ) ) painter . setOpacity ( options . get ( 'opacity' , 1.0 ) ) painter . drawText ( rect , Qt . AlignCenter | Qt . AlignVCenter , char ) painter . restore ( ) | Paint a single icon . |
42,164 | def icon ( self , * names , ** kwargs ) : cache_key = '{}{}' . format ( names , kwargs ) if cache_key not in self . icon_cache : options_list = kwargs . pop ( 'options' , [ { } ] * len ( names ) ) general_options = kwargs if len ( options_list ) != len ( names ) : error = '"options" must be a list of size {0}' . format ( len ( names ) ) raise Exception ( error ) if QApplication . instance ( ) is not None : parsed_options = [ ] for i in range ( len ( options_list ) ) : specific_options = options_list [ i ] parsed_options . append ( self . _parse_options ( specific_options , general_options , names [ i ] ) ) api_options = parsed_options self . icon_cache [ cache_key ] = self . _icon_by_painter ( self . painter , api_options ) else : warnings . warn ( "You need to have a running " "QApplication to use QtAwesome!" ) return QIcon ( ) return self . icon_cache [ cache_key ] | Return a QIcon object corresponding to the provided icon name . |
42,165 | def font ( self , prefix , size ) : font = QFont ( self . fontname [ prefix ] ) font . setPixelSize ( size ) if prefix [ - 1 ] == 's' : font . setStyleName ( 'Solid' ) return font | Return a QFont corresponding to the given prefix and size . |
42,166 | def _custom_icon ( self , name , ** kwargs ) : options = dict ( _default_options , ** kwargs ) if name in self . painters : painter = self . painters [ name ] return self . _icon_by_painter ( painter , options ) else : return QIcon ( ) | Return the custom icon corresponding to the given name . |
42,167 | def _icon_by_painter ( self , painter , options ) : engine = CharIconEngine ( self , painter , options ) return QIcon ( engine ) | Return the icon corresponding to the given painter . |
42,168 | def finalize_options ( self ) : assert bool ( self . fa_version ) , 'FA version is mandatory for this command.' if self . zip_path : assert os . path . exists ( self . zip_path ) , ( 'Local zipfile does not exist: %s' % self . zip_path ) | Validate the command options . |
42,169 | def __print ( self , msg ) : self . announce ( msg , level = distutils . log . INFO ) | Shortcut for printing with the distutils logger . |
42,170 | def __zip_file ( self ) : if self . zip_path : self . __print ( 'Opening local zipfile: %s' % self . zip_path ) return open ( self . zip_path , 'rb' ) url = self . __release_url self . __print ( 'Downloading from URL: %s' % url ) response = urlopen ( url ) return io . BytesIO ( response . read ( ) ) | Get a file object of the FA zip file . |
42,171 | def __zipped_files_data ( self ) : files = { } with zipfile . ZipFile ( self . __zip_file ) as thezip : for zipinfo in thezip . infolist ( ) : if zipinfo . filename . endswith ( 'metadata/icons.json' ) : with thezip . open ( zipinfo ) as compressed_file : files [ 'icons.json' ] = compressed_file . read ( ) elif zipinfo . filename . endswith ( '.ttf' ) : name = os . path . basename ( zipinfo . filename ) tokens = name . split ( '-' ) style = tokens [ 1 ] if style in self . FA_STYLES : with thezip . open ( zipinfo ) as compressed_file : files [ style ] = compressed_file . read ( ) assert all ( style in files for style in self . FA_STYLES ) , 'Not all FA styles found! Update code is broken.' assert 'icons.json' in files , 'icons.json not found! Update code is broken.' return files | Get a dict of all files of interest from the FA release zipfile . |
42,172 | def from_string ( proto_str ) : _ , proto_file = tempfile . mkstemp ( suffix = '.proto' ) with open ( proto_file , 'w+' ) as proto_f : proto_f . write ( proto_str ) return from_file ( proto_file ) | Produce a Protobuf module from a string description . Return the module if successfully compiled otherwise raise a BadProtobuf exception . |
42,173 | def _load_module ( path ) : 'Helper to load a Python file at path and return as a module' module_name = os . path . splitext ( os . path . basename ( path ) ) [ 0 ] module = None if sys . version_info . minor < 5 : loader = importlib . machinery . SourceFileLoader ( module_name , path ) module = loader . load_module ( ) else : spec = importlib . util . spec_from_file_location ( module_name , path ) module = importlib . util . module_from_spec ( spec ) spec . loader . exec_module ( module ) return module | Helper to load a Python file at path and return as a module |
42,174 | def _compile_proto ( full_path , dest ) : 'Helper to compile protobuf files' proto_path = os . path . dirname ( full_path ) protoc_args = [ find_protoc ( ) , '--python_out={}' . format ( dest ) , '--proto_path={}' . format ( proto_path ) , full_path ] proc = subprocess . Popen ( protoc_args , stdout = subprocess . PIPE , stderr = subprocess . PIPE ) try : outs , errs = proc . communicate ( timeout = 5 ) except subprocess . TimeoutExpired : proc . kill ( ) outs , errs = proc . communicate ( ) return False if proc . returncode != 0 : msg = 'Failed compiling "{}": \n\nstderr: {}\nstdout: {}' . format ( full_path , errs . decode ( 'utf-8' ) , outs . decode ( 'utf-8' ) ) raise BadProtobuf ( msg ) return True | Helper to compile protobuf files |
42,175 | def from_file ( proto_file ) : if not proto_file . endswith ( '.proto' ) : raise BadProtobuf ( ) dest = tempfile . mkdtemp ( ) full_path = os . path . abspath ( proto_file ) _compile_proto ( full_path , dest ) filename = os . path . split ( full_path ) [ - 1 ] name = re . search ( r'^(.*)\.proto$' , filename ) . group ( 1 ) target = os . path . join ( dest , name + '_pb2.py' ) return _load_module ( target ) | Take a filename |protoc_file| compile it via the Protobuf compiler and import the module . Return the module if successfully compiled otherwise raise either a ProtocNotFound or BadProtobuf exception . |
42,176 | def types_from_module ( pb_module ) : types = pb_module . DESCRIPTOR . message_types_by_name return [ getattr ( pb_module , name ) for name in types ] | Return protobuf class types from an imported generated module . |
42,177 | def _resolve_child ( self , path ) : 'Return a member generator by a dot-delimited path' obj = self for component in path . split ( '.' ) : ptr = obj if not isinstance ( ptr , Permuter ) : raise self . MessageNotFound ( "Bad element path [wrong type]" ) found_gen = ( _ for _ in ptr . _generators if _ . name ( ) == component ) obj = next ( found_gen , None ) if not obj : raise self . MessageNotFound ( "Path '{}' unresolved to member." . format ( path ) ) return ptr , obj | Return a member generator by a dot - delimited path |
42,178 | def make_dependent ( self , source , target , action ) : if not self . _generators : return src_permuter , src = self . _resolve_child ( source ) dest = self . _resolve_child ( target ) [ 1 ] container = src_permuter . _generators idx = container . index ( src ) container [ idx ] = DependentValueGenerator ( src . name ( ) , dest , action ) self . _update_independent_generators ( ) | Create a dependency between path source and path target via the callable action . |
42,179 | def get ( self ) : 'Retrieve the most recent value generated' return tuple ( [ ( x . name ( ) , x . get ( ) ) for x in self . _generators ] ) | Retrieve the most recent value generated |
42,180 | def _fuzzdb_integers ( limit = 0 ) : 'Helper to grab some integers from fuzzdb' path = os . path . join ( BASE_PATH , 'integer-overflow/integer-overflows.txt' ) stream = _open_fuzzdb_file ( path ) for line in _limit_helper ( stream , limit ) : yield int ( line . decode ( 'utf-8' ) , 0 ) | Helper to grab some integers from fuzzdb |
42,181 | def _fuzzdb_get_strings ( max_len = 0 ) : 'Helper to get all the strings from fuzzdb' ignored = [ 'integer-overflow' ] for subdir in pkg_resources . resource_listdir ( 'protofuzz' , BASE_PATH ) : if subdir in ignored : continue path = '{}/{}' . format ( BASE_PATH , subdir ) listing = pkg_resources . resource_listdir ( 'protofuzz' , path ) for filename in listing : if not filename . endswith ( '.txt' ) : continue path = '{}/{}/{}' . format ( BASE_PATH , subdir , filename ) source = _open_fuzzdb_file ( path ) for line in source : string = line . decode ( 'utf-8' ) . strip ( ) if not string or string . startswith ( '#' ) : continue if max_len != 0 and len ( line ) > max_len : continue yield string | Helper to get all the strings from fuzzdb |
42,182 | def get_integers ( bitwidth , unsigned , limit = 0 ) : if unsigned : start , stop = 0 , ( ( 1 << bitwidth ) - 1 ) else : start , stop = ( - ( 1 << bitwidth - 1 ) ) , ( 1 << ( bitwidth - 1 ) - 1 ) for num in _fuzzdb_integers ( limit ) : if num >= start and num <= stop : yield num | Get integers from fuzzdb database |
42,183 | def get_floats ( bitwidth , limit = 0 ) : assert bitwidth in ( 32 , 64 , 80 ) values = [ 0.0 , - 1.0 , 1.0 , - 1231231231231.0123 , 123123123123123.123 ] for val in _limit_helper ( values , limit ) : yield val | Return a number of interesting floating point values |
42,184 | def _int_generator ( descriptor , bitwidth , unsigned ) : 'Helper to create a basic integer value generator' vals = list ( values . get_integers ( bitwidth , unsigned ) ) return gen . IterValueGenerator ( descriptor . name , vals ) | Helper to create a basic integer value generator |
42,185 | def _string_generator ( descriptor , max_length = 0 , limit = 0 ) : 'Helper to create a string generator' vals = list ( values . get_strings ( max_length , limit ) ) return gen . IterValueGenerator ( descriptor . name , vals ) | Helper to create a string generator |
42,186 | def _float_generator ( descriptor , bitwidth ) : 'Helper to create floating point values' return gen . IterValueGenerator ( descriptor . name , values . get_floats ( bitwidth ) ) | Helper to create floating point values |
42,187 | def _enum_generator ( descriptor ) : 'Helper to create protobuf enums' vals = descriptor . enum_type . values_by_number . keys ( ) return gen . IterValueGenerator ( descriptor . name , vals ) | Helper to create protobuf enums |
42,188 | def _prototype_to_generator ( descriptor , cls ) : 'Helper to map a descriptor to a protofuzz generator' _fd = D . FieldDescriptor generator = None ints32 = [ _fd . TYPE_INT32 , _fd . TYPE_UINT32 , _fd . TYPE_FIXED32 , _fd . TYPE_SFIXED32 , _fd . TYPE_SINT32 ] ints64 = [ _fd . TYPE_INT64 , _fd . TYPE_UINT64 , _fd . TYPE_FIXED64 , _fd . TYPE_SFIXED64 , _fd . TYPE_SINT64 ] ints_signed = [ _fd . TYPE_INT32 , _fd . TYPE_SFIXED32 , _fd . TYPE_SINT32 , _fd . TYPE_INT64 , _fd . TYPE_SFIXED64 , _fd . TYPE_SINT64 ] if descriptor . type in ints32 + ints64 : bitwidth = [ 32 , 64 ] [ descriptor . type in ints64 ] unsigned = descriptor . type not in ints_signed generator = _int_generator ( descriptor , bitwidth , unsigned ) elif descriptor . type == _fd . TYPE_DOUBLE : generator = _float_generator ( descriptor , 64 ) elif descriptor . type == _fd . TYPE_FLOAT : generator = _float_generator ( descriptor , 32 ) elif descriptor . type == _fd . TYPE_STRING : generator = _string_generator ( descriptor ) elif descriptor . type == _fd . TYPE_BYTES : generator = _bytes_generator ( descriptor ) elif descriptor . type == _fd . TYPE_BOOL : generator = gen . IterValueGenerator ( descriptor . name , [ True , False ] ) elif descriptor . type == _fd . TYPE_ENUM : generator = _enum_generator ( descriptor ) elif descriptor . type == _fd . TYPE_MESSAGE : generator = descriptor_to_generator ( descriptor . message_type , cls ) generator . set_name ( descriptor . name ) else : raise RuntimeError ( "type {} unsupported" . format ( descriptor . type ) ) return generator | Helper to map a descriptor to a protofuzz generator |
42,189 | def descriptor_to_generator ( cls_descriptor , cls , limit = 0 ) : 'Convert a protobuf descriptor to a protofuzz generator for same type' generators = [ ] for descriptor in cls_descriptor . fields_by_name . values ( ) : generator = _prototype_to_generator ( descriptor , cls ) if limit != 0 : generator . set_limit ( limit ) generators . append ( generator ) obj = cls ( cls_descriptor . name , * generators ) return obj | Convert a protobuf descriptor to a protofuzz generator for same type |
42,190 | def _assign_to_field ( obj , name , val ) : 'Helper to assign an arbitrary value to a protobuf field' target = getattr ( obj , name ) if isinstance ( target , containers . RepeatedScalarFieldContainer ) : target . append ( val ) elif isinstance ( target , containers . RepeatedCompositeFieldContainer ) : target = target . add ( ) target . CopyFrom ( val ) elif isinstance ( target , ( int , float , bool , str , bytes ) ) : setattr ( obj , name , val ) elif isinstance ( target , message . Message ) : target . CopyFrom ( val ) else : raise RuntimeError ( "Unsupported type: {}" . format ( type ( target ) ) ) | Helper to assign an arbitrary value to a protobuf field |
42,191 | def _fields_to_object ( descriptor , fields ) : 'Helper to convert a descriptor and a set of fields to a Protobuf instance' obj = descriptor . _concrete_class ( ) for name , value in fields : if isinstance ( value , tuple ) : subtype = descriptor . fields_by_name [ name ] . message_type value = _fields_to_object ( subtype , value ) _assign_to_field ( obj , name , value ) return obj | Helper to convert a descriptor and a set of fields to a Protobuf instance |
42,192 | def _module_to_generators ( pb_module ) : if not pb_module : return None message_types = pb_module . DESCRIPTOR . message_types_by_name return { k : ProtobufGenerator ( v ) for k , v in message_types . items ( ) } | Convert a protobuf module to a dict of generators . |
42,193 | def add_dependency ( self , source , target , action ) : self . _dependencies . append ( ( source , target , action ) ) | Create a dependency between fields source and target via callable action . |
42,194 | def print_report ( self ) : report = compare_report_print ( self . sorted , self . scores , self . best_name ) print ( report ) | Print Compare report . |
42,195 | def F_calc ( TP , FP , FN , beta ) : try : result = ( ( 1 + ( beta ) ** 2 ) * TP ) / ( ( 1 + ( beta ) ** 2 ) * TP + FP + ( beta ** 2 ) * FN ) return result except ZeroDivisionError : return "None" | Calculate F - score . |
42,196 | def G_calc ( item1 , item2 ) : try : result = math . sqrt ( item1 * item2 ) return result except Exception : return "None" | Calculate G - measure & G - mean . |
42,197 | def RACC_calc ( TOP , P , POP ) : try : result = ( TOP * P ) / ( ( POP ) ** 2 ) return result except Exception : return "None" | Calculate random accuracy . |
42,198 | def CEN_misclassification_calc ( table , TOP , P , i , j , subject_class , modified = False ) : try : result = TOP + P if modified : result -= table [ subject_class ] [ subject_class ] result = table [ i ] [ j ] / result return result except Exception : return "None" | Calculate misclassification probability of classifying . |
42,199 | def html_init ( name ) : result = "" result += "<html>\n" result += "<head>\n" result += "<title>" + str ( name ) + "</title>\n" result += "</head>\n" result += "<body>\n" result += '<h1 style="border-bottom:1px solid ' 'black;text-align:center;">PyCM Report</h1>' return result | Return HTML report file first lines . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.