idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
39,400
def on ( self ) : on_command = StandardSend ( self . _address , COMMAND_LIGHT_ON_0X11_NONE , 0xff ) self . _send_method ( on_command , self . _on_message_received )
Send ON command to device .
39,401
def off ( self ) : self . _send_method ( StandardSend ( self . _address , COMMAND_LIGHT_OFF_0X13_0X00 ) , self . _off_message_received )
Send OFF command to device .
39,402
def _send_status_0x01_request ( self ) : status_command = StandardSend ( self . _address , COMMAND_LIGHT_STATUS_REQUEST_0X19_0X01 ) self . _send_method ( status_command , self . _status_message_0x01_received )
Sent status request to device .
39,403
def _status_message_0x01_received ( self , msg ) : if msg . cmd2 == 0x00 or msg . cmd2 == 0x02 : self . _update_subscribers ( 0x00 ) elif msg . cmd2 == 0x01 or msg . cmd2 == 0x03 : self . _update_subscribers ( 0xff ) else : raise ValueError
Handle status received messages .
39,404
def on ( self ) : on_command = ExtendedSend ( self . _address , COMMAND_LIGHT_ON_0X11_NONE , self . _udata , cmd2 = 0xff ) on_command . set_checksum ( ) self . _send_method ( on_command , self . _on_message_received )
Send an ON message to device group .
39,405
def off ( self ) : off_command = ExtendedSend ( self . _address , COMMAND_LIGHT_OFF_0X13_0X00 , self . _udata ) off_command . set_checksum ( ) self . _send_method ( off_command , self . _off_message_received )
Send an OFF message to device group .
39,406
def _send_status_0x01_request ( self ) : status_command = StandardSend ( self . _address , COMMAND_LIGHT_STATUS_REQUEST_0X19_0X01 ) self . _send_method ( status_command , self . _status_message_received )
Send a status request .
39,407
def _status_message_received ( self , msg ) : if msg . cmd2 == 0x00 or msg . cmd2 == 0x01 : self . _update_subscribers ( 0x00 ) elif msg . cmd2 == 0x02 or msg . cmd2 == 0x03 : self . _update_subscribers ( 0xff ) else : raise ValueError
Receive a status message .
39,408
def close ( self ) : close_command = StandardSend ( self . _address , COMMAND_LIGHT_OFF_0X13_0X00 ) self . _send_method ( close_command , self . _close_message_received )
Send CLOSE command to device .
39,409
def led_changed ( self , addr , group , val ) : _LOGGER . debug ( "Button %d LED changed from %d to %d" , self . _group , self . _value , val ) led_on = bool ( val ) if led_on != bool ( self . _value ) : self . _update_subscribers ( int ( led_on ) )
Capture a change to the LED for this button .
39,410
def _status_message_received ( self , msg ) : if not self . _status_received : asyncio . ensure_future ( self . _confirm_status_received ( ) , loop = self . _loop )
Receive confirmation that the status message is coming .
39,411
def _status_extended_message_received ( self , msg ) : self . _status_received = True self . _status_retries = 0 _LOGGER . debug ( "Extended status message received" ) if self . _status_response_lock . locked ( ) : self . _status_response_lock . release ( ) user_data = msg . userdata self . _set_status_data ( user_data...
Receeive an extended status message .
39,412
def _property_set ( self , msg ) : prop = self . _sent_property . get ( 'prop' ) if prop and hasattr ( self , prop ) : setattr ( self , prop , self . _sent_property . get ( 'val' ) ) self . _sent_property = { }
Set command received and acknowledged .
39,413
def _set_status_data ( self , userdata ) : self . _on_mask = userdata [ 'd3' ] self . _off_mask = userdata [ 'd4' ] self . _x10_house_code = userdata [ 'd5' ] self . _x10_unit = userdata [ 'd6' ] self . _ramp_rate = userdata [ 'd7' ] self . _on_level = userdata [ 'd8' ] self . _led_brightness = userdata [ 'd9' ] self ....
Set status properties from userdata response .
39,414
def _create_set_property_msg ( self , prop , cmd , val ) : user_data = Userdata ( { 'd1' : self . group , 'd2' : cmd , 'd3' : val } ) msg = ExtendedSend ( self . _address , COMMAND_EXTENDED_GET_SET_0X2E_0X00 , user_data ) msg . set_checksum ( ) self . _set_sent_property ( prop , val ) return msg
Create an extended message to set a property .
39,415
def on ( self , group ) : asyncio . ensure_future ( self . _send_led_on_off_request ( group , 1 ) , loop = self . _loop )
Turn the LED on for a group .
39,416
def off ( self , group ) : asyncio . ensure_future ( self . _send_led_on_off_request ( group , 0 ) , loop = self . _loop )
Turn the LED off for a group .
39,417
def register_led_updates ( self , callback , button ) : button_callbacks = self . _button_observer_callbacks . get ( button ) if not button_callbacks : self . _button_observer_callbacks [ button ] = [ ] _LOGGER . debug ( 'New callback for button %d' , button ) self . _button_observer_callbacks [ button ] . append ( cal...
Register a callback when a specific button LED changes .
39,418
def _set_led_value ( self , group , val ) : new_bitmask = set_bit ( self . _value , group , bool ( val ) ) self . _set_led_bitmask ( new_bitmask )
Set the LED value and confirm with a status check .
39,419
def set ( self , val ) : msg = ExtendedSend ( address = self . _address , commandtuple = COMMAND_THERMOSTAT_SET_COOL_SETPOINT_0X6C_NONE , cmd2 = int ( val * 2 ) , userdata = Userdata ( ) ) msg . set_checksum ( ) self . _send_method ( msg , self . _set_cool_point_ack )
Set the cool set point .
39,420
def set ( self , val ) : msg = ExtendedSend ( address = self . _address , commandtuple = COMMAND_THERMOSTAT_SET_HEAT_SETPOINT_0X6D_NONE , cmd2 = int ( val * 2 ) , userdata = Userdata ( ) ) msg . set_checksum ( ) self . _send_method ( msg , self . _set_heat_point_ack )
Set the heat set point .
39,421
def add_device_callback ( self , callback ) : _LOGGER . debug ( 'Added new callback %s ' , callback ) self . _cb_new_device . append ( callback )
Register a callback to be invoked when a new device appears .
39,422
def add_override ( self , addr , key , value ) : address = Address ( str ( addr ) ) . id _LOGGER . debug ( 'New override for %s %s is %s' , address , key , value ) device_override = self . _overrides . get ( address , { } ) device_override [ key ] = value self . _overrides [ address ] = device_override
Register an attribute override for a device .
39,423
def create_device_from_category ( self , plm , addr , cat , subcat , product_key = 0x00 ) : saved_device = self . _saved_devices . get ( Address ( addr ) . id , { } ) cat = saved_device . get ( 'cat' , cat ) subcat = saved_device . get ( 'subcat' , subcat ) product_key = saved_device . get ( 'product_key' , product_key...
Create a new device from the cat subcat and product_key data .
39,424
def has_saved ( self , addr ) : saved = False if self . _saved_devices . get ( addr , None ) is not None : saved = True return saved
Test if device has data from the saved data file .
39,425
def has_override ( self , addr ) : override = False if self . _overrides . get ( addr , None ) is not None : override = True return override
Test if device has data from a device override setting .
39,426
def add_known_devices ( self , plm ) : from insteonplm . devices import ALDBStatus for addr in self . _saved_devices : if not self . _devices . get ( addr ) : saved_device = self . _saved_devices . get ( Address ( addr ) . id , { } ) cat = saved_device . get ( 'cat' ) subcat = saved_device . get ( 'subcat' ) product_ke...
Add devices from the saved devices or from the device overrides .
39,427
def save_device_info ( self ) : if self . _workdir is not None : devices = [ ] for addr in self . _devices : device = self . _devices . get ( addr ) if not device . address . is_x10 : aldb = { } for mem in device . aldb : rec = device . aldb [ mem ] if rec : aldbRec = { 'memory' : mem , 'control_flags' : rec . control_...
Save all device information to the device info file .
39,428
def _add_saved_device_info ( self , ** kwarg ) : addr = kwarg . get ( 'address' ) _LOGGER . debug ( 'Found saved device with address %s' , addr ) self . _saved_devices [ addr ] = kwarg
Register device info from the saved data file .
39,429
async def load_saved_device_info ( self ) : _LOGGER . debug ( "Loading saved device info." ) deviceinfo = [ ] if self . _workdir : _LOGGER . debug ( "Really Loading saved device info." ) try : device_file = '{}/{}' . format ( self . _workdir , DEVICE_INFO_FILE ) with open ( device_file , 'r' ) as infile : try : devicei...
Load device information from the device info file .
39,430
def unit_code_msg ( housecode , unitcode ) : house_byte = 0 unit_byte = 0 if isinstance ( housecode , str ) : house_byte = insteonplm . utils . housecode_to_byte ( housecode ) << 4 unit_byte = insteonplm . utils . unitcode_to_byte ( unitcode ) elif isinstance ( housecode , int ) and housecode < 16 : house_byte = housec...
Create an X10 message to send the house code and unit code .
39,431
def command_msg ( housecode , command ) : house_byte = 0 if isinstance ( housecode , str ) : house_byte = insteonplm . utils . housecode_to_byte ( housecode ) << 4 elif isinstance ( housecode , int ) and housecode < 16 : house_byte = housecode << 4 else : house_byte = housecode return X10Received ( house_byte + command...
Create an X10 message to send the house code and a command code .
39,432
async def create_http_connection ( loop , protocol_factory , host , port = 25105 , auth = None ) : protocol = protocol_factory ( ) transport = HttpTransport ( loop , protocol , host , port , auth ) _LOGGER . debug ( "create_http_connection Finished creating connection" ) return ( transport , protocol )
Create an HTTP session used to connect to the Insteon Hub .
39,433
async def create ( cls , device = '/dev/ttyUSB0' , host = None , username = None , password = None , port = 25010 , hub_version = 2 , auto_reconnect = True , loop = None , workdir = None , poll_devices = True , load_aldb = True ) : _LOGGER . debug ( "Starting Modified Connection.create" ) conn = cls ( device = device ,...
Create a connection to a specific device .
39,434
async def reconnect ( self ) : _LOGGER . debug ( 'starting Connection.reconnect' ) await self . _connect ( ) while self . _closed : await self . _retry_connection ( ) _LOGGER . debug ( 'ending Connection.reconnect' )
Reconnect to the modem .
39,435
async def close ( self , event ) : _LOGGER . info ( 'Closing connection to Insteon Modem' ) self . _closing = True self . _auto_reconnect = False await self . protocol . close ( ) if self . protocol . transport : self . protocol . transport . close ( ) await asyncio . sleep ( 0 , loop = self . _loop ) _LOGGER . info ( ...
Close the PLM device connection and don t try to reconnect .
39,436
def dump_conndata ( self ) : attrs = vars ( self ) return ', ' . join ( "%s: %s" % item for item in attrs . items ( ) )
Developer tool for debugging forensics .
39,437
def on ( self ) : msg = X10Send . unit_code_msg ( self . address . x10_housecode , self . address . x10_unitcode ) self . _send_method ( msg ) msg = X10Send . command_msg ( self . address . x10_housecode , X10_COMMAND_ON ) self . _send_method ( msg , False ) self . _update_subscribers ( 0xff )
Send the On command to an X10 device .
39,438
def off ( self ) : msg = X10Send . unit_code_msg ( self . address . x10_housecode , self . address . x10_unitcode ) self . _send_method ( msg ) msg = X10Send . command_msg ( self . address . x10_housecode , X10_COMMAND_OFF ) self . _send_method ( msg , False ) self . _update_subscribers ( 0x00 )
Send the Off command to an X10 device .
39,439
def set_level ( self , val ) : if val == 0 : self . off ( ) elif val == 255 : self . on ( ) else : setlevel = 255 if val < 1 : setlevel = val * 255 elif val <= 0xff : setlevel = val change = setlevel - self . _value increment = 255 / self . _steps steps = round ( abs ( change ) / increment ) print ( 'Steps: ' , steps )...
Set the device ON LEVEL .
39,440
def matches_pattern ( self , other ) : matches = False if hasattr ( other , 'addr' ) : if self . addr is None or other . addr is None : matches = True else : matches = self . addr == other . addr return matches
Test Address object matches the pattern of another object .
39,441
def _normalize ( self , addr ) : normalize = None if isinstance ( addr , Address ) : normalize = addr . addr self . _is_x10 = addr . is_x10 elif isinstance ( addr , bytearray ) : normalize = binascii . unhexlify ( binascii . hexlify ( addr ) . decode ( ) ) elif isinstance ( addr , bytes ) : normalize = addr elif isinst...
Take any format of address and turn it into a hex string .
39,442
def id ( self ) : dev_id = '' if self . _is_x10 : dev_id = 'x10{}{:02d}' . format ( self . x10_housecode , self . x10_unitcode ) else : dev_id = self . hex return dev_id
Return the ID of the device address .
39,443
def x10_housecode ( self ) : housecode = None if self . is_x10 : housecode = insteonplm . utils . byte_to_housecode ( self . addr [ 1 ] ) return housecode
Emit the X10 house code .
39,444
def x10_unitcode ( self ) : unitcode = None if self . is_x10 : unitcode = insteonplm . utils . byte_to_unitcode ( self . addr [ 2 ] ) return unitcode
Emit the X10 unit code .
39,445
def x10 ( cls , housecode , unitcode ) : if housecode . lower ( ) in [ 'a' , 'b' , 'c' , 'd' , 'e' , 'f' , 'g' , 'h' , 'i' , 'j' , 'k' , 'l' , 'm' , 'n' , 'o' , 'p' ] : byte_housecode = insteonplm . utils . housecode_to_byte ( housecode ) else : if isinstance ( housecode , str ) : _LOGGER . error ( 'X10 house code erro...
Create an X10 device address .
39,446
def _term_to_xapian_value ( term , field_type ) : assert field_type in FIELD_TYPES def strf ( dt ) : return '%04d%02d%02d%02d%02d%02d' % ( dt . year , dt . month , dt . day , dt . hour , dt . minute , dt . second ) if field_type == 'boolean' : assert isinstance ( term , bool ) if term : value = 't' else : value = 'f' e...
Converts a term to a serialized Xapian value based on the field_type .
39,447
def _from_xapian_value ( value , field_type ) : assert field_type in FIELD_TYPES if field_type == 'boolean' : if value == 't' : return True elif value == 'f' : return False else : InvalidIndexError ( 'Field type "%d" does not accept value "%s"' % ( field_type , value ) ) elif field_type == 'integer' : return int ( valu...
Converts a serialized Xapian value to Python equivalent based on the field_type .
39,448
def remove ( self , obj , commit = True ) : database = self . _database ( writable = True ) database . delete_document ( TERM_PREFIXES [ ID ] + get_identifier ( obj ) ) database . close ( )
Remove indexes for obj from the database .
39,449
def clear ( self , models = ( ) , commit = True ) : if not models : if os . path . exists ( self . path ) : shutil . rmtree ( self . path ) else : database = self . _database ( writable = True ) for model in models : database . delete_document ( TERM_PREFIXES [ DJANGO_CT ] + get_model_ct ( model ) ) database . close ( ...
Clear all instances of models from the database or all models if not specified .
39,450
def _build_models_query ( self , query ) : registered_models_ct = self . build_models_list ( ) if registered_models_ct : restrictions = [ xapian . Query ( '%s%s' % ( TERM_PREFIXES [ DJANGO_CT ] , model_ct ) ) for model_ct in registered_models_ct ] limit_query = xapian . Query ( xapian . Query . OP_OR , restrictions ) q...
Builds a query from query that filters to documents only from registered models .
39,451
def _check_field_names ( self , field_names ) : if field_names : for field_name in field_names : try : self . column [ field_name ] except KeyError : raise InvalidIndexError ( 'Trying to use non indexed field "%s"' % field_name )
Raises InvalidIndexError if any of a field_name in field_names is not indexed .
39,452
def more_like_this ( self , model_instance , additional_query = None , start_offset = 0 , end_offset = None , limit_to_registered_models = True , result_class = None , ** kwargs ) : database = self . _database ( ) if result_class is None : result_class = SearchResult query = xapian . Query ( TERM_PREFIXES [ ID ] + get_...
Given a model instance returns a result set of similar documents .
39,453
def parse_query ( self , query_string ) : if query_string == '*' : return xapian . Query ( '' ) elif query_string == '' : return xapian . Query ( ) qp = xapian . QueryParser ( ) qp . set_database ( self . _database ( ) ) qp . set_stemmer ( xapian . Stem ( self . language ) ) qp . set_stemming_strategy ( self . stemming...
Given a query_string will attempt to return a xapian . Query
39,454
def build_schema ( self , fields ) : content_field_name = '' schema_fields = [ { 'field_name' : ID , 'type' : 'text' , 'multi_valued' : 'false' , 'column' : 0 } , { 'field_name' : DJANGO_ID , 'type' : 'integer' , 'multi_valued' : 'false' , 'column' : 1 } , { 'field_name' : DJANGO_CT , 'type' : 'text' , 'multi_valued' :...
Build the schema from fields .
39,455
def _do_highlight ( content , query , tag = 'em' ) : for term in query : term = term . decode ( 'utf-8' ) for match in re . findall ( '[^A-Z]+' , term ) : match_re = re . compile ( match , re . I ) content = match_re . sub ( '<%s>%s</%s>' % ( tag , term , tag ) , content ) return content
Highlight query terms in content with html tag .
39,456
def _prepare_facet_field_spies ( self , facets ) : spies = [ ] for facet in facets : slot = self . column [ facet ] spy = xapian . ValueCountMatchSpy ( slot ) spy . slot = slot spies . append ( spy ) return spies
Returns a list of spies based on the facets used to count frequencies .
39,457
def _do_multivalued_field_facets ( self , results , field_facets ) : facet_dict = { } for field in field_facets : facet_list = { } if not self . _multi_value_field ( field ) : continue for result in results : field_value = getattr ( result , field ) for item in field_value : facet_list [ item ] = facet_list . get ( ite...
Implements a multivalued field facet on the results .
39,458
def _do_date_facets ( results , date_facets ) : def next_datetime ( previous , gap_value , gap_type ) : year = previous . year month = previous . month if gap_type == 'year' : next = previous . replace ( year = year + gap_value ) elif gap_type == 'month' : if month + gap_value <= 12 : next = previous . replace ( month ...
Private method that facets a document by date ranges
39,459
def _do_query_facets ( self , results , query_facets ) : facet_dict = { } for field , query in list ( dict ( query_facets ) . items ( ) ) : facet_dict [ field ] = ( query , self . search ( self . parse_query ( query ) ) [ 'hits' ] ) return facet_dict
Private method that facets a document by query
39,460
def _do_spelling_suggestion ( database , query , spelling_query ) : if spelling_query : if ' ' in spelling_query : return ' ' . join ( [ database . get_spelling_suggestion ( term ) . decode ( 'utf-8' ) for term in spelling_query . split ( ) ] ) else : return database . get_spelling_suggestion ( spelling_query ) . decod...
Private method that returns a single spelling suggestion based on spelling_query or query .
39,461
def _database ( self , writable = False ) : if self . path == MEMORY_DB_NAME : if not self . inmemory_db : self . inmemory_db = xapian . inmemory_open ( ) return self . inmemory_db if writable : database = xapian . WritableDatabase ( self . path , xapian . DB_CREATE_OR_OPEN ) else : try : database = xapian . Database (...
Private method that returns a xapian . Database for use .
39,462
def _get_document_data ( database , document ) : try : return document . get_data ( ) except xapian . DatabaseModifiedError : database . reopen ( ) return document . get_data ( )
A safer version of Xapian . document . get_data
39,463
def _get_hit_count ( self , database , enquire ) : return self . _get_enquire_mset ( database , enquire , 0 , database . get_doccount ( ) ) . size ( )
Given a database and enquire instance returns the estimated number of matches .
39,464
def _multi_value_field ( self , field ) : for field_dict in self . schema : if field_dict [ 'field_name' ] == field : return field_dict [ 'multi_valued' ] == 'true' return False
Private method that returns True if a field is multi - valued else False .
39,465
def _query_from_term ( self , term , field_name , filter_type , is_not ) : if field_name != 'content' and field_name not in self . backend . column : raise InvalidIndexError ( 'field "%s" not indexed' % field_name ) if isinstance ( term , AutoQuery ) : if field_name != 'content' : query = '%s:%s' % ( field_name , term ...
Uses arguments to construct a list of xapian . Query s .
39,466
def _filter_contains ( self , term , field_name , field_type , is_not ) : if field_type == 'text' : term_list = term . split ( ) else : term_list = [ term ] query = self . _or_query ( term_list , field_name , field_type ) if is_not : return xapian . Query ( xapian . Query . OP_AND_NOT , self . _all_query ( ) , query ) ...
Splits the sentence in terms and join them with OR using stemmed and un - stemmed .
39,467
def _filter_in ( self , term_list , field_name , field_type , is_not ) : query_list = [ self . _filter_exact ( term , field_name , field_type , is_not = False ) for term in term_list ] if is_not : return xapian . Query ( xapian . Query . OP_AND_NOT , self . _all_query ( ) , xapian . Query ( xapian . Query . OP_OR , que...
Returns a query that matches exactly ANY term in term_list .
39,468
def _filter_exact ( self , term , field_name , field_type , is_not ) : if field_type == 'text' and field_name not in ( DJANGO_CT , ) : term = '^ %s $' % term query = self . _phrase_query ( term . split ( ) , field_name , field_type ) else : query = self . _term_query ( term , field_name , field_type , stemmed = False )...
Returns a query that matches exactly the un - stemmed term with positional order .
39,469
def _filter_startswith ( self , term , field_name , field_type , is_not ) : if field_type == 'text' : if len ( term . split ( ) ) == 1 : term = '^ %s*' % term query = self . backend . parse_query ( term ) else : term = '^ %s' % term query = self . _phrase_query ( term . split ( ) , field_name , field_type ) else : term...
Returns a startswith query on the un - stemmed term .
39,470
def _or_query ( self , term_list , field , field_type ) : term_list = [ self . _term_query ( term , field , field_type ) for term in term_list ] return xapian . Query ( xapian . Query . OP_OR , term_list )
Joins each item of term_list decorated by _term_query with an OR .
39,471
def _term_query ( self , term , field_name , field_type , stemmed = True ) : constructor = '{prefix}{term}' prefix = '' if field_name : prefix = TERM_PREFIXES [ 'field' ] + field_name . upper ( ) term = _to_xapian_term ( term ) if field_name in ( ID , DJANGO_ID , DJANGO_CT ) : if field_name == DJANGO_ID : term = int ( ...
Constructs a query of a single term .
39,472
def _filter_gte ( self , term , field_name , field_type , is_not ) : vrp = XHValueRangeProcessor ( self . backend ) pos , begin , end = vrp ( '%s:%s' % ( field_name , _term_to_xapian_value ( term , field_type ) ) , '*' ) if is_not : return xapian . Query ( xapian . Query . OP_AND_NOT , self . _all_query ( ) , xapian . ...
Private method that returns a xapian . Query that searches for any term that is greater than term in a specified field .
39,473
def get ( company = '' , company_uri = '' ) : if not company and not company_uri : raise Exception ( "glassdoor.gd.get(company='', company_uri=''): " " company or company_uri required" ) payload = { } if not company_uri : payload . update ( { 'clickSource' : 'searchBtn' , 'sc.keyword' : company } ) uri = '%s/%s' % ( GL...
Performs a HTTP GET for a glassdoor page and returns json
39,474
def parse ( soup ) : if is_direct_match ( soup ) : return { 'satisfaction' : parse_satisfaction ( soup ) , 'ceo' : parse_ceo ( soup ) , 'meta' : parse_meta ( soup ) , 'salary' : parse_salary ( soup ) } suggestions = parse_suggestions ( soup ) exact_match = next ( ( s for s in suggestions if s [ 'exact' ] ) , None ) if ...
Parses the results for a company search and return the results if is_direct_match . If no company is found a list of suggestions are returned as dict . If one such recommendation is found to be an exact match re - perform request for this exact match
39,475
def get_jwt_data ( token , token_type ) : jwt_data = decode_jwt ( encoded_token = token , secret = current_app . config [ 'JWT_SECRET_KEY' ] , algorithm = 'HS256' , identity_claim_key = current_app . config [ 'JWT_IDENTITY_CLAIM' ] , user_claims_key = current_app . config [ 'JWT_USER_CLAIMS' ] ) if jwt_data [ 'type' ] ...
Decodes encoded JWT token by using extension setting and validates token type
39,476
def query_jwt_required ( fn ) : @ wraps ( fn ) def wrapper ( * args , ** kwargs ) : print ( args [ 0 ] ) token = kwargs . pop ( current_app . config [ 'JWT_TOKEN_ARGUMENT_NAME' ] ) try : verify_jwt_in_argument ( token ) except Exception as e : return AuthInfoField ( message = str ( e ) ) return fn ( * args , ** kwargs ...
A decorator to protect a query resolver .
39,477
def open ( self ) : if self . _is_open : raise HIDException ( "Failed to open device: HIDDevice already open" ) path = self . path . encode ( 'utf-8' ) dev = hidapi . hid_open_path ( path ) if dev : self . _is_open = True self . _device = dev else : raise HIDException ( "Failed to open device" )
Open the HID device for reading and writing .
39,478
def close ( self ) : if self . _is_open : self . _is_open = False hidapi . hid_close ( self . _device )
Closes the hid device
39,479
def write ( self , data , report_id = 0 ) : if not self . _is_open : raise HIDException ( "HIDDevice not open" ) write_data = bytearray ( [ report_id ] ) + bytearray ( data ) cdata = ffi . new ( "const unsigned char[]" , bytes ( write_data ) ) num_written = hidapi . hid_write ( self . _device , cdata , len ( write_data...
Writes data to the HID device on its endpoint .
39,480
def read ( self , size = 64 , timeout = None ) : if not self . _is_open : raise HIDException ( "HIDDevice not open" ) data = [ 0 ] * size cdata = ffi . new ( "unsigned char[]" , data ) bytes_read = 0 if timeout == None : bytes_read = hidapi . hid_read ( self . _device , cdata , len ( cdata ) ) else : bytes_read = hidap...
Read from the hid device on its endpoint .
39,481
def is_connected ( self ) : if self . _is_open : err = hidapi . hid_read_timeout ( self . _device , ffi . NULL , 0 , 0 ) if err == - 1 : return False else : return True else : en = Enumeration ( vid = self . vendor_id , pid = self . product_id ) . find ( path = self . path ) if len ( en ) == 0 : return False else : ret...
Checks if the USB device is still connected
39,482
def send_feature_report ( self , data , report_id = 0x00 ) : if not self . _is_open : raise HIDException ( "HIDDevice not open" ) report = bytearray ( [ report_id ] ) + bytearray ( data ) cdata = ffi . new ( "const unsigned char[]" , bytes ( report ) ) bytes_written = hidapi . hid_send_feature_report ( self . _device ,...
Send a Feature report to a HID device .
39,483
def get_feature_report ( self , size , report_id = 0x00 ) : data = [ 0 ] * ( size + 1 ) cdata = ffi . new ( "unsigned char[]" , bytes ( data ) ) cdata [ 0 ] = report_id bytes_read = hidapi . hid_get_feature_report ( self . _device , cdata , len ( cdata ) ) if bytes_read == - 1 : raise HIDException ( "Failed to get feat...
Get a feature report from a HID device .
39,484
def get_error ( self ) : err_str = hidapi . hid_error ( self . _device ) if err_str == ffi . NULL : return None else : return ffi . string ( err_str )
Get an error string from the device
39,485
def get_indexed_string ( self , index ) : max_len = 128 str_buf = ffi . new ( "wchar_t[]" , str ( bytearray ( max_len ) ) ) ret = hidapi . hid_get_indexed_string ( self . _device , index , str_buf , max_len ) if ret < 0 : raise HIDException ( self . _device . get_error ( ) ) elif ret == 0 : return None else : return ff...
Get the string with the given index from the device
39,486
def find ( self , vid = None , pid = None , serial = None , interface = None , path = None , release_number = None , manufacturer = None , product = None , usage = None , usage_page = None ) : result = [ ] for dev in self . device_list : if vid not in [ 0 , None ] and dev . vendor_id != vid : continue if pid not in [ 0...
Attempts to open a device in this Enumeration object . Optional arguments can be provided to filter the resulting list based on various parameters of the HID devices .
39,487
def str2fl ( x ) : def helper_to_fl ( s_ ) : if s_ == "" : return "null" elif "," in s_ : s_ = s_ . replace ( "," , "" ) try : return float ( s_ ) except : return ( s_ ) fl_lst = [ ] if isinstance ( x [ 0 ] , str ) : for xi in range ( len ( x ) ) : fl_lst . append ( helper_to_fl ( x [ xi ] ) ) elif isinstance ( x [ 0 ]...
Recurses through lists and converts lists of string to float
39,488
def procMat ( materials , max_thickness , min_thickness ) : newmat = [ ] newthickness = [ ] k = materials . layerThermalCond Vhc = materials . layerVolHeat if len ( materials . layerThickness ) > 1 : for j in range ( len ( materials . layerThickness ) ) : if materials . layerThickness [ j ] > max_thickness : nlayers = ...
Processes material layer so that a material with single layer thickness is divided into two and material layer that is too thick is subdivided
39,489
def set_input ( self ) : if self . uwgParamFileName is not None : print ( "\nReading uwg file input." ) self . read_input ( ) else : print ( "\nNo .uwg file input." ) self . check_required_inputs ( ) self . zone = int ( self . zone ) - 1
Set inputs from . uwg input file if not already defined the check if all the required input parameters are there .
39,490
def write_epw ( self ) : epw_prec = self . epw_precision for iJ in range ( len ( self . UCMData ) ) : self . epwinput [ iJ + self . simTime . timeInitial - 8 ] [ 6 ] = "{0:.{1}f}" . format ( self . UCMData [ iJ ] . canTemp - 273.15 , epw_prec ) self . epwinput [ iJ + self . simTime . timeInitial - 8 ] [ 7 ] = "{0:.{1}f...
Section 8 - Writing new EPW file
39,491
def SurfFlux ( self , forc , parameter , simTime , humRef , tempRef , windRef , boundCond , intFlux ) : dens = forc . pres / ( 1000 * 0.287042 * tempRef * ( 1. + 1.607858 * humRef ) ) self . aeroCond = 5.8 + 3.7 * windRef if ( self . horizontal ) : if not self . is_near_zero ( self . waterStorage ) and self . waterStor...
Calculate net heat flux and update element layer temperatures
39,492
def readPlist ( pathOrFile ) : didOpen = False result = None if isinstance ( pathOrFile , ( bytes , unicode ) ) : pathOrFile = open ( pathOrFile , 'rb' ) didOpen = True try : reader = PlistReader ( pathOrFile ) result = reader . parse ( ) except NotBinaryPlistException as e : try : pathOrFile . seek ( 0 ) result = None...
Raises NotBinaryPlistException InvalidPlistException
39,493
def getSizedInteger ( self , data , byteSize , as_number = False ) : result = 0 if byteSize == 0 : raise InvalidPlistException ( "Encountered integer with byte size of 0." ) elif byteSize == 1 : result = unpack ( '>B' , data ) [ 0 ] elif byteSize == 2 : result = unpack ( '>H' , data ) [ 0 ] elif byteSize == 4 : result ...
Numbers of 8 bytes are signed integers when they refer to numbers but unsigned otherwise .
39,494
def writeOffsetTable ( self , output ) : all_positions = [ ] writtenReferences = list ( self . writtenReferences . items ( ) ) writtenReferences . sort ( key = lambda x : x [ 1 ] ) for obj , order in writtenReferences : if bytes != str and obj == unicodeEmpty : obj = b'' position = self . referencePositions . get ( obj...
Writes all of the object reference offsets .
39,495
def intSize ( self , obj ) : if obj < 0 : return 8 elif obj <= 0xFF : return 1 elif obj <= 0xFFFF : return 2 elif obj <= 0xFFFFFFFF : return 4 elif obj <= 0x7FFFFFFFFFFFFFFF : return 8 elif obj <= 0xffffffffffffffff : return 16 else : raise InvalidPlistException ( "Core Foundation can't handle integers with size greate...
Returns the number of bytes necessary to store the given integer .
39,496
def load_z_meso ( self , z_meso_path ) : self . z_meso = [ ] z_meso_file_path = os . path . join ( z_meso_path , self . Z_MESO_FILE_NAME ) if not os . path . exists ( z_meso_file_path ) : raise Exception ( "z_meso.txt file: '{}' does not exist." . format ( uwg_param_file ) ) f = open ( z_meso_file_path , 'r' ) for txtl...
Open the z_meso . txt file and return heights as list
39,497
def get_task ( task_id , completed = True ) : tasks = get_tasks ( task_id = task_id , completed = completed ) if len ( tasks ) == 0 : return None assert len ( tasks ) == 1 , 'get_task should return at max 1 task for a task id' return tasks [ 0 ]
Get a task by task id where a task_id is required .
39,498
def task_completed ( task_id ) : tasks = get_tasks ( task_id = task_id ) completed_states = ( 'TASK_FINISHED' , 'TASK_FAILED' , 'TASK_KILLED' , 'TASK_LOST' , 'TASK_ERROR' ) for task in tasks : if task [ 'state' ] in completed_states : return True return False
Check whether a task has completed .
39,499
def task_property_present_predicate ( service , task , prop ) : try : response = get_service_task ( service , task ) except Exception as e : pass return ( response is not None ) and ( prop in response )
True if the json_element passed is present for the task specified .