Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def validate_api_call(schema, raw_request, raw_response):
request = normalize_request(raw_request)
with ErrorDict() as errors:
try:
validate_request(
request=request,
schema=schema,
)
excep... | [
"\n Validate the request/response cycle of an api call against a swagger\n schema. Request/Response objects from the `requests` and `urllib` library\n are supported.\n "
] |
Please provide a description of the function:def validate_email(email, check_mx=False, verify=False, debug=False, smtp_timeout=10):
if debug:
logger = logging.getLogger('validate_email')
logger.setLevel(logging.DEBUG)
else:
logger = None
try:
assert re.match(VALID_ADDRE... | [
"Indicate whether the given string is a valid email address\n according to the 'addr-spec' portion of RFC 2822 (see section\n 3.4.1). Parts of the spec that are marked obsolete are *not*\n included in this test, and certain arcane constructions that\n depend on circular definitions in the spec may not ... |
Please provide a description of the function: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()
rai... | [
"\n Given a list of parameters, find the one with the given name.\n "
] |
Please provide a description of the function: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
... | [
"\n Merge multiple lists of parameters into a single list. If there are any\n duplicate definitions, the last write wins.\n "
] |
Please provide a description of the function: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_cod... | [
"\n Given a response, validate that the response status code is in the accepted\n status codes defined by this endpoint.\n\n If so, return the response definition that corresponds to the status code.\n "
] |
Please provide a description of the function:def generate_path_validator(api_path, path_definition, parameters,
context, **kwargs):
path_level_parameters = dereference_parameter_list(
path_definition.get('parameters', []),
context,
)
operation_level_parameter... | [
"\n Generates a callable for validating the parameters in a response object.\n "
] |
Please provide a description of the function:def validate_response(response, request_method, schema):
with ErrorDict() as errors:
# 1
# TODO: tests
try:
api_path = validate_path_to_api_path(
path=response.path,
context=schema,
... | [
"\n Response validation involves the following steps.\n 4. validate that the response status_code is in the allowed responses for\n the request method.\n 5. validate that the response content validates against any provided\n schemas for the responses.\n 6. headers, content-typ... |
Please provide a description of the function: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 pro... | [
"\n Given a schema object, construct a dictionary of validators needed to\n validate a response matching the given schema.\n\n Special Cases:\n - $ref:\n These validators need to be Lazily evaluating so that circular\n validation dependencies do not result in an infinitely deep... |
Please provide a description of the function: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,
)) | [
"\n Validate that the value is one of the provided primative types.\n "
] |
Please provide a description of the function:def generate_type_validator(type_, **kwargs):
if is_non_string_iterable(type_):
types = tuple(type_)
else:
types = (type_,)
# support x-nullable since Swagger 2.0 doesn't support null type
# (see https://github.com/OAI/OpenAPI-Specificati... | [
"\n Generates a callable validator for the given type or iterable of types.\n "
] |
Please provide a description of the function: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),
) | [
"\n Given a value and a divisor, validate that the value is divisible by the\n divisor.\n "
] |
Please provide a description of the function: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 compa... | [
"\n Validator function for validating that a value does not violate it's\n minimum allowed value. This validation can be inclusive, or exclusive of\n the minimum depending on the value of `is_exclusive`.\n "
] |
Please provide a description of the function:def generate_minimum_validator(minimum, exclusiveMinimum=False, **kwargs):
return functools.partial(validate_minimum, minimum=minimum, is_exclusive=exclusiveMinimum) | [
"\n Generator function returning a callable for minimum value validation.\n "
] |
Please provide a description of the function: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(... | [
"\n Validator function for validating that a value does not violate it's\n maximum allowed value. This validation can be inclusive, or exclusive of\n the maximum depending on the value of `is_exclusive`.\n "
] |
Please provide a description of the function:def generate_maximum_validator(maximum, exclusiveMaximum=False, **kwargs):
return functools.partial(validate_maximum, maximum=maximum, is_exclusive=exclusiveMaximum) | [
"\n Generator function returning a callable for maximum value validation.\n "
] |
Please provide a description of the function:def validate_min_items(value, minimum, **kwargs):
if len(value) < minimum:
raise ValidationError(
MESSAGES['min_items']['invalid'].format(
minimum, len(value),
),
) | [
"\n Validator for ARRAY types to enforce a minimum number of items allowed for\n the ARRAY to be valid.\n "
] |
Please provide a description of the function:def validate_max_items(value, maximum, **kwargs):
if len(value) > maximum:
raise ValidationError(
MESSAGES['max_items']['invalid'].format(
maximum, len(value),
),
) | [
"\n Validator for ARRAY types to enforce a maximum number of items allowed for\n the ARRAY to be valid.\n "
] |
Please provide a description of the function:def validate_unique_items(value, **kwargs):
# we can't just look at the items themselves since 0 and False are treated
# the same as dictionary keys, and objects aren't hashable.
counter = collections.Counter((
json.dumps(v, sort_keys=True) for v in... | [
"\n Validator for ARRAY types to enforce that all array items must be unique.\n "
] |
Please provide a description of the function: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 =... | [
"\n Takes a mapping and applies a mapping of validator functions to it\n collecting and reraising any validation errors that occur.\n "
] |
Please provide a description of the function:def generate_value_processor(type_, collectionFormat=None, items=None, **kwargs):
processors = []
if is_non_string_iterable(type_):
assert False, "This should not be possible"
else:
if type_ == ARRAY and collectionFormat:
if colle... | [
"\n Create a callable that will take the string value of a header and cast it\n to the appropriate type. This can involve:\n\n - splitting a header of type 'array' by its delimeters.\n - type casting the internal elements of the array.\n "
] |
Please provide a description of the function: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 Vali... | [
"\n Given a request method, validate that the request method is valid for the\n api path.\n\n If so, return the operation definition related to this request method.\n "
] |
Please provide a description of the function: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=base... | [
"\n Given a path, find the api_path it matches.\n "
] |
Please provide a description of the function: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,... | [
"\n Helper function for validating a request path\n "
] |
Please provide a description of the function:def construct_parameter_validators(parameter, context):
validators = ValidationDict()
if '$ref' in parameter:
validators.add_validator(
'$ref', ParameterReferenceValidator(parameter['$ref'], context),
)
for key in parameter:
... | [
"\n Constructs a dictionary of validator functions for the provided parameter\n definition.\n "
] |
Please provide a description of the function: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))
... | [
"\n Given an iterable of parameters, returns a dictionary of validator\n functions for each parameter. Note that this expects the parameters to be\n unique in their name value, and throws an error if this is not the case.\n "
] |
Please provide a description of the function: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 ... | [
"\n Generates a validator function that given a path, validates that it against\n the path parameters\n "
] |
Please provide a description of the function: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) | [
"\n Turns the non prametrized path components into strings subtable for using\n as a regex pattern. This primarily involves escaping special characters so\n that the actual character is matched in the regex.\n "
] |
Please provide a description of the function: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) | [
"\n Given a parameter definition returns a regex pattern that will match that\n part of the path.\n "
] |
Please provide a description of the function:def process_path_part(part, parameters):
if PARAMETER_REGEX.match(part):
parameter_name = part.strip('{}')
try:
parameter = find_parameter(
parameters,
name=parameter_name,
in_=PATH
... | [
"\n Given a part of a path either:\n - If it is a parameter:\n parse it to a regex group\n - Otherwise:\n escape any special regex characters\n "
] |
Please provide a description of the function: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.end... | [
"\n Given an api path, possibly with parameter notation, return a pattern\n suitable for turing into a regular expression which will match request\n paths that conform to the parameter definitions and the api path.\n "
] |
Please provide a description of the function: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):
# Convert... | [
"\n Match a request or response path to one of the api paths.\n\n Anything other than exactly one match is an error condition.\n "
] |
Please provide a description of the function:def validate_request(request, schema):
with ErrorDict() as errors:
# 1
try:
api_path = validate_path_to_api_path(
path=request.path,
context=schema,
**schema
)
except Val... | [
"\n Request validation does the following steps.\n\n 1. validate that the path matches one of the defined paths in the schema.\n 2. validate that the request method conforms to a supported methods for the given path.\n 3. validate that the request parameters conform to the parameter\n ... |
Please provide a description of the function: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 no... | [
"\n Given a request, normalize it to the internal Request class.\n "
] |
Please provide a description of the function: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:
... | [
"\n Given a response, normalize it to the internal Response class. This also\n involves normalizing the associated request object.\n "
] |
Please provide a description of the function:def data(self):
if not self.body:
return self.body
elif self.body is EMPTY:
return EMPTY
elif self.content_type and self.content_type.startswith('application/json'):
try:
if isinstance(self.... | [
"\n TODO: What is the right way to do this?\n "
] |
Please provide a description of the function:def add_error(self, error):
if is_non_string_iterable(error) and not isinstance(error, collections.Mapping):
for value in error:
self.add_error(value)
else:
self.append(error) | [
"\n In the case where a list/tuple is passed in this just extends the list\n rather than having nested lists.\n\n Otherwise, the value is appended.\n "
] |
Please provide a description of the function:def deep_equal(a, b):
if is_any_string_type(a) and is_any_string_type(b):
if isinstance(a, six.binary_type):
a = six.text_type(a, encoding='utf-8')
if isinstance(b, six.binary_type):
b = six.text_type(b, encoding='utf-8')
... | [
"\n Because of things in python like:\n >>> 1 == 1.0\n True\n >>> 1 == True\n True\n >>> b'test' == 'test' # python3\n False\n "
] |
Please provide a description of the function:def format_errors(errors, indent=0, prefix='', suffix=''):
if is_single_item_iterable(errors):
errors = errors[0]
if isinstance(errors, SINGULAR_TYPES):
yield indent_message(repr(errors), indent, prefix=prefix, suffix=suffix)
elif isinstance... | [
"\n string: \"example\"\n\n \"example\"\n\n dict:\n \"example\":\n -\n\n "
] |
Please provide a description of the function:def generate_header_validator(headers, context, **kwargs):
validators = ValidationDict()
for header_definition in headers:
header_processor = generate_value_processor(
context=context,
**header_definition
)
header_... | [
"\n Generates a validation function that will validate a dictionary of headers.\n "
] |
Please provide a description of the function:def generate_parameters_validator(api_path, path_definition, parameters,
context, **kwargs):
# TODO: figure out how to merge this with the same code in response
# validation.
validators = ValidationDict()
path_level_para... | [
"\n Generates a validator function to validate.\n\n - request.path against the path parameters.\n - request.query against the query parameters.\n - request.headers against the header parameters.\n - TODO: request.body against the body parameters.\n - TODO: request.formData against any form data.\n... |
Please provide a description of the function:def construct_operation_validators(api_path, path_definition, operation_definition, context):
validators = {}
# sanity check
assert 'context' not in operation_definition
assert 'api_path' not in operation_definition
assert 'path_definition' not in o... | [
"\n - consumes (did the request conform to the content types this api consumes)\n - produces (did the response conform to the content types this endpoint produces)\n - parameters (did the parameters of this request validate)\n TODO: move path parameter validation to here, because each operation\n ... |
Please provide a description of the function: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) | [
"\n A version of `functools.wraps` that is safe to wrap a partial in.\n "
] |
Please provide a description of the function: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 | [
"\n Decorator for validation functions which makes them pass if the value\n passed in is the EMPTY sentinal value.\n "
] |
Please provide a description of the function: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(*ar... | [
"\n Given a function whos kwargs need to contain a reserved word such as `in`,\n allow calling that function with the keyword as `in_`, such that function\n kwargs are rewritten to use the reserved word.\n "
] |
Please provide a description of the function: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, valida... | [
"\n Attempt multiple validators on an object.\n\n - If any pass, then all validation passes.\n - Otherwise, raise all of the errors.\n "
] |
Please provide a description of the function: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 t... | [
"extract the given tarball or zipfile to a tempdir and change\n the cwd to the new tempdir. Delete the tempdir at the end"
] |
Please provide a description of the function: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):
... | [
"if the given directory has just a single subdir, enter that"
] |
Please provide a description of the function: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\n is not entirely correct because we don't know the encoding of the\n given file but it's at least a chance to get metadata from the setup.py"
] |
Please provide a description of the function: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))
... | [
"run the extractmeta command via the setup.py in the given root_dir.\n the output of extractmeta is json and is stored in a tempfile\n which is then read in and returned as data"
] |
Please provide a description of the function: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\n\n :param archive_filename: a sdist archive file\n :param py_interpreter: The full path to the used python interpreter\n\n :returns: a json blob with metadata\n"
] |
Please provide a description of the function:def cimread(source, packageMap=None, nsURI=None, start_dict=None):
# Start the clock.
t0 = time()
#logger.info('##########################################################################')
logger.info('START of parsing file \"%s\"', source)
logger_e... | [
" CIM RDF/XML parser.\n\n @type source: File-like object or a path to a file.\n @param source: CIM RDF/XML file.\n @type profile: dict\n @param packageMap: Map of class name to PyCIM package name. All CIM\n classes are under the one namespace, but are arranged into sub-packages\n so a map from cla... |
Please provide a description of the function: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":
... | [
"\n Returns a map of prefix to namespace for the given XML file.\n\n "
] |
Please provide a description of the function:def get_cim_ns(namespaces):
try:
ns = namespaces['cim']
if ns.endswith('#'):
ns = ns[:-1]
except KeyError:
ns = ''
logger.error('No CIM namespace defined in input file.')
CIM16nsURI = 'http://iec.ch/TC57/2013/CIM-... | [
"\n Tries to obtain the CIM version from the given map of namespaces and\n returns the appropriate *nsURI* and *packageMap*.\n\n "
] |
Please provide a description of the function:def cimwrite(d, source, encoding="utf-8"):
# Start the clock
t0 = time()
w = XMLWriter(source, encoding)
# Write the XML declaration.
w.declaration()
# Add a '#' suffix to the CIM namespace URI if not present.
nsCIM = nsURI if nsURI[-1] ==... | [
"CIM RDF/XML serializer.\n\n @type d: dict\n @param d: Map of URIs to CIM objects.\n @type source: File or file-like object.\n @param source: This object must implement a C{write} method\n that takes an 8-bit string.\n @type encoding: string\n @param encoding: Character encoding defaults to \"u... |
Please provide a description of the function:def create_block(mc, block_id, subtype=None):
# Get player tile position and real position.
ptx, pty, ptz = mc.player.getTilePos()
px, py, pz = mc.player.getPos()
# Create block at current player tile location.
if subtype is None:
mc.setBlock... | [
"Build a block with the specified id and subtype under the player in the\n Minecraft world. Subtype is optional and can be specified as None to use\n the default subtype for the block.\n "
] |
Please provide a description of the function: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."
] |
Please provide a description of the function:def _write_frame(self, data):
assert data is not None and 0 < len(data) < 255, 'Data must be array of 1 to 255 bytes.'
# Build frame to send as:
# - SPI data write (0x01)
# - Preamble (0x00)
# - Start code (0x00, 0xFF)
... | [
"Write a frame to the PN532 with the specified data bytearray."
] |
Please provide a description of the function:def _read_data(self, count):
# Build a read request frame.
frame = bytearray(count)
frame[0] = PN532_SPI_DATAREAD
# Send the frame and return the response, ignoring the SPI header byte.
self._gpio.set_low(self._cs)
sel... | [
"Read a specified count of bytes from the PN532."
] |
Please provide a description of the function:def _read_frame(self, length):
# Read frame with expected length of data.
response = self._read_data(length+8)
logger.debug('Read frame: 0x{0}'.format(binascii.hexlify(response)))
# Check frame starts with 0x01 and then has 0x00FF (pr... | [
"Read a response frame from the PN532 of at most length bytes in size.\n Returns the data inside the frame if found, otherwise raises an exception\n if there is an error parsing the frame. Note that less than length bytes\n might be returned!\n "
] |
Please provide a description of the function:def _wait_ready(self, timeout_sec=1):
start = time.time()
# Send a SPI status read command and read response.
self._gpio.set_low(self._cs)
self._busy_wait_ms(2)
response = self._spi.transfer([PN532_SPI_STATREAD, 0x00])
... | [
"Wait until the PN532 is ready to receive commands. At most wait\n timeout_sec seconds for the PN532 to be ready. If the PN532 is ready\n before the timeout is exceeded then True will be returned, otherwise\n False is returned when the timeout is exceeded.\n "
] |
Please provide a description of the function:def call_function(self, command, response_length=0, params=[], timeout_sec=1):
# Build frame data with command and parameters.
data = bytearray(2+len(params))
data[0] = PN532_HOSTTOPN532
data[1] = command & 0xFF
data[2:] = p... | [
"Send specified command to the PN532 and expect up to response_length\n bytes back in a response. Note that less than the expected bytes might\n be returned! Params can optionally specify an array of bytes to send as\n parameters to the function call. Will wait up to timeout_secs seconds\n ... |
Please provide a description of the function:def begin(self):
# Assert CS pin low for a second for PN532 to be ready.
self._gpio.set_low(self._cs)
time.sleep(1.0)
# Call GetFirmwareVersion to sync up with the PN532. This might not be
# required but is done in the Arduin... | [
"Initialize communication with the PN532. Must be called before any\n other calls are made against the PN532.\n "
] |
Please provide a description of the function: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 sup... | [
"Call PN532 GetFirmwareVersion function and return a tuple with the IC,\n Ver, Rev, and Support values.\n "
] |
Please provide a description of the function:def read_passive_target(self, card_baud=PN532_MIFARE_ISO14443A, timeout_sec=1):
# Send passive read command for 1 card. Expect at most a 7 byte UUID.
response = self.call_function(PN532_COMMAND_INLISTPASSIVETARGET,
... | [
"Wait for a MiFare card to be available and return its UID when found.\n Will wait up to timeout_sec seconds and return None if no card is found,\n otherwise a bytearray with the UID of the found card is returned.\n "
] |
Please provide a description of the function:def mifare_classic_authenticate_block(self, uid, block_number, key_number, key):
# Build parameters for InDataExchange command to authenticate MiFare card.
uidlen = len(uid)
keylen = len(key)
params = bytearray(3+uidlen+keylen)
... | [
"Authenticate specified block number for a MiFare classic card. Uid\n should be a byte array with the UID of the card, block number should be\n the block to authenticate, key number should be the key type (like\n MIFARE_CMD_AUTH_A or MIFARE_CMD_AUTH_B), and key should be a byte array\n ... |
Please provide a description of the function:def mifare_classic_read_block(self, block_number):
# Send InDataExchange request to read block of MiFare data.
response = self.call_function(PN532_COMMAND_INDATAEXCHANGE,
params=[0x01, MIFARE_CMD_READ, block_numb... | [
"Read a block of data from the card. Block number should be the block\n to read. If the block is successfully read a bytearray of length 16 with\n data starting at the specified block will be returned. If the block is\n not read then None will be returned.\n "
] |
Please provide a description of the function: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!'
# Build parameters for InDataExchange command to do MiFare classic write.
params = bytearray(19)
... | [
"Write a block of data to the card. Block number should be the block\n to write and data should be a byte array of length 16 with the data to\n write. If the data is successfully written then True is returned,\n otherwise False is returned.\n "
] |
Please provide a description of the function: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.\n\n >>> _dirmatch('/home/foo/bar', '/home/foo/bar')\n True\n >>> _dirmatch('/home/foo/bar/', '/home/foo/bar')\n True\n >>> _dirmatch('/home/foo/bar/etc', '/home/foo/bar')\n True\n >>> _dirmatch('/home/foo/bar2', '/home/foo/bar')\n False\n >>> _di... |
Please provide a description of the function:def _virtualenv_sys(venv_path):
"obtain version and path info from a virtualenv."
executable = os.path.join(venv_path, env_bin_dir, 'python')
# Must use "executable" as the first argument rather than as the
# keyword argument "executable" to get correct value... | [] |
Please provide a description of the function: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\n useful as many of the flags are just combinations of other flags. The\n relationships are defined by the OS in ways that aren't semantically\n intuitive to this project.\n "
] |
Please provide a description of the function: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:
... | [
"Return an archive enumerator from a user-defined source, using a user-\n defined entry type.\n "
] |
Please provide a description of the function: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_fil... | [
"Return an enumerator that knows how to read a physical file."
] |
Please provide a description of the function: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).",
... | [
"Return an enumerator that knows how to read raw memory."
] |
Please provide a description of the function: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()
... | [
"A flexible pouring facility that knows how to enumerate entry data."
] |
Please provide a description of the function: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... | [
"Write physical files from entries."
] |
Please provide a description of the function: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."
] |
Please provide a description of the function: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(ar... | [
"Write data to archive. This will only be called with a non-empty string.\n "
] |
Please provide a description of the function:def _create(opener,
format_code,
files,
filter_code=None,
block_size=16384):
a = _archive_write_new()
_set_write_context(a, format_code, filter_code)
_LOGGER.debug("Opening archive (create).")
opener(a)
... | [
"Create an archive from a collection of files (not recursive)."
] |
Please provide a description of the function: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) | [
"\n Write the values to the ctrl_meas and ctrl_hum registers in the device\n ctrl_meas sets the pressure and temperature data acquistion options\n ctrl_hum sets the humidty oversampling and must be written to first\n "
] |
Please provide a description of the function:def _write_config(self):
normal_flag = False
if self._mode == MODE_NORMAL:
#Writes to the config register may be ignored while in Normal mode
normal_flag = True
self.mode = MODE_SLEEP #So we switch to Sleep mode fi... | [
"Write the value to the config register in the device "
] |
Please provide a description of the function: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 "
] |
Please provide a description of the function: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 "
] |
Please provide a description of the function: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:
... | [
"Typical time in milliseconds required to complete a measurement in normal mode"
] |
Please provide a description of the function:def pressure(self):
self._read_temperature()
# Algorithm from the BME280 driver
# https://github.com/BoschSensortec/BME280_driver/blob/master/bme280.c
adc = self._read24(_BME280_REGISTER_PRESSUREDATA) / 16 # lowest 4 bits get droppe... | [
"\n The compensated pressure in hectoPascals.\n returns None if pressure measurement is disabled\n "
] |
Please provide a description of the function:def humidity(self):
self._read_temperature()
hum = self._read_register(_BME280_REGISTER_HUMIDDATA, 2)
#print("Humidity data: ", hum)
adc = float(hum[0] << 8 | hum[1])
#print("adc:", adc)
# Algorithm from the BME280 dr... | [
"\n The relative humidity in RH %\n returns None if humidity measurement is disabled\n "
] |
Please provide a description of the function:def altitude(self):
pressure = self.pressure # in Si units for hPascal
return 44330 * (1.0 - math.pow(pressure / self.sea_level_pressure, 0.1903)) | [
"The altitude based on current ``pressure`` versus the sea level pressure\n (``sea_level_pressure``) - which you must enter ahead of time)"
] |
Please provide a description of the function: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_ca... | [
"Read & save the calibration coefficients"
] |
Please provide a description of the function: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."
] |
Please provide a description of the function: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... | [
"Creates an index of any type according to postData"
] |
Please provide a description of the function: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=docAttr... | [
"adds a vertex to the graph and returns it"
] |
Please provide a description of the function: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.stat... | [
"deletes a vertex from the graph as well as al linked edges"
] |
Please provide a description of the function: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)
... | [
"creates an edge between two documents"
] |
Please provide a description of the function: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._... | [] |
Please provide a description of the function: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) | [] |
Please provide a description of the function:def deleteEdge(self, edge, waitForSync = False) :
url = "%s/edge/%s" % (self.URL, edge._id)
r = self.connection.session.delete(url, params = {'waitForSync' : waitForSync})
if r.status_code == 200 or r.status_code == 202 :
return T... | [
"removes an edge from the graph"
] |
Please provide a description of the function:def traverse(self, startVertex, **kwargs) :
url = "%s/traversal" % self.database.URL
if type(startVertex) is DOC.Document :
startVertex_id = startVertex._id
else :
startVertex_id = startVertex
payload = {"sta... | [
"Traversal! see: https://docs.arangodb.com/HttpTraversal/README.html for a full list of the possible kwargs.\n The function must have as argument either: direction = \"outbout\"/\"any\"/\"inbound\" or expander = \"custom JS (see arangodb's doc)\".\n The function can't have both 'direction' and 'expand... |
Please provide a description of the function:def delete(self, _key) :
"removes a document from the cache"
try :
doc = self.cacheStore[_key]
doc.prev.nextDoc = doc.nextDoc
doc.nextDoc.prev = doc.prev
del(self.cacheStore[_key])
except KeyError :
... | [] |
Please provide a description of the function:def getChain(self) :
"returns a list of keys representing the chain of documents"
l = []
h = self.head
while h :
l.append(h._key)
h = h.nextDoc
return l | [] |
Please provide a description of the function:def stringify(self) :
"a pretty str version of getChain()"
l = []
h = self.head
while h :
l.append(str(h._key))
h = h.nextDoc
return "<->".join(l) | [] |
Please provide a description of the function:def validate(self, value) :
for v in self.validators :
v.validate(value)
return True | [
"checks the validity of 'value' given the lits of validators"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.