idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
22,500
def post_info ( self , name , message ) : self . post_command ( OPERATIONS . CMD_POST_MESSAGE , _create_message ( name , states . INFO_LEVEL , message ) )
Asynchronously post a user facing info message about a service .
22,501
async def _on_status_change ( self , update ) : info = update [ 'payload' ] new_number = info [ 'new_status' ] name = update [ 'service' ] if name not in self . services : return with self . _state_lock : is_changed = self . services [ name ] . state != new_number self . services [ name ] . state = new_number if self ....
Update a service that has its status updated .
22,502
async def _on_heartbeat ( self , update ) : name = update [ 'service' ] if name not in self . services : return with self . _state_lock : self . services [ name ] . heartbeat ( )
Receive a new heartbeat for a service .
22,503
async def _on_message ( self , update ) : name = update [ 'service' ] message_obj = update [ 'payload' ] if name not in self . services : return with self . _state_lock : self . services [ name ] . post_message ( message_obj [ 'level' ] , message_obj [ 'message' ] )
Receive a message from a service .
22,504
async def _on_headline ( self , update ) : name = update [ 'service' ] message_obj = update [ 'payload' ] new_headline = False if name not in self . services : return with self . _state_lock : self . services [ name ] . set_headline ( message_obj [ 'level' ] , message_obj [ 'message' ] ) if self . services [ name ] . h...
Receive a headline from a service .
22,505
async def _on_rpc_command ( self , event ) : payload = event [ 'payload' ] rpc_id = payload [ 'rpc_id' ] tag = payload [ 'response_uuid' ] args = payload [ 'payload' ] result = 'success' response = b'' if self . _rpc_dispatcher is None or not self . _rpc_dispatcher . has_rpc ( rpc_id ) : result = 'rpc_not_found' else :...
Received an RPC command that we should execute .
22,506
def _decode_datetime ( obj ) : if '__datetime__' in obj : obj = datetime . datetime . strptime ( obj [ 'as_str' ] . decode ( ) , "%Y%m%dT%H:%M:%S.%f" ) return obj
Decode a msgpack ed datetime .
22,507
def _encode_datetime ( obj ) : if isinstance ( obj , datetime . datetime ) : obj = { '__datetime__' : True , 'as_str' : obj . strftime ( "%Y%m%dT%H:%M:%S.%f" ) . encode ( ) } return obj
Encode a msgpck ed datetime .
22,508
def _versioned_lib_suffix ( env , suffix , version ) : Verbose = False if Verbose : print ( "_versioned_lib_suffix: suffix= " , suffix ) print ( "_versioned_lib_suffix: version= " , version ) cygversion = re . sub ( '\.' , '-' , version ) if not suffix . startswith ( '-' + cygversion ) : suffix = '-' + cygversion + suf...
Generate versioned shared library suffix from a unversioned one . If suffix = . dll and version = 0 . 1 . 2 then it returns - 0 - 1 - 2 . dll
22,509
def generate ( env ) : gnulink . generate ( env ) env [ 'LINKFLAGS' ] = SCons . Util . CLVar ( '-Wl,-no-undefined' ) env [ 'SHLINKCOM' ] = shlib_action env [ 'LDMODULECOM' ] = ldmod_action env . Append ( SHLIBEMITTER = [ shlib_emitter ] ) env . Append ( LDMODULEEMITTER = [ ldmod_emitter ] ) env [ 'SHLIBPREFIX' ] = 'cyg...
Add Builders and construction variables for cyglink to an Environment .
22,510
def dispatch ( self , message ) : for validator , callback in self . validators : if not validator . matches ( message ) : continue callback ( message ) return raise ArgumentError ( "No handler was registered for message" , message = message )
Dispatch a message to a callback based on its schema .
22,511
def main ( raw_args = None ) : if raw_args is None : raw_args = sys . argv [ 1 : ] parser = build_parser ( ) args = parser . parse_args ( raw_args ) if args . firmware_image is None and args . gdb is None : print ( "You must specify either a firmware image or attach a debugger with --gdb <PORT>" ) return 1 test_args = ...
Run the iotile - emulate script .
22,512
def _detect ( env ) : QTDIR = None if not QTDIR : QTDIR = env . get ( 'QTDIR' , None ) if not QTDIR : QTDIR = os . environ . get ( 'QTDIR' , None ) if not QTDIR : moc = env . WhereIs ( 'moc' ) if moc : QTDIR = os . path . dirname ( os . path . dirname ( moc ) ) SCons . Warnings . warn ( QtdirNotFound , "Could not detec...
Not really safe but fast method to detect the QT library
22,513
def generate ( env ) : CLVar = SCons . Util . CLVar Action = SCons . Action . Action Builder = SCons . Builder . Builder env . SetDefault ( QTDIR = _detect ( env ) , QT_BINPATH = os . path . join ( '$QTDIR' , 'bin' ) , QT_CPPPATH = os . path . join ( '$QTDIR' , 'include' ) , QT_LIBPATH = os . path . join ( '$QTDIR' , '...
Add Builders and construction variables for qt to an Environment .
22,514
def CPP_to_Python ( s ) : s = CPP_to_Python_Ops_Expression . sub ( CPP_to_Python_Ops_Sub , s ) for expr , repl in CPP_to_Python_Eval_List : s = expr . sub ( repl , s ) return s
Converts a C pre - processor expression into an equivalent Python expression that can be evaluated .
22,515
def tupleize ( self , contents ) : global CPP_Expression , Table contents = line_continuations . sub ( '' , contents ) cpp_tuples = CPP_Expression . findall ( contents ) return [ ( m [ 0 ] , ) + Table [ m [ 0 ] ] . match ( m [ 1 ] ) . groups ( ) for m in cpp_tuples ]
Turns the contents of a file into a list of easily - processed tuples describing the CPP lines in the file .
22,516
def process_contents ( self , contents , fname = None ) : self . stack = [ ] self . dispatch_table = self . default_table . copy ( ) self . current_file = fname self . tuples = self . tupleize ( contents ) self . initialize_result ( fname ) while self . tuples : t = self . tuples . pop ( 0 ) self . dispatch_table [ t [...
Pre - processes a file contents .
22,517
def save ( self ) : self . stack . append ( self . dispatch_table ) self . dispatch_table = self . default_table . copy ( )
Pushes the current dispatch table on the stack and re - initializes the current dispatch table to the default .
22,518
def eval_expression ( self , t ) : t = CPP_to_Python ( ' ' . join ( t [ 1 : ] ) ) try : return eval ( t , self . cpp_namespace ) except ( NameError , TypeError ) : return 0
Evaluates a C preprocessor expression .
22,519
def emit_rmic_classes ( target , source , env ) : class_suffix = env . get ( 'JAVACLASSSUFFIX' , '.class' ) classdir = env . get ( 'JAVACLASSDIR' ) if not classdir : try : s = source [ 0 ] except IndexError : classdir = '.' else : try : classdir = s . attributes . java_classdir except AttributeError : classdir = '.' cl...
Create and return lists of Java RMI stub and skeleton class files to be created from a set of class files .
22,520
def generate ( env ) : env [ 'BUILDERS' ] [ 'RMIC' ] = RMICBuilder env [ 'RMIC' ] = 'rmic' env [ 'RMICFLAGS' ] = SCons . Util . CLVar ( '' ) env [ 'RMICCOM' ] = '$RMIC $RMICFLAGS -d ${TARGET.attributes.java_lookupdir} -classpath ${SOURCE.attributes.java_classdir} ${SOURCES.attributes.java_classname}' env [ 'JAVACLASSSU...
Add Builders and construction variables for rmic to an Environment .
22,521
def _set_scan_parameters ( self , interval = 2100 , window = 2100 , active = False ) : active_num = 0 if bool ( active ) : active_num = 1 interval_num = int ( interval * 1000 / 625 ) window_num = int ( window * 1000 / 625 ) payload = struct . pack ( "<HHB" , interval_num , window_num , active_num ) try : response = sel...
Set the scan interval and window in units of ms and set whether active scanning is performed
22,522
def _query_systemstate ( self ) : def status_filter_func ( event ) : if event . command_class == 3 and event . command == 0 : return True return False try : response = self . _send_command ( 0 , 6 , [ ] ) maxconn , = unpack ( "<B" , response . payload ) except InternalTimeoutError : return False , { 'reason' : 'Timeout...
Query the maximum number of connections supported by this adapter
22,523
def _start_scan ( self , active ) : success , retval = self . _set_scan_parameters ( active = active ) if not success : return success , retval try : response = self . _send_command ( 6 , 2 , [ 2 ] ) if response . payload [ 0 ] != 0 : self . _logger . error ( 'Error starting scan for devices, error=%d' , response . pay...
Begin scanning forever
22,524
def _stop_scan ( self ) : try : response = self . _send_command ( 6 , 4 , [ ] ) if response . payload [ 0 ] != 0 : if response . payload [ 0 ] != 129 : self . _logger . error ( 'Error stopping scan for devices, error=%d' , response . payload [ 0 ] ) return False , { 'reason' : "Could not stop scan for ble devices" } ex...
Stop scanning for BLE devices
22,525
def _probe_services ( self , handle ) : code = 0x2800 def event_filter_func ( event ) : if ( event . command_class == 4 and event . command == 2 ) : event_handle , = unpack ( "B" , event . payload [ 0 : 1 ] ) return event_handle == handle return False def end_filter_func ( event ) : if ( event . command_class == 4 and ...
Probe for all primary services and characteristics in those services
22,526
def _probe_characteristics ( self , conn , services , timeout = 5.0 ) : for service in services . values ( ) : success , result = self . _enumerate_handles ( conn , service [ 'start_handle' ] , service [ 'end_handle' ] ) if not success : return False , None attributes = result [ 'attributes' ] service [ 'characteristic...
Probe gatt services for all associated characteristics in a BLE device
22,527
def _enable_rpcs ( self , conn , services , timeout = 1.0 ) : success , result = self . _set_notification ( conn , services [ TileBusService ] [ 'characteristics' ] [ TileBusReceiveHeaderCharacteristic ] , True , timeout ) if not success : return success , result return self . _set_notification ( conn , services [ Tile...
Prepare this device to receive RPCs
22,528
def _disable_rpcs ( self , conn , services , timeout = 1.0 ) : success , result = self . _set_notification ( conn , services [ TileBusService ] [ 'characteristics' ] [ TileBusReceiveHeaderCharacteristic ] , False , timeout ) if not success : return success , result return self . _set_notification ( conn , services [ Ti...
Prevent this device from receiving more RPCs
22,529
def _write_handle ( self , conn , handle , ack , value , timeout = 1.0 ) : conn_handle = conn char_handle = handle def write_handle_acked ( event ) : if event . command_class == 4 and event . command == 1 : conn , _ , char = unpack ( "<BHH" , event . payload ) return conn_handle == conn and char_handle == char data_len...
Write to a BLE device characteristic by its handle
22,530
def _set_advertising_data ( self , packet_type , data ) : payload = struct . pack ( "<BB%ss" % ( len ( data ) ) , packet_type , len ( data ) , bytes ( data ) ) response = self . _send_command ( 6 , 9 , payload ) result , = unpack ( "<H" , response . payload ) if result != 0 : return False , { 'reason' : 'Error code fro...
Set the advertising data for advertisements sent out by this bled112
22,531
def _set_mode ( self , discover_mode , connect_mode ) : payload = struct . pack ( "<BB" , discover_mode , connect_mode ) response = self . _send_command ( 6 , 1 , payload ) result , = unpack ( "<H" , response . payload ) if result != 0 : return False , { 'reason' : 'Error code from BLED112 setting mode' , 'code' : resu...
Set the mode of the BLED112 used to enable and disable advertising
22,532
def _send_notification ( self , handle , value ) : value_len = len ( value ) value = bytes ( value ) payload = struct . pack ( "<BHB%ds" % value_len , 0xFF , handle , value_len , value ) response = self . _send_command ( 2 , 5 , payload ) result , = unpack ( "<H" , response . payload ) if result != 0 : return False , {...
Send a notification to all connected clients on a characteristic
22,533
def _disconnect ( self , handle ) : payload = struct . pack ( '<B' , handle ) response = self . _send_command ( 3 , 0 , payload ) conn_handle , result = unpack ( "<BH" , response . payload ) if result != 0 : self . _logger . info ( "Disconnection failed result=%d" , result ) return False , None assert conn_handle == ha...
Disconnect from a device that we have previously connected to
22,534
def _send_command ( self , cmd_class , command , payload , timeout = 3.0 ) : if len ( payload ) > 60 : return ValueError ( "Attempting to send a BGAPI packet with length > 60 is not allowed" , actual_length = len ( payload ) , command = command , command_class = cmd_class ) header = bytearray ( 4 ) header [ 0 ] = 0 hea...
Send a BGAPI packet to the dongle and return the response
22,535
def _receive_packet ( self , timeout = 3.0 ) : while True : response_data = self . _stream . read_packet ( timeout = timeout ) response = BGAPIPacket ( is_event = ( response_data [ 0 ] == 0x80 ) , command_class = response_data [ 2 ] , command = response_data [ 3 ] , payload = response_data [ 4 : ] ) if response . is_ev...
Receive a response packet to a command
22,536
def _wait_process_events ( self , total_time , return_filter , end_filter ) : acc = [ ] delta = 0.01 start_time = time . time ( ) end_time = start_time + total_time while time . time ( ) < end_time : events = self . _process_events ( lambda x : return_filter ( x ) or end_filter ( x ) , max_events = 1 ) acc += events fo...
Synchronously process events until a specific event is found or we timeout
22,537
def connect ( self , client_id ) : if self . client is not None : raise InternalError ( "Connect called on an alreaded connected MQTT client" ) client = AWSIoTPythonSDK . MQTTLib . AWSIoTMQTTClient ( client_id , useWebsocket = self . websockets ) if self . websockets : client . configureEndpoint ( self . endpoint , 443...
Connect to AWS IOT with the given client_id
22,538
def disconnect ( self ) : if self . client is None : return try : self . client . disconnect ( ) except operationError as exc : raise InternalError ( "Could not disconnect from AWS IOT" , message = exc . message )
Disconnect from AWS IOT message broker
22,539
def publish ( self , topic , message ) : seq = self . sequencer . next_id ( topic ) packet = { 'sequence' : seq , 'message' : message } if 'key' in packet [ 'message' ] : packet [ 'message' ] [ 'key' ] = packet [ 'message' ] [ 'key' ] . decode ( 'utf8' ) if 'payload' in packet [ 'message' ] : packet [ 'message' ] [ 'pa...
Publish a json message to a topic with a type and a sequence number
22,540
def subscribe ( self , topic , callback , ordered = True ) : if '+' in topic or '#' in topic : regex = re . compile ( topic . replace ( '+' , '[^/]+' ) . replace ( '#' , '.*' ) ) self . wildcard_queues . append ( ( topic , regex , callback , ordered ) ) else : self . queues [ topic ] = PacketQueue ( 0 , callback , orde...
Subscribe to future messages in the given topic
22,541
def reset_sequence ( self , topic ) : if topic in self . queues : self . queues [ topic ] . reset ( )
Reset the expected sequence number for a topic
22,542
def unsubscribe ( self , topic ) : del self . queues [ topic ] try : self . client . unsubscribe ( topic ) except operationError as exc : raise InternalError ( "Could not unsubscribe from topic" , topic = topic , message = exc . message )
Unsubscribe from messages on a given topic
22,543
def _on_receive ( self , client , userdata , message ) : topic = message . topic encoded = message . payload try : packet = json . loads ( encoded ) except ValueError : self . _logger . warn ( "Could not decode json packet: %s" , encoded ) return try : seq = packet [ 'sequence' ] message_data = packet [ 'message' ] exc...
Callback called whenever we receive a message on a subscribed topic
22,544
def run ( self , resources ) : hwman = resources [ 'connection' ] con = hwman . hwman . controller ( ) test_interface = con . test_interface ( ) try : test_interface . synchronize_clock ( ) print ( 'Time currently set at %s' % test_interface . current_time_str ( ) ) except : raise ArgumentError ( 'Error setting RTC tim...
Sets the RTC timestamp to UTC .
22,545
def add ( self , command , * args ) : cmd = Command ( command , args ) self . commands . append ( cmd )
Add a command to this command file .
22,546
def save ( self , outpath ) : with open ( outpath , "w" ) as outfile : outfile . write ( self . dump ( ) )
Save this command file as an ascii file .
22,547
def dump ( self ) : out = [ ] out . append ( self . filetype ) out . append ( "Format: {}" . format ( self . version ) ) out . append ( "Type: ASCII" ) out . append ( "" ) for cmd in self . commands : out . append ( self . encode ( cmd ) ) return "\n" . join ( out ) + "\n"
Dump all commands in this object to a string .
22,548
def FromString ( cls , indata ) : lines = [ x . strip ( ) for x in indata . split ( "\n" ) if not x . startswith ( '#' ) and not x . strip ( ) == "" ] if len ( lines ) < 3 : raise DataError ( "Invalid CommandFile string that did not contain 3 header lines" , lines = lines ) fmt_line , version_line , ascii_line = lines ...
Load a CommandFile from a string .
22,549
def FromFile ( cls , inpath ) : with open ( inpath , "r" ) as infile : indata = infile . read ( ) return cls . FromString ( indata )
Load a CommandFile from a path .
22,550
def encode ( cls , command ) : args = [ ] for arg in command . args : if not isinstance ( arg , str ) : arg = str ( arg ) if "," in arg or arg . startswith ( " " ) or arg . endswith ( " " ) or arg . startswith ( "hex:" ) : arg = "hex:{}" . format ( hexlify ( arg . encode ( 'utf-8' ) ) . decode ( 'utf-8' ) ) args . appe...
Encode a command as an unambiguous string .
22,551
def decode ( cls , command_str ) : name , _ , arg = command_str . partition ( " " ) args = [ ] if len ( arg ) > 0 : if arg [ 0 ] != '{' or arg [ - 1 ] != '}' : raise DataError ( "Invalid command, argument is not contained in { and }" , arg = arg , cmd = name ) arg = arg [ 1 : - 1 ] args = arg . split ( "," ) proc = [ ]...
Decode a string encoded command back into a Command object .
22,552
def receive ( self , sequence , args ) : if not self . _reorder : self . _callback ( * args ) return if self . _next_expected is not None and sequence < self . _next_expected : print ( "Dropping out of order packet, seq=%d" % sequence ) return self . _out_of_order . append ( ( sequence , args ) ) self . _out_of_order ....
Receive one packet
22,553
def set_vars ( env ) : desired = env . get ( 'MWCW_VERSION' , '' ) if isinstance ( desired , MWVersion ) : return 1 elif desired is None : return 0 versions = find_versions ( ) version = None if desired : for v in versions : if str ( v ) == desired : version = v elif versions : version = versions [ - 1 ] env [ 'MWCW_VE...
Set MWCW_VERSION MWCW_VERSIONS and some codewarrior environment vars
22,554
def find_versions ( ) : versions = [ ] if SCons . Util . can_read_reg : try : HLM = SCons . Util . HKEY_LOCAL_MACHINE product = 'SOFTWARE\\Metrowerks\\CodeWarrior\\Product Versions' product_key = SCons . Util . RegOpenKeyEx ( HLM , product ) i = 0 while True : name = product + '\\' + SCons . Util . RegEnumKey ( product...
Return a list of MWVersion objects representing installed versions
22,555
def generate ( env ) : import SCons . Defaults import SCons . Tool set_vars ( env ) static_obj , shared_obj = SCons . Tool . createObjBuilders ( env ) for suffix in CSuffixes : static_obj . add_action ( suffix , SCons . Defaults . CAction ) shared_obj . add_action ( suffix , SCons . Defaults . ShCAction ) for suffix in...
Add Builders and construction variables for the mwcc to an Environment .
22,556
def run ( self , resources ) : if not resources [ 'connection' ] . _port . startswith ( 'jlink' ) : raise ArgumentError ( "FlashBoardStep is currently only possible through jlink" , invalid_port = args [ 'port' ] ) hwman = resources [ 'connection' ] debug = hwman . hwman . debug ( self . _debug_string ) debug . flash (...
Runs the flash step
22,557
def copyto_emitter ( target , source , env ) : n_target = [ ] for t in target : n_target = n_target + [ t . File ( str ( s ) ) for s in source ] return ( n_target , source )
changes the path of the source to be under the target ( which are assumed to be directories .
22,558
def getPharLapPath ( ) : if not SCons . Util . can_read_reg : raise SCons . Errors . InternalError ( "No Windows registry module was found" ) try : k = SCons . Util . RegOpenKeyEx ( SCons . Util . HKEY_LOCAL_MACHINE , 'SOFTWARE\\Pharlap\\ETS' ) val , type = SCons . Util . RegQueryValueEx ( k , 'BaseDir' ) idx = val . f...
Reads the registry to find the installed path of the Phar Lap ETS development kit .
22,559
def addPharLapPaths ( env ) : ph_path = getPharLapPath ( ) try : env_dict = env [ 'ENV' ] except KeyError : env_dict = { } env [ 'ENV' ] = env_dict SCons . Util . AddPathIfNotExists ( env_dict , 'PATH' , os . path . join ( ph_path , 'bin' ) ) SCons . Util . AddPathIfNotExists ( env_dict , 'INCLUDE' , os . path . join (...
This function adds the path to the Phar Lap binaries includes and libraries if they are not already there .
22,560
def _update_or_init_po_files ( target , source , env ) : import SCons . Action from SCons . Tool . GettextCommon import _init_po_files for tgt in target : if tgt . rexists ( ) : action = SCons . Action . Action ( '$MSGMERGECOM' , '$MSGMERGECOMSTR' ) else : action = _init_po_files status = action ( [ tgt ] , source , en...
Action function for POUpdate builder
22,561
def _POUpdateBuilder ( env , ** kw ) : import SCons . Action from SCons . Tool . GettextCommon import _POFileBuilder action = SCons . Action . Action ( _update_or_init_po_files , None ) return _POFileBuilder ( env , action = action , target_alias = '$POUPDATE_ALIAS' )
Create an object of POUpdate builder
22,562
def _POUpdateBuilderWrapper ( env , target = None , source = _null , ** kw ) : if source is _null : if 'POTDOMAIN' in kw : domain = kw [ 'POTDOMAIN' ] elif 'POTDOMAIN' in env and env [ 'POTDOMAIN' ] : domain = env [ 'POTDOMAIN' ] else : domain = 'messages' source = [ domain ] return env . _POUpdateBuilder ( target , so...
Wrapper for POUpdate builder - make user s life easier
22,563
def generate ( env , ** kw ) : from SCons . Tool . GettextCommon import _detect_msgmerge try : env [ 'MSGMERGE' ] = _detect_msgmerge ( env ) except : env [ 'MSGMERGE' ] = 'msgmerge' env . SetDefault ( POTSUFFIX = [ '.pot' ] , POSUFFIX = [ '.po' ] , MSGMERGECOM = '$MSGMERGE $MSGMERGEFLAGS --update $TARGET $SOURCE' , MS...
Generate the xgettext tool
22,564
def _create_filter ( self ) : self . _product_filter = { } for chip in itertools . chain ( iter ( self . _family . targets ( self . _tile . short_name ) ) , iter ( [ self . _family . platform_independent_target ( ) ] ) ) : for key , prods in chip . property ( 'depends' , { } ) . items ( ) : name , _ , _ = key . partiti...
Create a filter of all of the dependency products that we have selected .
22,565
def _create_product_map ( self ) : self . _product_map = { } for dep in self . _tile . dependencies : try : dep_tile = IOTile ( os . path . join ( 'build' , 'deps' , dep [ 'unique_id' ] ) ) except ( ArgumentError , EnvironmentError ) : raise BuildError ( "Could not find required dependency" , name = dep [ 'name' ] ) se...
Create a map of all products produced by this or a dependency .
22,566
def _add_products ( self , tile , show_all = False ) : products = tile . products unique_id = tile . unique_id base_path = tile . output_folder for prod_path , prod_type in products . items ( ) : if prod_path == 'tilebus_definitions' or prod_path == 'include_directories' : continue if prod_type in self . IGNORED_PRODUC...
Add all products from a tile into our product map .
22,567
def find_all ( self , product_type , short_name , include_hidden = False ) : all_prods = [ ] if product_type is None : for prod_dict in self . _product_map . values ( ) : all_prods . extend ( [ prod for prod in prod_dict . get ( short_name , [ ] ) if include_hidden or not prod . hidden ] ) return all_prods all_prods = ...
Find all providers of a given product by its short name .
22,568
def find_unique ( self , product_type , short_name , include_hidden = False ) : prods = self . find_all ( product_type , short_name , include_hidden ) if len ( prods ) == 0 : raise BuildError ( "Could not find product by name in find_unique" , name = short_name , type = product_type ) if len ( prods ) > 1 : raise Build...
Find the unique provider of a given product by its short name .
22,569
def main ( raw_args = None ) : multifile_choices = frozenset ( [ 'c_files' ] ) if raw_args is None : raw_args = sys . argv [ 1 : ] parser = build_parser ( ) args = parser . parse_args ( raw_args ) if args . output is None and args . format in multifile_choices : print ( "You must specify an output file with -o, --outpu...
Run the iotile - tbcompile script .
22,570
def generate ( env ) : "Add RPCGEN Builders and construction variables for an Environment." client = Builder ( action = rpcgen_client , suffix = '_clnt.c' , src_suffix = '.x' ) header = Builder ( action = rpcgen_header , suffix = '.h' , src_suffix = '.x' ) service = Builder ( action = rpcgen_service , suffix = '_svc.c'...
Add RPCGEN Builders and construction variables for an Environment .
22,571
def build_parser ( ) : parser = argparse . ArgumentParser ( "Release packages to pypi" ) parser . add_argument ( '--check' , '-c' , action = "store_true" , help = "Do a dry run without uploading" ) parser . add_argument ( 'component' , help = "The component to release as component-version" ) return parser
Build argument parsers .
22,572
def get_release_component ( comp ) : name , vers = comp . split ( "-" ) if name not in comp_names : print ( "Known components:" ) for comp in comp_names : print ( "- %s" % comp ) raise EnvironmentError ( "Unknown release component name '%s'" % name ) return name , vers
Split the argument passed on the command line into a component name and expected version
22,573
def check_compatibility ( name ) : comp = comp_names [ name ] if sys . version_info . major < 3 and comp . compat == "python3" : return False if sys . version_info . major >= 3 and comp . compat != "python3" : return False return True
Verify if we can release this component on the running interpreter .
22,574
def build_component ( component ) : comp = comp_names [ component ] curr = os . getcwd ( ) os . chdir ( comp . path ) args = [ '-q' , 'clean' , 'sdist' , 'bdist_wheel' ] if comp . compat == 'universal' : args . append ( '--universal' ) try : setuptools . sandbox . run_setup ( 'setup.py' , args ) finally : os . chdir ( ...
Create an sdist and a wheel for the desired component
22,575
def uuid_to_slug ( uuid ) : if not isinstance ( uuid , int ) : raise ArgumentError ( "Invalid id that is not an integer" , id = uuid ) if uuid < 0 or uuid > 0x7fffffff : raise ArgumentError ( "Integer should be a positive number and smaller than 0x7fffffff" , id = uuid ) return '--' . join ( [ 'd' , int64gid ( uuid ) ]...
Return IOTile Cloud compatible Device Slug
22,576
def package ( env , target , source , PACKAGEROOT , NAME , VERSION , DESCRIPTION , SUMMARY , X_IPK_PRIORITY , X_IPK_SECTION , SOURCE_URL , X_IPK_MAINTAINER , X_IPK_DEPENDS , ** kw ) : SCons . Tool . Tool ( 'ipkg' ) . generate ( env ) bld = env [ 'BUILDERS' ] [ 'Ipkg' ] target , source = stripinstallbuilder ( target , s...
This function prepares the packageroot directory for packaging with the ipkg builder .
22,577
def build_specfiles ( source , target , env ) : opened_files = { } def open_file ( needle , haystack ) : try : return opened_files [ needle ] except KeyError : file = filter ( lambda x : x . get_path ( ) . rfind ( needle ) != - 1 , haystack ) [ 0 ] opened_files [ needle ] = open ( file . get_abspath ( ) , 'w' ) return ...
Filter the targets for the needed files and use the variables in env to create the specfile .
22,578
def emit_java_headers ( target , source , env ) : class_suffix = env . get ( 'JAVACLASSSUFFIX' , '.class' ) classdir = env . get ( 'JAVACLASSDIR' ) if not classdir : try : s = source [ 0 ] except IndexError : classdir = '.' else : try : classdir = s . attributes . java_classdir except AttributeError : classdir = '.' cl...
Create and return lists of Java stub header files that will be created from a set of class files .
22,579
def generate ( env ) : java_javah = SCons . Tool . CreateJavaHBuilder ( env ) java_javah . emitter = emit_java_headers env [ '_JAVAHOUTFLAG' ] = JavaHOutFlagGenerator env [ 'JAVAH' ] = 'javah' env [ 'JAVAHFLAGS' ] = SCons . Util . CLVar ( '' ) env [ '_JAVAHCLASSPATH' ] = getJavaHClassPath env [ 'JAVAHCOM' ] = '$JAVAH $...
Add Builders and construction variables for javah to an Environment .
22,580
def dump ( self ) : return { u'storage_data' : [ x . asdict ( ) for x in self . storage_data ] , u'streaming_data' : [ x . asdict ( ) for x in self . streaming_data ] }
Serialize the state of this InMemoryStorageEngine to a dict .
22,581
def restore ( self , state ) : storage_data = state . get ( u'storage_data' , [ ] ) streaming_data = state . get ( u'streaming_data' , [ ] ) if len ( storage_data ) > self . storage_length or len ( streaming_data ) > self . streaming_length : raise ArgumentError ( "Cannot restore InMemoryStorageEngine, too many reading...
Restore the state of this InMemoryStorageEngine from a dict .
22,582
def count_matching ( self , selector , offset = 0 ) : if selector . output : data = self . streaming_data elif selector . buffered : data = self . storage_data else : raise ArgumentError ( "You can only pass a buffered selector to count_matching" , selector = selector ) count = 0 for i in range ( offset , len ( data ) ...
Count the number of readings matching selector .
22,583
def scan_storage ( self , area_name , callable , start = 0 , stop = None ) : if area_name == u'storage' : data = self . storage_data elif area_name == u'streaming' : data = self . streaming_data else : raise ArgumentError ( "Unknown area name in scan_storage (%s) should be storage or streaming" % area_name ) if len ( d...
Iterate over streaming or storage areas calling callable .
22,584
def push ( self , value ) : stream = DataStream . FromEncoded ( value . stream ) if stream . stream_type == DataStream . OutputType : if len ( self . streaming_data ) == self . streaming_length : raise StorageFullError ( 'Streaming buffer full' ) self . streaming_data . append ( value ) else : if len ( self . storage_d...
Store a new value for the given stream .
22,585
def get ( self , buffer_type , offset ) : if buffer_type == u'streaming' : chosen_buffer = self . streaming_data else : chosen_buffer = self . storage_data if offset >= len ( chosen_buffer ) : raise StreamEmptyError ( "Invalid index given in get command" , requested = offset , stored = len ( chosen_buffer ) , buffer = ...
Get a reading from the buffer at offset .
22,586
def popn ( self , buffer_type , count ) : buffer_type = str ( buffer_type ) if buffer_type == u'streaming' : chosen_buffer = self . streaming_data else : chosen_buffer = self . storage_data if count > len ( chosen_buffer ) : raise StreamEmptyError ( "Not enough data in buffer for popn command" , requested = count , sto...
Remove and return the oldest count values from the named buffer
22,587
async def send_script ( self , conn_id , data ) : self . _ensure_connection ( conn_id , True ) connection_string = self . _get_property ( conn_id , "connection_string" ) msg = dict ( connection_string = connection_string , fragment_count = 1 , fragment_index = 0 , script = base64 . b64encode ( data ) ) await self . _se...
Send a a script to this IOTile device
22,588
async def _on_report_notification ( self , event ) : conn_string = event . get ( 'connection_string' ) report = self . _report_parser . deserialize_report ( event . get ( 'serialized_report' ) ) self . notify_event ( conn_string , 'report' , report )
Callback function called when a report event is received .
22,589
async def _on_trace_notification ( self , trace_event ) : conn_string = trace_event . get ( 'connection_string' ) payload = trace_event . get ( 'payload' ) await self . notify_event ( conn_string , 'trace' , payload )
Callback function called when a trace chunk is received .
22,590
async def _on_progress_notification ( self , progress ) : conn_string = progress . get ( 'connection_string' ) done = progress . get ( 'done_count' ) total = progress . get ( 'total_count' ) operation = progress . get ( 'operation' ) await self . notify_progress ( conn_string , operation , done , total , wait = True )
Callback function called when a progress notification is received .
22,591
def _extract_variables ( param ) : variables = set ( ) if isinstance ( param , list ) : variables . update ( * [ _extract_variables ( x ) for x in param ] ) elif isinstance ( param , dict ) : variables . update ( * [ _extract_variables ( x ) for x in param . values ( ) ] ) elif isinstance ( param , str ) : for match in...
Find all template variables in args .
22,592
def _run_step ( step_obj , step_declaration , initialized_resources ) : start_time = time . time ( ) for res_name in step_declaration . resources . opened : initialized_resources [ res_name ] . open ( ) used_resources = { local_name : initialized_resources [ global_name ] for local_name , global_name in step_declaratio...
Actually run a step .
22,593
def archive ( self , output_path ) : if self . path is None : raise ArgumentError ( "Cannot archive a recipe yet without a reference to its original yaml file in self.path" ) outfile = zipfile . ZipFile ( output_path , 'w' , zipfile . ZIP_DEFLATED ) outfile . write ( self . path , arcname = "recipe_script.yaml" ) writt...
Archive this recipe and all associated files into a . ship archive .
22,594
def FromArchive ( cls , path , actions_dict , resources_dict , temp_dir = None ) : if not path . endswith ( ".ship" ) : raise ArgumentError ( "Attempted to unpack a recipe archive from a file that did not end in .ship" , path = path ) name = os . path . basename ( path ) [ : - 5 ] if temp_dir is None : temp_dir = tempf...
Create a RecipeObject from a . ship archive .
22,595
def FromFile ( cls , path , actions_dict , resources_dict , file_format = "yaml" , name = None ) : format_map = { "yaml" : cls . _process_yaml } format_handler = format_map . get ( file_format ) if format_handler is None : raise ArgumentError ( "Unknown file format or file extension" , file_format = file_format , known...
Create a RecipeObject from a file .
22,596
def _parse_file_usage ( cls , action_class , args ) : fixed_files = { } variable_files = [ ] if not hasattr ( action_class , 'FILES' ) : return fixed_files , variable_files for file_arg in action_class . FILES : arg_value = args . get ( file_arg ) if arg_value is None : raise RecipeFileInvalid ( "Action lists a file ar...
Find all external files referenced by an action .
22,597
def _parse_resource_declarations ( cls , declarations , resource_map ) : resources = { } for decl in declarations : name = decl . pop ( 'name' ) typename = decl . pop ( 'type' ) desc = decl . pop ( 'description' , None ) autocreate = decl . pop ( 'autocreate' , False ) args = decl res_type = resource_map . get ( typena...
Parse out what resources are declared as shared for this recipe .
22,598
def _parse_variable_defaults ( cls , defaults ) : default_dict = { } for item in defaults : key = next ( iter ( item ) ) value = item [ key ] if key in default_dict : raise RecipeFileInvalid ( "Default variable value specified twice" , name = key , old_value = default_dict [ key ] , new_value = value ) default_dict [ k...
Parse out all of the variable defaults .
22,599
def _parse_resource_usage ( cls , action_dict , declarations ) : raw_used = action_dict . pop ( 'use' , [ ] ) opened = [ x . strip ( ) for x in action_dict . pop ( 'open_before' , [ ] ) ] closed = [ x . strip ( ) for x in action_dict . pop ( 'close_after' , [ ] ) ] used = { } for resource in raw_used : if 'as' in resou...
Parse out what resources are used opened and closed in an action step .