idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
32,900 | def run_nested_error_groups ( ) : test = htf . Test ( htf . PhaseGroup ( main = [ htf . PhaseGroup . with_teardown ( inner_teardown_phase ) ( error_main_phase , main_phase ) , main_phase , ] , teardown = [ teardown_phase ] , ) ) test . execute ( ) | Run nested groups example where an error occurs in nested main phase . |
32,901 | def main ( ) : parser = argparse . ArgumentParser ( description = 'Reads in a .xls file and generates a units module for ' 'OpenHTF.' , prog = 'python units_from_xls.py' ) parser . add_argument ( 'xlsfile' , type = str , help = 'the .xls file to parse' ) parser . add_argument ( '--outfile' , type = str , default = os .... | Main entry point for UNECE code . xls parsing . |
32,902 | def unit_defs_from_sheet ( sheet , column_names ) : seen = set ( ) try : col_indices = { } rows = sheet . get_rows ( ) for idx , cell in enumerate ( six . next ( rows ) ) : if cell . value in column_names : col_indices [ cell . value ] = idx for row in rows : name = row [ col_indices [ column_names [ 0 ] ] ] . value . ... | A generator that parses a worksheet containing UNECE code definitions . |
32,903 | def unit_key_from_name ( name ) : result = name for old , new in six . iteritems ( UNIT_KEY_REPLACEMENTS ) : result = result . replace ( old , new ) result = re . sub ( r'_+' , '_' , result . upper ( ) ) return result | Return a legal python name for the given name for use as a unit key . |
32,904 | def make_wire_commands ( * ids ) : cmd_to_wire = { cmd : sum ( ord ( c ) << ( i * 8 ) for i , c in enumerate ( cmd ) ) for cmd in ids } wire_to_cmd = { wire : cmd for cmd , wire in six . iteritems ( cmd_to_wire ) } return cmd_to_wire , wire_to_cmd | Assemble the commands . |
32,905 | def to_adb_message ( self , data ) : message = AdbMessage ( AdbMessage . WIRE_TO_CMD . get ( self . cmd ) , self . arg0 , self . arg1 , data ) if ( len ( data ) != self . data_length or message . data_crc32 != self . data_checksum ) : raise usb_exceptions . AdbDataIntegrityError ( '%s (%s) received invalid data: %s' , ... | Turn the data into an ADB message . |
32,906 | def write_message ( self , message , timeout ) : with self . _writer_lock : self . _transport . write ( message . header , timeout . remaining_ms ) if timeout . has_expired ( ) : _LOG . warning ( 'Timed out between AdbMessage header and data, sending ' 'data anyway with 10ms timeout' ) timeout = timeouts . PolledTimeou... | Send the given message over this transport . |
32,907 | def read_message ( self , timeout ) : with self . _reader_lock : raw_header = self . _transport . read ( struct . calcsize ( AdbMessage . HEADER_STRUCT_FORMAT ) , timeout . remaining_ms ) if not raw_header : raise usb_exceptions . AdbProtocolError ( 'Adb connection lost' ) try : raw_message = RawAdbMessage ( * struct .... | Read an AdbMessage from this transport . |
32,908 | def read_until ( self , expected_commands , timeout ) : msg = timeouts . loop_until_timeout_or_valid ( timeout , lambda : self . read_message ( timeout ) , lambda m : m . command in expected_commands , 0 ) if msg . command not in expected_commands : raise usb_exceptions . AdbTimeoutError ( 'Timed out establishing conne... | Read AdbMessages from this transport until we get an expected command . |
32,909 | def header ( self ) : return struct . pack ( self . HEADER_STRUCT_FORMAT , self . _command , self . arg0 , self . arg1 , len ( self . data ) , self . data_crc32 , self . magic ) | The message header . |
32,910 | def _make_message_type ( name , attributes , has_data = True ) : def assert_command_is ( self , command ) : if self . command != command : raise usb_exceptions . AdbProtocolError ( 'Expected %s command, received %s' , command , self ) return type ( name , ( collections . namedtuple ( name , attributes ) , ) , { 'assert... | Make a message type for the AdbTransport subclasses . |
32,911 | def stat ( self , filename , timeout = None ) : transport = StatFilesyncTransport ( self . stream ) transport . write_data ( 'STAT' , filename , timeout ) stat_msg = transport . read_message ( timeout ) stat_msg . assert_command_is ( 'STAT' ) return DeviceFileStat ( filename , stat_msg . mode , stat_msg . size , stat_m... | Return device file stat . |
32,912 | def list ( self , path , timeout = None ) : transport = DentFilesyncTransport ( self . stream ) transport . write_data ( 'LIST' , path , timeout ) return ( DeviceFileStat ( dent_msg . name , dent_msg . mode , dent_msg . size , dent_msg . time ) for dent_msg in transport . read_until_done ( 'DENT' , timeout ) ) | List directory contents on the device . |
32,913 | def recv ( self , filename , dest_file , timeout = None ) : transport = DataFilesyncTransport ( self . stream ) transport . write_data ( 'RECV' , filename , timeout ) for data_msg in transport . read_until_done ( 'DATA' , timeout ) : dest_file . write ( data_msg . data ) | Retrieve a file from the device into the file - like dest_file . |
32,914 | def _check_for_fail_message ( self , transport , exc_info , timeout ) : try : transport . read_message ( timeout ) except usb_exceptions . CommonUsbError : if sys . exc_info ( ) [ 0 ] is usb_exceptions . AdbRemoteError : raise raise_with_traceback ( exc_info [ 0 ] ( exc_info [ 1 ] ) , traceback = exc_info [ 2 ] ) | Check for a FAIL message from transport . |
32,915 | def write_data ( self , command , data , timeout = None ) : self . write_message ( FilesyncMessageTypes . DataMessage ( command , data ) , timeout ) | Shortcut for writing specifically a DataMessage . |
32,916 | def read_until_done ( self , command , timeout = None ) : message = self . read_message ( timeout ) while message . command != 'DONE' : message . assert_command_is ( command ) yield message message = self . read_message ( timeout ) | Yield messages read until we receive a DONE command . |
32,917 | def read_message ( self , timeout = None ) : raw_data = self . stream . read ( struct . calcsize ( self . RECV_MSG_TYPE . struct_format ) , timeout ) try : raw_message = struct . unpack ( self . RECV_MSG_TYPE . struct_format , raw_data ) except struct . error : raise usb_exceptions . AdbProtocolError ( '%s expected for... | Read a message from this transport and return it . |
32,918 | def _lazy_load_units_by_code ( ) : if UNITS_BY_CODE : return for unit in units . UNITS_BY_NAME . values ( ) : UNITS_BY_CODE [ unit . code ] = unit | Populate dict of units by code iff UNITS_BY_CODE is empty . |
32,919 | def _populate_basic_data ( mfg_event , record ) : mfg_event . dut_serial = record . dut_id mfg_event . start_time_ms = record . start_time_millis mfg_event . end_time_ms = record . end_time_millis mfg_event . tester_name = record . station_id mfg_event . test_name = record . metadata . get ( 'test_name' ) or record . s... | Copies data from the OpenHTF TestRecord to the MfgEvent proto . |
32,920 | def _attach_record_as_json ( mfg_event , record ) : attachment = mfg_event . attachment . add ( ) attachment . name = TEST_RECORD_ATTACHMENT_NAME test_record_dict = htf_data . convert_to_base_types ( record ) attachment . value_binary = _convert_object_to_json ( test_record_dict ) attachment . type = test_runs_pb2 . TE... | Attach a copy of the record as JSON so we have an un - mangled copy . |
32,921 | def _attach_config ( mfg_event , record ) : if 'config' not in record . metadata : return attachment = mfg_event . attachment . add ( ) attachment . name = 'config' attachment . value_binary = _convert_object_to_json ( record . metadata [ 'config' ] ) attachment . type = test_runs_pb2 . TEXT_UTF8 | Attaches the OpenHTF config file as JSON . |
32,922 | def phase_uniquizer ( all_phases ) : measurement_name_maker = UniqueNameMaker ( itertools . chain . from_iterable ( phase . measurements . keys ( ) for phase in all_phases if phase . measurements ) ) attachment_names = list ( itertools . chain . from_iterable ( phase . attachments . keys ( ) for phase in all_phases ) )... | Makes the names of phase measurement and attachments unique . |
32,923 | def multidim_measurement_to_attachment ( name , measurement ) : dimensions = list ( measurement . dimensions ) if measurement . units : dimensions . append ( measurements . Dimension . from_unit_descriptor ( measurement . units ) ) dims = [ ] for d in dimensions : if d . suffix is None : suffix = u'' elif isinstance ( ... | Convert a multi - dim measurement to an openhtf . test_record . Attachment . |
32,924 | def convert_multidim_measurements ( all_phases ) : attachment_names = list ( itertools . chain . from_iterable ( phase . attachments . keys ( ) for phase in all_phases ) ) attachment_names . extend ( itertools . chain . from_iterable ( [ 'multidim_' + name for name , meas in phase . measurements . items ( ) if meas . d... | Converts each multidim measurements into attachments for all phases .. |
32,925 | def attachment_to_multidim_measurement ( attachment , name = None ) : data = json . loads ( attachment . data ) name = name or data . get ( 'name' ) attachment_dims = data . get ( 'dimensions' , [ ] ) attachment_values = data . get ( 'value' ) attachment_outcome_str = data . get ( 'outcome' ) if attachment_outcome_str ... | Convert an OpenHTF test record attachment to a multi - dim measurement . |
32,926 | def _copy_unidimensional_measurement ( self , phase , name , measurement , mfg_event ) : mfg_measurement = mfg_event . measurement . add ( ) mfg_measurement . name = name if measurement . docstring : mfg_measurement . description = measurement . docstring mfg_measurement . parameter_tag . append ( phase . name ) if ( m... | Copy uni - dimensional measurements to the MfgEvent . |
32,927 | def _copy_attachment ( self , name , data , mimetype , mfg_event ) : attachment = mfg_event . attachment . add ( ) attachment . name = name if isinstance ( data , unicode ) : data = data . encode ( 'utf8' ) attachment . value_binary = data if mimetype in test_runs_converter . MIMETYPE_MAP : attachment . type = test_run... | Copies an attachment to mfg_event . |
32,928 | def write ( self , data , timeout_ms = None ) : timeout = timeouts . PolledTimeout . from_millis ( timeout_ms ) while data : self . _transport . write ( data [ : self . _transport . adb_connection . maxdata ] , timeout ) data = data [ self . _transport . adb_connection . maxdata : ] | Write data to this stream . |
32,929 | def read ( self , length = 0 , timeout_ms = None ) : return self . _transport . read ( length , timeouts . PolledTimeout . from_millis ( timeout_ms ) ) | Reads data from the remote end of this stream . |
32,930 | def read_until_close ( self , timeout_ms = None ) : while True : try : yield self . read ( timeout_ms = timeout_ms ) except usb_exceptions . AdbStreamClosedError : break | Yield data until this stream is closed . |
32,931 | def _set_or_check_remote_id ( self , remote_id ) : if not self . remote_id : assert self . closed_state == self . ClosedState . PENDING , 'Bad ClosedState!' self . remote_id = remote_id self . closed_state = self . ClosedState . OPEN elif self . remote_id != remote_id : raise usb_exceptions . AdbProtocolError ( '%s rem... | Set or check the remote id . |
32,932 | def _handle_message ( self , message , handle_wrte = True ) : if message . command == 'OKAY' : self . _set_or_check_remote_id ( message . arg0 ) if not self . _expecting_okay : raise usb_exceptions . AdbProtocolError ( '%s received unexpected OKAY: %s' , self , message ) self . _expecting_okay = False elif message . co... | Handle a message that was read for this stream . |
32,933 | def _read_messages_until_true ( self , predicate , timeout ) : while not predicate ( ) : self . _message_received . acquire ( ) if self . _reader_lock . acquire ( False ) : try : self . _message_received . release ( ) if predicate ( ) : return self . _handle_message ( self . adb_connection . read_for_stream ( self , ti... | Read a message from this stream and handle it . |
32,934 | def ensure_opened ( self , timeout ) : self . _handle_message ( self . adb_connection . read_for_stream ( self , timeout ) , handle_wrte = False ) return self . is_open ( ) | Ensure this stream transport was successfully opened . |
32,935 | def enqueue_message ( self , message , timeout ) : if message . command == 'WRTE' : self . _send_command ( 'OKAY' , timeout = timeout ) elif message . command == 'OKAY' : self . _set_or_check_remote_id ( message . arg0 ) self . message_queue . put ( message ) | Add the given message to this transport s queue . |
32,936 | def write ( self , data , timeout ) : if not self . remote_id : raise usb_exceptions . AdbStreamClosedError ( 'Cannot write() to half-opened %s' , self ) if self . closed_state != self . ClosedState . OPEN : raise usb_exceptions . AdbStreamClosedError ( 'Cannot write() to closed %s' , self ) elif self . _expecting_okay... | Write data to this stream using the given timeouts . PolledTimeout . |
32,937 | def read ( self , length , timeout ) : self . _read_messages_until_true ( lambda : self . _buffer_size and self . _buffer_size >= length , timeout ) with self . _read_buffer_lock : data , push_back = '' . join ( self . _read_buffer ) , '' if length : data , push_back = data [ : length ] , data [ length : ] self . _read... | Read length bytes from this stream transport . |
32,938 | def _make_stream_transport ( self ) : msg_queue = queue . Queue ( ) with self . _stream_transport_map_lock : self . _last_id_used = ( self . _last_id_used % STREAM_ID_LIMIT ) + 1 for local_id in itertools . islice ( itertools . chain ( range ( self . _last_id_used , STREAM_ID_LIMIT ) , range ( 1 , self . _last_id_used ... | Create an AdbStreamTransport with a newly allocated local_id . |
32,939 | def _handle_message_for_stream ( self , stream_transport , message , timeout ) : if message . command not in ( 'OKAY' , 'CLSE' , 'WRTE' ) : raise usb_exceptions . AdbProtocolError ( '%s received unexpected message: %s' , self , message ) if message . arg1 == stream_transport . local_id : if message . command == 'WRTE' ... | Handle an incoming message check if it s for the given stream . |
32,940 | def open_stream ( self , destination , timeout_ms = None ) : timeout = timeouts . PolledTimeout . from_millis ( timeout_ms ) stream_transport = self . _make_stream_transport ( ) self . transport . write_message ( adb_message . AdbMessage ( command = 'OPEN' , arg0 = stream_transport . local_id , arg1 = 0 , data = destin... | Opens a new stream to a destination service on the device . |
32,941 | def close_stream_transport ( self , stream_transport , timeout ) : with self . _stream_transport_map_lock : if stream_transport . local_id in self . _stream_transport_map : del self . _stream_transport_map [ stream_transport . local_id ] if stream_transport . remote_id : self . transport . write_message ( adb_message .... | Remove the given stream transport s id from our map of id s . |
32,942 | def streaming_command ( self , service , command = '' , timeout_ms = None ) : timeout = timeouts . PolledTimeout . from_millis ( timeout_ms ) stream = self . open_stream ( '%s:%s' % ( service , command ) , timeout ) if not stream : raise usb_exceptions . AdbStreamUnavailableError ( '%s does not support service: %s' , s... | One complete set of packets for a single command . |
32,943 | def read_for_stream ( self , stream_transport , timeout_ms = None ) : timeout = timeouts . PolledTimeout . from_millis ( timeout_ms ) while ( not timeout . has_expired ( ) and stream_transport . local_id in self . _stream_transport_map ) : try : return stream_transport . message_queue . get ( True , .01 ) except queue ... | Attempt to read a packet for the given stream transport . |
32,944 | def connect ( cls , transport , rsa_keys = None , timeout_ms = 1000 , auth_timeout_ms = 100 ) : timeout = timeouts . PolledTimeout . from_millis ( timeout_ms ) if ADB_MESSAGE_LOG : adb_transport = adb_message . DebugAdbTransportAdapter ( transport ) else : adb_transport = adb_message . AdbTransportAdapter ( transport )... | Establish a new connection to a device connected via transport . |
32,945 | def increment ( self ) : self . value += self . increment_size return self . value - self . increment_size | Increment our value return the previous value . |
32,946 | def plug ( update_kwargs = True , ** plugs_map ) : for a_plug in plugs_map . values ( ) : if not ( isinstance ( a_plug , PlugPlaceholder ) or issubclass ( a_plug , BasePlug ) ) : raise InvalidPlugError ( 'Plug %s is not a subclass of plugs.BasePlug nor a placeholder ' 'for one' % a_plug ) def result ( func ) : phase = ... | Creates a decorator that passes in plugs when invoked . |
32,947 | def uses_base_tear_down ( cls ) : this_tear_down = getattr ( cls , 'tearDown' ) base_tear_down = getattr ( BasePlug , 'tearDown' ) return this_tear_down . __code__ is base_tear_down . __code__ | Checks whether the tearDown method is the BasePlug implementation . |
32,948 | def get_plug_mro ( self , plug_type ) : ignored_classes = ( BasePlug , FrontendAwareBasePlug ) return [ self . get_plug_name ( base_class ) for base_class in plug_type . mro ( ) if ( issubclass ( base_class , BasePlug ) and base_class not in ignored_classes ) ] | Returns a list of names identifying the plug classes in the plug s MRO . |
32,949 | def initialize_plugs ( self , plug_types = None ) : types = plug_types if plug_types is not None else self . _plug_types for plug_type in types : plug_logger = self . logger . getChild ( plug_type . __name__ ) if plug_type in self . _plugs_by_type : continue try : if not issubclass ( plug_type , BasePlug ) : raise Inva... | Instantiate required plugs . |
32,950 | def update_plug ( self , plug_type , plug_value ) : self . _plug_types . add ( plug_type ) if plug_type in self . _plugs_by_type : self . _plugs_by_type [ plug_type ] . tearDown ( ) plug_name = self . get_plug_name ( plug_type ) self . _plugs_by_type [ plug_type ] = plug_value self . _plugs_by_name [ plug_name ] = plug... | Update internal data stores with the given plug value for plug type . |
32,951 | def wait_for_plug_update ( self , plug_name , remote_state , timeout_s ) : plug = self . _plugs_by_name . get ( plug_name ) if plug is None : raise InvalidPlugError ( 'Cannot wait on unknown plug "%s".' % plug_name ) if not isinstance ( plug , FrontendAwareBasePlug ) : raise InvalidPlugError ( 'Cannot wait on a plug %s... | Wait for a change in the state of a frontend - aware plug . |
32,952 | def get_frontend_aware_plug_names ( self ) : return [ name for name , plug in six . iteritems ( self . _plugs_by_name ) if isinstance ( plug , FrontendAwareBasePlug ) ] | Returns the names of frontend - aware plugs . |
32,953 | def _wait_for_any_event ( events , timeout_s ) : def any_event_set ( ) : return any ( event . is_set ( ) for event in events ) result = timeouts . loop_until_timeout_or_true ( timeout_s , any_event_set , sleep_s = _WAIT_FOR_ANY_EVENT_POLL_S ) return result or any_event_set ( ) | Wait for any in a list of threading . Event s to be set . |
32,954 | def _poll_for_update ( self ) : test , test_state = _get_executing_test ( ) if test is None : time . sleep ( _WAIT_FOR_EXECUTING_TEST_POLL_S ) return state_dict , event = self . _to_dict_with_event ( test_state ) self . _update_callback ( state_dict ) plug_manager = test_state . plug_manager plug_events = [ plug_manage... | Call the callback with the current test state then wait for a change . |
32,955 | def _to_dict_with_event ( cls , test_state ) : original_dict , event = test_state . asdict_with_event ( ) test_state_dict = data . convert_to_base_types ( original_dict ) test_state_dict [ 'execution_uid' ] = test_state . execution_uid return test_state_dict , event | Process a test state into the format we want to send to the frontend . |
32,956 | def _safe_lock_release_py2 ( rlock ) : assert isinstance ( rlock , threading . _RLock ) ident = _thread . get_ident ( ) expected_count = 0 if rlock . _RLock__owner == ident : expected_count = rlock . _RLock__count try : yield except ThreadTerminationError : if rlock . _RLock__block . acquire ( 0 ) : rlock . _RLock__blo... | Ensure that a threading . RLock is fully released for Python 2 . |
32,957 | def loop ( _ = None , force = False ) : if not force : raise AttributeError ( 'threads.loop() is DEPRECATED. If you really like this and want to ' 'keep it, file an issue at https://github.com/google/openhtf/issues ' 'and use it as @loop(force=True) for now.' ) def real_loop ( fn ) : @ functools . wraps ( fn ) def _pr... | Causes a function to loop indefinitely . |
32,958 | def synchronized ( func ) : @ functools . wraps ( func ) def synchronized_method ( self , * args , ** kwargs ) : if not hasattr ( self , '_lock' ) : if func . __name__ in type ( self ) . __dict__ : hint = '' else : hint = ( ' Might be missing call to super in %s.__init__?' % type ( self ) . __name__ ) raise RuntimeErro... | Hold self . _lock while executing func . |
32,959 | def kill ( self ) : self . _killed . set ( ) if not self . is_alive ( ) : logging . debug ( 'Cannot kill thread that is no longer running.' ) return if not self . _is_thread_proc_running ( ) : logging . debug ( "Thread's _thread_proc function is no longer running, " 'will not kill; letting thread exit gracefully.' ) re... | Terminates the current thread by raising an error . |
32,960 | def async_raise ( self , exc_type ) : assert self . ident is not None , 'Only started threads have thread identifier' if not self . is_alive ( ) : _LOG . debug ( 'Not raising %s because thread %s (%s) is not alive' , exc_type , self . name , self . ident ) return result = ctypes . pythonapi . PyThreadState_SetAsyncExc ... | Raise the exception . |
32,961 | def get_record_logger_for ( test_uid ) : htf_logger = logging . getLogger ( RECORD_LOGGER_PREFIX ) record_logger = HtfTestLogger ( '.' . join ( ( ( RECORD_LOGGER_PREFIX , test_uid ) ) ) ) record_logger . parent = htf_logger return record_logger | Return the child logger associated with the specified test UID . |
32,962 | def initialize_record_handler ( test_uid , test_record , notify_update ) : htf_logger = logging . getLogger ( LOGGER_PREFIX ) htf_logger . addHandler ( RecordHandler ( test_uid , test_record , notify_update ) ) | Initialize the record handler for a test . |
32,963 | def log_once ( log_func , msg , * args , ** kwargs ) : if msg not in _LOG_ONCE_SEEN : log_func ( msg , * args , ** kwargs ) _LOG_ONCE_SEEN . add ( msg ) | Logs a message only once . |
32,964 | def configure_logging ( ) : htf_logger = logging . getLogger ( LOGGER_PREFIX ) htf_logger . propagate = False htf_logger . setLevel ( logging . DEBUG ) if CLI_LOGGING_VERBOSITY == 0 : htf_logger . addHandler ( logging . NullHandler ( ) ) return if CLI_LOGGING_VERBOSITY == 1 : logging_level = logging . INFO else : loggi... | One - time initialization of loggers . See module docstring for more info . |
32,965 | def emit ( self , record ) : try : message = self . format ( record ) log_record = LogRecord ( record . levelno , record . name , os . path . basename ( record . pathname ) , record . lineno , int ( record . created * 1000 ) , message , ) self . _test_record . add_log_record ( log_record ) self . _notify_update ( ) exc... | Save a logging . LogRecord to our test record . |
32,966 | def format ( self , record ) : super ( CliFormatter , self ) . format ( record ) localized_time = datetime . datetime . fromtimestamp ( record . created ) terse_time = localized_time . strftime ( u'%H:%M:%S' ) terse_level = record . levelname [ 0 ] terse_name = record . name . split ( '.' ) [ - 1 ] match = RECORD_LOGGE... | Format the record as tersely as possible but preserve info . |
32,967 | def _send_mfg_inspector_request ( envelope_data , credentials , destination_url ) : logging . info ( 'Uploading result...' ) http = httplib2 . Http ( ) if credentials . access_token_expired : credentials . refresh ( http ) credentials . authorize ( http ) resp , content = http . request ( destination_url , 'POST' , env... | Send upload http request . Intended to be run in retry loop . |
32,968 | def send_mfg_inspector_data ( inspector_proto , credentials , destination_url ) : envelope = guzzle_pb2 . TestRunEnvelope ( ) envelope . payload = zlib . compress ( inspector_proto . SerializeToString ( ) ) envelope . payload_type = guzzle_pb2 . COMPRESSED_MFG_EVENT envelope_data = envelope . SerializeToString ( ) for ... | Upload MfgEvent to steam_engine . |
32,969 | def _convert ( self , test_record_obj ) : if self . _cached_proto is None : self . _cached_proto = self . _converter ( test_record_obj ) return self . _cached_proto | Convert and cache a test record to a mfg - inspector proto . |
32,970 | def save_to_disk ( self , filename_pattern = None ) : if not self . _converter : raise RuntimeError ( 'Must set _converter on subclass or via set_converter before calling ' 'save_to_disk.' ) pattern = filename_pattern or self . _default_filename_pattern if not pattern : raise RuntimeError ( 'Must specify provide a file... | Returns a callback to convert test record to proto and save to disk . |
32,971 | def upload ( self ) : if not self . _converter : raise RuntimeError ( 'Must set _converter on subclass or via set_converter before calling ' 'upload.' ) if not self . credentials : raise RuntimeError ( 'Must provide credentials to use upload callback.' ) def upload_callback ( test_record_obj ) : proto = self . _convert... | Returns a callback to convert a test record to a proto and upload . |
32,972 | def _writer_thread_proc ( self , is_raw ) : reader = self . stdin . read if is_raw else self . stdin . readline while not self . stream . is_closed ( ) : self . stream . write ( reader ( adb_protocol . MAX_ADB_DATA ) ) | Write as long as the stream is not closed . |
32,973 | def _reader_thread_proc ( self , timeout ) : for data in self . stream . read_until_close ( timeout_ms = timeout ) : if self . stdout is not None : self . stdout . write ( data ) | Read until the stream is closed . |
32,974 | def wait ( self , timeout_ms = None ) : closed = timeouts . loop_until_timeout_or_true ( timeouts . PolledTimeout . from_millis ( timeout_ms ) , self . stream . is_closed , .1 ) if closed : if hasattr ( self . stdout , 'getvalue' ) : return self . stdout . getvalue ( ) return True return None | Block until this command has completed . |
32,975 | def command ( self , command , raw = False , timeout_ms = None ) : return '' . join ( self . streaming_command ( command , raw , timeout_ms ) ) | Run the given command and return the output . |
32,976 | def streaming_command ( self , command , raw = False , timeout_ms = None ) : if raw : command = self . _to_raw_command ( command ) return self . adb_connection . streaming_command ( 'shell' , command , timeout_ms ) | Run the given command and yield the output as we receive it . |
32,977 | def async_command ( self , command , stdin = None , stdout = None , raw = False , timeout_ms = None ) : timeout = timeouts . PolledTimeout . from_millis ( timeout_ms ) if raw : command = self . _to_raw_command ( command ) stream = self . adb_connection . open_stream ( 'shell:%s' % command , timeout ) if not stream : ra... | Run the given command on the device asynchronously . |
32,978 | def load_flag_values ( self , flags = None ) : if flags is None : flags = self . _flags for keyval in flags . config_value : k , v = keyval . split ( '=' , 1 ) v = self . _modules [ 'yaml' ] . load ( v ) if isinstance ( v , str ) else v k = k . decode ( ) if isinstance ( k , bytes ) else k v = v . decode ( ) if isinsta... | Load flag values given from command line flags . |
32,979 | def declare ( self , name , description = None , ** kwargs ) : if not self . _is_valid_key ( name ) : raise self . InvalidKeyError ( 'Invalid key name, must begin with a lowercase letter' , name ) if name in self . _declarations : raise self . KeyAlreadyDeclaredError ( 'Configuration key already declared' , name ) self... | Declare a configuration key with the given name . |
32,980 | def reset ( self ) : self . _loaded_values = { } if self . _flags . config_file is not None : self . load_from_file ( self . _flags . config_file , _allow_undeclared = True ) | Reset the loaded state of the configuration to what it was at import . |
32,981 | def load_from_file ( self , yamlfile , _override = True , _allow_undeclared = False ) : self . _logger . info ( 'Loading configuration from file: %s' , yamlfile ) try : parsed_yaml = self . _modules [ 'yaml' ] . safe_load ( yamlfile . read ( ) ) except self . _modules [ 'yaml' ] . YAMLError : self . _logger . exception... | Loads the configuration from a file . |
32,982 | def load_from_dict ( self , dictionary , _override = True , _allow_undeclared = False ) : undeclared_keys = [ ] for key , value in self . _modules [ 'six' ] . iteritems ( dictionary ) : if key not in self . _declarations and not _allow_undeclared : undeclared_keys . append ( key ) continue if key in self . _loaded_valu... | Loads the config with values from a dictionary instead of a file . |
32,983 | def _asdict ( self ) : retval = { key : self . _declarations [ key ] . default_value for key in self . _declarations if self . _declarations [ key ] . has_default } retval . update ( self . _loaded_values ) for key , value in self . _modules [ 'six' ] . iteritems ( self . _flag_values ) : if key in self . _declarations... | Create a dictionary snapshot of the current config values . |
32,984 | def help_text ( self ) : result = [ ] for name in sorted ( self . _declarations . keys ( ) ) : result . append ( name ) result . append ( '-' * len ( name ) ) decl = self . _declarations [ name ] if decl . description : result . append ( decl . description . strip ( ) ) else : result . append ( '(no description found)'... | Return a string with all config keys and their descriptions . |
32,985 | def save_and_restore ( self , _func = None , ** config_values ) : functools = self . _modules [ 'functools' ] if not _func : return functools . partial ( self . save_and_restore , ** config_values ) @ functools . wraps ( _func ) def _saving_wrapper ( * args , ** kwargs ) : saved_config = dict ( self . _loaded_values ) ... | Decorator for saving conf state and restoring it after a function . |
32,986 | def inject_positional_args ( self , method ) : inspect = self . _modules [ 'inspect' ] argspec = inspect . getargspec ( method ) keyword_arg_index = - 1 * len ( argspec . defaults or [ ] ) arg_names = argspec . args [ : keyword_arg_index or None ] kwarg_names = argspec . args [ len ( arg_names ) : ] functools = self . ... | Decorator for injecting positional arguments from the configuration . |
32,987 | def call_once ( func ) : argspec = inspect . getargspec ( func ) if argspec . args or argspec . varargs or argspec . keywords : raise ValueError ( 'Can only decorate functions with no args' , func , argspec ) @ functools . wraps ( func ) def _wrapper ( ) : if not _wrapper . HasRun ( ) : _wrapper . MarkAsRun ( ) _wrappe... | Decorate a function to only allow it to be called once . |
32,988 | def call_at_most_every ( seconds , count = 1 ) : def decorator ( func ) : try : call_history = getattr ( func , '_call_history' ) except AttributeError : call_history = collections . deque ( maxlen = count ) setattr ( func , '_call_history' , call_history ) @ functools . wraps ( func ) def _wrapper ( * args , ** kwargs... | Call the decorated function at most count times every seconds seconds . |
32,989 | def _open_usb_handle ( serial_number = None , ** kwargs ) : init_dependent_flags ( ) remote_usb = conf . remote_usb if remote_usb : if remote_usb . strip ( ) == 'ethersync' : device = conf . ethersync try : mac_addr = device [ 'mac_addr' ] port = device [ 'plug_port' ] except ( KeyError , TypeError ) : raise ValueError... | Open a UsbHandle subclass based on configuration . |
32,990 | def _try_open ( cls ) : handle = None for usb_cls , subcls , protocol in [ ( adb_device . CLASS , adb_device . SUBCLASS , adb_device . PROTOCOL ) , ( fastboot_device . CLASS , fastboot_device . SUBCLASS , fastboot_device . PROTOCOL ) ] : try : handle = local_usb . LibUsbHandle . open ( serial_number = cls . serial_numb... | Try to open a USB handle . |
32,991 | def _retry_usb_function ( count , func , * args , ** kwargs ) : helper = timeouts . RetryHelper ( count ) while True : try : return func ( * args , ** kwargs ) except usb_exceptions . CommonUsbError : if not helper . retry_if_possible ( ) : raise time . sleep ( 0.1 ) else : break | Helper function to retry USB . |
32,992 | def get_boot_config ( self , name , info_cb = None ) : result = { } def default_info_cb ( msg ) : if not msg . message : return key , value = msg . message . split ( ':' , 1 ) result [ key . strip ( ) ] = value . strip ( ) info_cb = info_cb or default_info_cb final_result = self . oem ( 'bootconfig %s' % name , info_cb... | Get bootconfig either as full dict or specific value for key . |
32,993 | def _device_to_sysfs_path ( device ) : return '%s-%s' % ( device . getBusNumber ( ) , '.' . join ( [ str ( item ) for item in device . GetPortNumberList ( ) ] ) ) | Convert device to corresponding sysfs path . |
32,994 | def open ( cls , ** kwargs ) : handle_iter = cls . iter_open ( ** kwargs ) try : handle = six . next ( handle_iter ) except StopIteration : raise usb_exceptions . DeviceNotFoundError ( 'Open failed with args: %s' , kwargs ) try : multiple_handle = six . next ( handle_iter ) except StopIteration : return handle handle .... | See iter_open but raises if multiple or no matches found . |
32,995 | def iter_open ( cls , name = None , interface_class = None , interface_subclass = None , interface_protocol = None , serial_number = None , port_path = None , default_timeout_ms = None ) : ctx = usb1 . USBContext ( ) try : devices = ctx . getDeviceList ( skip_on_error = True ) except libusb1 . USBError as exception : r... | Find and yield locally connected devices that match . |
32,996 | def hello_world ( test , example , prompts ) : test . logger . info ( 'Hello World!' ) test . measurements . widget_type = prompts . prompt ( 'What\'s the widget type? (Hint: try `MyWidget` to PASS)' , text_input = True ) if test . measurements . widget_type == 'raise' : raise Exception ( ) test . measurements . widget... | A hello world test phase . |
32,997 | def set_measurements ( test ) : test . measurements . level_none = 0 time . sleep ( 1 ) test . measurements . level_some = 8 time . sleep ( 1 ) test . measurements . level_all = 9 time . sleep ( 1 ) level_all = test . get_measurement ( 'level_all' ) assert level_all . value == 9 | Test phase that sets a measurement . |
32,998 | def pprint_diff ( first , second , first_name = 'first' , second_name = 'second' ) : return difflib . unified_diff ( pprint . pformat ( first ) . splitlines ( ) , pprint . pformat ( second ) . splitlines ( ) , fromfile = first_name , tofile = second_name , lineterm = '' ) | Compare the pprint representation of two objects and yield diff lines . |
32,999 | def equals_log_diff ( expected , actual , level = logging . ERROR ) : if expected == actual : return True logging . log ( level , '***** Data mismatch: *****' ) for line in difflib . unified_diff ( expected . splitlines ( ) , actual . splitlines ( ) , fromfile = 'expected' , tofile = 'actual' , lineterm = '' ) : loggin... | Compare two string blobs error log diff if they don t match . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.