idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
20,500
def get_cas_client ( self , request , provider , renew = False ) : service_url = utils . get_current_url ( request , { "ticket" , "provider" } ) self . service_url = service_url return CASFederateValidateUser ( provider , service_url , renew = renew )
return a CAS client object matching provider
20,501
def post ( self , request , provider = None ) : if not settings . CAS_FEDERATE : logger . warning ( "CAS_FEDERATE is False, set it to True to use federation" ) return redirect ( "cas_server:login" ) try : provider = FederatedIendityProvider . objects . get ( suffix = provider ) auth = self . get_cas_client ( request , ...
method called on POST request
20,502
def get ( self , request , provider = None ) : if not settings . CAS_FEDERATE : logger . warning ( "CAS_FEDERATE is False, set it to True to use federation" ) return redirect ( "cas_server:login" ) renew = bool ( request . GET . get ( 'renew' ) and request . GET [ 'renew' ] != "False" ) if self . request . session . ge...
method called on GET request
20,503
def init_post ( self , request ) : self . request = request self . service = request . POST . get ( 'service' ) self . renew = bool ( request . POST . get ( 'renew' ) and request . POST [ 'renew' ] != "False" ) self . gateway = request . POST . get ( 'gateway' ) self . method = request . POST . get ( 'method' ) self . ...
Initialize POST received parameters
20,504
def gen_lt ( self ) : self . request . session [ 'lt' ] = self . request . session . get ( 'lt' , [ ] ) + [ utils . gen_lt ( ) ] if len ( self . request . session [ 'lt' ] ) > 100 : self . request . session [ 'lt' ] = self . request . session [ 'lt' ] [ - 100 : ]
Generate a new LoginTicket and add it to the list of valid LT for the user
20,505
def check_lt ( self ) : lt_valid = self . request . session . get ( 'lt' , [ ] ) lt_send = self . request . POST . get ( 'lt' ) self . gen_lt ( ) if lt_send not in lt_valid : return False else : self . request . session [ 'lt' ] . remove ( lt_send ) self . request . session [ 'lt' ] = self . request . session [ 'lt' ] ...
Check is the POSTed LoginTicket is valid if yes invalide it
20,506
def init_get ( self , request ) : self . request = request self . service = request . GET . get ( 'service' ) self . renew = bool ( request . GET . get ( 'renew' ) and request . GET [ 'renew' ] != "False" ) self . gateway = request . GET . get ( 'gateway' ) self . method = request . GET . get ( 'method' ) self . ajax =...
Initialize GET received parameters
20,507
def process_get ( self ) : self . gen_lt ( ) if not self . request . session . get ( "authenticated" ) or self . renew : self . init_form ( ) return self . USER_NOT_AUTHENTICATED return self . USER_AUTHENTICATED
Analyse the GET request
20,508
def init_form ( self , values = None ) : if values : values = values . copy ( ) values [ 'lt' ] = self . request . session [ 'lt' ] [ - 1 ] form_initial = { 'service' : self . service , 'method' : self . method , 'warn' : ( self . warn or self . request . session . get ( "warn" ) or self . request . COOKIES . get ( 'wa...
Initialization of the good form depending of POST and GET parameters
20,509
def service_login ( self ) : try : service_pattern = ServicePattern . validate ( self . service ) service_pattern . check_user ( self . user ) if self . request . session . get ( "warn" , True ) and not self . warned : messages . add_message ( self . request , messages . WARNING , _ ( u"Authentication has been required...
Perform login against a service
20,510
def authenticated ( self ) : try : self . user = models . User . objects . get ( username = self . request . session . get ( "username" ) , session_key = self . request . session . session_key ) except models . User . DoesNotExist : logger . warning ( "User %s seems authenticated but is not found in the database." % ( ...
Processing authenticated users
20,511
def not_authenticated ( self ) : if self . service : try : service_pattern = ServicePattern . validate ( self . service ) if self . gateway and not self . ajax : list ( messages . get_messages ( self . request ) ) return HttpResponseRedirect ( self . service ) if settings . CAS_SHOW_SERVICE_MESSAGES : if self . request...
Processing non authenticated users
20,512
def common ( self ) : if self . request . session . get ( "authenticated" ) and ( not self . renew or self . renewed ) : return self . authenticated ( ) else : return self . not_authenticated ( )
Common part execute uppon GET and POST request
20,513
def process_ticket ( self ) : try : proxies = [ ] if self . allow_proxy_ticket : ticket = models . Ticket . get ( self . ticket , self . renew ) else : ticket = models . ServiceTicket . get ( self . ticket , self . renew ) try : for prox in ticket . proxies . all ( ) : proxies . append ( prox . url ) except AttributeEr...
fetch the ticket against the database and check its validity
20,514
def process_pgturl ( self , params ) : try : pattern = ServicePattern . validate ( self . pgt_url ) if pattern . proxy_callback : proxyid = utils . gen_pgtiou ( ) pticket = ProxyGrantingTicket . objects . create ( user = self . ticket . user , service = self . pgt_url , service_pattern = pattern , single_log_out = patt...
Handle PGT request
20,515
def process_proxy ( self ) : try : pattern = ServicePattern . validate ( self . target_service ) if not pattern . proxy : raise ValidateError ( u'UNAUTHORIZED_SERVICE' , u'the service %s does not allow proxy tickets' % self . target_service ) ticket = ProxyGrantingTicket . get ( self . pgt ) pattern . check_user ( tick...
handle PT request
20,516
def process_ticket ( self ) : try : auth_req = self . root . getchildren ( ) [ 1 ] . getchildren ( ) [ 0 ] ticket = auth_req . getchildren ( ) [ 0 ] . text ticket = models . Ticket . get ( ticket ) if ticket . service != self . target : raise SamlValidateError ( u'AuthnFailed' , u'TARGET %s does not match ticket servic...
validate ticket from SAML XML body
20,517
def main ( source ) : if source is None : click . echo ( "You need to supply a file or url to a schema to a swagger schema, for" "the validator to work." ) return 1 try : load ( source ) click . echo ( "Validation passed" ) return 0 except ValidationError as e : raise click . ClickException ( str ( e ) )
For a given command line supplied argument negotiate the content parse the schema and then return any issues to stdout or if no schema issues return success exit code .
20,518
def load_source ( source ) : if isinstance ( source , collections . Mapping ) : return deepcopy ( source ) elif hasattr ( source , 'read' ) and callable ( source . read ) : raw_source = source . read ( ) elif os . path . exists ( os . path . expanduser ( str ( source ) ) ) : with open ( os . path . expanduser ( str ( s...
Common entry point for loading some form of raw swagger schema .
20,519
def validate ( raw_schema , target = None , ** kwargs ) : schema = schema_validator ( raw_schema , ** kwargs ) if target is not None : validate_object ( target , schema = schema , ** kwargs )
Given the python representation of a JSONschema as defined in the swagger spec validate that the schema complies to spec . If target is provided that target will be validated against the provided schema .
20,520
def validate_api_response ( schema , raw_response , request_method = 'get' , raw_request = None ) : request = None if raw_request is not None : request = normalize_request ( raw_request ) response = None if raw_response is not None : response = normalize_response ( raw_response , request = request ) if response is not ...
Validate the response of an api call against a swagger schema .
20,521
def find_parameter ( parameters , ** kwargs ) : matching_parameters = filter_parameters ( parameters , ** kwargs ) if len ( matching_parameters ) == 1 : return matching_parameters [ 0 ] elif len ( matching_parameters ) > 1 : raise MultipleParametersFound ( ) raise NoParameterFound ( )
Given a list of parameters find the one with the given name .
20,522
def merge_parameter_lists ( * parameter_definitions ) : merged_parameters = { } for parameter_list in parameter_definitions : for parameter in parameter_list : key = ( parameter [ 'name' ] , parameter [ 'in' ] ) merged_parameters [ key ] = parameter return merged_parameters . values ( )
Merge multiple lists of parameters into a single list . If there are any duplicate definitions the last write wins .
20,523
def validate_status_code_to_response_definition ( response , operation_definition ) : status_code = response . status_code operation_responses = { str ( code ) : val for code , val in operation_definition [ 'responses' ] . items ( ) } key = status_code if key not in operation_responses : key = 'default' try : response_...
Given a response validate that the response status code is in the accepted status codes defined by this endpoint .
20,524
def generate_path_validator ( api_path , path_definition , parameters , context , ** kwargs ) : path_level_parameters = dereference_parameter_list ( path_definition . get ( 'parameters' , [ ] ) , context , ) operation_level_parameters = dereference_parameter_list ( parameters , context , ) all_parameters = merge_parame...
Generates a callable for validating the parameters in a response object .
20,525
def validate_response ( response , request_method , schema ) : with ErrorDict ( ) as errors : try : api_path = validate_path_to_api_path ( path = response . path , context = schema , ** schema ) except ValidationError as err : errors [ 'path' ] . extend ( list ( err . messages ) ) return path_definition = schema [ 'pat...
Response validation involves the following steps . 4 . validate that the response status_code is in the allowed responses for the request method . 5 . validate that the response content validates against any provided schemas for the responses . 6 . headers content - types etc ... ???
20,526
def construct_schema_validators ( schema , context ) : validators = ValidationDict ( ) if '$ref' in schema : validators . add_validator ( '$ref' , SchemaReferenceValidator ( schema [ '$ref' ] , context ) , ) if 'properties' in schema : for property_ , property_schema in schema [ 'properties' ] . items ( ) : property_va...
Given a schema object construct a dictionary of validators needed to validate a response matching the given schema .
20,527
def validate_type ( value , types , ** kwargs ) : if not is_value_of_any_type ( value , types ) : raise ValidationError ( MESSAGES [ 'type' ] [ 'invalid' ] . format ( repr ( value ) , get_type_for_value ( value ) , types , ) )
Validate that the value is one of the provided primative types .
20,528
def generate_type_validator ( type_ , ** kwargs ) : if is_non_string_iterable ( type_ ) : types = tuple ( type_ ) else : types = ( type_ , ) if kwargs . get ( 'x-nullable' , False ) and NULL not in types : types = types + ( NULL , ) return functools . partial ( validate_type , types = types )
Generates a callable validator for the given type or iterable of types .
20,529
def validate_multiple_of ( value , divisor , ** kwargs ) : if not decimal . Decimal ( str ( value ) ) % decimal . Decimal ( str ( divisor ) ) == 0 : raise ValidationError ( MESSAGES [ 'multiple_of' ] [ 'invalid' ] . format ( divisor , value ) , )
Given a value and a divisor validate that the value is divisible by the divisor .
20,530
def validate_minimum ( value , minimum , is_exclusive , ** kwargs ) : if is_exclusive : comparison_text = "greater than" compare_fn = operator . gt else : comparison_text = "greater than or equal to" compare_fn = operator . ge if not compare_fn ( value , minimum ) : raise ValidationError ( MESSAGES [ 'minimum' ] [ 'inv...
Validator function for validating that a value does not violate it s minimum allowed value . This validation can be inclusive or exclusive of the minimum depending on the value of is_exclusive .
20,531
def generate_minimum_validator ( minimum , exclusiveMinimum = False , ** kwargs ) : return functools . partial ( validate_minimum , minimum = minimum , is_exclusive = exclusiveMinimum )
Generator function returning a callable for minimum value validation .
20,532
def validate_maximum ( value , maximum , is_exclusive , ** kwargs ) : if is_exclusive : comparison_text = "less than" compare_fn = operator . lt else : comparison_text = "less than or equal to" compare_fn = operator . le if not compare_fn ( value , maximum ) : raise ValidationError ( MESSAGES [ 'maximum' ] [ 'invalid' ...
Validator function for validating that a value does not violate it s maximum allowed value . This validation can be inclusive or exclusive of the maximum depending on the value of is_exclusive .
20,533
def generate_maximum_validator ( maximum , exclusiveMaximum = False , ** kwargs ) : return functools . partial ( validate_maximum , maximum = maximum , is_exclusive = exclusiveMaximum )
Generator function returning a callable for maximum value validation .
20,534
def validate_min_items ( value , minimum , ** kwargs ) : if len ( value ) < minimum : raise ValidationError ( MESSAGES [ 'min_items' ] [ 'invalid' ] . format ( minimum , len ( value ) , ) , )
Validator for ARRAY types to enforce a minimum number of items allowed for the ARRAY to be valid .
20,535
def validate_max_items ( value , maximum , ** kwargs ) : if len ( value ) > maximum : raise ValidationError ( MESSAGES [ 'max_items' ] [ 'invalid' ] . format ( maximum , len ( value ) , ) , )
Validator for ARRAY types to enforce a maximum number of items allowed for the ARRAY to be valid .
20,536
def validate_unique_items ( value , ** kwargs ) : counter = collections . Counter ( ( json . dumps ( v , sort_keys = True ) for v in value ) ) dupes = [ json . loads ( v ) for v , count in counter . items ( ) if count > 1 ] if dupes : raise ValidationError ( MESSAGES [ 'unique_items' ] [ 'invalid' ] . format ( repr ( d...
Validator for ARRAY types to enforce that all array items must be unique .
20,537
def validate_object ( obj , field_validators = None , non_field_validators = None , schema = None , context = None ) : if schema is None : schema = { } if context is None : context = { } if field_validators is None : field_validators = ValidationDict ( ) if non_field_validators is None : non_field_validators = Validati...
Takes a mapping and applies a mapping of validator functions to it collecting and reraising any validation errors that occur .
20,538
def validate_request_method_to_operation ( request_method , path_definition ) : try : operation_definition = path_definition [ request_method ] except KeyError : allowed_methods = set ( REQUEST_METHODS ) . intersection ( path_definition . keys ( ) ) raise ValidationError ( MESSAGES [ 'request' ] [ 'invalid_method' ] . ...
Given a request method validate that the request method is valid for the api path .
20,539
def validate_path_to_api_path ( path , paths , basePath = '' , context = None , ** kwargs ) : if context is None : context = { } try : api_path = match_path_to_api_path ( path_definitions = paths , target_path = path , base_path = basePath , context = context , ) except LookupError as err : raise ValidationError ( str ...
Given a path find the api_path it matches .
20,540
def validate_path_parameters ( target_path , api_path , path_parameters , context ) : base_path = context . get ( 'basePath' , '' ) full_api_path = re . sub ( NORMALIZE_SLASH_REGEX , '/' , base_path + api_path ) parameter_values = get_path_parameter_values ( target_path , full_api_path , path_parameters , context , ) v...
Helper function for validating a request path
20,541
def construct_parameter_validators ( parameter , context ) : validators = ValidationDict ( ) if '$ref' in parameter : validators . add_validator ( '$ref' , ParameterReferenceValidator ( parameter [ '$ref' ] , context ) , ) for key in parameter : if key in validator_mapping : validators . add_validator ( key , validator...
Constructs a dictionary of validator functions for the provided parameter definition .
20,542
def construct_multi_parameter_validators ( parameters , context ) : validators = ValidationDict ( ) for parameter in parameters : key = parameter [ 'name' ] if key in validators : raise ValueError ( "Duplicate parameter name {0}" . format ( key ) ) parameter_validators = construct_parameter_validators ( parameter , con...
Given an iterable of parameters returns a dictionary of validator functions for each parameter . Note that this expects the parameters to be unique in their name value and throws an error if this is not the case .
20,543
def generate_path_parameters_validator ( api_path , path_parameters , context ) : path_parameter_validator = functools . partial ( validate_path_parameters , api_path = api_path , path_parameters = path_parameters , context = context , ) return path_parameter_validator
Generates a validator function that given a path validates that it against the path parameters
20,544
def escape_regex_special_chars ( api_path ) : def substitute ( string , replacements ) : pattern , repl = replacements return re . sub ( pattern , repl , string ) return functools . reduce ( substitute , REGEX_REPLACEMENTS , api_path )
Turns the non prametrized path components into strings subtable for using as a regex pattern . This primarily involves escaping special characters so that the actual character is matched in the regex .
20,545
def construct_parameter_pattern ( parameter ) : name = parameter [ 'name' ] type = parameter [ 'type' ] repeated = '[^/]' if type == 'integer' : repeated = '\d' return "(?P<{name}>{repeated}+)" . format ( name = name , repeated = repeated )
Given a parameter definition returns a regex pattern that will match that part of the path .
20,546
def path_to_pattern ( api_path , parameters ) : parts = re . split ( PARAMETER_REGEX , api_path ) pattern = '' . join ( ( process_path_part ( part , parameters ) for part in parts ) ) if not pattern . startswith ( '^' ) : pattern = "^{0}" . format ( pattern ) if not pattern . endswith ( '$' ) : pattern = "{0}$" . forma...
Given an api path possibly with parameter notation return a pattern suitable for turing into a regular expression which will match request paths that conform to the parameter definitions and the api path .
20,547
def match_path_to_api_path ( path_definitions , target_path , base_path = '' , context = None ) : if context is None : context = { } assert isinstance ( context , collections . Mapping ) if target_path . startswith ( base_path ) : normalized_target_path = re . sub ( NORMALIZE_SLASH_REGEX , '/' , target_path ) matching_...
Match a request or response path to one of the api paths .
20,548
def validate_request ( request , schema ) : with ErrorDict ( ) as errors : try : api_path = validate_path_to_api_path ( path = request . path , context = schema , ** schema ) except ValidationError as err : errors [ 'path' ] . add_error ( err . detail ) return path_definition = schema [ 'paths' ] [ api_path ] or { } if...
Request validation does the following steps .
20,549
def normalize_request ( request ) : if isinstance ( request , Request ) : return request for normalizer in REQUEST_NORMALIZERS : try : return normalizer ( request ) except TypeError : continue raise ValueError ( "Unable to normalize the provided request" )
Given a request normalize it to the internal Request class .
20,550
def normalize_response ( response , request = None ) : if isinstance ( response , Response ) : return response if request is not None and not isinstance ( request , Request ) : request = normalize_request ( request ) for normalizer in RESPONSE_NORMALIZERS : try : return normalizer ( response , request = request ) excep...
Given a response normalize it to the internal Response class . This also involves normalizing the associated request object .
20,551
def generate_header_validator ( headers , context , ** kwargs ) : validators = ValidationDict ( ) for header_definition in headers : header_processor = generate_value_processor ( context = context , ** header_definition ) header_validator = generate_object_validator ( field_validators = construct_header_validators ( he...
Generates a validation function that will validate a dictionary of headers .
20,552
def generate_parameters_validator ( api_path , path_definition , parameters , context , ** kwargs ) : validators = ValidationDict ( ) path_level_parameters = dereference_parameter_list ( path_definition . get ( 'parameters' , [ ] ) , context , ) operation_level_parameters = dereference_parameter_list ( parameters , con...
Generates a validator function to validate .
20,553
def partial_safe_wraps ( wrapped_func , * args , ** kwargs ) : if isinstance ( wrapped_func , functools . partial ) : return partial_safe_wraps ( wrapped_func . func ) else : return functools . wraps ( wrapped_func )
A version of functools . wraps that is safe to wrap a partial in .
20,554
def skip_if_empty ( func ) : @ partial_safe_wraps ( func ) def inner ( value , * args , ** kwargs ) : if value is EMPTY : return else : return func ( value , * args , ** kwargs ) return inner
Decorator for validation functions which makes them pass if the value passed in is the EMPTY sentinal value .
20,555
def rewrite_reserved_words ( func ) : @ partial_safe_wraps ( func ) def inner ( * args , ** kwargs ) : for word in RESERVED_WORDS : key = "{0}_" . format ( word ) if key in kwargs : kwargs [ word ] = kwargs . pop ( key ) return func ( * args , ** kwargs ) return inner
Given a function whos kwargs need to contain a reserved word such as in allow calling that function with the keyword as in_ such that function kwargs are rewritten to use the reserved word .
20,556
def any_validator ( obj , validators , ** kwargs ) : if not len ( validators ) > 1 : raise ValueError ( "any_validator requires at least 2 validator. Only got " "{0}" . format ( len ( validators ) ) ) errors = ErrorDict ( ) for key , validator in validators . items ( ) : try : validator ( obj , ** kwargs ) except Vali...
Attempt multiple validators on an object .
20,557
def _extract_to_tempdir ( archive_filename ) : if not os . path . exists ( archive_filename ) : raise Exception ( "Archive '%s' does not exist" % ( archive_filename ) ) tempdir = tempfile . mkdtemp ( prefix = "metaextract_" ) current_cwd = os . getcwd ( ) try : if tarfile . is_tarfile ( archive_filename ) : with tarfil...
extract the given tarball or zipfile to a tempdir and change the cwd to the new tempdir . Delete the tempdir at the end
20,558
def _enter_single_subdir ( root_dir ) : current_cwd = os . getcwd ( ) try : dest_dir = root_dir dir_list = os . listdir ( root_dir ) if len ( dir_list ) == 1 : first = os . path . join ( root_dir , dir_list [ 0 ] ) if os . path . isdir ( first ) : dest_dir = first else : dest_dir = root_dir os . chdir ( dest_dir ) yiel...
if the given directory has just a single subdir enter that
20,559
def _set_file_encoding_utf8 ( filename ) : with open ( filename , 'r+' ) as f : content = f . read ( ) f . seek ( 0 , 0 ) f . write ( "# -*- coding: utf-8 -*-\n" + content )
set a encoding header as suggested in PEP - 0263 . This is not entirely correct because we don t know the encoding of the given file but it s at least a chance to get metadata from the setup . py
20,560
def _setup_py_run_from_dir ( root_dir , py_interpreter ) : data = { } with _enter_single_subdir ( root_dir ) as single_subdir : if not os . path . exists ( "setup.py" ) : raise Exception ( "'setup.py' does not exist in '%s'" % ( single_subdir ) ) output_json = tempfile . NamedTemporaryFile ( ) cmd = "%s setup.py -q --c...
run the extractmeta command via the setup . py in the given root_dir . the output of extractmeta is json and is stored in a tempfile which is then read in and returned as data
20,561
def from_archive ( archive_filename , py_interpreter = sys . executable ) : with _extract_to_tempdir ( archive_filename ) as root_dir : data = _setup_py_run_from_dir ( root_dir , py_interpreter ) return data
extract metadata from a given sdist archive file
20,562
def xmlns ( source ) : namespaces = { } events = ( "end" , "start-ns" , "end-ns" ) for ( event , elem ) in iterparse ( source , events ) : if event == "start-ns" : prefix , ns = elem namespaces [ prefix ] = ns elif event == "end" : break if hasattr ( source , "seek" ) : source . seek ( 0 ) return namespaces
Returns a map of prefix to namespace for the given XML file .
20,563
def create_block ( mc , block_id , subtype = None ) : ptx , pty , ptz = mc . player . getTilePos ( ) px , py , pz = mc . player . getPos ( ) if subtype is None : mc . setBlock ( ptx , pty , ptz , block_id ) else : mc . setBlock ( ptx , pty , ptz , block_id , subtype ) mc . player . setPos ( px , py + 1 , pz )
Build a block with the specified id and subtype under the player in the Minecraft world . Subtype is optional and can be specified as None to use the default subtype for the block .
20,564
def _busy_wait_ms ( self , ms ) : start = time . time ( ) delta = ms / 1000.0 while ( time . time ( ) - start ) <= delta : pass
Busy wait for the specified number of milliseconds .
20,565
def _write_frame ( self , data ) : assert data is not None and 0 < len ( data ) < 255 , 'Data must be array of 1 to 255 bytes.' length = len ( data ) frame = bytearray ( length + 8 ) frame [ 0 ] = PN532_SPI_DATAWRITE frame [ 1 ] = PN532_PREAMBLE frame [ 2 ] = PN532_STARTCODE1 frame [ 3 ] = PN532_STARTCODE2 frame [ 4 ] ...
Write a frame to the PN532 with the specified data bytearray .
20,566
def _read_data ( self , count ) : frame = bytearray ( count ) frame [ 0 ] = PN532_SPI_DATAREAD self . _gpio . set_low ( self . _cs ) self . _busy_wait_ms ( 2 ) response = self . _spi . transfer ( frame ) self . _gpio . set_high ( self . _cs ) return response
Read a specified count of bytes from the PN532 .
20,567
def _read_frame ( self , length ) : response = self . _read_data ( length + 8 ) logger . debug ( 'Read frame: 0x{0}' . format ( binascii . hexlify ( response ) ) ) if response [ 0 ] != 0x01 : raise RuntimeError ( 'Response frame does not start with 0x01!' ) offset = 1 while response [ offset ] == 0x00 : offset += 1 if ...
Read a response frame from the PN532 of at most length bytes in size . Returns the data inside the frame if found otherwise raises an exception if there is an error parsing the frame . Note that less than length bytes might be returned!
20,568
def _wait_ready ( self , timeout_sec = 1 ) : start = time . time ( ) self . _gpio . set_low ( self . _cs ) self . _busy_wait_ms ( 2 ) response = self . _spi . transfer ( [ PN532_SPI_STATREAD , 0x00 ] ) self . _gpio . set_high ( self . _cs ) while response [ 1 ] != PN532_SPI_READY : if time . time ( ) - start >= timeout...
Wait until the PN532 is ready to receive commands . At most wait timeout_sec seconds for the PN532 to be ready . If the PN532 is ready before the timeout is exceeded then True will be returned otherwise False is returned when the timeout is exceeded .
20,569
def call_function ( self , command , response_length = 0 , params = [ ] , timeout_sec = 1 ) : data = bytearray ( 2 + len ( params ) ) data [ 0 ] = PN532_HOSTTOPN532 data [ 1 ] = command & 0xFF data [ 2 : ] = params self . _write_frame ( data ) if not self . _wait_ready ( timeout_sec ) : return None response = self . _r...
Send specified command to the PN532 and expect up to response_length bytes back in a response . Note that less than the expected bytes might be returned! Params can optionally specify an array of bytes to send as parameters to the function call . Will wait up to timeout_secs seconds for a response and return a bytearra...
20,570
def begin ( self ) : self . _gpio . set_low ( self . _cs ) time . sleep ( 1.0 ) self . get_firmware_version ( ) self . _gpio . set_high ( self . _cs )
Initialize communication with the PN532 . Must be called before any other calls are made against the PN532 .
20,571
def get_firmware_version ( self ) : response = self . call_function ( PN532_COMMAND_GETFIRMWAREVERSION , 4 ) if response is None : raise RuntimeError ( 'Failed to detect the PN532! Make sure there is sufficient power (use a 1 amp or greater power supply), the PN532 is wired correctly to the device, and the solder join...
Call PN532 GetFirmwareVersion function and return a tuple with the IC Ver Rev and Support values .
20,572
def read_passive_target ( self , card_baud = PN532_MIFARE_ISO14443A , timeout_sec = 1 ) : response = self . call_function ( PN532_COMMAND_INLISTPASSIVETARGET , params = [ 0x01 , card_baud ] , response_length = 17 ) if response is None : return None if response [ 0 ] != 0x01 : raise RuntimeError ( 'More than one card de...
Wait for a MiFare card to be available and return its UID when found . Will wait up to timeout_sec seconds and return None if no card is found otherwise a bytearray with the UID of the found card is returned .
20,573
def mifare_classic_read_block ( self , block_number ) : response = self . call_function ( PN532_COMMAND_INDATAEXCHANGE , params = [ 0x01 , MIFARE_CMD_READ , block_number & 0xFF ] , response_length = 17 ) if response [ 0 ] != 0x00 : return None return response [ 1 : ]
Read a block of data from the card . Block number should be the block to read . If the block is successfully read a bytearray of length 16 with data starting at the specified block will be returned . If the block is not read then None will be returned .
20,574
def mifare_classic_write_block ( self , block_number , data ) : assert data is not None and len ( data ) == 16 , 'Data must be an array of 16 bytes!' params = bytearray ( 19 ) params [ 0 ] = 0x01 params [ 1 ] = MIFARE_CMD_WRITE params [ 2 ] = block_number & 0xFF params [ 3 : ] = data response = self . call_function ( P...
Write a block of data to the card . Block number should be the block to write and data should be a byte array of length 16 with the data to write . If the data is successfully written then True is returned otherwise False is returned .
20,575
def _dirmatch ( path , matchwith ) : matchlen = len ( matchwith ) if ( path . startswith ( matchwith ) and path [ matchlen : matchlen + 1 ] in [ os . sep , '' ] ) : return True return False
Check if path is within matchwith s tree .
20,576
def _virtualenv_sys ( venv_path ) : "obtain version and path info from a virtualenv." executable = os . path . join ( venv_path , env_bin_dir , 'python' ) p = subprocess . Popen ( [ executable , '-c' , 'import sys;' 'print (sys.version[:3]);' 'print ("\\n".join(sys.path));' ] , env = { } , stdout = subprocess . PIPE ) ...
obtain version and path info from a virtualenv .
20,577
def int_to_ef ( n ) : flags = { } for name , value in libarchive . constants . archive_entry . FILETYPES . items ( ) : flags [ name ] = ( n & value ) > 0 return ENTRY_FILETYPE ( ** flags )
This is here for testing support but in practice this isn t very useful as many of the flags are just combinations of other flags . The relationships are defined by the OS in ways that aren t semantically intuitive to this project .
20,578
def _enumerator ( opener , entry_cls , format_code = None , filter_code = None ) : archive_res = _archive_read_new ( ) try : r = _set_read_context ( archive_res , format_code , filter_code ) opener ( archive_res ) def it ( ) : while 1 : with _archive_read_next_header ( archive_res ) as entry_res : if entry_res is None ...
Return an archive enumerator from a user - defined source using a user - defined entry type .
20,579
def file_enumerator ( filepath , block_size = 10240 , * args , ** kwargs ) : _LOGGER . debug ( "Enumerating through archive file: %s" , filepath ) def opener ( archive_res ) : _LOGGER . debug ( "Opening from file (file_enumerator): %s" , filepath ) _archive_read_open_filename ( archive_res , filepath , block_size ) if ...
Return an enumerator that knows how to read a physical file .
20,580
def memory_enumerator ( buffer_ , * args , ** kwargs ) : _LOGGER . debug ( "Enumerating through (%d) bytes of archive data." , len ( buffer_ ) ) def opener ( archive_res ) : _LOGGER . debug ( "Opening from (%d) bytes (memory_enumerator)." , len ( buffer_ ) ) _archive_read_open_memory ( archive_res , buffer_ ) if 'entry...
Return an enumerator that knows how to read raw memory .
20,581
def _pour ( opener , flags = 0 , * args , ** kwargs ) : with _enumerator ( opener , * args , entry_cls = _ArchiveEntryItState , ** kwargs ) as r : ext = libarchive . calls . archive_write . c_archive_write_disk_new ( ) libarchive . calls . archive_write . c_archive_write_disk_set_options ( ext , flags ) for state in r ...
A flexible pouring facility that knows how to enumerate entry data .
20,582
def file_pour ( filepath , block_size = 10240 , * args , ** kwargs ) : def opener ( archive_res ) : _LOGGER . debug ( "Opening from file (file_pour): %s" , filepath ) _archive_read_open_filename ( archive_res , filepath , block_size ) return _pour ( opener , * args , flags = 0 , ** kwargs )
Write physical files from entries .
20,583
def memory_pour ( buffer_ , * args , ** kwargs ) : def opener ( archive_res ) : _LOGGER . debug ( "Opening from (%d) bytes (memory_pour)." , len ( buffer_ ) ) _archive_read_open_memory ( archive_res , buffer_ ) return _pour ( opener , * args , flags = 0 , ** kwargs )
Yield data from entries .
20,584
def _archive_write_data ( archive , data ) : n = libarchive . calls . archive_write . c_archive_write_data ( archive , ctypes . cast ( ctypes . c_char_p ( data ) , ctypes . c_void_p ) , len ( data ) ) if n == 0 : message = c_archive_error_string ( archive ) raise ValueError ( "No bytes were written. Error? [%s]" % ( me...
Write data to archive . This will only be called with a non - empty string .
20,585
def _write_ctrl_meas ( self ) : self . _write_register_byte ( _BME280_REGISTER_CTRL_HUM , self . overscan_humidity ) self . _write_register_byte ( _BME280_REGISTER_CTRL_MEAS , self . _ctrl_meas )
Write the values to the ctrl_meas and ctrl_hum registers in the device ctrl_meas sets the pressure and temperature data acquistion options ctrl_hum sets the humidty oversampling and must be written to first
20,586
def _write_config ( self ) : normal_flag = False if self . _mode == MODE_NORMAL : normal_flag = True self . mode = MODE_SLEEP self . _write_register_byte ( _BME280_REGISTER_CONFIG , self . _config ) if normal_flag : self . mode = MODE_NORMAL
Write the value to the config register in the device
20,587
def _config ( self ) : config = 0 if self . mode == MODE_NORMAL : config += ( self . _t_standby << 5 ) if self . _iir_filter : config += ( self . _iir_filter << 2 ) return config
Value to be written to the device s config register
20,588
def _ctrl_meas ( self ) : ctrl_meas = ( self . overscan_temperature << 5 ) ctrl_meas += ( self . overscan_pressure << 2 ) ctrl_meas += self . mode return ctrl_meas
Value to be written to the device s ctrl_meas register
20,589
def measurement_time_typical ( self ) : meas_time_ms = 1.0 if self . overscan_temperature != OVERSCAN_DISABLE : meas_time_ms += ( 2 * _BME280_OVERSCANS . get ( self . overscan_temperature ) ) if self . overscan_pressure != OVERSCAN_DISABLE : meas_time_ms += ( 2 * _BME280_OVERSCANS . get ( self . overscan_pressure ) + 0...
Typical time in milliseconds required to complete a measurement in normal mode
20,590
def pressure ( self ) : self . _read_temperature ( ) adc = self . _read24 ( _BME280_REGISTER_PRESSUREDATA ) / 16 var1 = float ( self . _t_fine ) / 2.0 - 64000.0 var2 = var1 * var1 * self . _pressure_calib [ 5 ] / 32768.0 var2 = var2 + var1 * self . _pressure_calib [ 4 ] * 2.0 var2 = var2 / 4.0 + self . _pressure_calib ...
The compensated pressure in hectoPascals . returns None if pressure measurement is disabled
20,591
def humidity ( self ) : self . _read_temperature ( ) hum = self . _read_register ( _BME280_REGISTER_HUMIDDATA , 2 ) adc = float ( hum [ 0 ] << 8 | hum [ 1 ] ) var1 = float ( self . _t_fine ) - 76800.0 var2 = ( self . _humidity_calib [ 3 ] * 64.0 + ( self . _humidity_calib [ 4 ] / 16384.0 ) * var1 ) var3 = adc - var2 va...
The relative humidity in RH % returns None if humidity measurement is disabled
20,592
def _read_coefficients ( self ) : coeff = self . _read_register ( _BME280_REGISTER_DIG_T1 , 24 ) coeff = list ( struct . unpack ( '<HhhHhhhhhhhh' , bytes ( coeff ) ) ) coeff = [ float ( i ) for i in coeff ] self . _temp_calib = coeff [ : 3 ] self . _pressure_calib = coeff [ 3 : ] self . _humidity_calib = [ 0 ] * 6 self...
Read & save the calibration coefficients
20,593
def _read24 ( self , register ) : ret = 0.0 for b in self . _read_register ( register , 3 ) : ret *= 256.0 ret += float ( b & 0xFF ) return ret
Read an unsigned 24 - bit value as a floating point and return it .
20,594
def _create ( self , postData ) : if self . infos is None : r = self . connection . session . post ( self . indexesURL , params = { "collection" : self . collection . name } , data = json . dumps ( postData , default = str ) ) data = r . json ( ) if ( r . status_code >= 400 ) or data [ 'error' ] : raise CreationError (...
Creates an index of any type according to postData
20,595
def createVertex ( self , collectionName , docAttributes , waitForSync = False ) : url = "%s/vertex/%s" % ( self . URL , collectionName ) store = DOC . DocumentStore ( self . database [ collectionName ] , validators = self . database [ collectionName ] . _fields , initDct = docAttributes ) store . validate ( ) r = self...
adds a vertex to the graph and returns it
20,596
def deleteVertex ( self , document , waitForSync = False ) : url = "%s/vertex/%s" % ( self . URL , document . _id ) r = self . connection . session . delete ( url , params = { 'waitForSync' : waitForSync } ) data = r . json ( ) if r . status_code == 200 or r . status_code == 202 : return True raise DeletionError ( "Una...
deletes a vertex from the graph as well as al linked edges
20,597
def createEdge ( self , collectionName , _fromId , _toId , edgeAttributes , waitForSync = False ) : if not _fromId : raise ValueError ( "Invalid _fromId: %s" % _fromId ) if not _toId : raise ValueError ( "Invalid _toId: %s" % _toId ) if collectionName not in self . definitions : raise KeyError ( "'%s' is not among the ...
creates an edge between two documents
20,598
def link ( self , definition , doc1 , doc2 , edgeAttributes , waitForSync = False ) : "A shorthand for createEdge that takes two documents as input" if type ( doc1 ) is DOC . Document : if not doc1 . _id : doc1 . save ( ) doc1_id = doc1 . _id else : doc1_id = doc1 if type ( doc2 ) is DOC . Document : if not doc2 . _id ...
A shorthand for createEdge that takes two documents as input
20,599
def unlink ( self , definition , doc1 , doc2 ) : "deletes all links between doc1 and doc2" links = self . database [ definition ] . fetchByExample ( { "_from" : doc1 . _id , "_to" : doc2 . _id } , batchSize = 100 ) for l in links : self . deleteEdge ( l )
deletes all links between doc1 and doc2