id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
22,000 | pipermerriam/flex | flex/validation/path.py | generate_path_parameters_validator | def generate_path_parameters_validator(api_path, path_parameters, context):
"""
Generates a validator function that given a path, validates that it against
the path parameters
"""
path_parameter_validator = functools.partial(
validate_path_parameters,
api_path=api_path,
path_parameters=path_parameters,
context=context,
)
return path_parameter_validator | python | 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 | [
"def",
"generate_path_parameters_validator",
"(",
"api_path",
",",
"path_parameters",
",",
"context",
")",
":",
"path_parameter_validator",
"=",
"functools",
".",
"partial",
"(",
"validate_path_parameters",
",",
"api_path",
"=",
"api_path",
",",
"path_parameters",
"=",
... | Generates a validator function that given a path, validates that it against
the path parameters | [
"Generates",
"a",
"validator",
"function",
"that",
"given",
"a",
"path",
"validates",
"that",
"it",
"against",
"the",
"path",
"parameters"
] | 233f8149fb851a6255753bcec948cb6fefb2723b | https://github.com/pipermerriam/flex/blob/233f8149fb851a6255753bcec948cb6fefb2723b/flex/validation/path.py#L8-L19 |
22,001 | pipermerriam/flex | flex/paths.py | escape_regex_special_chars | def escape_regex_special_chars(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.
"""
def substitute(string, replacements):
pattern, repl = replacements
return re.sub(pattern, repl, string)
return functools.reduce(substitute, REGEX_REPLACEMENTS, api_path) | python | 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) | [
"def",
"escape_regex_special_chars",
"(",
"api_path",
")",
":",
"def",
"substitute",
"(",
"string",
",",
"replacements",
")",
":",
"pattern",
",",
"repl",
"=",
"replacements",
"return",
"re",
".",
"sub",
"(",
"pattern",
",",
"repl",
",",
"string",
")",
"re... | 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. | [
"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",... | 233f8149fb851a6255753bcec948cb6fefb2723b | https://github.com/pipermerriam/flex/blob/233f8149fb851a6255753bcec948cb6fefb2723b/flex/paths.py#L26-L36 |
22,002 | pipermerriam/flex | flex/paths.py | construct_parameter_pattern | def construct_parameter_pattern(parameter):
"""
Given a parameter definition returns a regex pattern that will match that
part of the path.
"""
name = parameter['name']
type = parameter['type']
repeated = '[^/]'
if type == 'integer':
repeated = '\d'
return "(?P<{name}>{repeated}+)".format(name=name, repeated=repeated) | python | 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) | [
"def",
"construct_parameter_pattern",
"(",
"parameter",
")",
":",
"name",
"=",
"parameter",
"[",
"'name'",
"]",
"type",
"=",
"parameter",
"[",
"'type'",
"]",
"repeated",
"=",
"'[^/]'",
"if",
"type",
"==",
"'integer'",
":",
"repeated",
"=",
"'\\d'",
"return",... | Given a parameter definition returns a regex pattern that will match that
part of the path. | [
"Given",
"a",
"parameter",
"definition",
"returns",
"a",
"regex",
"pattern",
"that",
"will",
"match",
"that",
"part",
"of",
"the",
"path",
"."
] | 233f8149fb851a6255753bcec948cb6fefb2723b | https://github.com/pipermerriam/flex/blob/233f8149fb851a6255753bcec948cb6fefb2723b/flex/paths.py#L44-L57 |
22,003 | pipermerriam/flex | flex/paths.py | path_to_pattern | def path_to_pattern(api_path, parameters):
"""
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.
"""
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}$".format(pattern)
return pattern | python | 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}$".format(pattern)
return pattern | [
"def",
"path_to_pattern",
"(",
"api_path",
",",
"parameters",
")",
":",
"parts",
"=",
"re",
".",
"split",
"(",
"PARAMETER_REGEX",
",",
"api_path",
")",
"pattern",
"=",
"''",
".",
"join",
"(",
"(",
"process_path_part",
"(",
"part",
",",
"parameters",
")",
... | 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. | [
"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",
"... | 233f8149fb851a6255753bcec948cb6fefb2723b | https://github.com/pipermerriam/flex/blob/233f8149fb851a6255753bcec948cb6fefb2723b/flex/paths.py#L87-L101 |
22,004 | pipermerriam/flex | flex/paths.py | match_path_to_api_path | def match_path_to_api_path(path_definitions, target_path, base_path='',
context=None):
"""
Match a request or response path to one of the api paths.
Anything other than exactly one match is an error condition.
"""
if context is None:
context = {}
assert isinstance(context, collections.Mapping)
if target_path.startswith(base_path):
# Convert all of the api paths into Path instances for easier regex
# matching.
normalized_target_path = re.sub(NORMALIZE_SLASH_REGEX, '/',
target_path)
matching_api_paths = list()
matching_api_paths_regex = list()
for p, v in path_definitions.items():
# Doing this to help with case where we might have base_path
# being just /, and then the path starts with / as well.
full_path = re.sub(NORMALIZE_SLASH_REGEX, '/', base_path + p)
r = path_to_regex(
api_path=full_path,
path_parameters=extract_path_parameters(v),
operation_parameters=extract_operation_parameters(v),
context=context,
)
if full_path == normalized_target_path:
matching_api_paths.append(p)
elif r.match(normalized_target_path):
matching_api_paths_regex.\
append((p, r.match(normalized_target_path)))
# Keep it consistent with the previous behavior
target_path = target_path[len(base_path):]
else:
matching_api_paths = []
matching_api_paths_regex = []
if not matching_api_paths and not matching_api_paths_regex:
fstr = MESSAGES['path']['no_matching_paths_found'].format(target_path)
raise LookupError(fstr)
elif len(matching_api_paths) == 1:
return matching_api_paths[0]
elif len(matching_api_paths) > 1:
raise MultiplePathsFound(
MESSAGES['path']['multiple_paths_found'].format(
target_path, [v[0] for v in matching_api_paths],
)
)
elif len(matching_api_paths_regex) == 1:
return matching_api_paths_regex[0][0]
elif len(matching_api_paths_regex) > 1:
# TODO: This area needs improved logic.
# We check to see if any of the matched paths is longers than
# the others. If so, we *assume* it is the correct match. This is
# going to be prone to false positives. in certain cases.
matches_by_path_size = collections.defaultdict(list)
for path, match in matching_api_paths_regex:
matches_by_path_size[len(path)].append(path)
longest_match = max(matches_by_path_size.keys())
if len(matches_by_path_size[longest_match]) == 1:
return matches_by_path_size[longest_match][0]
raise MultiplePathsFound(
MESSAGES['path']['multiple_paths_found'].format(
target_path, [v[0] for v in matching_api_paths_regex],
)
)
else:
return matching_api_paths_regex[0][0] | python | 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 all of the api paths into Path instances for easier regex
# matching.
normalized_target_path = re.sub(NORMALIZE_SLASH_REGEX, '/',
target_path)
matching_api_paths = list()
matching_api_paths_regex = list()
for p, v in path_definitions.items():
# Doing this to help with case where we might have base_path
# being just /, and then the path starts with / as well.
full_path = re.sub(NORMALIZE_SLASH_REGEX, '/', base_path + p)
r = path_to_regex(
api_path=full_path,
path_parameters=extract_path_parameters(v),
operation_parameters=extract_operation_parameters(v),
context=context,
)
if full_path == normalized_target_path:
matching_api_paths.append(p)
elif r.match(normalized_target_path):
matching_api_paths_regex.\
append((p, r.match(normalized_target_path)))
# Keep it consistent with the previous behavior
target_path = target_path[len(base_path):]
else:
matching_api_paths = []
matching_api_paths_regex = []
if not matching_api_paths and not matching_api_paths_regex:
fstr = MESSAGES['path']['no_matching_paths_found'].format(target_path)
raise LookupError(fstr)
elif len(matching_api_paths) == 1:
return matching_api_paths[0]
elif len(matching_api_paths) > 1:
raise MultiplePathsFound(
MESSAGES['path']['multiple_paths_found'].format(
target_path, [v[0] for v in matching_api_paths],
)
)
elif len(matching_api_paths_regex) == 1:
return matching_api_paths_regex[0][0]
elif len(matching_api_paths_regex) > 1:
# TODO: This area needs improved logic.
# We check to see if any of the matched paths is longers than
# the others. If so, we *assume* it is the correct match. This is
# going to be prone to false positives. in certain cases.
matches_by_path_size = collections.defaultdict(list)
for path, match in matching_api_paths_regex:
matches_by_path_size[len(path)].append(path)
longest_match = max(matches_by_path_size.keys())
if len(matches_by_path_size[longest_match]) == 1:
return matches_by_path_size[longest_match][0]
raise MultiplePathsFound(
MESSAGES['path']['multiple_paths_found'].format(
target_path, [v[0] for v in matching_api_paths_regex],
)
)
else:
return matching_api_paths_regex[0][0] | [
"def",
"match_path_to_api_path",
"(",
"path_definitions",
",",
"target_path",
",",
"base_path",
"=",
"''",
",",
"context",
"=",
"None",
")",
":",
"if",
"context",
"is",
"None",
":",
"context",
"=",
"{",
"}",
"assert",
"isinstance",
"(",
"context",
",",
"co... | Match a request or response path to one of the api paths.
Anything other than exactly one match is an error condition. | [
"Match",
"a",
"request",
"or",
"response",
"path",
"to",
"one",
"of",
"the",
"api",
"paths",
"."
] | 233f8149fb851a6255753bcec948cb6fefb2723b | https://github.com/pipermerriam/flex/blob/233f8149fb851a6255753bcec948cb6fefb2723b/flex/paths.py#L140-L209 |
22,005 | pipermerriam/flex | flex/validation/request.py | validate_request | def validate_request(request, schema):
"""
Request validation does the following steps.
1. validate that the path matches one of the defined paths in the schema.
2. validate that the request method conforms to a supported methods for the given path.
3. validate that the request parameters conform to the parameter
definitions for the operation definition.
"""
with ErrorDict() as errors:
# 1
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 # this causes an exception to be raised since errors is no longer falsy.
path_definition = schema['paths'][api_path] or {}
if not path_definition:
# TODO: is it valid to not have a definition for a path?
return
# 2
try:
operation_definition = validate_request_method_to_operation(
request_method=request.method,
path_definition=path_definition,
)
except ValidationError as err:
errors['method'].add_error(err.detail)
return
if operation_definition is None:
# TODO: is this compliant with swagger, can path operations have a null
# definition?
return
# 3
operation_validators = construct_operation_validators(
api_path=api_path,
path_definition=path_definition,
operation_definition=operation_definition,
context=schema,
)
try:
validate_operation(request, operation_validators, context=schema)
except ValidationError as err:
errors['method'].add_error(err.detail) | python | 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 ValidationError as err:
errors['path'].add_error(err.detail)
return # this causes an exception to be raised since errors is no longer falsy.
path_definition = schema['paths'][api_path] or {}
if not path_definition:
# TODO: is it valid to not have a definition for a path?
return
# 2
try:
operation_definition = validate_request_method_to_operation(
request_method=request.method,
path_definition=path_definition,
)
except ValidationError as err:
errors['method'].add_error(err.detail)
return
if operation_definition is None:
# TODO: is this compliant with swagger, can path operations have a null
# definition?
return
# 3
operation_validators = construct_operation_validators(
api_path=api_path,
path_definition=path_definition,
operation_definition=operation_definition,
context=schema,
)
try:
validate_operation(request, operation_validators, context=schema)
except ValidationError as err:
errors['method'].add_error(err.detail) | [
"def",
"validate_request",
"(",
"request",
",",
"schema",
")",
":",
"with",
"ErrorDict",
"(",
")",
"as",
"errors",
":",
"# 1",
"try",
":",
"api_path",
"=",
"validate_path_to_api_path",
"(",
"path",
"=",
"request",
".",
"path",
",",
"context",
"=",
"schema"... | Request validation does the following steps.
1. validate that the path matches one of the defined paths in the schema.
2. validate that the request method conforms to a supported methods for the given path.
3. validate that the request parameters conform to the parameter
definitions for the operation definition. | [
"Request",
"validation",
"does",
"the",
"following",
"steps",
"."
] | 233f8149fb851a6255753bcec948cb6fefb2723b | https://github.com/pipermerriam/flex/blob/233f8149fb851a6255753bcec948cb6fefb2723b/flex/validation/request.py#L13-L65 |
22,006 | pipermerriam/flex | flex/http.py | normalize_request | def normalize_request(request):
"""
Given a request, normalize it to the internal Request class.
"""
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") | python | 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") | [
"def",
"normalize_request",
"(",
"request",
")",
":",
"if",
"isinstance",
"(",
"request",
",",
"Request",
")",
":",
"return",
"request",
"for",
"normalizer",
"in",
"REQUEST_NORMALIZERS",
":",
"try",
":",
"return",
"normalizer",
"(",
"request",
")",
"except",
... | Given a request, normalize it to the internal Request class. | [
"Given",
"a",
"request",
"normalize",
"it",
"to",
"the",
"internal",
"Request",
"class",
"."
] | 233f8149fb851a6255753bcec948cb6fefb2723b | https://github.com/pipermerriam/flex/blob/233f8149fb851a6255753bcec948cb6fefb2723b/flex/http.py#L279-L292 |
22,007 | pipermerriam/flex | flex/http.py | normalize_response | def normalize_response(response, request=None):
"""
Given a response, normalize it to the internal Response class. This also
involves normalizing the associated request object.
"""
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)
except TypeError:
continue
raise ValueError("Unable to normalize the provided response") | python | 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)
except TypeError:
continue
raise ValueError("Unable to normalize the provided response") | [
"def",
"normalize_response",
"(",
"response",
",",
"request",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"response",
",",
"Response",
")",
":",
"return",
"response",
"if",
"request",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"request",
","... | Given a response, normalize it to the internal Response class. This also
involves normalizing the associated request object. | [
"Given",
"a",
"response",
"normalize",
"it",
"to",
"the",
"internal",
"Response",
"class",
".",
"This",
"also",
"involves",
"normalizing",
"the",
"associated",
"request",
"object",
"."
] | 233f8149fb851a6255753bcec948cb6fefb2723b | https://github.com/pipermerriam/flex/blob/233f8149fb851a6255753bcec948cb6fefb2723b/flex/http.py#L474-L490 |
22,008 | pipermerriam/flex | flex/validation/operation.py | generate_header_validator | def generate_header_validator(headers, context, **kwargs):
"""
Generates a validation function that will validate a dictionary of headers.
"""
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(header_definition, context=context),
)
validators.add_property_validator(
header_definition['name'],
chain_reduce_partial(
header_processor,
header_validator,
),
)
return generate_object_validator(field_validators=validators) | python | 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(header_definition, context=context),
)
validators.add_property_validator(
header_definition['name'],
chain_reduce_partial(
header_processor,
header_validator,
),
)
return generate_object_validator(field_validators=validators) | [
"def",
"generate_header_validator",
"(",
"headers",
",",
"context",
",",
"*",
"*",
"kwargs",
")",
":",
"validators",
"=",
"ValidationDict",
"(",
")",
"for",
"header_definition",
"in",
"headers",
":",
"header_processor",
"=",
"generate_value_processor",
"(",
"conte... | Generates a validation function that will validate a dictionary of headers. | [
"Generates",
"a",
"validation",
"function",
"that",
"will",
"validate",
"a",
"dictionary",
"of",
"headers",
"."
] | 233f8149fb851a6255753bcec948cb6fefb2723b | https://github.com/pipermerriam/flex/blob/233f8149fb851a6255753bcec948cb6fefb2723b/flex/validation/operation.py#L62-L82 |
22,009 | pipermerriam/flex | flex/validation/operation.py | generate_parameters_validator | def generate_parameters_validator(api_path, path_definition, parameters,
context, **kwargs):
"""
Generates a validator function to validate.
- request.path against the path parameters.
- request.query against the query parameters.
- request.headers against the header parameters.
- TODO: request.body against the body parameters.
- TODO: request.formData against any form data.
"""
# TODO: figure out how to merge this with the same code in response
# validation.
validators = ValidationDict()
path_level_parameters = dereference_parameter_list(
path_definition.get('parameters', []),
context,
)
operation_level_parameters = dereference_parameter_list(
parameters,
context,
)
all_parameters = merge_parameter_lists(
path_level_parameters,
operation_level_parameters,
)
# PATH
in_path_parameters = filter_parameters(all_parameters, in_=PATH)
validators.add_validator(
'path',
chain_reduce_partial(
attrgetter('path'),
generate_path_parameters_validator(api_path, in_path_parameters, context),
),
)
# QUERY
in_query_parameters = filter_parameters(all_parameters, in_=QUERY)
validators.add_validator(
'query',
chain_reduce_partial(
attrgetter('query_data'),
functools.partial(
validate_query_parameters,
query_parameters=in_query_parameters,
context=context,
),
),
)
# HEADERS
in_header_parameters = filter_parameters(all_parameters, in_=HEADER)
validators.add_validator(
'headers',
chain_reduce_partial(
attrgetter('headers'),
generate_header_validator(in_header_parameters, context),
),
)
# FORM_DATA
# in_form_data_parameters = filter_parameters(all_parameters, in_=FORM_DATA)
# validators.add_validator(
# 'form_data',
# chain_reduce_partial(
# attrgetter('data'),
# generate_form_data_validator(in_form_data_parameters, context),
# )
# )
# REQUEST_BODY
in_request_body_parameters = filter_parameters(all_parameters, in_=BODY)
validators.add_validator(
'request_body',
chain_reduce_partial(
attrgetter('data'),
generate_request_body_validator(in_request_body_parameters, context),
)
)
return generate_object_validator(field_validators=validators) | python | 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_parameters = dereference_parameter_list(
path_definition.get('parameters', []),
context,
)
operation_level_parameters = dereference_parameter_list(
parameters,
context,
)
all_parameters = merge_parameter_lists(
path_level_parameters,
operation_level_parameters,
)
# PATH
in_path_parameters = filter_parameters(all_parameters, in_=PATH)
validators.add_validator(
'path',
chain_reduce_partial(
attrgetter('path'),
generate_path_parameters_validator(api_path, in_path_parameters, context),
),
)
# QUERY
in_query_parameters = filter_parameters(all_parameters, in_=QUERY)
validators.add_validator(
'query',
chain_reduce_partial(
attrgetter('query_data'),
functools.partial(
validate_query_parameters,
query_parameters=in_query_parameters,
context=context,
),
),
)
# HEADERS
in_header_parameters = filter_parameters(all_parameters, in_=HEADER)
validators.add_validator(
'headers',
chain_reduce_partial(
attrgetter('headers'),
generate_header_validator(in_header_parameters, context),
),
)
# FORM_DATA
# in_form_data_parameters = filter_parameters(all_parameters, in_=FORM_DATA)
# validators.add_validator(
# 'form_data',
# chain_reduce_partial(
# attrgetter('data'),
# generate_form_data_validator(in_form_data_parameters, context),
# )
# )
# REQUEST_BODY
in_request_body_parameters = filter_parameters(all_parameters, in_=BODY)
validators.add_validator(
'request_body',
chain_reduce_partial(
attrgetter('data'),
generate_request_body_validator(in_request_body_parameters, context),
)
)
return generate_object_validator(field_validators=validators) | [
"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",
... | Generates a validator function to validate.
- request.path against the path parameters.
- request.query against the query parameters.
- request.headers against the header parameters.
- TODO: request.body against the body parameters.
- TODO: request.formData against any form data. | [
"Generates",
"a",
"validator",
"function",
"to",
"validate",
"."
] | 233f8149fb851a6255753bcec948cb6fefb2723b | https://github.com/pipermerriam/flex/blob/233f8149fb851a6255753bcec948cb6fefb2723b/flex/validation/operation.py#L100-L182 |
22,010 | pipermerriam/flex | flex/decorators.py | partial_safe_wraps | def partial_safe_wraps(wrapped_func, *args, **kwargs):
"""
A version of `functools.wraps` that is safe to wrap a partial in.
"""
if isinstance(wrapped_func, functools.partial):
return partial_safe_wraps(wrapped_func.func)
else:
return functools.wraps(wrapped_func) | python | 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) | [
"def",
"partial_safe_wraps",
"(",
"wrapped_func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"wrapped_func",
",",
"functools",
".",
"partial",
")",
":",
"return",
"partial_safe_wraps",
"(",
"wrapped_func",
".",
"func",
")",... | A version of `functools.wraps` that is safe to wrap a partial in. | [
"A",
"version",
"of",
"functools",
".",
"wraps",
"that",
"is",
"safe",
"to",
"wrap",
"a",
"partial",
"in",
"."
] | 233f8149fb851a6255753bcec948cb6fefb2723b | https://github.com/pipermerriam/flex/blob/233f8149fb851a6255753bcec948cb6fefb2723b/flex/decorators.py#L10-L17 |
22,011 | pipermerriam/flex | flex/decorators.py | skip_if_empty | def skip_if_empty(func):
"""
Decorator for validation functions which makes them pass if the value
passed in is the EMPTY sentinal value.
"""
@partial_safe_wraps(func)
def inner(value, *args, **kwargs):
if value is EMPTY:
return
else:
return func(value, *args, **kwargs)
return inner | python | 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 | [
"def",
"skip_if_empty",
"(",
"func",
")",
":",
"@",
"partial_safe_wraps",
"(",
"func",
")",
"def",
"inner",
"(",
"value",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"value",
"is",
"EMPTY",
":",
"return",
"else",
":",
"return",
"func",... | Decorator for validation functions which makes them pass if the value
passed in is the EMPTY sentinal value. | [
"Decorator",
"for",
"validation",
"functions",
"which",
"makes",
"them",
"pass",
"if",
"the",
"value",
"passed",
"in",
"is",
"the",
"EMPTY",
"sentinal",
"value",
"."
] | 233f8149fb851a6255753bcec948cb6fefb2723b | https://github.com/pipermerriam/flex/blob/233f8149fb851a6255753bcec948cb6fefb2723b/flex/decorators.py#L42-L53 |
22,012 | pipermerriam/flex | flex/decorators.py | rewrite_reserved_words | def rewrite_reserved_words(func):
"""
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.
"""
@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 | python | 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 | [
"def",
"rewrite_reserved_words",
"(",
"func",
")",
":",
"@",
"partial_safe_wraps",
"(",
"func",
")",
"def",
"inner",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"word",
"in",
"RESERVED_WORDS",
":",
"key",
"=",
"\"{0}_\"",
".",
"format",
... | 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. | [
"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",
... | 233f8149fb851a6255753bcec948cb6fefb2723b | https://github.com/pipermerriam/flex/blob/233f8149fb851a6255753bcec948cb6fefb2723b/flex/decorators.py#L74-L87 |
22,013 | pipermerriam/flex | flex/validation/utils.py | any_validator | def any_validator(obj, validators, **kwargs):
"""
Attempt multiple validators on an object.
- If any pass, then all validation passes.
- Otherwise, raise all of the errors.
"""
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 ValidationError as err:
errors[key] = err.detail
else:
break
else:
if len(errors) == 1:
# Special case for a single error. Just raise it as if it was the
# only validator run.
error = errors.values()[0]
raise ValidationError(error)
else:
# Raise all of the errors with the key namespaces.
errors.raise_() | python | 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 ValidationError as err:
errors[key] = err.detail
else:
break
else:
if len(errors) == 1:
# Special case for a single error. Just raise it as if it was the
# only validator run.
error = errors.values()[0]
raise ValidationError(error)
else:
# Raise all of the errors with the key namespaces.
errors.raise_() | [
"def",
"any_validator",
"(",
"obj",
",",
"validators",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"len",
"(",
"validators",
")",
">",
"1",
":",
"raise",
"ValueError",
"(",
"\"any_validator requires at least 2 validator. Only got \"",
"\"{0}\"",
".",
"forma... | Attempt multiple validators on an object.
- If any pass, then all validation passes.
- Otherwise, raise all of the errors. | [
"Attempt",
"multiple",
"validators",
"on",
"an",
"object",
"."
] | 233f8149fb851a6255753bcec948cb6fefb2723b | https://github.com/pipermerriam/flex/blob/233f8149fb851a6255753bcec948cb6fefb2723b/flex/validation/utils.py#L9-L37 |
22,014 | toabctl/metaextract | metaextract/utils.py | _extract_to_tempdir | def _extract_to_tempdir(archive_filename):
"""extract the given tarball or zipfile to a tempdir and change
the cwd to the new tempdir. Delete the tempdir at the end"""
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 tarfile.open(archive_filename) as f:
f.extractall(tempdir)
elif zipfile.is_zipfile(archive_filename):
with zipfile.ZipFile(archive_filename) as f:
f.extractall(tempdir)
else:
raise Exception("Can not extract '%s'. "
"Not a tar or zip file" % archive_filename)
os.chdir(tempdir)
yield tempdir
finally:
os.chdir(current_cwd)
shutil.rmtree(tempdir) | python | 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 tarfile.open(archive_filename) as f:
f.extractall(tempdir)
elif zipfile.is_zipfile(archive_filename):
with zipfile.ZipFile(archive_filename) as f:
f.extractall(tempdir)
else:
raise Exception("Can not extract '%s'. "
"Not a tar or zip file" % archive_filename)
os.chdir(tempdir)
yield tempdir
finally:
os.chdir(current_cwd)
shutil.rmtree(tempdir) | [
"def",
"_extract_to_tempdir",
"(",
"archive_filename",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"archive_filename",
")",
":",
"raise",
"Exception",
"(",
"\"Archive '%s' does not exist\"",
"%",
"(",
"archive_filename",
")",
")",
"tempdir",
"=... | extract the given tarball or zipfile to a tempdir and change
the cwd to the new tempdir. Delete the tempdir at the end | [
"extract",
"the",
"given",
"tarball",
"or",
"zipfile",
"to",
"a",
"tempdir",
"and",
"change",
"the",
"cwd",
"to",
"the",
"new",
"tempdir",
".",
"Delete",
"the",
"tempdir",
"at",
"the",
"end"
] | 0515490b5983d888bbbaec5fdb5a0a4214743335 | https://github.com/toabctl/metaextract/blob/0515490b5983d888bbbaec5fdb5a0a4214743335/metaextract/utils.py#L37-L59 |
22,015 | toabctl/metaextract | metaextract/utils.py | _enter_single_subdir | def _enter_single_subdir(root_dir):
"""if the given directory has just a single subdir, enter that"""
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)
yield dest_dir
finally:
os.chdir(current_cwd) | python | 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)
yield dest_dir
finally:
os.chdir(current_cwd) | [
"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",
")",
"==",
... | if the given directory has just a single subdir, enter that | [
"if",
"the",
"given",
"directory",
"has",
"just",
"a",
"single",
"subdir",
"enter",
"that"
] | 0515490b5983d888bbbaec5fdb5a0a4214743335 | https://github.com/toabctl/metaextract/blob/0515490b5983d888bbbaec5fdb5a0a4214743335/metaextract/utils.py#L63-L78 |
22,016 | toabctl/metaextract | metaextract/utils.py | _set_file_encoding_utf8 | def _set_file_encoding_utf8(filename):
"""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"""
with open(filename, 'r+') as f:
content = f.read()
f.seek(0, 0)
f.write("# -*- coding: utf-8 -*-\n" + content) | python | 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) | [
"def",
"_set_file_encoding_utf8",
"(",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'r+'",
")",
"as",
"f",
":",
"content",
"=",
"f",
".",
"read",
"(",
")",
"f",
".",
"seek",
"(",
"0",
",",
"0",
")",
"f",
".",
"write",
"(",
"\"# -*... | 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 | [
"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",
... | 0515490b5983d888bbbaec5fdb5a0a4214743335 | https://github.com/toabctl/metaextract/blob/0515490b5983d888bbbaec5fdb5a0a4214743335/metaextract/utils.py#L81-L88 |
22,017 | toabctl/metaextract | metaextract/utils.py | _setup_py_run_from_dir | def _setup_py_run_from_dir(root_dir, py_interpreter):
"""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"""
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))
# generate a temporary json file which contains the metadata
output_json = tempfile.NamedTemporaryFile()
cmd = "%s setup.py -q --command-packages metaextract " \
"metaextract -o %s " % (py_interpreter, output_json.name)
try:
subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True)
except subprocess.CalledProcessError:
# try again with a encoding in setup.py
_set_file_encoding_utf8("setup.py")
subprocess.check_output(cmd, shell=True)
# read json file and return data
with open(output_json.name, "r") as f:
data = json.loads(f.read())
# sort some of the keys if the dict values are lists
for key in ['data_files', 'entry_points', 'extras_require',
'install_requires', 'setup_requires', 'scripts',
'tests_require', 'tests_suite']:
if key in data['data'] and isinstance(data['data'][key], list):
data['data'][key] = sorted(data['data'][key])
return data | python | 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))
# generate a temporary json file which contains the metadata
output_json = tempfile.NamedTemporaryFile()
cmd = "%s setup.py -q --command-packages metaextract " \
"metaextract -o %s " % (py_interpreter, output_json.name)
try:
subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True)
except subprocess.CalledProcessError:
# try again with a encoding in setup.py
_set_file_encoding_utf8("setup.py")
subprocess.check_output(cmd, shell=True)
# read json file and return data
with open(output_json.name, "r") as f:
data = json.loads(f.read())
# sort some of the keys if the dict values are lists
for key in ['data_files', 'entry_points', 'extras_require',
'install_requires', 'setup_requires', 'scripts',
'tests_require', 'tests_suite']:
if key in data['data'] and isinstance(data['data'][key], list):
data['data'][key] = sorted(data['data'][key])
return data | [
"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\"",
")... | 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 | [
"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",... | 0515490b5983d888bbbaec5fdb5a0a4214743335 | https://github.com/toabctl/metaextract/blob/0515490b5983d888bbbaec5fdb5a0a4214743335/metaextract/utils.py#L91-L121 |
22,018 | toabctl/metaextract | metaextract/utils.py | from_archive | def from_archive(archive_filename, py_interpreter=sys.executable):
"""extract metadata from a given sdist archive file
:param archive_filename: a sdist archive file
:param py_interpreter: The full path to the used python interpreter
:returns: a json blob with metadata
"""
with _extract_to_tempdir(archive_filename) as root_dir:
data = _setup_py_run_from_dir(root_dir, py_interpreter)
return data | python | 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 | [
"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_int... | extract metadata from a given sdist archive file
:param archive_filename: a sdist archive file
:param py_interpreter: The full path to the used python interpreter
:returns: a json blob with metadata | [
"extract",
"metadata",
"from",
"a",
"given",
"sdist",
"archive",
"file"
] | 0515490b5983d888bbbaec5fdb5a0a4214743335 | https://github.com/toabctl/metaextract/blob/0515490b5983d888bbbaec5fdb5a0a4214743335/metaextract/utils.py#L125-L135 |
22,019 | rwl/PyCIM | PyCIM/RDFXMLReader.py | xmlns | def xmlns(source):
"""
Returns a map of prefix to namespace for the given XML file.
"""
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
# Reset stream
if hasattr(source, "seek"):
source.seek(0)
return namespaces | python | 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
# Reset stream
if hasattr(source, "seek"):
source.seek(0)
return namespaces | [
"def",
"xmlns",
"(",
"source",
")",
":",
"namespaces",
"=",
"{",
"}",
"events",
"=",
"(",
"\"end\"",
",",
"\"start-ns\"",
",",
"\"end-ns\"",
")",
"for",
"(",
"event",
",",
"elem",
")",
"in",
"iterparse",
"(",
"source",
",",
"events",
")",
":",
"if",
... | Returns a map of prefix to namespace for the given XML file. | [
"Returns",
"a",
"map",
"of",
"prefix",
"to",
"namespace",
"for",
"the",
"given",
"XML",
"file",
"."
] | 4a12ebb5a7fb03c7790d396910daef9b97c4ef99 | https://github.com/rwl/PyCIM/blob/4a12ebb5a7fb03c7790d396910daef9b97c4ef99/PyCIM/RDFXMLReader.py#L226-L244 |
22,020 | adafruit/Adafruit_Python_PN532 | examples/mcpi_listen.py | create_block | def create_block(mc, block_id, subtype=None):
"""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.
"""
# 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(ptx, pty, ptz, block_id)
else:
mc.setBlock(ptx, pty, ptz, block_id, subtype)
# Move the player's real positon up one block.
mc.player.setPos(px, py+1, pz) | python | 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(ptx, pty, ptz, block_id)
else:
mc.setBlock(ptx, pty, ptz, block_id, subtype)
# Move the player's real positon up one block.
mc.player.setPos(px, py+1, pz) | [
"def",
"create_block",
"(",
"mc",
",",
"block_id",
",",
"subtype",
"=",
"None",
")",
":",
"# Get player tile position and real position.",
"ptx",
",",
"pty",
",",
"ptz",
"=",
"mc",
".",
"player",
".",
"getTilePos",
"(",
")",
"px",
",",
"py",
",",
"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. | [
"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... | 343521a8ec842ea82f680a5ed868fee16e9609bd | https://github.com/adafruit/Adafruit_Python_PN532/blob/343521a8ec842ea82f680a5ed868fee16e9609bd/examples/mcpi_listen.py#L48-L62 |
22,021 | adafruit/Adafruit_Python_PN532 | Adafruit_PN532/PN532.py | PN532._busy_wait_ms | def _busy_wait_ms(self, ms):
"""Busy wait for the specified number of milliseconds."""
start = time.time()
delta = ms/1000.0
while (time.time() - start) <= delta:
pass | python | def _busy_wait_ms(self, ms):
start = time.time()
delta = ms/1000.0
while (time.time() - start) <= delta:
pass | [
"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. | [
"Busy",
"wait",
"for",
"the",
"specified",
"number",
"of",
"milliseconds",
"."
] | 343521a8ec842ea82f680a5ed868fee16e9609bd | https://github.com/adafruit/Adafruit_Python_PN532/blob/343521a8ec842ea82f680a5ed868fee16e9609bd/Adafruit_PN532/PN532.py#L191-L196 |
22,022 | adafruit/Adafruit_Python_PN532 | Adafruit_PN532/PN532.py | PN532._write_frame | def _write_frame(self, data):
"""Write a frame to the PN532 with the specified data bytearray."""
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)
# - Command length (1 byte)
# - Command length checksum
# - Command bytes
# - Checksum
# - Postamble (0x00)
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] = length & 0xFF
frame[5] = self._uint8_add(~length, 1)
frame[6:-2] = data
checksum = reduce(self._uint8_add, data, 0xFF)
frame[-2] = ~checksum & 0xFF
frame[-1] = PN532_POSTAMBLE
# Send frame.
logger.debug('Write frame: 0x{0}'.format(binascii.hexlify(frame)))
self._gpio.set_low(self._cs)
self._busy_wait_ms(2)
self._spi.write(frame)
self._gpio.set_high(self._cs) | python | 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)
# - Command length (1 byte)
# - Command length checksum
# - Command bytes
# - Checksum
# - Postamble (0x00)
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] = length & 0xFF
frame[5] = self._uint8_add(~length, 1)
frame[6:-2] = data
checksum = reduce(self._uint8_add, data, 0xFF)
frame[-2] = ~checksum & 0xFF
frame[-1] = PN532_POSTAMBLE
# Send frame.
logger.debug('Write frame: 0x{0}'.format(binascii.hexlify(frame)))
self._gpio.set_low(self._cs)
self._busy_wait_ms(2)
self._spi.write(frame)
self._gpio.set_high(self._cs) | [
"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)",
"# - P... | Write a frame to the PN532 with the specified data bytearray. | [
"Write",
"a",
"frame",
"to",
"the",
"PN532",
"with",
"the",
"specified",
"data",
"bytearray",
"."
] | 343521a8ec842ea82f680a5ed868fee16e9609bd | https://github.com/adafruit/Adafruit_Python_PN532/blob/343521a8ec842ea82f680a5ed868fee16e9609bd/Adafruit_PN532/PN532.py#L198-L227 |
22,023 | adafruit/Adafruit_Python_PN532 | Adafruit_PN532/PN532.py | PN532._read_data | def _read_data(self, count):
"""Read a specified count of bytes from the PN532."""
# 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)
self._busy_wait_ms(2)
response = self._spi.transfer(frame)
self._gpio.set_high(self._cs)
return response | python | 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)
self._busy_wait_ms(2)
response = self._spi.transfer(frame)
self._gpio.set_high(self._cs)
return response | [
"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",
... | Read a specified count of bytes from the PN532. | [
"Read",
"a",
"specified",
"count",
"of",
"bytes",
"from",
"the",
"PN532",
"."
] | 343521a8ec842ea82f680a5ed868fee16e9609bd | https://github.com/adafruit/Adafruit_Python_PN532/blob/343521a8ec842ea82f680a5ed868fee16e9609bd/Adafruit_PN532/PN532.py#L229-L239 |
22,024 | adafruit/Adafruit_Python_PN532 | Adafruit_PN532/PN532.py | PN532._read_frame | def _read_frame(self, length):
"""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!
"""
# 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 (preceeded by optional
# zeros).
if response[0] != 0x01:
raise RuntimeError('Response frame does not start with 0x01!')
# Swallow all the 0x00 values that preceed 0xFF.
offset = 1
while response[offset] == 0x00:
offset += 1
if offset >= len(response):
raise RuntimeError('Response frame preamble does not contain 0x00FF!')
if response[offset] != 0xFF:
raise RuntimeError('Response frame preamble does not contain 0x00FF!')
offset += 1
if offset >= len(response):
raise RuntimeError('Response contains no data!')
# Check length & length checksum match.
frame_len = response[offset]
if (frame_len + response[offset+1]) & 0xFF != 0:
raise RuntimeError('Response length checksum did not match length!')
# Check frame checksum value matches bytes.
checksum = reduce(self._uint8_add, response[offset+2:offset+2+frame_len+1], 0)
if checksum != 0:
raise RuntimeError('Response checksum did not match expected value!')
# Return frame data.
return response[offset+2:offset+2+frame_len] | python | 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 (preceeded by optional
# zeros).
if response[0] != 0x01:
raise RuntimeError('Response frame does not start with 0x01!')
# Swallow all the 0x00 values that preceed 0xFF.
offset = 1
while response[offset] == 0x00:
offset += 1
if offset >= len(response):
raise RuntimeError('Response frame preamble does not contain 0x00FF!')
if response[offset] != 0xFF:
raise RuntimeError('Response frame preamble does not contain 0x00FF!')
offset += 1
if offset >= len(response):
raise RuntimeError('Response contains no data!')
# Check length & length checksum match.
frame_len = response[offset]
if (frame_len + response[offset+1]) & 0xFF != 0:
raise RuntimeError('Response length checksum did not match length!')
# Check frame checksum value matches bytes.
checksum = reduce(self._uint8_add, response[offset+2:offset+2+frame_len+1], 0)
if checksum != 0:
raise RuntimeError('Response checksum did not match expected value!')
# Return frame data.
return response[offset+2:offset+2+frame_len] | [
"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"... | 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! | [
"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",
"e... | 343521a8ec842ea82f680a5ed868fee16e9609bd | https://github.com/adafruit/Adafruit_Python_PN532/blob/343521a8ec842ea82f680a5ed868fee16e9609bd/Adafruit_PN532/PN532.py#L241-L274 |
22,025 | adafruit/Adafruit_Python_PN532 | Adafruit_PN532/PN532.py | PN532._wait_ready | def _wait_ready(self, timeout_sec=1):
"""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.
"""
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])
self._gpio.set_high(self._cs)
# Loop until a ready response is received.
while response[1] != PN532_SPI_READY:
# Check if the timeout has been exceeded.
if time.time() - start >= timeout_sec:
return False
# Wait a little while and try reading the status again.
time.sleep(0.01)
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)
return True | python | 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])
self._gpio.set_high(self._cs)
# Loop until a ready response is received.
while response[1] != PN532_SPI_READY:
# Check if the timeout has been exceeded.
if time.time() - start >= timeout_sec:
return False
# Wait a little while and try reading the status again.
time.sleep(0.01)
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)
return True | [
"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",
".",
... | 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. | [
"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",
"exc... | 343521a8ec842ea82f680a5ed868fee16e9609bd | https://github.com/adafruit/Adafruit_Python_PN532/blob/343521a8ec842ea82f680a5ed868fee16e9609bd/Adafruit_PN532/PN532.py#L276-L299 |
22,026 | adafruit/Adafruit_Python_PN532 | Adafruit_PN532/PN532.py | PN532.call_function | def call_function(self, command, response_length=0, params=[], timeout_sec=1):
"""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 bytearray of response bytes, or None if no
response is available within the timeout.
"""
# Build frame data with command and parameters.
data = bytearray(2+len(params))
data[0] = PN532_HOSTTOPN532
data[1] = command & 0xFF
data[2:] = params
# Send frame and wait for response.
self._write_frame(data)
if not self._wait_ready(timeout_sec):
return None
# Verify ACK response and wait to be ready for function response.
response = self._read_data(len(PN532_ACK))
if response != PN532_ACK:
raise RuntimeError('Did not receive expected ACK from PN532!')
if not self._wait_ready(timeout_sec):
return None
# Read response bytes.
response = self._read_frame(response_length+2)
# Check that response is for the called function.
if not (response[0] == PN532_PN532TOHOST and response[1] == (command+1)):
raise RuntimeError('Received unexpected command response!')
# Return response data.
return response[2:] | python | 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:] = params
# Send frame and wait for response.
self._write_frame(data)
if not self._wait_ready(timeout_sec):
return None
# Verify ACK response and wait to be ready for function response.
response = self._read_data(len(PN532_ACK))
if response != PN532_ACK:
raise RuntimeError('Did not receive expected ACK from PN532!')
if not self._wait_ready(timeout_sec):
return None
# Read response bytes.
response = self._read_frame(response_length+2)
# Check that response is for the called function.
if not (response[0] == PN532_PN532TOHOST and response[1] == (command+1)):
raise RuntimeError('Received unexpected command response!')
# Return response data.
return response[2:] | [
"def",
"call_function",
"(",
"self",
",",
"command",
",",
"response_length",
"=",
"0",
",",
"params",
"=",
"[",
"]",
",",
"timeout_sec",
"=",
"1",
")",
":",
"# Build frame data with command and parameters.",
"data",
"=",
"bytearray",
"(",
"2",
"+",
"len",
"(... | 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 bytearray of response bytes, or None if no
response is available within the timeout. | [
"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",
"optio... | 343521a8ec842ea82f680a5ed868fee16e9609bd | https://github.com/adafruit/Adafruit_Python_PN532/blob/343521a8ec842ea82f680a5ed868fee16e9609bd/Adafruit_PN532/PN532.py#L301-L330 |
22,027 | adafruit/Adafruit_Python_PN532 | Adafruit_PN532/PN532.py | PN532.begin | def begin(self):
"""Initialize communication with the PN532. Must be called before any
other calls are made against the PN532.
"""
# 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 Arduino library and kept for consistency.
self.get_firmware_version()
self._gpio.set_high(self._cs) | python | 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 Arduino library and kept for consistency.
self.get_firmware_version()
self._gpio.set_high(self._cs) | [
"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... | Initialize communication with the PN532. Must be called before any
other calls are made against the PN532. | [
"Initialize",
"communication",
"with",
"the",
"PN532",
".",
"Must",
"be",
"called",
"before",
"any",
"other",
"calls",
"are",
"made",
"against",
"the",
"PN532",
"."
] | 343521a8ec842ea82f680a5ed868fee16e9609bd | https://github.com/adafruit/Adafruit_Python_PN532/blob/343521a8ec842ea82f680a5ed868fee16e9609bd/Adafruit_PN532/PN532.py#L332-L342 |
22,028 | adafruit/Adafruit_Python_PN532 | Adafruit_PN532/PN532.py | PN532.get_firmware_version | def get_firmware_version(self):
"""Call PN532 GetFirmwareVersion function and return a tuple with the IC,
Ver, Rev, and Support values.
"""
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 joints on the PN532 headers are solidly connected.')
return (response[0], response[1], response[2], response[3]) | python | 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 joints on the PN532 headers are solidly connected.')
return (response[0], response[1], response[2], response[3]) | [
"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 the... | Call PN532 GetFirmwareVersion function and return a tuple with the IC,
Ver, Rev, and Support values. | [
"Call",
"PN532",
"GetFirmwareVersion",
"function",
"and",
"return",
"a",
"tuple",
"with",
"the",
"IC",
"Ver",
"Rev",
"and",
"Support",
"values",
"."
] | 343521a8ec842ea82f680a5ed868fee16e9609bd | https://github.com/adafruit/Adafruit_Python_PN532/blob/343521a8ec842ea82f680a5ed868fee16e9609bd/Adafruit_PN532/PN532.py#L344-L351 |
22,029 | adafruit/Adafruit_Python_PN532 | Adafruit_PN532/PN532.py | PN532.read_passive_target | def read_passive_target(self, card_baud=PN532_MIFARE_ISO14443A, timeout_sec=1):
"""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.
"""
# Send passive read command for 1 card. Expect at most a 7 byte UUID.
response = self.call_function(PN532_COMMAND_INLISTPASSIVETARGET,
params=[0x01, card_baud],
response_length=17)
# If no response is available return None to indicate no card is present.
if response is None:
return None
# Check only 1 card with up to a 7 byte UID is present.
if response[0] != 0x01:
raise RuntimeError('More than one card detected!')
if response[5] > 7:
raise RuntimeError('Found card with unexpectedly long UID!')
# Return UID of card.
return response[6:6+response[5]] | python | 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,
params=[0x01, card_baud],
response_length=17)
# If no response is available return None to indicate no card is present.
if response is None:
return None
# Check only 1 card with up to a 7 byte UID is present.
if response[0] != 0x01:
raise RuntimeError('More than one card detected!')
if response[5] > 7:
raise RuntimeError('Found card with unexpectedly long UID!')
# Return UID of card.
return response[6:6+response[5]] | [
"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_I... | 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. | [
"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",
"bytea... | 343521a8ec842ea82f680a5ed868fee16e9609bd | https://github.com/adafruit/Adafruit_Python_PN532/blob/343521a8ec842ea82f680a5ed868fee16e9609bd/Adafruit_PN532/PN532.py#L363-L381 |
22,030 | adafruit/Adafruit_Python_PN532 | Adafruit_PN532/PN532.py | PN532.mifare_classic_read_block | def mifare_classic_read_block(self, block_number):
"""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.
"""
# Send InDataExchange request to read block of MiFare data.
response = self.call_function(PN532_COMMAND_INDATAEXCHANGE,
params=[0x01, MIFARE_CMD_READ, block_number & 0xFF],
response_length=17)
# Check first response is 0x00 to show success.
if response[0] != 0x00:
return None
# Return first 4 bytes since 16 bytes are always returned.
return response[1:] | python | 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_number & 0xFF],
response_length=17)
# Check first response is 0x00 to show success.
if response[0] != 0x00:
return None
# Return first 4 bytes since 16 bytes are always returned.
return response[1:] | [
"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... | 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. | [
"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",
... | 343521a8ec842ea82f680a5ed868fee16e9609bd | https://github.com/adafruit/Adafruit_Python_PN532/blob/343521a8ec842ea82f680a5ed868fee16e9609bd/Adafruit_PN532/PN532.py#L406-L420 |
22,031 | adafruit/Adafruit_Python_PN532 | Adafruit_PN532/PN532.py | PN532.mifare_classic_write_block | def mifare_classic_write_block(self, block_number, data):
"""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.
"""
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)
params[0] = 0x01 # Max card numbers
params[1] = MIFARE_CMD_WRITE
params[2] = block_number & 0xFF
params[3:] = data
# Send InDataExchange request.
response = self.call_function(PN532_COMMAND_INDATAEXCHANGE,
params=params,
response_length=1)
return response[0] == 0x00 | python | 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)
params[0] = 0x01 # Max card numbers
params[1] = MIFARE_CMD_WRITE
params[2] = block_number & 0xFF
params[3:] = data
# Send InDataExchange request.
response = self.call_function(PN532_COMMAND_INDATAEXCHANGE,
params=params,
response_length=1)
return response[0] == 0x00 | [
"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... | 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. | [
"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... | 343521a8ec842ea82f680a5ed868fee16e9609bd | https://github.com/adafruit/Adafruit_Python_PN532/blob/343521a8ec842ea82f680a5ed868fee16e9609bd/Adafruit_PN532/PN532.py#L422-L439 |
22,032 | edwardgeorge/virtualenv-clone | clonevirtualenv.py | _dirmatch | def _dirmatch(path, matchwith):
"""Check if path is within matchwith's tree.
>>> _dirmatch('/home/foo/bar', '/home/foo/bar')
True
>>> _dirmatch('/home/foo/bar/', '/home/foo/bar')
True
>>> _dirmatch('/home/foo/bar/etc', '/home/foo/bar')
True
>>> _dirmatch('/home/foo/bar2', '/home/foo/bar')
False
>>> _dirmatch('/home/foo/bar2/etc', '/home/foo/bar')
False
"""
matchlen = len(matchwith)
if (path.startswith(matchwith)
and path[matchlen:matchlen + 1] in [os.sep, '']):
return True
return False | python | def _dirmatch(path, matchwith):
matchlen = len(matchwith)
if (path.startswith(matchwith)
and path[matchlen:matchlen + 1] in [os.sep, '']):
return True
return False | [
"def",
"_dirmatch",
"(",
"path",
",",
"matchwith",
")",
":",
"matchlen",
"=",
"len",
"(",
"matchwith",
")",
"if",
"(",
"path",
".",
"startswith",
"(",
"matchwith",
")",
"and",
"path",
"[",
"matchlen",
":",
"matchlen",
"+",
"1",
"]",
"in",
"[",
"os",
... | Check if path is within matchwith's tree.
>>> _dirmatch('/home/foo/bar', '/home/foo/bar')
True
>>> _dirmatch('/home/foo/bar/', '/home/foo/bar')
True
>>> _dirmatch('/home/foo/bar/etc', '/home/foo/bar')
True
>>> _dirmatch('/home/foo/bar2', '/home/foo/bar')
False
>>> _dirmatch('/home/foo/bar2/etc', '/home/foo/bar')
False | [
"Check",
"if",
"path",
"is",
"within",
"matchwith",
"s",
"tree",
"."
] | 434b12eb725ac1850b60f2bad8e848540e5596de | https://github.com/edwardgeorge/virtualenv-clone/blob/434b12eb725ac1850b60f2bad8e848540e5596de/clonevirtualenv.py#L29-L47 |
22,033 | edwardgeorge/virtualenv-clone | clonevirtualenv.py | _virtualenv_sys | 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 from sys.path
p = subprocess.Popen([executable,
'-c', 'import sys;'
'print (sys.version[:3]);'
'print ("\\n".join(sys.path));'],
env={},
stdout=subprocess.PIPE)
stdout, err = p.communicate()
assert not p.returncode and stdout
lines = stdout.decode('utf-8').splitlines()
return lines[0], list(filter(bool, lines[1:])) | python | 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 from sys.path
p = subprocess.Popen([executable,
'-c', 'import sys;'
'print (sys.version[:3]);'
'print ("\\n".join(sys.path));'],
env={},
stdout=subprocess.PIPE)
stdout, err = p.communicate()
assert not p.returncode and stdout
lines = stdout.decode('utf-8').splitlines()
return lines[0], list(filter(bool, lines[1:])) | [
"def",
"_virtualenv_sys",
"(",
"venv_path",
")",
":",
"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 g... | obtain version and path info from a virtualenv. | [
"obtain",
"version",
"and",
"path",
"info",
"from",
"a",
"virtualenv",
"."
] | 434b12eb725ac1850b60f2bad8e848540e5596de | https://github.com/edwardgeorge/virtualenv-clone/blob/434b12eb725ac1850b60f2bad8e848540e5596de/clonevirtualenv.py#L50-L64 |
22,034 | dsoprea/PyEasyArchive | libarchive/types/archive_entry.py | int_to_ef | def int_to_ef(n):
"""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.
"""
flags = {}
for name, value in libarchive.constants.archive_entry.FILETYPES.items():
flags[name] = (n & value) > 0
return ENTRY_FILETYPE(**flags) | python | 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) | [
"def",
"int_to_ef",
"(",
"n",
")",
":",
"flags",
"=",
"{",
"}",
"for",
"name",
",",
"value",
"in",
"libarchive",
".",
"constants",
".",
"archive_entry",
".",
"FILETYPES",
".",
"items",
"(",
")",
":",
"flags",
"[",
"name",
"]",
"=",
"(",
"n",
"&",
... | 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. | [
"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"... | 50414b9fa9a1055435499b5b2e4b2a336a40dff6 | https://github.com/dsoprea/PyEasyArchive/blob/50414b9fa9a1055435499b5b2e4b2a336a40dff6/libarchive/types/archive_entry.py#L24-L35 |
22,035 | dsoprea/PyEasyArchive | libarchive/adapters/archive_read.py | _enumerator | def _enumerator(opener, entry_cls, format_code=None, filter_code=None):
"""Return an archive enumerator from a user-defined source, using a user-
defined entry type.
"""
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:
break
e = entry_cls(archive_res, entry_res)
yield e
if e.is_consumed is False:
_archive_read_data_skip(archive_res)
yield it()
finally:
_archive_read_free(archive_res) | python | 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:
break
e = entry_cls(archive_res, entry_res)
yield e
if e.is_consumed is False:
_archive_read_data_skip(archive_res)
yield it()
finally:
_archive_read_free(archive_res) | [
"def",
"_enumerator",
"(",
"opener",
",",
"entry_cls",
",",
"format_code",
"=",
"None",
",",
"filter_code",
"=",
"None",
")",
":",
"archive_res",
"=",
"_archive_read_new",
"(",
")",
"try",
":",
"r",
"=",
"_set_read_context",
"(",
"archive_res",
",",
"format_... | Return an archive enumerator from a user-defined source, using a user-
defined entry type. | [
"Return",
"an",
"archive",
"enumerator",
"from",
"a",
"user",
"-",
"defined",
"source",
"using",
"a",
"user",
"-",
"defined",
"entry",
"type",
"."
] | 50414b9fa9a1055435499b5b2e4b2a336a40dff6 | https://github.com/dsoprea/PyEasyArchive/blob/50414b9fa9a1055435499b5b2e4b2a336a40dff6/libarchive/adapters/archive_read.py#L270-L293 |
22,036 | dsoprea/PyEasyArchive | libarchive/adapters/archive_read.py | file_enumerator | def file_enumerator(filepath, block_size=10240, *args, **kwargs):
"""Return an enumerator that knows how to read a physical file."""
_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 'entry_cls' not in kwargs:
kwargs['entry_cls'] = _ArchiveEntryItReadable
return _enumerator(opener,
*args,
**kwargs) | python | 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 'entry_cls' not in kwargs:
kwargs['entry_cls'] = _ArchiveEntryItReadable
return _enumerator(opener,
*args,
**kwargs) | [
"def",
"file_enumerator",
"(",
"filepath",
",",
"block_size",
"=",
"10240",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Enumerating through archive file: %s\"",
",",
"filepath",
")",
"def",
"opener",
"(",
"archive_res"... | Return an enumerator that knows how to read a physical file. | [
"Return",
"an",
"enumerator",
"that",
"knows",
"how",
"to",
"read",
"a",
"physical",
"file",
"."
] | 50414b9fa9a1055435499b5b2e4b2a336a40dff6 | https://github.com/dsoprea/PyEasyArchive/blob/50414b9fa9a1055435499b5b2e4b2a336a40dff6/libarchive/adapters/archive_read.py#L295-L309 |
22,037 | dsoprea/PyEasyArchive | libarchive/adapters/archive_read.py | memory_enumerator | def memory_enumerator(buffer_, *args, **kwargs):
"""Return an enumerator that knows how to read raw memory."""
_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_cls' not in kwargs:
kwargs['entry_cls'] = _ArchiveEntryItReadable
return _enumerator(opener,
*args,
**kwargs) | python | 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_cls' not in kwargs:
kwargs['entry_cls'] = _ArchiveEntryItReadable
return _enumerator(opener,
*args,
**kwargs) | [
"def",
"memory_enumerator",
"(",
"buffer_",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Enumerating through (%d) bytes of archive data.\"",
",",
"len",
"(",
"buffer_",
")",
")",
"def",
"opener",
"(",
"archive_res",
")"... | Return an enumerator that knows how to read raw memory. | [
"Return",
"an",
"enumerator",
"that",
"knows",
"how",
"to",
"read",
"raw",
"memory",
"."
] | 50414b9fa9a1055435499b5b2e4b2a336a40dff6 | https://github.com/dsoprea/PyEasyArchive/blob/50414b9fa9a1055435499b5b2e4b2a336a40dff6/libarchive/adapters/archive_read.py#L311-L328 |
22,038 | dsoprea/PyEasyArchive | libarchive/adapters/archive_read.py | _pour | def _pour(opener, flags=0, *args, **kwargs):
"""A flexible pouring facility that knows how to enumerate entry data."""
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:
yield state
if state.selected is False:
continue
r = libarchive.calls.archive_write.c_archive_write_header(
ext,
state.entry_res)
buff = ctypes.c_void_p()
size = ctypes.c_size_t()
offset = ctypes.c_longlong()
while 1:
r = libarchive.calls.archive_read.\
c_archive_read_data_block(
state.reader_res,
ctypes.byref(buff),
ctypes.byref(size),
ctypes.byref(offset))
if r == libarchive.constants.archive.ARCHIVE_EOF:
break
elif r != libarchive.constants.archive.ARCHIVE_OK:
message = c_archive_error_string(state.reader_res)
raise libarchive.exception.ArchiveError(
"Pour failed: (%d) [%s]" % (r, message))
r = libarchive.calls.archive_write.c_archive_write_data_block(
ext,
buff,
size,
offset)
r = libarchive.calls.archive_write.\
c_archive_write_finish_entry(ext) | python | 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:
yield state
if state.selected is False:
continue
r = libarchive.calls.archive_write.c_archive_write_header(
ext,
state.entry_res)
buff = ctypes.c_void_p()
size = ctypes.c_size_t()
offset = ctypes.c_longlong()
while 1:
r = libarchive.calls.archive_read.\
c_archive_read_data_block(
state.reader_res,
ctypes.byref(buff),
ctypes.byref(size),
ctypes.byref(offset))
if r == libarchive.constants.archive.ARCHIVE_EOF:
break
elif r != libarchive.constants.archive.ARCHIVE_OK:
message = c_archive_error_string(state.reader_res)
raise libarchive.exception.ArchiveError(
"Pour failed: (%d) [%s]" % (r, message))
r = libarchive.calls.archive_write.c_archive_write_data_block(
ext,
buff,
size,
offset)
r = libarchive.calls.archive_write.\
c_archive_write_finish_entry(ext) | [
"def",
"_pour",
"(",
"opener",
",",
"flags",
"=",
"0",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"_enumerator",
"(",
"opener",
",",
"*",
"args",
",",
"entry_cls",
"=",
"_ArchiveEntryItState",
",",
"*",
"*",
"kwargs",
")",
"as",
"... | A flexible pouring facility that knows how to enumerate entry data. | [
"A",
"flexible",
"pouring",
"facility",
"that",
"knows",
"how",
"to",
"enumerate",
"entry",
"data",
"."
] | 50414b9fa9a1055435499b5b2e4b2a336a40dff6 | https://github.com/dsoprea/PyEasyArchive/blob/50414b9fa9a1055435499b5b2e4b2a336a40dff6/libarchive/adapters/archive_read.py#L348-L397 |
22,039 | dsoprea/PyEasyArchive | libarchive/adapters/archive_read.py | file_pour | def file_pour(filepath, block_size=10240, *args, **kwargs):
"""Write physical files from entries."""
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) | python | 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) | [
"def",
"file_pour",
"(",
"filepath",
",",
"block_size",
"=",
"10240",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"opener",
"(",
"archive_res",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Opening from file (file_pour): %s\"",
",",
"filepath",
... | Write physical files from entries. | [
"Write",
"physical",
"files",
"from",
"entries",
"."
] | 50414b9fa9a1055435499b5b2e4b2a336a40dff6 | https://github.com/dsoprea/PyEasyArchive/blob/50414b9fa9a1055435499b5b2e4b2a336a40dff6/libarchive/adapters/archive_read.py#L399-L406 |
22,040 | dsoprea/PyEasyArchive | libarchive/adapters/archive_read.py | memory_pour | def memory_pour(buffer_, *args, **kwargs):
"""Yield data from entries."""
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) | python | 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) | [
"def",
"memory_pour",
"(",
"buffer_",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"opener",
"(",
"archive_res",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Opening from (%d) bytes (memory_pour).\"",
",",
"len",
"(",
"buffer_",
")",
")",
"_ar... | Yield data from entries. | [
"Yield",
"data",
"from",
"entries",
"."
] | 50414b9fa9a1055435499b5b2e4b2a336a40dff6 | https://github.com/dsoprea/PyEasyArchive/blob/50414b9fa9a1055435499b5b2e4b2a336a40dff6/libarchive/adapters/archive_read.py#L408-L415 |
22,041 | dsoprea/PyEasyArchive | libarchive/adapters/archive_write.py | _archive_write_data | def _archive_write_data(archive, data):
"""Write data to archive. This will only be called with a non-empty string.
"""
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]" % (message)) | python | 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]" % (message)) | [
"def",
"_archive_write_data",
"(",
"archive",
",",
"data",
")",
":",
"n",
"=",
"libarchive",
".",
"calls",
".",
"archive_write",
".",
"c_archive_write_data",
"(",
"archive",
",",
"ctypes",
".",
"cast",
"(",
"ctypes",
".",
"c_char_p",
"(",
"data",
")",
",",... | Write data to archive. This will only be called with a non-empty string. | [
"Write",
"data",
"to",
"archive",
".",
"This",
"will",
"only",
"be",
"called",
"with",
"a",
"non",
"-",
"empty",
"string",
"."
] | 50414b9fa9a1055435499b5b2e4b2a336a40dff6 | https://github.com/dsoprea/PyEasyArchive/blob/50414b9fa9a1055435499b5b2e4b2a336a40dff6/libarchive/adapters/archive_write.py#L71-L82 |
22,042 | adafruit/Adafruit_CircuitPython_BME280 | adafruit_bme280.py | Adafruit_BME280._write_ctrl_meas | def _write_ctrl_meas(self):
"""
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
"""
self._write_register_byte(_BME280_REGISTER_CTRL_HUM, self.overscan_humidity)
self._write_register_byte(_BME280_REGISTER_CTRL_MEAS, self._ctrl_meas) | python | 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) | [
"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 | [
"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",
... | febcd51983dc2bc3cd006bacaada505251c39af1 | https://github.com/adafruit/Adafruit_CircuitPython_BME280/blob/febcd51983dc2bc3cd006bacaada505251c39af1/adafruit_bme280.py#L161-L168 |
22,043 | adafruit/Adafruit_CircuitPython_BME280 | adafruit_bme280.py | Adafruit_BME280._write_config | def _write_config(self):
"""Write the value to the config register in the device """
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 first
self._write_register_byte(_BME280_REGISTER_CONFIG, self._config)
if normal_flag:
self.mode = MODE_NORMAL | python | 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 first
self._write_register_byte(_BME280_REGISTER_CONFIG, self._config)
if normal_flag:
self.mode = MODE_NORMAL | [
"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",
... | Write the value to the config register in the device | [
"Write",
"the",
"value",
"to",
"the",
"config",
"register",
"in",
"the",
"device"
] | febcd51983dc2bc3cd006bacaada505251c39af1 | https://github.com/adafruit/Adafruit_CircuitPython_BME280/blob/febcd51983dc2bc3cd006bacaada505251c39af1/adafruit_bme280.py#L178-L187 |
22,044 | adafruit/Adafruit_CircuitPython_BME280 | adafruit_bme280.py | Adafruit_BME280._config | def _config(self):
"""Value to be written to the device's config register """
config = 0
if self.mode == MODE_NORMAL:
config += (self._t_standby << 5)
if self._iir_filter:
config += (self._iir_filter << 2)
return config | python | 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 | [
"def",
"_config",
"(",
"self",
")",
":",
"config",
"=",
"0",
"if",
"self",
".",
"mode",
"==",
"MODE_NORMAL",
":",
"config",
"+=",
"(",
"self",
".",
"_t_standby",
"<<",
"5",
")",
"if",
"self",
".",
"_iir_filter",
":",
"config",
"+=",
"(",
"self",
".... | Value to be written to the device's config register | [
"Value",
"to",
"be",
"written",
"to",
"the",
"device",
"s",
"config",
"register"
] | febcd51983dc2bc3cd006bacaada505251c39af1 | https://github.com/adafruit/Adafruit_CircuitPython_BME280/blob/febcd51983dc2bc3cd006bacaada505251c39af1/adafruit_bme280.py#L282-L289 |
22,045 | adafruit/Adafruit_CircuitPython_BME280 | adafruit_bme280.py | Adafruit_BME280._ctrl_meas | def _ctrl_meas(self):
"""Value to be written to the device's ctrl_meas register """
ctrl_meas = (self.overscan_temperature << 5)
ctrl_meas += (self.overscan_pressure << 2)
ctrl_meas += self.mode
return ctrl_meas | python | def _ctrl_meas(self):
ctrl_meas = (self.overscan_temperature << 5)
ctrl_meas += (self.overscan_pressure << 2)
ctrl_meas += self.mode
return ctrl_meas | [
"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 | [
"Value",
"to",
"be",
"written",
"to",
"the",
"device",
"s",
"ctrl_meas",
"register"
] | febcd51983dc2bc3cd006bacaada505251c39af1 | https://github.com/adafruit/Adafruit_CircuitPython_BME280/blob/febcd51983dc2bc3cd006bacaada505251c39af1/adafruit_bme280.py#L292-L297 |
22,046 | adafruit/Adafruit_CircuitPython_BME280 | adafruit_bme280.py | Adafruit_BME280.measurement_time_typical | def measurement_time_typical(self):
"""Typical time in milliseconds required to complete a measurement in normal mode"""
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.5)
if self.overscan_humidity != OVERSCAN_DISABLE:
meas_time_ms += (2 * _BME280_OVERSCANS.get(self.overscan_humidity) + 0.5)
return meas_time_ms | python | 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.5)
if self.overscan_humidity != OVERSCAN_DISABLE:
meas_time_ms += (2 * _BME280_OVERSCANS.get(self.overscan_humidity) + 0.5)
return meas_time_ms | [
"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_temp... | Typical time in milliseconds required to complete a measurement in normal mode | [
"Typical",
"time",
"in",
"milliseconds",
"required",
"to",
"complete",
"a",
"measurement",
"in",
"normal",
"mode"
] | febcd51983dc2bc3cd006bacaada505251c39af1 | https://github.com/adafruit/Adafruit_CircuitPython_BME280/blob/febcd51983dc2bc3cd006bacaada505251c39af1/adafruit_bme280.py#L300-L309 |
22,047 | adafruit/Adafruit_CircuitPython_BME280 | adafruit_bme280.py | Adafruit_BME280.pressure | def pressure(self):
"""
The compensated pressure in hectoPascals.
returns None if pressure measurement is disabled
"""
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 dropped
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[3] * 65536.0
var3 = self._pressure_calib[2] * var1 * var1 / 524288.0
var1 = (var3 + self._pressure_calib[1] * var1) / 524288.0
var1 = (1.0 + var1 / 32768.0) * self._pressure_calib[0]
if var1 == 0:
return 0
if var1:
pressure = 1048576.0 - adc
pressure = ((pressure - var2 / 4096.0) * 6250.0) / var1
var1 = self._pressure_calib[8] * pressure * pressure / 2147483648.0
var2 = pressure * self._pressure_calib[7] / 32768.0
pressure = pressure + (var1 + var2 + self._pressure_calib[6]) / 16.0
pressure /= 100
if pressure < _BME280_PRESSURE_MIN_HPA:
return _BME280_PRESSURE_MIN_HPA
if pressure > _BME280_PRESSURE_MAX_HPA:
return _BME280_PRESSURE_MAX_HPA
return pressure
else:
return _BME280_PRESSURE_MIN_HPA | python | 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 dropped
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[3] * 65536.0
var3 = self._pressure_calib[2] * var1 * var1 / 524288.0
var1 = (var3 + self._pressure_calib[1] * var1) / 524288.0
var1 = (1.0 + var1 / 32768.0) * self._pressure_calib[0]
if var1 == 0:
return 0
if var1:
pressure = 1048576.0 - adc
pressure = ((pressure - var2 / 4096.0) * 6250.0) / var1
var1 = self._pressure_calib[8] * pressure * pressure / 2147483648.0
var2 = pressure * self._pressure_calib[7] / 32768.0
pressure = pressure + (var1 + var2 + self._pressure_calib[6]) / 16.0
pressure /= 100
if pressure < _BME280_PRESSURE_MIN_HPA:
return _BME280_PRESSURE_MIN_HPA
if pressure > _BME280_PRESSURE_MAX_HPA:
return _BME280_PRESSURE_MAX_HPA
return pressure
else:
return _BME280_PRESSURE_MIN_HPA | [
"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",
")",... | The compensated pressure in hectoPascals.
returns None if pressure measurement is disabled | [
"The",
"compensated",
"pressure",
"in",
"hectoPascals",
".",
"returns",
"None",
"if",
"pressure",
"measurement",
"is",
"disabled"
] | febcd51983dc2bc3cd006bacaada505251c39af1 | https://github.com/adafruit/Adafruit_CircuitPython_BME280/blob/febcd51983dc2bc3cd006bacaada505251c39af1/adafruit_bme280.py#L330-L363 |
22,048 | adafruit/Adafruit_CircuitPython_BME280 | adafruit_bme280.py | Adafruit_BME280.humidity | def humidity(self):
"""
The relative humidity in RH %
returns None if humidity measurement is disabled
"""
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 driver
# https://github.com/BoschSensortec/BME280_driver/blob/master/bme280.c
var1 = float(self._t_fine) - 76800.0
#print("var1 ", var1)
var2 = (self._humidity_calib[3] * 64.0 + (self._humidity_calib[4] / 16384.0) * var1)
#print("var2 ",var2)
var3 = adc - var2
#print("var3 ",var3)
var4 = self._humidity_calib[1] / 65536.0
#print("var4 ",var4)
var5 = (1.0 + (self._humidity_calib[2] / 67108864.0) * var1)
#print("var5 ",var5)
var6 = 1.0 + (self._humidity_calib[5] / 67108864.0) * var1 * var5
#print("var6 ",var6)
var6 = var3 * var4 * (var5 * var6)
humidity = var6 * (1.0 - self._humidity_calib[0] * var6 / 524288.0)
if humidity > _BME280_HUMIDITY_MAX:
return _BME280_HUMIDITY_MAX
if humidity < _BME280_HUMIDITY_MIN:
return _BME280_HUMIDITY_MIN
# else...
return humidity | python | 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 driver
# https://github.com/BoschSensortec/BME280_driver/blob/master/bme280.c
var1 = float(self._t_fine) - 76800.0
#print("var1 ", var1)
var2 = (self._humidity_calib[3] * 64.0 + (self._humidity_calib[4] / 16384.0) * var1)
#print("var2 ",var2)
var3 = adc - var2
#print("var3 ",var3)
var4 = self._humidity_calib[1] / 65536.0
#print("var4 ",var4)
var5 = (1.0 + (self._humidity_calib[2] / 67108864.0) * var1)
#print("var5 ",var5)
var6 = 1.0 + (self._humidity_calib[5] / 67108864.0) * var1 * var5
#print("var6 ",var6)
var6 = var3 * var4 * (var5 * var6)
humidity = var6 * (1.0 - self._humidity_calib[0] * var6 / 524288.0)
if humidity > _BME280_HUMIDITY_MAX:
return _BME280_HUMIDITY_MAX
if humidity < _BME280_HUMIDITY_MIN:
return _BME280_HUMIDITY_MIN
# else...
return humidity | [
"def",
"humidity",
"(",
"self",
")",
":",
"self",
".",
"_read_temperature",
"(",
")",
"hum",
"=",
"self",
".",
"_read_register",
"(",
"_BME280_REGISTER_HUMIDDATA",
",",
"2",
")",
"#print(\"Humidity data: \", hum)",
"adc",
"=",
"float",
"(",
"hum",
"[",
"0",
... | The relative humidity in RH %
returns None if humidity measurement is disabled | [
"The",
"relative",
"humidity",
"in",
"RH",
"%",
"returns",
"None",
"if",
"humidity",
"measurement",
"is",
"disabled"
] | febcd51983dc2bc3cd006bacaada505251c39af1 | https://github.com/adafruit/Adafruit_CircuitPython_BME280/blob/febcd51983dc2bc3cd006bacaada505251c39af1/adafruit_bme280.py#L366-L399 |
22,049 | adafruit/Adafruit_CircuitPython_BME280 | adafruit_bme280.py | Adafruit_BME280._read_coefficients | def _read_coefficients(self):
"""Read & save the calibration coefficients"""
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._humidity_calib[0] = self._read_byte(_BME280_REGISTER_DIG_H1)
coeff = self._read_register(_BME280_REGISTER_DIG_H2, 7)
coeff = list(struct.unpack('<hBBBBb', bytes(coeff)))
self._humidity_calib[1] = float(coeff[0])
self._humidity_calib[2] = float(coeff[1])
self._humidity_calib[3] = float((coeff[2] << 4) | (coeff[3] & 0xF))
self._humidity_calib[4] = float((coeff[4] << 4) | (coeff[3] >> 4))
self._humidity_calib[5] = float(coeff[5]) | python | 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._humidity_calib[0] = self._read_byte(_BME280_REGISTER_DIG_H1)
coeff = self._read_register(_BME280_REGISTER_DIG_H2, 7)
coeff = list(struct.unpack('<hBBBBb', bytes(coeff)))
self._humidity_calib[1] = float(coeff[0])
self._humidity_calib[2] = float(coeff[1])
self._humidity_calib[3] = float((coeff[2] << 4) | (coeff[3] & 0xF))
self._humidity_calib[4] = float((coeff[4] << 4) | (coeff[3] >> 4))
self._humidity_calib[5] = float(coeff[5]) | [
"def",
"_read_coefficients",
"(",
"self",
")",
":",
"coeff",
"=",
"self",
".",
"_read_register",
"(",
"_BME280_REGISTER_DIG_T1",
",",
"24",
")",
"coeff",
"=",
"list",
"(",
"struct",
".",
"unpack",
"(",
"'<HhhHhhhhhhhh'",
",",
"bytes",
"(",
"coeff",
")",
")... | Read & save the calibration coefficients | [
"Read",
"&",
"save",
"the",
"calibration",
"coefficients"
] | febcd51983dc2bc3cd006bacaada505251c39af1 | https://github.com/adafruit/Adafruit_CircuitPython_BME280/blob/febcd51983dc2bc3cd006bacaada505251c39af1/adafruit_bme280.py#L408-L424 |
22,050 | adafruit/Adafruit_CircuitPython_BME280 | adafruit_bme280.py | Adafruit_BME280._read24 | def _read24(self, register):
"""Read an unsigned 24-bit value as a floating point and return it."""
ret = 0.0
for b in self._read_register(register, 3):
ret *= 256.0
ret += float(b & 0xFF)
return ret | python | def _read24(self, register):
ret = 0.0
for b in self._read_register(register, 3):
ret *= 256.0
ret += float(b & 0xFF)
return ret | [
"def",
"_read24",
"(",
"self",
",",
"register",
")",
":",
"ret",
"=",
"0.0",
"for",
"b",
"in",
"self",
".",
"_read_register",
"(",
"register",
",",
"3",
")",
":",
"ret",
"*=",
"256.0",
"ret",
"+=",
"float",
"(",
"b",
"&",
"0xFF",
")",
"return",
"... | Read an unsigned 24-bit value as a floating point and return it. | [
"Read",
"an",
"unsigned",
"24",
"-",
"bit",
"value",
"as",
"a",
"floating",
"point",
"and",
"return",
"it",
"."
] | febcd51983dc2bc3cd006bacaada505251c39af1 | https://github.com/adafruit/Adafruit_CircuitPython_BME280/blob/febcd51983dc2bc3cd006bacaada505251c39af1/adafruit_bme280.py#L430-L436 |
22,051 | ArangoDB-Community/pyArango | pyArango/index.py | Index._create | def _create(self, postData) :
"""Creates an index of any type according to 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(data['errorMessage'], data)
self.infos = data | python | 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(data['errorMessage'], data)
self.infos = data | [
"def",
"_create",
"(",
"self",
",",
"postData",
")",
":",
"if",
"self",
".",
"infos",
"is",
"None",
":",
"r",
"=",
"self",
".",
"connection",
".",
"session",
".",
"post",
"(",
"self",
".",
"indexesURL",
",",
"params",
"=",
"{",
"\"collection\"",
":",... | Creates an index of any type according to postData | [
"Creates",
"an",
"index",
"of",
"any",
"type",
"according",
"to",
"postData"
] | dd72e5f6c540e5e148943d615ddf7553bb78ce0b | https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/index.py#L22-L29 |
22,052 | ArangoDB-Community/pyArango | pyArango/graph.py | Graph.createVertex | def createVertex(self, collectionName, docAttributes, waitForSync = False) :
"""adds a vertex to the graph and returns it"""
url = "%s/vertex/%s" % (self.URL, collectionName)
store = DOC.DocumentStore(self.database[collectionName], validators=self.database[collectionName]._fields, initDct=docAttributes)
# self.database[collectionName].validateDct(docAttributes)
store.validate()
r = self.connection.session.post(url, data = json.dumps(docAttributes, default=str), params = {'waitForSync' : waitForSync})
data = r.json()
if r.status_code == 201 or r.status_code == 202 :
return self.database[collectionName][data["vertex"]["_key"]]
raise CreationError("Unable to create vertice, %s" % data["errorMessage"], data) | python | 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)
# self.database[collectionName].validateDct(docAttributes)
store.validate()
r = self.connection.session.post(url, data = json.dumps(docAttributes, default=str), params = {'waitForSync' : waitForSync})
data = r.json()
if r.status_code == 201 or r.status_code == 202 :
return self.database[collectionName][data["vertex"]["_key"]]
raise CreationError("Unable to create vertice, %s" % data["errorMessage"], data) | [
"def",
"createVertex",
"(",
"self",
",",
"collectionName",
",",
"docAttributes",
",",
"waitForSync",
"=",
"False",
")",
":",
"url",
"=",
"\"%s/vertex/%s\"",
"%",
"(",
"self",
".",
"URL",
",",
"collectionName",
")",
"store",
"=",
"DOC",
".",
"DocumentStore",
... | adds a vertex to the graph and returns it | [
"adds",
"a",
"vertex",
"to",
"the",
"graph",
"and",
"returns",
"it"
] | dd72e5f6c540e5e148943d615ddf7553bb78ce0b | https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/graph.py#L115-L129 |
22,053 | ArangoDB-Community/pyArango | pyArango/graph.py | Graph.deleteVertex | def deleteVertex(self, document, waitForSync = False) :
"""deletes a vertex from the graph as well as al linked edges"""
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("Unable to delete vertice, %s" % document._id, data) | python | 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("Unable to delete vertice, %s" % document._id, data) | [
"def",
"deleteVertex",
"(",
"self",
",",
"document",
",",
"waitForSync",
"=",
"False",
")",
":",
"url",
"=",
"\"%s/vertex/%s\"",
"%",
"(",
"self",
".",
"URL",
",",
"document",
".",
"_id",
")",
"r",
"=",
"self",
".",
"connection",
".",
"session",
".",
... | deletes a vertex from the graph as well as al linked edges | [
"deletes",
"a",
"vertex",
"from",
"the",
"graph",
"as",
"well",
"as",
"al",
"linked",
"edges"
] | dd72e5f6c540e5e148943d615ddf7553bb78ce0b | https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/graph.py#L131-L140 |
22,054 | ArangoDB-Community/pyArango | pyArango/graph.py | Graph.createEdge | def createEdge(self, collectionName, _fromId, _toId, edgeAttributes, waitForSync = False) :
"""creates an edge between two documents"""
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 edge definitions" % collectionName)
url = "%s/edge/%s" % (self.URL, collectionName)
self.database[collectionName].validatePrivate("_from", _fromId)
self.database[collectionName].validatePrivate("_to", _toId)
ed = self.database[collectionName].createEdge()
ed.set(edgeAttributes)
ed.validate()
payload = ed.getStore()
payload.update({'_from' : _fromId, '_to' : _toId})
r = self.connection.session.post(url, data = json.dumps(payload, default=str), params = {'waitForSync' : waitForSync})
data = r.json()
if r.status_code == 201 or r.status_code == 202 :
return self.database[collectionName][data["edge"]["_key"]]
# print "\ngraph 160, ", data, payload, _fromId
raise CreationError("Unable to create edge, %s" % r.json()["errorMessage"], data) | python | 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 edge definitions" % collectionName)
url = "%s/edge/%s" % (self.URL, collectionName)
self.database[collectionName].validatePrivate("_from", _fromId)
self.database[collectionName].validatePrivate("_to", _toId)
ed = self.database[collectionName].createEdge()
ed.set(edgeAttributes)
ed.validate()
payload = ed.getStore()
payload.update({'_from' : _fromId, '_to' : _toId})
r = self.connection.session.post(url, data = json.dumps(payload, default=str), params = {'waitForSync' : waitForSync})
data = r.json()
if r.status_code == 201 or r.status_code == 202 :
return self.database[collectionName][data["edge"]["_key"]]
# print "\ngraph 160, ", data, payload, _fromId
raise CreationError("Unable to create edge, %s" % r.json()["errorMessage"], data) | [
"def",
"createEdge",
"(",
"self",
",",
"collectionName",
",",
"_fromId",
",",
"_toId",
",",
"edgeAttributes",
",",
"waitForSync",
"=",
"False",
")",
":",
"if",
"not",
"_fromId",
":",
"raise",
"ValueError",
"(",
"\"Invalid _fromId: %s\"",
"%",
"_fromId",
")",
... | creates an edge between two documents | [
"creates",
"an",
"edge",
"between",
"two",
"documents"
] | dd72e5f6c540e5e148943d615ddf7553bb78ce0b | https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/graph.py#L142-L170 |
22,055 | ArangoDB-Community/pyArango | pyArango/graph.py | Graph.link | 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 :
doc2.save()
doc2_id = doc2._id
else :
doc2_id = doc2
return self.createEdge(definition, doc1_id, doc2_id, edgeAttributes, waitForSync) | python | 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 :
doc2.save()
doc2_id = doc2._id
else :
doc2_id = doc2
return self.createEdge(definition, doc1_id, doc2_id, edgeAttributes, waitForSync) | [
"def",
"link",
"(",
"self",
",",
"definition",
",",
"doc1",
",",
"doc2",
",",
"edgeAttributes",
",",
"waitForSync",
"=",
"False",
")",
":",
"if",
"type",
"(",
"doc1",
")",
"is",
"DOC",
".",
"Document",
":",
"if",
"not",
"doc1",
".",
"_id",
":",
"do... | A shorthand for createEdge that takes two documents as input | [
"A",
"shorthand",
"for",
"createEdge",
"that",
"takes",
"two",
"documents",
"as",
"input"
] | dd72e5f6c540e5e148943d615ddf7553bb78ce0b | https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/graph.py#L172-L188 |
22,056 | ArangoDB-Community/pyArango | pyArango/graph.py | Graph.unlink | 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) | python | 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) | [
"def",
"unlink",
"(",
"self",
",",
"definition",
",",
"doc1",
",",
"doc2",
")",
":",
"links",
"=",
"self",
".",
"database",
"[",
"definition",
"]",
".",
"fetchByExample",
"(",
"{",
"\"_from\"",
":",
"doc1",
".",
"_id",
",",
"\"_to\"",
":",
"doc2",
".... | deletes all links between doc1 and doc2 | [
"deletes",
"all",
"links",
"between",
"doc1",
"and",
"doc2"
] | dd72e5f6c540e5e148943d615ddf7553bb78ce0b | https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/graph.py#L190-L194 |
22,057 | ArangoDB-Community/pyArango | pyArango/graph.py | Graph.deleteEdge | def deleteEdge(self, edge, waitForSync = False) :
"""removes an edge from the graph"""
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 True
raise DeletionError("Unable to delete edge, %s" % edge._id, r.json()) | python | 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 True
raise DeletionError("Unable to delete edge, %s" % edge._id, r.json()) | [
"def",
"deleteEdge",
"(",
"self",
",",
"edge",
",",
"waitForSync",
"=",
"False",
")",
":",
"url",
"=",
"\"%s/edge/%s\"",
"%",
"(",
"self",
".",
"URL",
",",
"edge",
".",
"_id",
")",
"r",
"=",
"self",
".",
"connection",
".",
"session",
".",
"delete",
... | removes an edge from the graph | [
"removes",
"an",
"edge",
"from",
"the",
"graph"
] | dd72e5f6c540e5e148943d615ddf7553bb78ce0b | https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/graph.py#L196-L202 |
22,058 | ArangoDB-Community/pyArango | pyArango/collection.py | DocumentCache.delete | 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 :
raise KeyError("Document with _key %s is not available in cache" % _key) | python | 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 :
raise KeyError("Document with _key %s is not available in cache" % _key) | [
"def",
"delete",
"(",
"self",
",",
"_key",
")",
":",
"try",
":",
"doc",
"=",
"self",
".",
"cacheStore",
"[",
"_key",
"]",
"doc",
".",
"prev",
".",
"nextDoc",
"=",
"doc",
".",
"nextDoc",
"doc",
".",
"nextDoc",
".",
"prev",
"=",
"doc",
".",
"prev",... | removes a document from the cache | [
"removes",
"a",
"document",
"from",
"the",
"cache"
] | dd72e5f6c540e5e148943d615ddf7553bb78ce0b | https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/collection.py#L73-L81 |
22,059 | ArangoDB-Community/pyArango | pyArango/collection.py | DocumentCache.getChain | 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 | python | 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 | [
"def",
"getChain",
"(",
"self",
")",
":",
"l",
"=",
"[",
"]",
"h",
"=",
"self",
".",
"head",
"while",
"h",
":",
"l",
".",
"append",
"(",
"h",
".",
"_key",
")",
"h",
"=",
"h",
".",
"nextDoc",
"return",
"l"
] | returns a list of keys representing the chain of documents | [
"returns",
"a",
"list",
"of",
"keys",
"representing",
"the",
"chain",
"of",
"documents"
] | dd72e5f6c540e5e148943d615ddf7553bb78ce0b | https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/collection.py#L83-L90 |
22,060 | ArangoDB-Community/pyArango | pyArango/collection.py | Field.validate | def validate(self, value) :
"""checks the validity of 'value' given the lits of validators"""
for v in self.validators :
v.validate(value)
return True | python | def validate(self, value) :
for v in self.validators :
v.validate(value)
return True | [
"def",
"validate",
"(",
"self",
",",
"value",
")",
":",
"for",
"v",
"in",
"self",
".",
"validators",
":",
"v",
".",
"validate",
"(",
"value",
")",
"return",
"True"
] | checks the validity of 'value' given the lits of validators | [
"checks",
"the",
"validity",
"of",
"value",
"given",
"the",
"lits",
"of",
"validators"
] | dd72e5f6c540e5e148943d615ddf7553bb78ce0b | https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/collection.py#L121-L125 |
22,061 | ArangoDB-Community/pyArango | pyArango/collection.py | Collection_metaclass.getCollectionClass | def getCollectionClass(cls, name) :
"""Return the class object of a collection given its 'name'"""
try :
return cls.collectionClasses[name]
except KeyError :
raise KeyError( "There is no Collection Class of type: '%s'; currently supported values: [%s]" % (name, ', '.join(getCollectionClasses().keys())) ) | python | def getCollectionClass(cls, name) :
"""Return the class object of a collection given its 'name'"""
try :
return cls.collectionClasses[name]
except KeyError :
raise KeyError( "There is no Collection Class of type: '%s'; currently supported values: [%s]" % (name, ', '.join(getCollectionClasses().keys())) ) | [
"def",
"getCollectionClass",
"(",
"cls",
",",
"name",
")",
":",
"try",
":",
"return",
"cls",
".",
"collectionClasses",
"[",
"name",
"]",
"except",
"KeyError",
":",
"raise",
"KeyError",
"(",
"\"There is no Collection Class of type: '%s'; currently supported values: [%s]\... | Return the class object of a collection given its 'name | [
"Return",
"the",
"class",
"object",
"of",
"a",
"collection",
"given",
"its",
"name"
] | dd72e5f6c540e5e148943d615ddf7553bb78ce0b | https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/collection.py#L168-L173 |
22,062 | ArangoDB-Community/pyArango | pyArango/collection.py | Collection_metaclass.isDocumentCollection | def isDocumentCollection(cls, name) :
"""return true or false wether 'name' is the name of a document collection."""
try :
col = cls.getCollectionClass(name)
return issubclass(col, Collection)
except KeyError :
return False | python | def isDocumentCollection(cls, name) :
try :
col = cls.getCollectionClass(name)
return issubclass(col, Collection)
except KeyError :
return False | [
"def",
"isDocumentCollection",
"(",
"cls",
",",
"name",
")",
":",
"try",
":",
"col",
"=",
"cls",
".",
"getCollectionClass",
"(",
"name",
")",
"return",
"issubclass",
"(",
"col",
",",
"Collection",
")",
"except",
"KeyError",
":",
"return",
"False"
] | return true or false wether 'name' is the name of a document collection. | [
"return",
"true",
"or",
"false",
"wether",
"name",
"is",
"the",
"name",
"of",
"a",
"document",
"collection",
"."
] | dd72e5f6c540e5e148943d615ddf7553bb78ce0b | https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/collection.py#L181-L187 |
22,063 | ArangoDB-Community/pyArango | pyArango/collection.py | Collection_metaclass.isEdgeCollection | def isEdgeCollection(cls, name) :
"""return true or false wether 'name' is the name of an edge collection."""
try :
col = cls.getCollectionClass(name)
return issubclass(col, Edges)
except KeyError :
return False | python | def isEdgeCollection(cls, name) :
try :
col = cls.getCollectionClass(name)
return issubclass(col, Edges)
except KeyError :
return False | [
"def",
"isEdgeCollection",
"(",
"cls",
",",
"name",
")",
":",
"try",
":",
"col",
"=",
"cls",
".",
"getCollectionClass",
"(",
"name",
")",
"return",
"issubclass",
"(",
"col",
",",
"Edges",
")",
"except",
"KeyError",
":",
"return",
"False"
] | return true or false wether 'name' is the name of an edge collection. | [
"return",
"true",
"or",
"false",
"wether",
"name",
"is",
"the",
"name",
"of",
"an",
"edge",
"collection",
"."
] | dd72e5f6c540e5e148943d615ddf7553bb78ce0b | https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/collection.py#L190-L196 |
22,064 | ArangoDB-Community/pyArango | pyArango/collection.py | Collection.getIndexes | def getIndexes(self) :
"""Fills self.indexes with all the indexes associates with the collection and returns it"""
url = "%s/index" % self.database.URL
r = self.connection.session.get(url, params = {"collection": self.name})
data = r.json()
for ind in data["indexes"] :
self.indexes[ind["type"]][ind["id"]] = Index(collection = self, infos = ind)
return self.indexes | python | def getIndexes(self) :
url = "%s/index" % self.database.URL
r = self.connection.session.get(url, params = {"collection": self.name})
data = r.json()
for ind in data["indexes"] :
self.indexes[ind["type"]][ind["id"]] = Index(collection = self, infos = ind)
return self.indexes | [
"def",
"getIndexes",
"(",
"self",
")",
":",
"url",
"=",
"\"%s/index\"",
"%",
"self",
".",
"database",
".",
"URL",
"r",
"=",
"self",
".",
"connection",
".",
"session",
".",
"get",
"(",
"url",
",",
"params",
"=",
"{",
"\"collection\"",
":",
"self",
"."... | Fills self.indexes with all the indexes associates with the collection and returns it | [
"Fills",
"self",
".",
"indexes",
"with",
"all",
"the",
"indexes",
"associates",
"with",
"the",
"collection",
"and",
"returns",
"it"
] | dd72e5f6c540e5e148943d615ddf7553bb78ce0b | https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/collection.py#L265-L273 |
22,065 | ArangoDB-Community/pyArango | pyArango/collection.py | Collection.delete | def delete(self) :
"""deletes the collection from the database"""
r = self.connection.session.delete(self.URL)
data = r.json()
if not r.status_code == 200 or data["error"] :
raise DeletionError(data["errorMessage"], data) | python | def delete(self) :
r = self.connection.session.delete(self.URL)
data = r.json()
if not r.status_code == 200 or data["error"] :
raise DeletionError(data["errorMessage"], data) | [
"def",
"delete",
"(",
"self",
")",
":",
"r",
"=",
"self",
".",
"connection",
".",
"session",
".",
"delete",
"(",
"self",
".",
"URL",
")",
"data",
"=",
"r",
".",
"json",
"(",
")",
"if",
"not",
"r",
".",
"status_code",
"==",
"200",
"or",
"data",
... | deletes the collection from the database | [
"deletes",
"the",
"collection",
"from",
"the",
"database"
] | dd72e5f6c540e5e148943d615ddf7553bb78ce0b | https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/collection.py#L283-L288 |
22,066 | ArangoDB-Community/pyArango | pyArango/collection.py | Collection.createDocument | def createDocument(self, initDict = None) :
"""create and returns a document populated with the defaults or with the values in initDict"""
if initDict is not None :
return self.createDocument_(initDict)
else :
if self._validation["on_load"] :
self._validation["on_load"] = False
return self.createDocument_(self.defaultDocument)
self._validation["on_load"] = True
else :
return self.createDocument_(self.defaultDocument) | python | def createDocument(self, initDict = None) :
if initDict is not None :
return self.createDocument_(initDict)
else :
if self._validation["on_load"] :
self._validation["on_load"] = False
return self.createDocument_(self.defaultDocument)
self._validation["on_load"] = True
else :
return self.createDocument_(self.defaultDocument) | [
"def",
"createDocument",
"(",
"self",
",",
"initDict",
"=",
"None",
")",
":",
"if",
"initDict",
"is",
"not",
"None",
":",
"return",
"self",
".",
"createDocument_",
"(",
"initDict",
")",
"else",
":",
"if",
"self",
".",
"_validation",
"[",
"\"on_load\"",
"... | create and returns a document populated with the defaults or with the values in initDict | [
"create",
"and",
"returns",
"a",
"document",
"populated",
"with",
"the",
"defaults",
"or",
"with",
"the",
"values",
"in",
"initDict"
] | dd72e5f6c540e5e148943d615ddf7553bb78ce0b | https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/collection.py#L290-L300 |
22,067 | ArangoDB-Community/pyArango | pyArango/collection.py | Collection.createDocument_ | def createDocument_(self, initDict = None) :
"create and returns a completely empty document or one populated with initDict"
if initDict is None :
initV = {}
else :
initV = initDict
return self.documentClass(self, initV) | python | def createDocument_(self, initDict = None) :
"create and returns a completely empty document or one populated with initDict"
if initDict is None :
initV = {}
else :
initV = initDict
return self.documentClass(self, initV) | [
"def",
"createDocument_",
"(",
"self",
",",
"initDict",
"=",
"None",
")",
":",
"if",
"initDict",
"is",
"None",
":",
"initV",
"=",
"{",
"}",
"else",
":",
"initV",
"=",
"initDict",
"return",
"self",
".",
"documentClass",
"(",
"self",
",",
"initV",
")"
] | create and returns a completely empty document or one populated with initDict | [
"create",
"and",
"returns",
"a",
"completely",
"empty",
"document",
"or",
"one",
"populated",
"with",
"initDict"
] | dd72e5f6c540e5e148943d615ddf7553bb78ce0b | https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/collection.py#L302-L309 |
22,068 | ArangoDB-Community/pyArango | pyArango/collection.py | Collection.ensureHashIndex | def ensureHashIndex(self, fields, unique = False, sparse = True, deduplicate = False) :
"""Creates a hash index if it does not already exist, and returns it"""
data = {
"type" : "hash",
"fields" : fields,
"unique" : unique,
"sparse" : sparse,
"deduplicate": deduplicate
}
ind = Index(self, creationData = data)
self.indexes["hash"][ind.infos["id"]] = ind
return ind | python | def ensureHashIndex(self, fields, unique = False, sparse = True, deduplicate = False) :
data = {
"type" : "hash",
"fields" : fields,
"unique" : unique,
"sparse" : sparse,
"deduplicate": deduplicate
}
ind = Index(self, creationData = data)
self.indexes["hash"][ind.infos["id"]] = ind
return ind | [
"def",
"ensureHashIndex",
"(",
"self",
",",
"fields",
",",
"unique",
"=",
"False",
",",
"sparse",
"=",
"True",
",",
"deduplicate",
"=",
"False",
")",
":",
"data",
"=",
"{",
"\"type\"",
":",
"\"hash\"",
",",
"\"fields\"",
":",
"fields",
",",
"\"unique\"",... | Creates a hash index if it does not already exist, and returns it | [
"Creates",
"a",
"hash",
"index",
"if",
"it",
"does",
"not",
"already",
"exist",
"and",
"returns",
"it"
] | dd72e5f6c540e5e148943d615ddf7553bb78ce0b | https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/collection.py#L333-L344 |
22,069 | ArangoDB-Community/pyArango | pyArango/collection.py | Collection.ensureGeoIndex | def ensureGeoIndex(self, fields) :
"""Creates a geo index if it does not already exist, and returns it"""
data = {
"type" : "geo",
"fields" : fields,
}
ind = Index(self, creationData = data)
self.indexes["geo"][ind.infos["id"]] = ind
return ind | python | def ensureGeoIndex(self, fields) :
data = {
"type" : "geo",
"fields" : fields,
}
ind = Index(self, creationData = data)
self.indexes["geo"][ind.infos["id"]] = ind
return ind | [
"def",
"ensureGeoIndex",
"(",
"self",
",",
"fields",
")",
":",
"data",
"=",
"{",
"\"type\"",
":",
"\"geo\"",
",",
"\"fields\"",
":",
"fields",
",",
"}",
"ind",
"=",
"Index",
"(",
"self",
",",
"creationData",
"=",
"data",
")",
"self",
".",
"indexes",
... | Creates a geo index if it does not already exist, and returns it | [
"Creates",
"a",
"geo",
"index",
"if",
"it",
"does",
"not",
"already",
"exist",
"and",
"returns",
"it"
] | dd72e5f6c540e5e148943d615ddf7553bb78ce0b | https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/collection.py#L359-L367 |
22,070 | ArangoDB-Community/pyArango | pyArango/collection.py | Collection.ensureFulltextIndex | def ensureFulltextIndex(self, fields, minLength = None) :
"""Creates a fulltext index if it does not already exist, and returns it"""
data = {
"type" : "fulltext",
"fields" : fields,
}
if minLength is not None :
data["minLength"] = minLength
ind = Index(self, creationData = data)
self.indexes["fulltext"][ind.infos["id"]] = ind
return ind | python | def ensureFulltextIndex(self, fields, minLength = None) :
data = {
"type" : "fulltext",
"fields" : fields,
}
if minLength is not None :
data["minLength"] = minLength
ind = Index(self, creationData = data)
self.indexes["fulltext"][ind.infos["id"]] = ind
return ind | [
"def",
"ensureFulltextIndex",
"(",
"self",
",",
"fields",
",",
"minLength",
"=",
"None",
")",
":",
"data",
"=",
"{",
"\"type\"",
":",
"\"fulltext\"",
",",
"\"fields\"",
":",
"fields",
",",
"}",
"if",
"minLength",
"is",
"not",
"None",
":",
"data",
"[",
... | Creates a fulltext index if it does not already exist, and returns it | [
"Creates",
"a",
"fulltext",
"index",
"if",
"it",
"does",
"not",
"already",
"exist",
"and",
"returns",
"it"
] | dd72e5f6c540e5e148943d615ddf7553bb78ce0b | https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/collection.py#L369-L380 |
22,071 | ArangoDB-Community/pyArango | pyArango/collection.py | Collection.validatePrivate | def validatePrivate(self, field, value) :
"""validate a private field value"""
if field not in self.arangoPrivates :
raise ValueError("%s is not a private field of collection %s" % (field, self))
if field in self._fields :
self._fields[field].validate(value)
return True | python | def validatePrivate(self, field, value) :
if field not in self.arangoPrivates :
raise ValueError("%s is not a private field of collection %s" % (field, self))
if field in self._fields :
self._fields[field].validate(value)
return True | [
"def",
"validatePrivate",
"(",
"self",
",",
"field",
",",
"value",
")",
":",
"if",
"field",
"not",
"in",
"self",
".",
"arangoPrivates",
":",
"raise",
"ValueError",
"(",
"\"%s is not a private field of collection %s\"",
"%",
"(",
"field",
",",
"self",
")",
")",... | validate a private field value | [
"validate",
"a",
"private",
"field",
"value"
] | dd72e5f6c540e5e148943d615ddf7553bb78ce0b | https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/collection.py#L383-L390 |
22,072 | ArangoDB-Community/pyArango | pyArango/collection.py | Collection.simpleQuery | def simpleQuery(self, queryType, rawResults = False, **queryArgs) :
"""General interface for simple queries. queryType can be something like 'all', 'by-example' etc... everything is in the arango doc.
If rawResults, the query will return dictionaries instead of Document objetcs.
"""
return SimpleQuery(self, queryType, rawResults, **queryArgs) | python | def simpleQuery(self, queryType, rawResults = False, **queryArgs) :
return SimpleQuery(self, queryType, rawResults, **queryArgs) | [
"def",
"simpleQuery",
"(",
"self",
",",
"queryType",
",",
"rawResults",
"=",
"False",
",",
"*",
"*",
"queryArgs",
")",
":",
"return",
"SimpleQuery",
"(",
"self",
",",
"queryType",
",",
"rawResults",
",",
"*",
"*",
"queryArgs",
")"
] | General interface for simple queries. queryType can be something like 'all', 'by-example' etc... everything is in the arango doc.
If rawResults, the query will return dictionaries instead of Document objetcs. | [
"General",
"interface",
"for",
"simple",
"queries",
".",
"queryType",
"can",
"be",
"something",
"like",
"all",
"by",
"-",
"example",
"etc",
"...",
"everything",
"is",
"in",
"the",
"arango",
"doc",
".",
"If",
"rawResults",
"the",
"query",
"will",
"return",
... | dd72e5f6c540e5e148943d615ddf7553bb78ce0b | https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/collection.py#L486-L490 |
22,073 | ArangoDB-Community/pyArango | pyArango/collection.py | Collection.action | def action(self, method, action, **params) :
"""a generic fct for interacting everything that doesn't have an assigned fct"""
fct = getattr(self.connection.session, method.lower())
r = fct(self.URL + "/" + action, params = params)
return r.json() | python | def action(self, method, action, **params) :
fct = getattr(self.connection.session, method.lower())
r = fct(self.URL + "/" + action, params = params)
return r.json() | [
"def",
"action",
"(",
"self",
",",
"method",
",",
"action",
",",
"*",
"*",
"params",
")",
":",
"fct",
"=",
"getattr",
"(",
"self",
".",
"connection",
".",
"session",
",",
"method",
".",
"lower",
"(",
")",
")",
"r",
"=",
"fct",
"(",
"self",
".",
... | a generic fct for interacting everything that doesn't have an assigned fct | [
"a",
"generic",
"fct",
"for",
"interacting",
"everything",
"that",
"doesn",
"t",
"have",
"an",
"assigned",
"fct"
] | dd72e5f6c540e5e148943d615ddf7553bb78ce0b | https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/collection.py#L492-L496 |
22,074 | ArangoDB-Community/pyArango | pyArango/collection.py | Collection.bulkSave | def bulkSave(self, docs, onDuplicate="error", **params) :
"""Parameter docs must be either an iterrable of documents or dictionnaries.
This function will return the number of documents, created and updated, and will raise an UpdateError exception if there's at least one error.
params are any parameters from arango's documentation"""
payload = []
for d in docs :
if type(d) is dict :
payload.append(json.dumps(d, default=str))
else :
try:
payload.append(d.toJson())
except Exception as e:
payload.append(json.dumps(d.getStore(), default=str))
payload = '\n'.join(payload)
params["type"] = "documents"
params["onDuplicate"] = onDuplicate
params["collection"] = self.name
URL = "%s/import" % self.database.URL
r = self.connection.session.post(URL, params = params, data = payload)
data = r.json()
if (r.status_code == 201) and "error" not in data :
return True
else :
if data["errors"] > 0 :
raise UpdateError("%d documents could not be created" % data["errors"], data)
return data["updated"] + data["created"] | python | def bulkSave(self, docs, onDuplicate="error", **params) :
payload = []
for d in docs :
if type(d) is dict :
payload.append(json.dumps(d, default=str))
else :
try:
payload.append(d.toJson())
except Exception as e:
payload.append(json.dumps(d.getStore(), default=str))
payload = '\n'.join(payload)
params["type"] = "documents"
params["onDuplicate"] = onDuplicate
params["collection"] = self.name
URL = "%s/import" % self.database.URL
r = self.connection.session.post(URL, params = params, data = payload)
data = r.json()
if (r.status_code == 201) and "error" not in data :
return True
else :
if data["errors"] > 0 :
raise UpdateError("%d documents could not be created" % data["errors"], data)
return data["updated"] + data["created"] | [
"def",
"bulkSave",
"(",
"self",
",",
"docs",
",",
"onDuplicate",
"=",
"\"error\"",
",",
"*",
"*",
"params",
")",
":",
"payload",
"=",
"[",
"]",
"for",
"d",
"in",
"docs",
":",
"if",
"type",
"(",
"d",
")",
"is",
"dict",
":",
"payload",
".",
"append... | Parameter docs must be either an iterrable of documents or dictionnaries.
This function will return the number of documents, created and updated, and will raise an UpdateError exception if there's at least one error.
params are any parameters from arango's documentation | [
"Parameter",
"docs",
"must",
"be",
"either",
"an",
"iterrable",
"of",
"documents",
"or",
"dictionnaries",
".",
"This",
"function",
"will",
"return",
"the",
"number",
"of",
"documents",
"created",
"and",
"updated",
"and",
"will",
"raise",
"an",
"UpdateError",
"... | dd72e5f6c540e5e148943d615ddf7553bb78ce0b | https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/collection.py#L498-L528 |
22,075 | ArangoDB-Community/pyArango | pyArango/collection.py | Edges.getEdges | def getEdges(self, vertex, inEdges = True, outEdges = True, rawResults = False) :
"""returns in, out, or both edges liked to a given document. vertex can be either a Document object or a string for an _id.
If rawResults a arango results will be return as fetched, if false, will return a liste of Edge objects"""
if isinstance(vertex, Document):
vId = vertex._id
elif (type(vertex) is str) or (type(vertex) is bytes):
vId = vertex
else :
raise ValueError("Vertex is neither a Document nor a String")
params = {"vertex" : vId}
if inEdges and outEdges :
pass
elif inEdges :
params["direction"] = "in"
elif outEdges :
params["direction"] = "out"
else :
raise ValueError("inEdges, outEdges or both must have a boolean value")
r = self.connection.session.get(self.edgesURL, params = params)
data = r.json()
if r.status_code == 200 :
if not rawResults :
ret = []
for e in data["edges"] :
ret.append(Edge(self, e))
return ret
else :
return data["edges"]
else :
raise CreationError("Unable to return edges for vertex: %s" % vId, data) | python | def getEdges(self, vertex, inEdges = True, outEdges = True, rawResults = False) :
if isinstance(vertex, Document):
vId = vertex._id
elif (type(vertex) is str) or (type(vertex) is bytes):
vId = vertex
else :
raise ValueError("Vertex is neither a Document nor a String")
params = {"vertex" : vId}
if inEdges and outEdges :
pass
elif inEdges :
params["direction"] = "in"
elif outEdges :
params["direction"] = "out"
else :
raise ValueError("inEdges, outEdges or both must have a boolean value")
r = self.connection.session.get(self.edgesURL, params = params)
data = r.json()
if r.status_code == 200 :
if not rawResults :
ret = []
for e in data["edges"] :
ret.append(Edge(self, e))
return ret
else :
return data["edges"]
else :
raise CreationError("Unable to return edges for vertex: %s" % vId, data) | [
"def",
"getEdges",
"(",
"self",
",",
"vertex",
",",
"inEdges",
"=",
"True",
",",
"outEdges",
"=",
"True",
",",
"rawResults",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"vertex",
",",
"Document",
")",
":",
"vId",
"=",
"vertex",
".",
"_id",
"elif... | returns in, out, or both edges liked to a given document. vertex can be either a Document object or a string for an _id.
If rawResults a arango results will be return as fetched, if false, will return a liste of Edge objects | [
"returns",
"in",
"out",
"or",
"both",
"edges",
"liked",
"to",
"a",
"given",
"document",
".",
"vertex",
"can",
"be",
"either",
"a",
"Document",
"object",
"or",
"a",
"string",
"for",
"an",
"_id",
".",
"If",
"rawResults",
"a",
"arango",
"results",
"will",
... | dd72e5f6c540e5e148943d615ddf7553bb78ce0b | https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/collection.py#L695-L726 |
22,076 | ArangoDB-Community/pyArango | pyArango/database.py | Database.reloadCollections | def reloadCollections(self) :
"reloads the collection list."
r = self.connection.session.get(self.collectionsURL)
data = r.json()
if r.status_code == 200 :
self.collections = {}
for colData in data["result"] :
colName = colData['name']
if colData['isSystem'] :
colObj = COL.SystemCollection(self, colData)
else :
try :
colClass = COL.getCollectionClass(colName)
colObj = colClass(self, colData)
except KeyError :
if colData["type"] == CONST.COLLECTION_EDGE_TYPE :
colObj = COL.Edges(self, colData)
elif colData["type"] == CONST.COLLECTION_DOCUMENT_TYPE :
colObj = COL.Collection(self, colData)
else :
print(("Warning!! Collection of unknown type: %d, trying to load it as Collection nonetheless." % colData["type"]))
colObj = COL.Collection(self, colData)
self.collections[colName] = colObj
else :
raise UpdateError(data["errorMessage"], data) | python | def reloadCollections(self) :
"reloads the collection list."
r = self.connection.session.get(self.collectionsURL)
data = r.json()
if r.status_code == 200 :
self.collections = {}
for colData in data["result"] :
colName = colData['name']
if colData['isSystem'] :
colObj = COL.SystemCollection(self, colData)
else :
try :
colClass = COL.getCollectionClass(colName)
colObj = colClass(self, colData)
except KeyError :
if colData["type"] == CONST.COLLECTION_EDGE_TYPE :
colObj = COL.Edges(self, colData)
elif colData["type"] == CONST.COLLECTION_DOCUMENT_TYPE :
colObj = COL.Collection(self, colData)
else :
print(("Warning!! Collection of unknown type: %d, trying to load it as Collection nonetheless." % colData["type"]))
colObj = COL.Collection(self, colData)
self.collections[colName] = colObj
else :
raise UpdateError(data["errorMessage"], data) | [
"def",
"reloadCollections",
"(",
"self",
")",
":",
"r",
"=",
"self",
".",
"connection",
".",
"session",
".",
"get",
"(",
"self",
".",
"collectionsURL",
")",
"data",
"=",
"r",
".",
"json",
"(",
")",
"if",
"r",
".",
"status_code",
"==",
"200",
":",
"... | reloads the collection list. | [
"reloads",
"the",
"collection",
"list",
"."
] | dd72e5f6c540e5e148943d615ddf7553bb78ce0b | https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/database.py#L36-L62 |
22,077 | ArangoDB-Community/pyArango | pyArango/database.py | Database.reloadGraphs | def reloadGraphs(self) :
"reloads the graph list"
r = self.connection.session.get(self.graphsURL)
data = r.json()
if r.status_code == 200 :
self.graphs = {}
for graphData in data["graphs"] :
try :
self.graphs[graphData["_key"]] = GR.getGraphClass(graphData["_key"])(self, graphData)
except KeyError :
self.graphs[graphData["_key"]] = Graph(self, graphData)
else :
raise UpdateError(data["errorMessage"], data) | python | def reloadGraphs(self) :
"reloads the graph list"
r = self.connection.session.get(self.graphsURL)
data = r.json()
if r.status_code == 200 :
self.graphs = {}
for graphData in data["graphs"] :
try :
self.graphs[graphData["_key"]] = GR.getGraphClass(graphData["_key"])(self, graphData)
except KeyError :
self.graphs[graphData["_key"]] = Graph(self, graphData)
else :
raise UpdateError(data["errorMessage"], data) | [
"def",
"reloadGraphs",
"(",
"self",
")",
":",
"r",
"=",
"self",
".",
"connection",
".",
"session",
".",
"get",
"(",
"self",
".",
"graphsURL",
")",
"data",
"=",
"r",
".",
"json",
"(",
")",
"if",
"r",
".",
"status_code",
"==",
"200",
":",
"self",
"... | reloads the graph list | [
"reloads",
"the",
"graph",
"list"
] | dd72e5f6c540e5e148943d615ddf7553bb78ce0b | https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/database.py#L64-L76 |
22,078 | ArangoDB-Community/pyArango | pyArango/database.py | Database.createGraph | def createGraph(self, name, createCollections = True, isSmart = False, numberOfShards = None, smartGraphAttribute = None) :
"""Creates a graph and returns it. 'name' must be the name of a class inheriting from Graph.
Checks will be performed to make sure that every collection mentionned in the edges definition exist. Raises a ValueError in case of
a non-existing collection."""
def _checkCollectionList(lst) :
for colName in lst :
if not COL.isCollection(colName) :
raise ValueError("'%s' is not a defined Collection" % colName)
graphClass = GR.getGraphClass(name)
ed = []
for e in graphClass._edgeDefinitions :
if not COL.isEdgeCollection(e.edgesCollection) :
raise ValueError("'%s' is not a defined Edge Collection" % e.edgesCollection)
_checkCollectionList(e.fromCollections)
_checkCollectionList(e.toCollections)
ed.append(e.toJson())
_checkCollectionList(graphClass._orphanedCollections)
options = {}
if numberOfShards:
options['numberOfShards'] = numberOfShards
if smartGraphAttribute:
options['smartGraphAttribute'] = smartGraphAttribute
payload = {
"name": name,
"edgeDefinitions": ed,
"orphanCollections": graphClass._orphanedCollections
}
if isSmart :
payload['isSmart'] = isSmart
if options:
payload['options'] = options
payload = json.dumps(payload)
r = self.connection.session.post(self.graphsURL, data = payload)
data = r.json()
if r.status_code == 201 or r.status_code == 202 :
self.graphs[name] = graphClass(self, data["graph"])
else :
raise CreationError(data["errorMessage"], data)
return self.graphs[name] | python | def createGraph(self, name, createCollections = True, isSmart = False, numberOfShards = None, smartGraphAttribute = None) :
def _checkCollectionList(lst) :
for colName in lst :
if not COL.isCollection(colName) :
raise ValueError("'%s' is not a defined Collection" % colName)
graphClass = GR.getGraphClass(name)
ed = []
for e in graphClass._edgeDefinitions :
if not COL.isEdgeCollection(e.edgesCollection) :
raise ValueError("'%s' is not a defined Edge Collection" % e.edgesCollection)
_checkCollectionList(e.fromCollections)
_checkCollectionList(e.toCollections)
ed.append(e.toJson())
_checkCollectionList(graphClass._orphanedCollections)
options = {}
if numberOfShards:
options['numberOfShards'] = numberOfShards
if smartGraphAttribute:
options['smartGraphAttribute'] = smartGraphAttribute
payload = {
"name": name,
"edgeDefinitions": ed,
"orphanCollections": graphClass._orphanedCollections
}
if isSmart :
payload['isSmart'] = isSmart
if options:
payload['options'] = options
payload = json.dumps(payload)
r = self.connection.session.post(self.graphsURL, data = payload)
data = r.json()
if r.status_code == 201 or r.status_code == 202 :
self.graphs[name] = graphClass(self, data["graph"])
else :
raise CreationError(data["errorMessage"], data)
return self.graphs[name] | [
"def",
"createGraph",
"(",
"self",
",",
"name",
",",
"createCollections",
"=",
"True",
",",
"isSmart",
"=",
"False",
",",
"numberOfShards",
"=",
"None",
",",
"smartGraphAttribute",
"=",
"None",
")",
":",
"def",
"_checkCollectionList",
"(",
"lst",
")",
":",
... | Creates a graph and returns it. 'name' must be the name of a class inheriting from Graph.
Checks will be performed to make sure that every collection mentionned in the edges definition exist. Raises a ValueError in case of
a non-existing collection. | [
"Creates",
"a",
"graph",
"and",
"returns",
"it",
".",
"name",
"must",
"be",
"the",
"name",
"of",
"a",
"class",
"inheriting",
"from",
"Graph",
".",
"Checks",
"will",
"be",
"performed",
"to",
"make",
"sure",
"that",
"every",
"collection",
"mentionned",
"in",... | dd72e5f6c540e5e148943d615ddf7553bb78ce0b | https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/database.py#L129-L179 |
22,079 | ArangoDB-Community/pyArango | pyArango/database.py | Database.validateAQLQuery | def validateAQLQuery(self, query, bindVars = None, options = None) :
"returns the server answer is the query is valid. Raises an AQLQueryError if not"
if bindVars is None :
bindVars = {}
if options is None :
options = {}
payload = {'query' : query, 'bindVars' : bindVars, 'options' : options}
r = self.connection.session.post(self.cursorsURL, data = json.dumps(payload, default=str))
data = r.json()
if r.status_code == 201 and not data["error"] :
return data
else :
raise AQLQueryError(data["errorMessage"], query, data) | python | def validateAQLQuery(self, query, bindVars = None, options = None) :
"returns the server answer is the query is valid. Raises an AQLQueryError if not"
if bindVars is None :
bindVars = {}
if options is None :
options = {}
payload = {'query' : query, 'bindVars' : bindVars, 'options' : options}
r = self.connection.session.post(self.cursorsURL, data = json.dumps(payload, default=str))
data = r.json()
if r.status_code == 201 and not data["error"] :
return data
else :
raise AQLQueryError(data["errorMessage"], query, data) | [
"def",
"validateAQLQuery",
"(",
"self",
",",
"query",
",",
"bindVars",
"=",
"None",
",",
"options",
"=",
"None",
")",
":",
"if",
"bindVars",
"is",
"None",
":",
"bindVars",
"=",
"{",
"}",
"if",
"options",
"is",
"None",
":",
"options",
"=",
"{",
"}",
... | returns the server answer is the query is valid. Raises an AQLQueryError if not | [
"returns",
"the",
"server",
"answer",
"is",
"the",
"query",
"is",
"valid",
".",
"Raises",
"an",
"AQLQueryError",
"if",
"not"
] | dd72e5f6c540e5e148943d615ddf7553bb78ce0b | https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/database.py#L212-L224 |
22,080 | ArangoDB-Community/pyArango | pyArango/database.py | Database.transaction | def transaction(self, collections, action, waitForSync = False, lockTimeout = None, params = None) :
"""Execute a server-side transaction"""
payload = {
"collections": collections,
"action": action,
"waitForSync": waitForSync}
if lockTimeout is not None:
payload["lockTimeout"] = lockTimeout
if params is not None:
payload["params"] = params
self.connection.reportStart(action)
r = self.connection.session.post(self.transactionURL, data = json.dumps(payload, default=str))
self.connection.reportItem()
data = r.json()
if (r.status_code == 200 or r.status_code == 201 or r.status_code == 202) and not data.get("error") :
return data
else :
raise TransactionError(data["errorMessage"], action, data) | python | def transaction(self, collections, action, waitForSync = False, lockTimeout = None, params = None) :
payload = {
"collections": collections,
"action": action,
"waitForSync": waitForSync}
if lockTimeout is not None:
payload["lockTimeout"] = lockTimeout
if params is not None:
payload["params"] = params
self.connection.reportStart(action)
r = self.connection.session.post(self.transactionURL, data = json.dumps(payload, default=str))
self.connection.reportItem()
data = r.json()
if (r.status_code == 200 or r.status_code == 201 or r.status_code == 202) and not data.get("error") :
return data
else :
raise TransactionError(data["errorMessage"], action, data) | [
"def",
"transaction",
"(",
"self",
",",
"collections",
",",
"action",
",",
"waitForSync",
"=",
"False",
",",
"lockTimeout",
"=",
"None",
",",
"params",
"=",
"None",
")",
":",
"payload",
"=",
"{",
"\"collections\"",
":",
"collections",
",",
"\"action\"",
":... | Execute a server-side transaction | [
"Execute",
"a",
"server",
"-",
"side",
"transaction"
] | dd72e5f6c540e5e148943d615ddf7553bb78ce0b | https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/database.py#L226-L248 |
22,081 | ArangoDB-Community/pyArango | pyArango/document.py | DocumentStore.getPatches | def getPatches(self) :
"""get patches as a dictionary"""
if not self.mustValidate :
return self.getStore()
res = {}
res.update(self.patchStore)
for k, v in self.subStores.items() :
res[k] = v.getPatches()
return res | python | def getPatches(self) :
if not self.mustValidate :
return self.getStore()
res = {}
res.update(self.patchStore)
for k, v in self.subStores.items() :
res[k] = v.getPatches()
return res | [
"def",
"getPatches",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"mustValidate",
":",
"return",
"self",
".",
"getStore",
"(",
")",
"res",
"=",
"{",
"}",
"res",
".",
"update",
"(",
"self",
".",
"patchStore",
")",
"for",
"k",
",",
"v",
"in",
"... | get patches as a dictionary | [
"get",
"patches",
"as",
"a",
"dictionary"
] | dd72e5f6c540e5e148943d615ddf7553bb78ce0b | https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/document.py#L38-L48 |
22,082 | ArangoDB-Community/pyArango | pyArango/document.py | DocumentStore.getStore | def getStore(self) :
"""get the inner store as dictionary"""
res = {}
res.update(self.store)
for k, v in self.subStores.items() :
res[k] = v.getStore()
return res | python | def getStore(self) :
res = {}
res.update(self.store)
for k, v in self.subStores.items() :
res[k] = v.getStore()
return res | [
"def",
"getStore",
"(",
"self",
")",
":",
"res",
"=",
"{",
"}",
"res",
".",
"update",
"(",
"self",
".",
"store",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"subStores",
".",
"items",
"(",
")",
":",
"res",
"[",
"k",
"]",
"=",
"v",
".",
"g... | get the inner store as dictionary | [
"get",
"the",
"inner",
"store",
"as",
"dictionary"
] | dd72e5f6c540e5e148943d615ddf7553bb78ce0b | https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/document.py#L50-L57 |
22,083 | ArangoDB-Community/pyArango | pyArango/document.py | DocumentStore.validateField | def validateField(self, field) :
"""Validatie a field"""
if field not in self.validators and not self.collection._validation['allow_foreign_fields'] :
raise SchemaViolation(self.collection.__class__, field)
if field in self.store:
if isinstance(self.store[field], DocumentStore) :
return self[field].validate()
if field in self.patchStore :
return self.validators[field].validate(self.patchStore[field])
else :
try :
return self.validators[field].validate(self.store[field])
except ValidationError as e:
raise ValidationError( "'%s' -> %s" % ( field, str(e)) )
except AttributeError:
if isinstance(self.validators[field], dict) and not isinstance(self.store[field], dict) :
raise ValueError("Validator expected a sub document for field '%s', got '%s' instead" % (field, self.store[field]) )
else :
raise
return True | python | def validateField(self, field) :
if field not in self.validators and not self.collection._validation['allow_foreign_fields'] :
raise SchemaViolation(self.collection.__class__, field)
if field in self.store:
if isinstance(self.store[field], DocumentStore) :
return self[field].validate()
if field in self.patchStore :
return self.validators[field].validate(self.patchStore[field])
else :
try :
return self.validators[field].validate(self.store[field])
except ValidationError as e:
raise ValidationError( "'%s' -> %s" % ( field, str(e)) )
except AttributeError:
if isinstance(self.validators[field], dict) and not isinstance(self.store[field], dict) :
raise ValueError("Validator expected a sub document for field '%s', got '%s' instead" % (field, self.store[field]) )
else :
raise
return True | [
"def",
"validateField",
"(",
"self",
",",
"field",
")",
":",
"if",
"field",
"not",
"in",
"self",
".",
"validators",
"and",
"not",
"self",
".",
"collection",
".",
"_validation",
"[",
"'allow_foreign_fields'",
"]",
":",
"raise",
"SchemaViolation",
"(",
"self",... | Validatie a field | [
"Validatie",
"a",
"field"
] | dd72e5f6c540e5e148943d615ddf7553bb78ce0b | https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/document.py#L59-L80 |
22,084 | ArangoDB-Community/pyArango | pyArango/document.py | DocumentStore.validate | def validate(self) :
"""Validate the whole document"""
if not self.mustValidate :
return True
res = {}
for field in self.validators.keys() :
try :
if isinstance(self.validators[field], dict) and field not in self.store :
self.store[field] = DocumentStore(self.collection, validators = self.validators[field], initDct = {}, subStore=True, validateInit=self.validateInit)
self.validateField(field)
except InvalidDocument as e :
res.update(e.errors)
except (ValidationError, SchemaViolation) as e:
res[field] = str(e)
if len(res) > 0 :
raise InvalidDocument(res)
return True | python | def validate(self) :
if not self.mustValidate :
return True
res = {}
for field in self.validators.keys() :
try :
if isinstance(self.validators[field], dict) and field not in self.store :
self.store[field] = DocumentStore(self.collection, validators = self.validators[field], initDct = {}, subStore=True, validateInit=self.validateInit)
self.validateField(field)
except InvalidDocument as e :
res.update(e.errors)
except (ValidationError, SchemaViolation) as e:
res[field] = str(e)
if len(res) > 0 :
raise InvalidDocument(res)
return True | [
"def",
"validate",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"mustValidate",
":",
"return",
"True",
"res",
"=",
"{",
"}",
"for",
"field",
"in",
"self",
".",
"validators",
".",
"keys",
"(",
")",
":",
"try",
":",
"if",
"isinstance",
"(",
"self... | Validate the whole document | [
"Validate",
"the",
"whole",
"document"
] | dd72e5f6c540e5e148943d615ddf7553bb78ce0b | https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/document.py#L82-L101 |
22,085 | ArangoDB-Community/pyArango | pyArango/document.py | DocumentStore.set | def set(self, dct) :
"""Set the store using a dictionary"""
# if not self.mustValidate :
# self.store = dct
# self.patchStore = dct
# return
for field, value in dct.items() :
if field not in self.collection.arangoPrivates :
if isinstance(value, dict) :
if field in self.validators and isinstance(self.validators[field], dict):
vals = self.validators[field]
else :
vals = {}
self[field] = DocumentStore(self.collection, validators = vals, initDct = value, patch = self.patching, subStore=True, validateInit=self.validateInit)
self.subStores[field] = self.store[field]
else :
self[field] = value | python | def set(self, dct) :
# if not self.mustValidate :
# self.store = dct
# self.patchStore = dct
# return
for field, value in dct.items() :
if field not in self.collection.arangoPrivates :
if isinstance(value, dict) :
if field in self.validators and isinstance(self.validators[field], dict):
vals = self.validators[field]
else :
vals = {}
self[field] = DocumentStore(self.collection, validators = vals, initDct = value, patch = self.patching, subStore=True, validateInit=self.validateInit)
self.subStores[field] = self.store[field]
else :
self[field] = value | [
"def",
"set",
"(",
"self",
",",
"dct",
")",
":",
"# if not self.mustValidate :",
"# self.store = dct",
"# self.patchStore = dct",
"# return",
"for",
"field",
",",
"value",
"in",
"dct",
".",
"items",
"(",
")",
":",
"if",
"field",
"not",
"in",
"self",
... | Set the store using a dictionary | [
"Set",
"the",
"store",
"using",
"a",
"dictionary"
] | dd72e5f6c540e5e148943d615ddf7553bb78ce0b | https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/document.py#L103-L120 |
22,086 | ArangoDB-Community/pyArango | pyArango/document.py | Document.reset | def reset(self, collection, jsonFieldInit = None) :
if not jsonFieldInit:
jsonFieldInit = {}
"""replaces the current values in the document by those in jsonFieldInit"""
self.collection = collection
self.connection = self.collection.connection
self.documentsURL = self.collection.documentsURL
self.URL = None
self.setPrivates(jsonFieldInit)
self._store = DocumentStore(self.collection, validators=self.collection._fields, initDct=jsonFieldInit)
if self.collection._validation['on_load']:
self.validate()
self.modified = True | python | def reset(self, collection, jsonFieldInit = None) :
if not jsonFieldInit:
jsonFieldInit = {}
self.collection = collection
self.connection = self.collection.connection
self.documentsURL = self.collection.documentsURL
self.URL = None
self.setPrivates(jsonFieldInit)
self._store = DocumentStore(self.collection, validators=self.collection._fields, initDct=jsonFieldInit)
if self.collection._validation['on_load']:
self.validate()
self.modified = True | [
"def",
"reset",
"(",
"self",
",",
"collection",
",",
"jsonFieldInit",
"=",
"None",
")",
":",
"if",
"not",
"jsonFieldInit",
":",
"jsonFieldInit",
"=",
"{",
"}",
"self",
".",
"collection",
"=",
"collection",
"self",
".",
"connection",
"=",
"self",
".",
"co... | replaces the current values in the document by those in jsonFieldInit | [
"replaces",
"the",
"current",
"values",
"in",
"the",
"document",
"by",
"those",
"in",
"jsonFieldInit"
] | dd72e5f6c540e5e148943d615ddf7553bb78ce0b | https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/document.py#L191-L206 |
22,087 | ArangoDB-Community/pyArango | pyArango/document.py | Document.validate | def validate(self) :
"""validate the document"""
self._store.validate()
for pField in self.collection.arangoPrivates :
self.collection.validatePrivate(pField, getattr(self, pField)) | python | def validate(self) :
self._store.validate()
for pField in self.collection.arangoPrivates :
self.collection.validatePrivate(pField, getattr(self, pField)) | [
"def",
"validate",
"(",
"self",
")",
":",
"self",
".",
"_store",
".",
"validate",
"(",
")",
"for",
"pField",
"in",
"self",
".",
"collection",
".",
"arangoPrivates",
":",
"self",
".",
"collection",
".",
"validatePrivate",
"(",
"pField",
",",
"getattr",
"(... | validate the document | [
"validate",
"the",
"document"
] | dd72e5f6c540e5e148943d615ddf7553bb78ce0b | https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/document.py#L208-L212 |
22,088 | ArangoDB-Community/pyArango | pyArango/document.py | Document.setPrivates | def setPrivates(self, fieldDict) :
"""will set self._id, self._rev and self._key field."""
for priv in self.privates :
if priv in fieldDict :
setattr(self, priv, fieldDict[priv])
else :
setattr(self, priv, None)
if self._id is not None :
self.URL = "%s/%s" % (self.documentsURL, self._id) | python | def setPrivates(self, fieldDict) :
for priv in self.privates :
if priv in fieldDict :
setattr(self, priv, fieldDict[priv])
else :
setattr(self, priv, None)
if self._id is not None :
self.URL = "%s/%s" % (self.documentsURL, self._id) | [
"def",
"setPrivates",
"(",
"self",
",",
"fieldDict",
")",
":",
"for",
"priv",
"in",
"self",
".",
"privates",
":",
"if",
"priv",
"in",
"fieldDict",
":",
"setattr",
"(",
"self",
",",
"priv",
",",
"fieldDict",
"[",
"priv",
"]",
")",
"else",
":",
"setatt... | will set self._id, self._rev and self._key field. | [
"will",
"set",
"self",
".",
"_id",
"self",
".",
"_rev",
"and",
"self",
".",
"_key",
"field",
"."
] | dd72e5f6c540e5e148943d615ddf7553bb78ce0b | https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/document.py#L214-L224 |
22,089 | ArangoDB-Community/pyArango | pyArango/document.py | Document.patch | def patch(self, keepNull = True, **docArgs) :
"""Saves the document by only updating the modified fields.
The default behaviour concening the keepNull parameter is the opposite of ArangoDB's default, Null values won't be ignored
Use docArgs for things such as waitForSync = True"""
if self.URL is None :
raise ValueError("Cannot patch a document that was not previously saved")
payload = self._store.getPatches()
if self.collection._validation['on_save'] :
self.validate()
if len(payload) > 0 :
params = dict(docArgs)
params.update({'collection': self.collection.name, 'keepNull' : keepNull})
payload = json.dumps(payload, default=str)
r = self.connection.session.patch(self.URL, params = params, data = payload)
data = r.json()
if (r.status_code == 201 or r.status_code == 202) and "error" not in data :
self._rev = data['_rev']
else :
raise UpdateError(data['errorMessage'], data)
self.modified = False
self._store.resetPatch() | python | def patch(self, keepNull = True, **docArgs) :
if self.URL is None :
raise ValueError("Cannot patch a document that was not previously saved")
payload = self._store.getPatches()
if self.collection._validation['on_save'] :
self.validate()
if len(payload) > 0 :
params = dict(docArgs)
params.update({'collection': self.collection.name, 'keepNull' : keepNull})
payload = json.dumps(payload, default=str)
r = self.connection.session.patch(self.URL, params = params, data = payload)
data = r.json()
if (r.status_code == 201 or r.status_code == 202) and "error" not in data :
self._rev = data['_rev']
else :
raise UpdateError(data['errorMessage'], data)
self.modified = False
self._store.resetPatch() | [
"def",
"patch",
"(",
"self",
",",
"keepNull",
"=",
"True",
",",
"*",
"*",
"docArgs",
")",
":",
"if",
"self",
".",
"URL",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Cannot patch a document that was not previously saved\"",
")",
"payload",
"=",
"self",
... | Saves the document by only updating the modified fields.
The default behaviour concening the keepNull parameter is the opposite of ArangoDB's default, Null values won't be ignored
Use docArgs for things such as waitForSync = True | [
"Saves",
"the",
"document",
"by",
"only",
"updating",
"the",
"modified",
"fields",
".",
"The",
"default",
"behaviour",
"concening",
"the",
"keepNull",
"parameter",
"is",
"the",
"opposite",
"of",
"ArangoDB",
"s",
"default",
"Null",
"values",
"won",
"t",
"be",
... | dd72e5f6c540e5e148943d615ddf7553bb78ce0b | https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/document.py#L289-L316 |
22,090 | ArangoDB-Community/pyArango | pyArango/document.py | Document.delete | def delete(self) :
"deletes the document from the database"
if self.URL is None :
raise DeletionError("Can't delete a document that was not saved")
r = self.connection.session.delete(self.URL)
data = r.json()
if (r.status_code != 200 and r.status_code != 202) or 'error' in data :
raise DeletionError(data['errorMessage'], data)
self.reset(self.collection)
self.modified = True | python | def delete(self) :
"deletes the document from the database"
if self.URL is None :
raise DeletionError("Can't delete a document that was not saved")
r = self.connection.session.delete(self.URL)
data = r.json()
if (r.status_code != 200 and r.status_code != 202) or 'error' in data :
raise DeletionError(data['errorMessage'], data)
self.reset(self.collection)
self.modified = True | [
"def",
"delete",
"(",
"self",
")",
":",
"if",
"self",
".",
"URL",
"is",
"None",
":",
"raise",
"DeletionError",
"(",
"\"Can't delete a document that was not saved\"",
")",
"r",
"=",
"self",
".",
"connection",
".",
"session",
".",
"delete",
"(",
"self",
".",
... | deletes the document from the database | [
"deletes",
"the",
"document",
"from",
"the",
"database"
] | dd72e5f6c540e5e148943d615ddf7553bb78ce0b | https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/document.py#L318-L329 |
22,091 | ArangoDB-Community/pyArango | pyArango/document.py | Document.getEdges | def getEdges(self, edges, inEdges = True, outEdges = True, rawResults = False) :
"""returns in, out, or both edges linked to self belonging the collection 'edges'.
If rawResults a arango results will be return as fetched, if false, will return a liste of Edge objects"""
try :
return edges.getEdges(self, inEdges, outEdges, rawResults)
except AttributeError :
raise AttributeError("%s does not seem to be a valid Edges object" % edges) | python | def getEdges(self, edges, inEdges = True, outEdges = True, rawResults = False) :
try :
return edges.getEdges(self, inEdges, outEdges, rawResults)
except AttributeError :
raise AttributeError("%s does not seem to be a valid Edges object" % edges) | [
"def",
"getEdges",
"(",
"self",
",",
"edges",
",",
"inEdges",
"=",
"True",
",",
"outEdges",
"=",
"True",
",",
"rawResults",
"=",
"False",
")",
":",
"try",
":",
"return",
"edges",
".",
"getEdges",
"(",
"self",
",",
"inEdges",
",",
"outEdges",
",",
"ra... | returns in, out, or both edges linked to self belonging the collection 'edges'.
If rawResults a arango results will be return as fetched, if false, will return a liste of Edge objects | [
"returns",
"in",
"out",
"or",
"both",
"edges",
"linked",
"to",
"self",
"belonging",
"the",
"collection",
"edges",
".",
"If",
"rawResults",
"a",
"arango",
"results",
"will",
"be",
"return",
"as",
"fetched",
"if",
"false",
"will",
"return",
"a",
"liste",
"of... | dd72e5f6c540e5e148943d615ddf7553bb78ce0b | https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/document.py#L339-L345 |
22,092 | ArangoDB-Community/pyArango | pyArango/document.py | Document.getStore | def getStore(self) :
"""return the store in a dict format"""
store = self._store.getStore()
for priv in self.privates :
v = getattr(self, priv)
if v :
store[priv] = v
return store | python | def getStore(self) :
store = self._store.getStore()
for priv in self.privates :
v = getattr(self, priv)
if v :
store[priv] = v
return store | [
"def",
"getStore",
"(",
"self",
")",
":",
"store",
"=",
"self",
".",
"_store",
".",
"getStore",
"(",
")",
"for",
"priv",
"in",
"self",
".",
"privates",
":",
"v",
"=",
"getattr",
"(",
"self",
",",
"priv",
")",
"if",
"v",
":",
"store",
"[",
"priv",... | return the store in a dict format | [
"return",
"the",
"store",
"in",
"a",
"dict",
"format"
] | dd72e5f6c540e5e148943d615ddf7553bb78ce0b | https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/document.py#L347-L354 |
22,093 | ArangoDB-Community/pyArango | pyArango/document.py | Edge.links | def links(self, fromVertice, toVertice, **edgeArgs) :
"""
An alias to save that updates the _from and _to attributes.
fromVertice and toVertice, can be either strings or documents. It they are unsaved documents, they will be automatically saved.
"""
if isinstance(fromVertice, Document) or isinstance(getattr(fromVertice, 'document', None), Document):
if not fromVertice._id :
fromVertice.save()
self._from = fromVertice._id
elif (type(fromVertice) is bytes) or (type(fromVertice) is str):
self._from = fromVertice
elif not self._from:
raise CreationError('fromVertice %s is invalid!' % str(fromVertice))
if isinstance(toVertice, Document) or isinstance(getattr(toVertice, 'document', None), Document):
if not toVertice._id:
toVertice.save()
self._to = toVertice._id
elif (type(toVertice) is bytes) or (type(toVertice) is str):
self._to = toVertice
elif not self._to:
raise CreationError('toVertice %s is invalid!' % str(toVertice))
self.save(**edgeArgs) | python | def links(self, fromVertice, toVertice, **edgeArgs) :
if isinstance(fromVertice, Document) or isinstance(getattr(fromVertice, 'document', None), Document):
if not fromVertice._id :
fromVertice.save()
self._from = fromVertice._id
elif (type(fromVertice) is bytes) or (type(fromVertice) is str):
self._from = fromVertice
elif not self._from:
raise CreationError('fromVertice %s is invalid!' % str(fromVertice))
if isinstance(toVertice, Document) or isinstance(getattr(toVertice, 'document', None), Document):
if not toVertice._id:
toVertice.save()
self._to = toVertice._id
elif (type(toVertice) is bytes) or (type(toVertice) is str):
self._to = toVertice
elif not self._to:
raise CreationError('toVertice %s is invalid!' % str(toVertice))
self.save(**edgeArgs) | [
"def",
"links",
"(",
"self",
",",
"fromVertice",
",",
"toVertice",
",",
"*",
"*",
"edgeArgs",
")",
":",
"if",
"isinstance",
"(",
"fromVertice",
",",
"Document",
")",
"or",
"isinstance",
"(",
"getattr",
"(",
"fromVertice",
",",
"'document'",
",",
"None",
... | An alias to save that updates the _from and _to attributes.
fromVertice and toVertice, can be either strings or documents. It they are unsaved documents, they will be automatically saved. | [
"An",
"alias",
"to",
"save",
"that",
"updates",
"the",
"_from",
"and",
"_to",
"attributes",
".",
"fromVertice",
"and",
"toVertice",
"can",
"be",
"either",
"strings",
"or",
"documents",
".",
"It",
"they",
"are",
"unsaved",
"documents",
"they",
"will",
"be",
... | dd72e5f6c540e5e148943d615ddf7553bb78ce0b | https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/document.py#L403-L426 |
22,094 | ArangoDB-Community/pyArango | pyArango/users.py | User._set | def _set(self, jsonData) :
"""Initialize all fields at once. If no password is specified, it will be set as an empty string"""
self["username"] = jsonData["user"]
self["active"] = jsonData["active"]
self["extra"] = jsonData["extra"]
try:
self["changePassword"] = jsonData["changePassword"]
except Exception as e:
pass
# self["changePassword"] = ""
try :
self["password"] = jsonData["passwd"]
except KeyError :
self["password"] = ""
self.URL = "%s/user/%s" % (self.connection.URL, self["username"]) | python | def _set(self, jsonData) :
self["username"] = jsonData["user"]
self["active"] = jsonData["active"]
self["extra"] = jsonData["extra"]
try:
self["changePassword"] = jsonData["changePassword"]
except Exception as e:
pass
# self["changePassword"] = ""
try :
self["password"] = jsonData["passwd"]
except KeyError :
self["password"] = ""
self.URL = "%s/user/%s" % (self.connection.URL, self["username"]) | [
"def",
"_set",
"(",
"self",
",",
"jsonData",
")",
":",
"self",
"[",
"\"username\"",
"]",
"=",
"jsonData",
"[",
"\"user\"",
"]",
"self",
"[",
"\"active\"",
"]",
"=",
"jsonData",
"[",
"\"active\"",
"]",
"self",
"[",
"\"extra\"",
"]",
"=",
"jsonData",
"["... | Initialize all fields at once. If no password is specified, it will be set as an empty string | [
"Initialize",
"all",
"fields",
"at",
"once",
".",
"If",
"no",
"password",
"is",
"specified",
"it",
"will",
"be",
"set",
"as",
"an",
"empty",
"string"
] | dd72e5f6c540e5e148943d615ddf7553bb78ce0b | https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/users.py#L24-L41 |
22,095 | ArangoDB-Community/pyArango | pyArango/users.py | User.delete | def delete(self) :
"""Permanently remove the user"""
if not self.URL :
raise CreationError("Please save user first", None, None)
r = self.connection.session.delete(self.URL)
if r.status_code < 200 or r.status_code > 202 :
raise DeletionError("Unable to delete user, url: %s, status: %s" %(r.url, r.status_code), r.content )
self.URL = None | python | def delete(self) :
if not self.URL :
raise CreationError("Please save user first", None, None)
r = self.connection.session.delete(self.URL)
if r.status_code < 200 or r.status_code > 202 :
raise DeletionError("Unable to delete user, url: %s, status: %s" %(r.url, r.status_code), r.content )
self.URL = None | [
"def",
"delete",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"URL",
":",
"raise",
"CreationError",
"(",
"\"Please save user first\"",
",",
"None",
",",
"None",
")",
"r",
"=",
"self",
".",
"connection",
".",
"session",
".",
"delete",
"(",
"self",
"... | Permanently remove the user | [
"Permanently",
"remove",
"the",
"user"
] | dd72e5f6c540e5e148943d615ddf7553bb78ce0b | https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/users.py#L95-L104 |
22,096 | ArangoDB-Community/pyArango | pyArango/users.py | Users.fetchAllUsers | def fetchAllUsers(self, rawResults = False) :
"""Returns all available users. if rawResults, the result will be a list of python dicts instead of User objects"""
r = self.connection.session.get(self.URL)
if r.status_code == 200 :
data = r.json()
if rawResults :
return data["result"]
else :
res = []
for resu in data["result"] :
u = User(self, resu)
res.append(u)
return res
else :
raise ConnectionError("Unable to get user list", r.url, r.status_code) | python | def fetchAllUsers(self, rawResults = False) :
r = self.connection.session.get(self.URL)
if r.status_code == 200 :
data = r.json()
if rawResults :
return data["result"]
else :
res = []
for resu in data["result"] :
u = User(self, resu)
res.append(u)
return res
else :
raise ConnectionError("Unable to get user list", r.url, r.status_code) | [
"def",
"fetchAllUsers",
"(",
"self",
",",
"rawResults",
"=",
"False",
")",
":",
"r",
"=",
"self",
".",
"connection",
".",
"session",
".",
"get",
"(",
"self",
".",
"URL",
")",
"if",
"r",
".",
"status_code",
"==",
"200",
":",
"data",
"=",
"r",
".",
... | Returns all available users. if rawResults, the result will be a list of python dicts instead of User objects | [
"Returns",
"all",
"available",
"users",
".",
"if",
"rawResults",
"the",
"result",
"will",
"be",
"a",
"list",
"of",
"python",
"dicts",
"instead",
"of",
"User",
"objects"
] | dd72e5f6c540e5e148943d615ddf7553bb78ce0b | https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/users.py#L129-L143 |
22,097 | ArangoDB-Community/pyArango | pyArango/users.py | Users.fetchUser | def fetchUser(self, username, rawResults = False) :
"""Returns a single user. if rawResults, the result will be a list of python dicts instead of User objects"""
url = "%s/%s" % (self.URL, username)
r = self.connection.session.get(url)
if r.status_code == 200 :
data = r.json()
if rawResults :
return data["result"]
else :
u = User(self, data)
return u
else :
raise KeyError("Unable to get user: %s" % username) | python | def fetchUser(self, username, rawResults = False) :
url = "%s/%s" % (self.URL, username)
r = self.connection.session.get(url)
if r.status_code == 200 :
data = r.json()
if rawResults :
return data["result"]
else :
u = User(self, data)
return u
else :
raise KeyError("Unable to get user: %s" % username) | [
"def",
"fetchUser",
"(",
"self",
",",
"username",
",",
"rawResults",
"=",
"False",
")",
":",
"url",
"=",
"\"%s/%s\"",
"%",
"(",
"self",
".",
"URL",
",",
"username",
")",
"r",
"=",
"self",
".",
"connection",
".",
"session",
".",
"get",
"(",
"url",
"... | Returns a single user. if rawResults, the result will be a list of python dicts instead of User objects | [
"Returns",
"a",
"single",
"user",
".",
"if",
"rawResults",
"the",
"result",
"will",
"be",
"a",
"list",
"of",
"python",
"dicts",
"instead",
"of",
"User",
"objects"
] | dd72e5f6c540e5e148943d615ddf7553bb78ce0b | https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/users.py#L145-L158 |
22,098 | ArangoDB-Community/pyArango | pyArango/connection.py | Connection.resetSession | def resetSession(self, username=None, password=None, verify=True) :
"""resets the session"""
self.disconnectSession()
self.session = AikidoSession(username, password, verify) | python | def resetSession(self, username=None, password=None, verify=True) :
self.disconnectSession()
self.session = AikidoSession(username, password, verify) | [
"def",
"resetSession",
"(",
"self",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"verify",
"=",
"True",
")",
":",
"self",
".",
"disconnectSession",
"(",
")",
"self",
".",
"session",
"=",
"AikidoSession",
"(",
"username",
",",
"passwor... | resets the session | [
"resets",
"the",
"session"
] | dd72e5f6c540e5e148943d615ddf7553bb78ce0b | https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/connection.py#L129-L132 |
22,099 | ArangoDB-Community/pyArango | pyArango/connection.py | Connection.reload | def reload(self) :
"""Reloads the database list.
Because loading a database triggers the loading of all collections and graphs within,
only handles are loaded when this function is called. The full databases are loaded on demand when accessed
"""
r = self.session.get(self.databasesURL)
data = r.json()
if r.status_code == 200 and not data["error"] :
self.databases = {}
for dbName in data["result"] :
if dbName not in self.databases :
self.databases[dbName] = DBHandle(self, dbName)
else :
raise ConnectionError(data["errorMessage"], self.databasesURL, r.status_code, r.content) | python | def reload(self) :
r = self.session.get(self.databasesURL)
data = r.json()
if r.status_code == 200 and not data["error"] :
self.databases = {}
for dbName in data["result"] :
if dbName not in self.databases :
self.databases[dbName] = DBHandle(self, dbName)
else :
raise ConnectionError(data["errorMessage"], self.databasesURL, r.status_code, r.content) | [
"def",
"reload",
"(",
"self",
")",
":",
"r",
"=",
"self",
".",
"session",
".",
"get",
"(",
"self",
".",
"databasesURL",
")",
"data",
"=",
"r",
".",
"json",
"(",
")",
"if",
"r",
".",
"status_code",
"==",
"200",
"and",
"not",
"data",
"[",
"\"error\... | Reloads the database list.
Because loading a database triggers the loading of all collections and graphs within,
only handles are loaded when this function is called. The full databases are loaded on demand when accessed | [
"Reloads",
"the",
"database",
"list",
".",
"Because",
"loading",
"a",
"database",
"triggers",
"the",
"loading",
"of",
"all",
"collections",
"and",
"graphs",
"within",
"only",
"handles",
"are",
"loaded",
"when",
"this",
"function",
"is",
"called",
".",
"The",
... | dd72e5f6c540e5e148943d615ddf7553bb78ce0b | https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/connection.py#L134-L149 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.