code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
if job_request_payload.success_command != JobCommands.STORE_JOB_OUTPUT_COMPLETE:
raise ValueError("Programmer error only use job_step_store_output_complete for store_output_complete.")
payload = JobStepStoreOutputCompletePayload(job_request_payload, output_project_info)
self... | def job_step_store_output_complete(self, job_request_payload, output_project_info) | Send message that the store output job step is complete using payload data.
Raises ValueError if used for non-StoreJobOutputPayload message type.
:param job_request_payload: StoreJobOutputPayload payload from complete job
:param output_project_info: object: info about the project created | 5.233852 | 4.998327 | 1.047121 |
payload = JobStepErrorPayload(job_request_payload, message)
self.send(job_request_payload.error_command, payload) | def job_step_error(self, job_request_payload, message) | Send message that the job step failed using payload data.
:param job_request_payload: StageJobPayload|RunJobPayload|StoreJobOutputPayload payload from job with error
:param message: description of the error | 4.958196 | 6.716699 | 0.738189 |
self._send(JobCommands.STAGE_JOB, StageJobPayload(credentials, job_details, input_files, vm_instance_name)) | def stage_job(self, credentials, job_details, input_files, vm_instance_name) | Request that a job be staged on a worker(ie. download some files)
:param credentials: jobapi.Credentials: user's credentials used to download input_files
:param job_details: object: details about job(id, name, created date, workflow version)
:param input_files: [InputFile]: list of files to down... | 5.52377 | 4.914052 | 1.124076 |
self._send(JobCommands.RUN_JOB, RunJobPayload(job_details, workflow, vm_instance_name)) | def run_job(self, job_details, workflow, vm_instance_name) | Execute a workflow on a worker.
:param job_details: object: details about job(id, name, created date, workflow version)
:param workflow: jobapi.Workflow: url to workflow and parameters to use
:param vm_instance_name: name of the instance lando_worker is running on (this passed back in the respon... | 8.132145 | 7.256296 | 1.120702 |
payload = StoreJobOutputPayload(credentials, job_details, vm_instance_name)
self._send(JobCommands.STORE_JOB_OUTPUT, payload) | def store_job_output(self, credentials, job_details, vm_instance_name) | Store the output of a finished job.
:param credentials: jobapi.Credentials: user's credentials used to upload resulting files
:param job_details: object: details about job(id, name, created date, workflow version)
:param vm_instance_name: name of the instance lando_worker is running on (this pas... | 4.486994 | 4.898911 | 0.915917 |
frequency = max(frequency, 0)
for key in self._store.keys():
self._store[key] = (self._store[key][0], frequency)
return frequency | def reset_frequencies(self, frequency=0) | Resets all stored frequencies for the cache
:keyword int frequency: Frequency to reset to, must be >= 0 | 4.380423 | 4.944835 | 0.885858 |
if len(self._store) == 0:
return
kv = min(self._store.items(), key=lambda x: x[1][1])
return kv[0], kv[1][0] | def oldest(self) | Gets key, value pair for oldest item in cache
:returns: tuple | 3.762265 | 3.572766 | 1.05304 |
self._evict_old()
if key not in self._store:
raise KeyError("key {0!r} does not exist in cache".format(key))
return self.timeout - (time.time() - self._store[key][1]) | def time_left(self, key) | Gets the amount of time an item has left in the cache (in seconds), before it is evicted.
:param key: Key to check time for.
:returns: int | 4.027284 | 4.505221 | 0.893915 |
def more_than_one_index(s, brackets=2):
'''
Search for two sets of [] []
@param s: string to search
'''
start = 0
brackets_num = 0
while start != -1 and brackets_num < brackets:
start = s.find("[", start)
if start == -1:
break
start = s.find("]"... | Search for two sets of [] []
@param s: string to search | null | null | null | |
def get_key(s):
'''
Get data between [ and ] remove ' if exist
@param s: string to process
'''
start = s.find("[")
end = s.find("]")
if start == -1 or end == -1:
return None
if s[start + 1] == "'":
start += 1
if s[end - 1] == "'":
end -= 1
ret... | Get data between [ and ] remove ' if exist
@param s: string to process | null | null | null | |
def parser_helper(key, val):
'''
Helper for parser function
@param key:
@param val:
'''
start_bracket = key.find("[")
end_bracket = key.find("]")
pdict = {}
if has_variable_name(key): # var['key'][3]
pdict[key[:key.find("[")]] = parser_helper(key[start_bracket:], v... | Helper for parser function
@param key:
@param val: | null | null | null | |
def parse(query_string, unquote=True, normalized=False, encoding=DEFAULT_ENCODING):
'''
Main parse function
@param query_string:
@param unquote: unquote html query string ?
@param encoding: An optional encoding used to decode the keys and values. Defaults to utf-8, which the W3C declares as a d... | Main parse function
@param query_string:
@param unquote: unquote html query string ?
@param encoding: An optional encoding used to decode the keys and values. Defaults to utf-8, which the W3C declares as a defaul in the W3C algorithm for encoding.
@see http://www.w3.org/TR/html5/forms.html#applicati... | null | null | null | |
def _normalize(d):
'''
The above parse function generates output of list in dict form
i.e. {'abc' : {0: 'xyz', 1: 'pqr'}}. This function normalize it and turn
them into proper data type, i.e. {'abc': ['xyz', 'pqr']}
Note: if dict has element starts with 10, 11 etc.. this function won't fill
... | The above parse function generates output of list in dict form
i.e. {'abc' : {0: 'xyz', 1: 'pqr'}}. This function normalize it and turn
them into proper data type, i.e. {'abc': ['xyz', 'pqr']}
Note: if dict has element starts with 10, 11 etc.. this function won't fill
blanks.
for eg: {'abc': ... | null | null | null | |
settings = config.registry.settings
swagger_versions = get_swagger_versions(settings)
# for rendering /swagger.yaml
config.add_renderer(
'yaml', 'pyramid_swagger.api.YamlRendererFactory',
)
# Add the SwaggerSchema to settings to make it available to the validation
# tween and ... | def includeme(config) | :type config: :class:`pyramid.config.Configurator` | 3.377421 | 3.37742 | 1 |
schema_filepath = os.path.join(schema_dir, API_DOCS_FILENAME)
swagger_spec_validator.validator12.validate_spec(
resource_listing,
urlparse.urljoin('file:', pathname2url(os.path.abspath(schema_filepath))),
) | def validate_swagger_schema(schema_dir, resource_listing) | Validate the structure of Swagger schemas against the spec.
**Valid only for Swagger v1.2 spec**
Note: It is possible that resource_listing is not present in
the schema_dir. The path is passed in the call so that ssv
can fetch the api-declaration files from the path.
:param resource_listing: Swag... | 5.029961 | 5.009321 | 1.00412 |
properties = filter_params_by_type(schema, param_type)
if not properties:
return
# Generate a jsonschema that describes the set of all query parameters. We
# can then validate this against dict(request.params).
return {
'type': 'object',
'properties': dict((p['name'], p... | def build_param_schema(schema, param_type) | Turn a swagger endpoint schema into an equivalent one to validate our
request.
As an example, this would take this swagger schema:
{
"paramType": "query",
"name": "query",
"description": "Location to query",
"type": "string",
"required": true
... | 6.52998 | 6.644064 | 0.982829 |
if schema.get('type') == 'File':
return []
return _validators.type_draft3(validator, types, instance, schema) | def type_validator(validator, types, instance, schema) | Swagger 1.2 supports parameters of 'type': 'File'. Skip validation of
the 'type' field in this case. | 8.993059 | 5.826558 | 1.54346 |
if schema.get('paramType'):
if req is True and not instance:
return [ValidationError("%s is required" % schema['name'])]
return []
return _validators.required_draft4(validator, req, instance, schema) | def required_validator(validator, req, instance, schema) | Swagger 1.2 expects `required` to be a bool in the Parameter object, but
a list of properties in a Model object. | 7.099402 | 7.802059 | 0.90994 |
return validators.extend(
Draft4Validator,
{
'paramType': ignore,
'name': ignore,
'type': build_swagger_type_validator(models),
'required': required_validator,
}
) | def get_body_validator(models) | Returns a validator for the request body, based on a
:class:`jsonschema.validators.Draft4Validator`, with extra validations
added for swaggers extensions to jsonschema.
:param models: a mapping of reference to models
:returns: a :class:`jsonschema.validators.Validator` which can validate
the re... | 6.977268 | 6.869006 | 1.015761 |
schema_models = schema.get('models', {})
return dict(
(
RequestMatcher(api['path'], operation['method']),
ValidatorMap.from_operation(operation, schema_models, resolver)
)
for api in schema['apis']
for operation in api['operations']
) | def build_request_to_validator_map(schema, resolver) | Build a mapping from :class:`RequestMatcher` to :class:`ValidatorMap`
for each operation in the API spec. This mapping may be used to retrieve
the appropriate validators for a request. | 5.526288 | 3.721781 | 1.48485 |
with open(schema_path, 'r') as schema_file:
schema = simplejson.load(schema_file)
resolver = RefResolver('', '', schema.get('models', {}))
return build_request_to_validator_map(schema, resolver) | def load_schema(schema_path) | Prepare the api specification for request and response validation.
:returns: a mapping from :class:`RequestMatcher` to :class:`ValidatorMap`
for every operation in the api specification.
:rtype: dict | 4.811928 | 4.49301 | 1.070981 |
if not self.schema or (values is None and not self.schema.get('required', False)):
return
self.validator.validate(values) | def validate(self, values) | Validate a :class:`dict` of values. If `self.schema` is falsy this
is a noop. | 5.208377 | 4.538 | 1.147725 |
return (
partial_path_match(request.path_info, self.path) and
request.method == self.method
) | def matches(self, request) | :param request: a :class:`pyramid.request.Request`
:returns: True if this matcher matches the request, False otherwise | 5.126298 | 5.916601 | 0.866426 |
enabled_swagger_versions = get_swagger_versions(registry.settings)
schema12 = registry.settings['pyramid_swagger.schema12']
schema20 = registry.settings['pyramid_swagger.schema20']
fallback_to_swagger12_route = (
SWAGGER_20 in enabled_swagger_versions and
SWAGGER_12 in enabled_swag... | def get_swagger_objects(settings, route_info, registry) | Returns appropriate swagger handler and swagger spec schema.
Swagger Handler contains callables that isolate implementation differences
in the tween to handle both Swagger 1.2 and Swagger 2.0.
Exception is made when `settings.prefer_20_routes` are non-empty and
['1.2', '2.0'] both are present in avail... | 2.739825 | 2.205519 | 1.242258 |
settings = load_settings(registry)
route_mapper = registry.queryUtility(IRoutesMapper)
validation_context = _get_validation_context(registry)
def validator_tween(request):
# We don't have access to this yet but let's go ahead and build the
# matchdict so we can validate it and use... | def validation_tween_factory(handler, registry) | Pyramid tween for performing validation.
Note this is very simple -- it validates requests, responses, and paths
while delegating to the relevant matching view. | 4.025611 | 3.931545 | 1.023926 |
request_data = {}
validation_pairs = []
for validator, values in [
(validator_map.query, request.query),
(validator_map.path, request.path),
(validator_map.form, request.form),
(validator_map.headers, request.headers),
]:
values = cast_params(validator.schem... | def handle_request(request, validator_map, **kwargs) | Validate the request against the swagger spec and return a dict with
all parameter values available in the request, casted to the expected
python type.
:param request: a :class:`PyramidSwaggerRequest` to validate
:param validator_map: a :class:`pyramid_swagger.load_schema.ValidatorMap`
used to ... | 3.278318 | 3.112448 | 1.053292 |
if schema:
return SwaggerHandler(
op_for_request=schema.validators_for_request,
handle_request=handle_request,
handle_response=validate_response,
) | def build_swagger12_handler(schema) | Builds a swagger12 handler or returns None if no schema is present.
:type schema: :class:`pyramid_swagger.model.SwaggerSchema`
:rtype: :class:`SwaggerHandler` or None | 9.091004 | 8.94088 | 1.016791 |
# TODO(#63): remove deprecated `skip_validation` setting in v2.0.
regexes = registry.settings.get(
'pyramid_swagger.skip_validation',
registry.settings.get(
'pyramid_swagger.exclude_paths',
DEFAULT_EXCLUDED_PATHS
)
)
# being nice to users using strin... | def get_exclude_paths(registry) | Compiles a list of paths that should not be validated against.
:rtype: list of compiled validation regexes | 4.521651 | 4.411109 | 1.02506 |
try:
return CAST_TYPE_TO_FUNC.get(param_type, lambda x: x)(param_value)
except ValueError:
log.warn("Failed to cast %s value of %s to %s",
param_name, param_value, param_type)
# Ignore type error, let jsonschema validation handle incorrect types
return param... | def cast_request_param(param_type, param_name, param_value) | Try to cast a request param (e.g. query arg, POST data) from a string to
its specified type in the schema. This allows validating non-string params.
:param param_type: name of the type to be casted to
:type param_type: string
:param param_name: param name
:type param_name: string
:param param... | 4.351401 | 4.7894 | 0.908548 |
validator = validator_map.response
# Short circuit if we are supposed to not validate anything.
returns_nothing = validator.schema.get('type') == 'void'
body_empty = response.body in (None, b'', b'{}', b'null')
if returns_nothing and body_empty:
return
# Don't attempt to validate ... | def validate_response(response, validator_map) | Validates response against our schemas.
:param response: the response object to validate
:type response: :class:`pyramid.response.Response`
:type validator_map: :class:`pyramid_swagger.load_schema.ValidatorMap` | 5.988199 | 6.1387 | 0.975483 |
response_spec = get_response_spec(response.status_int, op)
bravado_core.response.validate_response(
response_spec, op, PyramidSwaggerResponse(response)) | def swaggerize_response(response, op) | Delegate handling the Swagger concerns of the response to bravado-core.
:type response: :class:`pyramid.response.Response`
:type op: :class:`bravado_core.operation.Operation` | 7.851099 | 6.2977 | 1.246661 |
# pyramid.urldispath.Route
route = route_info['route']
if hasattr(route, 'path'):
route_path = route.path
if route_path[0] != '/':
route_path = '/' + route_path
op = spec.get_op_for_request(request.method, route_path)
if op is not None:
return op
... | def get_op_for_request(request, route_info, spec) | Find out which operation in the Swagger schema corresponds to the given
pyramid request.
:type request: :class:`pyramid.request.Request`
:type route_info: dict (usually has 'match' and 'route' keys)
:type spec: :class:`bravado_core.spec.Spec`
:rtype: :class:`bravado_core.operation.Operation`
:r... | 3.276041 | 2.955796 | 1.108345 |
swagger_versions = set(aslist(settings.get(
'pyramid_swagger.swagger_versions', DEFAULT_SWAGGER_VERSIONS)))
if len(swagger_versions) == 0:
raise ValueError('pyramid_swagger.swagger_versions is empty')
for swagger_version in swagger_versions:
if swagger_version not in SUPPORTED... | def get_swagger_versions(settings) | Validates and returns the versions of the Swagger Spec that this pyramid
application supports.
:type settings: dict
:return: list of strings. eg ['1.2', '2.0']
:raises: ValueError when an unsupported Swagger version is encountered. | 2.289352 | 2.284883 | 1.001956 |
# Don't read the POST dict unless the body is form encoded
if self.request.content_type in self.FORM_TYPES:
return self.request.POST.mixed()
return {} | def form(self) | :rtype: dict | 9.977024 | 8.153104 | 1.223709 |
for endpoint in endpoints:
path = base_path.rstrip('/') + endpoint.path
config.add_route(endpoint.route_name, path)
config.add_view(
endpoint.view,
route_name=endpoint.route_name,
renderer=endpoint.renderer) | def register_api_doc_endpoints(config, endpoints, base_path='/api-docs') | Create and register pyramid endpoints to service swagger api docs.
Routes and views will be registered on the `config` at `path`.
:param config: a pyramid configuration to register the new views and routes
:type config: :class:`pyramid.config.Configurator`
:param endpoints: a list of endpoints to regi... | 2.130527 | 2.192165 | 0.971883 |
yield build_swagger_12_resource_listing(resource_listing)
for name, filepath in api_declarations.items():
with open(filepath) as input_file:
yield build_swagger_12_api_declaration(
name, simplejson.load(input_file)) | def build_swagger_12_endpoints(resource_listing, api_declarations) | :param resource_listing: JSON representing a Swagger 1.2 resource listing
:type resource_listing: dict
:param api_declarations: JSON representing Swagger 1.2 api declarations
:type api_declarations: dict
:rtype: iterable of :class:`pyramid_swagger.model.PyramidEndpoint` | 3.4076 | 4.256121 | 0.800635 |
def view_for_resource_listing(request):
# Thanks to the magic of closures, this means we gracefully return JSON
# without file IO at request time.
return resource_listing
return PyramidEndpoint(
path='',
route_name='pyramid_swagger.swagger12.api_docs',
view=... | def build_swagger_12_resource_listing(resource_listing) | :param resource_listing: JSON representing a Swagger 1.2 resource listing
:type resource_listing: dict
:rtype: :class:`pyramid_swagger.model.PyramidEndpoint` | 10.81226 | 9.556869 | 1.13136 |
# NOTE: This means our resource paths are currently constrained to be valid
# pyramid routes! (minus the leading /)
route_name = 'pyramid_swagger.swagger12.apidocs-{0}'.format(resource_name)
return PyramidEndpoint(
path='/{0}'.format(resource_name),
route_name=route_name,
vi... | def build_swagger_12_api_declaration(resource_name, api_declaration) | :param resource_name: The `path` parameter from the resource listing for
this resource.
:type resource_name: string
:param api_declaration: JSON representing a Swagger 1.2 api declaration
:type api_declaration: dict
:rtype: :class:`pyramid_swagger.model.PyramidEndpoint` | 6.322176 | 5.684193 | 1.112238 |
def view_for_api_declaration(request):
# Note that we rewrite basePath to always point at this server's root.
return dict(
api_declaration_json,
basePath=str(request.application_url),
)
return view_for_api_declaration | def build_swagger_12_api_declaration_view(api_declaration_json) | Thanks to the magic of closures, this means we gracefully return JSON
without file IO at request time. | 7.783555 | 6.838663 | 1.138169 |
split_p1 = path1.split('/')
split_p2 = path2.split('/')
pat = re.compile(kwarg_re)
if len(split_p1) != len(split_p2):
return False
for partial_p1, partial_p2 in zip(split_p1, split_p2):
if pat.match(partial_p1) or pat.match(partial_p2):
continue
if not partia... | def partial_path_match(path1, path2, kwarg_re=r'\{.*\}') | Validates if path1 and path2 matches, ignoring any kwargs in the string.
We need this to ensure we can match Swagger patterns like:
/foo/{id}
against the observed pyramid path
/foo/1
:param path1: path of a url
:type path1: string
:param path2: path of a url
:type path2: string... | 1.839709 | 2.033909 | 0.904519 |
for resource_validator in self.resource_validators:
for matcher, validator_map in resource_validator.items():
if matcher.matches(request):
return validator_map
raise PathNotMatchedError(
'Could not find the relevant path ({0}) in the ... | def validators_for_request(self, request, **kwargs) | Takes a request and returns a validator mapping for the request.
:param request: A Pyramid request to fetch schemas for
:type request: :class:`pyramid.request.Request`
:returns: a :class:`pyramid_swagger.load_schema.ValidatorMap` which can
be used to validate `request` | 5.855529 | 5.71384 | 1.024798 |
def not_api_doc_file(filename):
return not filename.endswith(API_DOCS_FILENAME)
def not_swagger_dot_json(filename):
# Exclude a Swagger 2.0 schema file if it happens to exist.
return not os.path.basename(filename) == 'swagger.json'
def filename_to_path(filename):
filen... | def find_resource_paths(schema_dir) | The inverse of :func:`find_resource_names` used to generate
a resource listing from a directory of swagger api docs. | 3.670079 | 3.559097 | 1.031183 |
def resource_name_to_filepath(name):
return os.path.join(schema_dir, '{0}.json'.format(name))
return dict(
(resource, resource_name_to_filepath(resource))
for resource in find_resource_names(resource_listing)
) | def build_schema_mapping(schema_dir, resource_listing) | Discovers schema file locations and relations.
:param schema_dir: the directory schema files live inside
:type schema_dir: string
:param resource_listing: A swagger resource listing
:type resource_listing: dict
:returns: a mapping from resource name to file path
:rtype: dict | 3.327604 | 3.223325 | 1.032352 |
try:
with open(resource_listing) as resource_listing_file:
return simplejson.load(resource_listing_file)
# If not found, raise a more user-friendly error.
except IOError:
raise ResourceListingNotFoundError(
'No resource listing found at {0}. Note that your json f... | def _load_resource_listing(resource_listing) | Load the resource listing from file, handling errors.
:param resource_listing: path to the api-docs resource listing file
:type resource_listing: string
:returns: contents of the resource listing file
:rtype: dict | 4.241815 | 3.774443 | 1.123825 |
listing_filename = os.path.join(schema_dir, API_DOCS_FILENAME)
resource_listing = _load_resource_listing(listing_filename)
if not should_generate_resource_listing:
return resource_listing
return generate_resource_listing(schema_dir, resource_listing) | def get_resource_listing(schema_dir, should_generate_resource_listing) | Return the resource listing document.
:param schema_dir: the directory which contains swagger spec files
:type schema_dir: string
:param should_generate_resource_listing: when True a resource listing will
be generated from the list of *.json files in the schema_dir. Otherwise
return the co... | 2.512165 | 3.065703 | 0.819442 |
mapping = build_schema_mapping(schema_dir, resource_listing)
resource_validators = ingest_resources(mapping, schema_dir)
endpoints = list(build_swagger_12_endpoints(resource_listing, mapping))
return SwaggerSchema(endpoints, resource_validators) | def compile_swagger_schema(schema_dir, resource_listing) | Build a SwaggerSchema from various files.
:param schema_dir: the directory schema files live inside
:type schema_dir: string
:returns: a SwaggerSchema object | 6.312445 | 6.713087 | 0.940319 |
schema_dir = settings.get('pyramid_swagger.schema_directory', 'api_docs')
resource_listing = get_resource_listing(
schema_dir,
settings.get('pyramid_swagger.generate_resource_listing', False)
)
if settings.get('pyramid_swagger.enable_swagger_spec_validation', True):
validat... | def get_swagger_schema(settings) | Return a :class:`pyramid_swagger.model.SwaggerSchema` constructed from
the swagger specs in `pyramid_swagger.schema_directory`. If
`pyramid_swagger.enable_swagger_spec_validation` is enabled the schema
will be validated before returning it.
:param settings: a pyramid registry settings with configuratio... | 2.909496 | 2.544947 | 1.143244 |
schema_dir = settings.get('pyramid_swagger.schema_directory', 'api_docs/')
schema_filename = settings.get('pyramid_swagger.schema_file',
'swagger.json')
schema_path = os.path.join(schema_dir, schema_filename)
schema_url = urlparse.urljoin('file:', pathname2url(os.... | def get_swagger_spec(settings) | Return a :class:`bravado_core.spec.Spec` constructed from
the swagger specs in `pyramid_swagger.schema_directory`. If
`pyramid_swagger.enable_swagger_spec_validation` is enabled the schema
will be validated before returning it.
:param settings: a pyramid registry settings with configuration for
... | 4.272684 | 3.711364 | 1.151244 |
# Map pyramid_swagger config key -> bravado_core config key
config_keys = {
'pyramid_swagger.enable_request_validation': 'validate_requests',
'pyramid_swagger.enable_response_validation': 'validate_responses',
'pyramid_swagger.enable_swagger_spec_validation': 'validate_swagger_spec'... | def create_bravado_core_config(settings) | Create a configuration dict for bravado_core based on pyramid_swagger
settings.
:param settings: pyramid registry settings with configuration for
building a swagger schema
:type settings: dict
:returns: config dict suitable for passing into
bravado_core.spec.Spec.from_dict(..)
:rtyp... | 2.184992 | 2.113739 | 1.03371 |
ingested_resources = []
for name, filepath in iteritems(mapping):
try:
ingested_resources.append(load_schema(filepath))
# If we have trouble reading any files, raise a more user-friendly
# error.
except IOError:
raise ApiDeclarationNotFoundError(
... | def ingest_resources(mapping, schema_dir) | Consume the Swagger schemas and produce a queryable datastructure.
:param mapping: Map from resource name to filepath of its api declaration
:type mapping: dict
:param schema_dir: the directory schema files live inside
:type schema_dir: string
:returns: A list of mapping from :class:`RequestMatcher... | 6.100425 | 5.827018 | 1.046921 |
with open(filename, 'w') as fh:
for v in vertices:
fh.write("v {} {} {}\n".format(*v))
for f in triangles:
fh.write("f {} {} {}\n".format(*(f + 1))) | def export_obj(vertices, triangles, filename) | Exports a mesh in the (.obj) format. | 2.252677 | 2.336751 | 0.964021 |
with open(filename, 'w') as fh:
fh.write('OFF\n')
fh.write('{} {} 0\n'.format(len(vertices), len(triangles)))
for v in vertices:
fh.write("{} {} {}\n".format(*v))
for f in triangles:
fh.write("3 {} {} {}\n".format(*f)) | def export_off(vertices, triangles, filename) | Exports a mesh in the (.off) format. | 1.971404 | 2.045892 | 0.963591 |
import collada
mesh = collada.Collada()
vert_src = collada.source.FloatSource("verts-array", vertices, ('X','Y','Z'))
geom = collada.geometry.Geometry(mesh, "geometry0", mesh_name, [vert_src])
input_list = collada.source.InputList()
input_list.addInput(0, 'VERTEX', "#ver... | def export_mesh(vertices, triangles, filename, mesh_name="mcubes_mesh") | Exports a mesh in the COLLADA (.dae) format.
Needs PyCollada (https://github.com/pycollada/pycollada). | 3.611038 | 3.448785 | 1.047046 |
def desc(func):
func.__doc__ = nco_self.call([tool, "--help"]).get("stdout")
return func
return desc | def auto_doc(tool, nco_self) | Generate the __doc__ string of the decorated function by calling the nco help command
:param tool:
:param nco_self:
:return: | 8.943636 | 7.912419 | 1.130329 |
if not self.return_cdf:
self.load_cdf_module()
if self.cdf_module == "scipy":
# making it compatible to older scipy versions
file_obj = self.cdf.netcdf_file(infile, mode="r")
elif self.cdf_module == "netcdf4":
file_obj = self.cdf.Dataset(... | def read_cdf(self, infile) | Return a cdf handle created by the available cdf library.
python-netcdf4 and scipy supported (default:scipy) | 4.858054 | 4.201269 | 1.15633 |
file_handle = self.read_cdf(infile)
try:
# return the data array
return file_handle.variables[var_name][:]
except KeyError:
print("Cannot find variable: {0}".format(var_name))
raise KeyError | def read_array(self, infile, var_name) | Directly return a numpy array for a given variable name | 4.154933 | 3.759461 | 1.105194 |
file_obj = self.read_cdf(infile)
# .data is not backwards compatible to old scipy versions, [:] is
data = file_obj.variables[var_name][:]
# load numpy if available
try:
import numpy as np
except Exception:
raise ImportError("numpy is req... | def read_ma_array(self, infile, var_name) | Create a masked array based on cdf's FillValue | 4.885238 | 4.597162 | 1.062664 |
form.save_m2m()
for formset in formsets:
self.save_formset(request, form, formset, change=change) | def save_related(self, request, form, formsets, change) | Given the ``HttpRequest``, the parent ``ModelForm`` instance, the
list of inline formsets and a boolean value based on whether the
parent is being added or changed, save the related objects to the
database. Note that at this point save_form() and save_model() have
already been called. | 2.800437 | 2.850443 | 0.982457 |
if data is not None:
self.update(data)
b=create_string_buffer(256)
size=c_size_t(256)
if libcrypto.EVP_DigestSignFinal(self.ctx,b,pointer(size))<=0:
raise DigestError('SignFinal')
self.digest_finalized=True
return b.raw[:size.value] | def digest(self,data=None) | Method digest is redefined to return keyed MAC value instead of
just digest. | 3.893085 | 4.126967 | 0.943328 |
if num <= 0:
raise ValueError("'num' should be > 0")
buf = create_string_buffer(num)
result = libcrypto.RAND_bytes(buf, num)
if check_result and result == 0:
raise RandError("Random Number Generator not seeded sufficiently")
return buf.raw[:num] | def bytes(num, check_result=False) | Returns num bytes of cryptographically strong pseudo-random
bytes. If checkc_result is True, raises error if PRNG is not
seeded enough | 4.123771 | 3.324056 | 1.240584 |
if num <= 0:
raise ValueError("'num' should be > 0")
buf = create_string_buffer(num)
libcrypto.RAND_pseudo_bytes(buf, num)
return buf.raw[:num] | def pseudo_bytes(num) | Returns num bytes of pseudo random data. Pseudo- random byte
sequences generated by pseudo_bytes() will be unique if
they are of sufficient length, but are not necessarily
unpredictable. They can be used for non-cryptographic purposes
and for certain purposes in cryptographic protocols, but usually
... | 2.939184 | 2.849895 | 1.031331 |
if not isinstance(data, bintype):
raise TypeError("A string is expected")
ptr = c_char_p(data)
size = len(data)
if entropy is None:
libcrypto.RAND_seed(ptr, size)
else:
libcrypto.RAND_add(ptr, size, entropy) | def seed(data, entropy=None) | Seeds random generator with data.
If entropy is not None, it should be floating point(double)
value estimating amount of entropy in the data (in bytes). | 3.92302 | 4.390425 | 0.89354 |
if pyver > 2:
dotted = dotted.encode('ascii')
shortname = shortname.encode('utf-8')
longname = longname.encode('utf-8')
nid = libcrypto.OBJ_create(dotted, shortname, longname)
if nid == 0:
raise LibCryptoError("Problem adding new OID to the database")
return Oid(ni... | def create(dotted, shortname, longname) | Creates new OID in the database
@param dotted - dotted-decimal representation of new OID
@param shortname - short name for new OID
@param longname - long name for new OID
@returns Oid object corresponding to new OID
This function should be used with exreme care. Whenever
possible, it is bette... | 4.484204 | 4.416254 | 1.015387 |
" Returns dotted-decimal reperesentation "
obj = libcrypto.OBJ_nid2obj(self.nid)
buf = create_string_buffer(256)
libcrypto.OBJ_obj2txt(buf, 256, obj, 1)
if pyver == 2:
return buf.value
else:
return buf.value.decode('ascii') | def dotted(self) | Returns dotted-decimal reperesentation | 5.075746 | 4.654943 | 1.090399 |
nid = libcrypto.OBJ_obj2nid(obj)
if nid == 0:
buf = create_string_buffer(80)
dotted_len = libcrypto.OBJ_obj2txt(buf, 80, obj, 1)
dotted = buf[:dotted_len]
oid = create(dotted, dotted, dotted)
else:
oid = Oid(nid)
return... | def fromobj(obj) | Creates an OID object from the pointer to ASN1_OBJECT c structure.
This method intended for internal use for submodules which deal
with libcrypto ASN1 parsing functions, such as x509 or CMS | 5.567646 | 5.077138 | 1.096611 |
if c is None:
return PW_CALLBACK_FUNC(0)
if callable(c):
if pyver ==2 :
def __cb(buf, length, rwflag, userdata):
pwd = c(rwflag)
cnt = min(len(pwd),length)
memmove(buf,pwd, cnt)
return cnt
else:
... | def _password_callback(c) | Converts given user function or string to C password callback
function, passable to openssl.
IF function is passed, it would be called upon reading or writing
PEM format private key with one argument which is True if we are
writing key and should verify passphrase and false if we are reading | 3.026352 | 3.111123 | 0.972752 |
ctx = libcrypto.EVP_PKEY_CTX_new(self.key, None)
if ctx is None:
raise PKeyError("Initailizing sign context")
if libcrypto.EVP_PKEY_sign_init(ctx) < 1:
raise PKeyError("sign_init")
self._configure_context(ctx, kwargs)
# Find out signature size
... | def sign(self, digest, **kwargs) | Signs given digest and retirns signature
Keyword arguments allows to set various algorithm-specific
parameters. See pkeyutl(1) manual. | 2.676385 | 2.72082 | 0.983669 |
ctx = libcrypto.EVP_PKEY_CTX_new(self.key, None)
if ctx is None:
raise PKeyError("Initailizing verify context")
if libcrypto.EVP_PKEY_verify_init(ctx) < 1:
raise PKeyError("verify_init")
self._configure_context(ctx, kwargs)
ret = libcrypto.EVP_PKE... | def verify(self, digest, signature, **kwargs) | Verifies given signature on given digest
Returns True if Ok, False if don't match
Keyword arguments allows to set algorithm-specific
parameters | 3.098189 | 3.473311 | 0.891999 |
if not self.cansign:
raise ValueError("No private key available")
ctx = libcrypto.EVP_PKEY_CTX_new(self.key, None)
if ctx is None:
raise PKeyError("Initailizing derive context")
if libcrypto.EVP_PKEY_derive_init(ctx) < 1:
raise PKeyError("deri... | def derive(self, peerkey, **kwargs) | Derives shared key (DH,ECDH,VKO 34.10). Requires
private key available
@param peerkey - other key (may be public only)
Keyword parameters are algorithm-specific | 4.199195 | 4.209722 | 0.997499 |
tmpeng = c_void_p(None)
if isinstance(algorithm, chartype):
alg = algorithm.encode("ascii")
else:
alg = algorithm
ameth = libcrypto.EVP_PKEY_asn1_find_str(byref(tmpeng), alg, -1)
if ameth is None:
raise PKeyError("Algorithm %s not foi... | def generate(algorithm, **kwargs) | Generates new private-public key pair for given algorithm
(string like 'rsa','ec','gost2001') and algorithm-specific
parameters.
Algorithm specific paramteers for RSA:
rsa_keygen_bits=number - size of key to be generated
rsa_keygen_pubexp - RSA public expontent(default 65537)
... | 4.888806 | 4.728815 | 1.033833 |
bio = Membio()
if format == "PEM":
retcode = libcrypto.PEM_write_bio_PUBKEY(bio.bio, self.key)
else:
retcode = libcrypto.i2d_PUBKEY_bio(bio.bio, self.key)
if retcode == 0:
raise PKeyError("error serializing public key")
return str(bio) | def exportpub(self, format="PEM") | Returns public key as PEM or DER structure. | 3.810318 | 3.679113 | 1.035662 |
bio = Membio()
if cipher is None:
evp_cipher = None
else:
evp_cipher = cipher.cipher
if format == "PEM":
ret = libcrypto.PEM_write_bio_PrivateKey(bio.bio, self.key,
evp_cipher, None, 0,
... | def exportpriv(self, format="PEM", password=None, cipher=None) | Returns private key as PEM or DER Structure.
If password and cipher are specified, encrypts key
on given password, using given algorithm. Cipher must be
an ctypescrypto.cipher.CipherType object
Password can be either string or function with one argument,
which returns password. ... | 3.703505 | 3.721314 | 0.995214 |
for oper in opts:
if oper in skip:
continue
if isinstance(oper,chartype):
op = oper.encode("ascii")
else:
op = oper
if isinstance(opts[oper],chartype):
value = opts[oper].encode("ascii")
... | def _configure_context(ctx, opts, skip=()) | Configures context of public key operations
@param ctx - context to configure
@param opts - dictionary of options (from kwargs of calling
function)
@param skip - list of options which shouldn't be passed to
context | 3.560403 | 3.336288 | 1.067175 |
if not length is None:
if not isinstance(length, inttype) :
raise TypeError("length to read should be number")
buf = create_string_buffer(length)
readbytes = libcrypto.BIO_read(self.bio, buf, length)
if readbytes == -2:
rai... | def read(self, length=None) | Reads data from readble BIO. For test purposes.
@param length - if specifed, limits amount of data read.
If not BIO is read until end of buffer | 2.509099 | 2.513837 | 0.998115 |
if pyver == 2:
if isinstance(data, unicode):
data = data.encode("utf-8")
else:
data = str(data)
else:
if not isinstance(data, bytes):
data=str(data).encode("utf-8")
written = libcrypto.BIO_write(... | def write(self, data) | Writes data to writable bio. For test purposes | 3.918358 | 3.762336 | 1.041469 |
bio = Membio(data)
if format == "PEM":
ptr = libcrypto.PEM_read_bio_CMS(bio.bio, None, None, None)
else:
ptr = libcrypto.d2i_CMS_bio(bio.bio, None)
if ptr is None:
raise CMSError("Error parsing CMS data")
typeoid = Oid(libcrypto.OBJ_obj2nid(libcrypto.CMS_get0_type(ptr)))... | def CMS(data, format="PEM") | Factory function to create CMS objects from received messages.
Parses CMS data and returns either SignedData or EnvelopedData
object. format argument can be either "PEM" or "DER".
It determines object type from the contents of received CMS
structure. | 3.123693 | 3.271231 | 0.954898 |
bio = Membio()
if not libcrypto.PEM_write_bio_CMS(bio.bio, self.ptr):
raise CMSError("writing CMS to PEM")
return str(bio) | def pem(self) | Serialize in PEM format | 12.664624 | 11.332577 | 1.117541 |
if not pkey.cansign:
raise ValueError("Specified keypair has no private part")
if cert.pubkey != pkey:
raise ValueError("Certificate doesn't match public key")
bio = Membio(data)
if certs is not None and len(certs) > 0:
certstack_obj = StackOf... | def create(data, cert, pkey, flags=Flags.BINARY, certs=None) | Creates SignedData message by signing data with pkey and
certificate.
@param data - data to sign
@param cert - signer's certificate
@param pkey - pkey object with private key to sign
@param flags - OReed combination of Flags constants
@param certs... | 6.491422 | 6.635016 | 0.978358 |
if not pkey.cansign:
raise ValueError("Specified keypair has no private part")
if cert.pubkey != pkey:
raise ValueError("Certificate doesn't match public key")
if libcrypto.CMS_add1_signer(self.ptr, cert.cert, pkey.key,
d... | def sign(self, cert, pkey, digest_type=None, data=None, flags=Flags.BINARY) | Adds another signer to already signed message
@param cert - signer's certificate
@param pkey - signer's private key
@param digest_type - message digest to use as DigestType object
(if None - default for key would be used)
@param data - data to sign (if det... | 5.704709 | 5.164763 | 1.104544 |
bio = None
if data != None:
bio_obj = Membio(data)
bio = bio_obj.bio
if certs is not None and len(certs) > 0:
certstack_obj = StackOfX509(certs) # keep reference to prevent immediate __del__ call
certstack = certstack_obj.ptr
else... | def verify(self, store, flags, data=None, certs=None) | Verifies signature under CMS message using trusted cert store
@param store - X509Store object with trusted certs
@param flags - OR-ed combination of flag consants
@param data - message data, if messge has detached signature
param certs - list of certificates to use during verification
... | 5.967069 | 6.030968 | 0.989405 |
signerlist = libcrypto.CMS_get0_signers(self.ptr)
if signerlist is None:
raise CMSError("Cannot get signers")
return StackOfX509(ptr=signerlist, disposable=False) | def signers(self) | Return list of signer's certificates | 10.203109 | 8.425934 | 1.210917 |
# Check if signatire is detached
if self.detached:
return None
bio = Membio()
if not libcrypto.CMS_verify(self.ptr, None, None, None, bio.bio,
Flags.NO_VERIFY):
raise CMSError("extract data")
return str(bio) | def data(self) | Returns signed data if present in the message | 18.055429 | 14.908837 | 1.211056 |
if libcrypto.CMS_add1_cert(self.ptr, cert.cert) <= 0:
raise CMSError("Cannot add cert") | def addcert(self, cert) | Adds a certificate (probably intermediate CA) to the SignedData
structure | 12.346114 | 11.731222 | 1.052415 |
certstack = libcrypto.CMS_get1_certs(self.ptr)
if certstack is None:
raise CMSError("getting certs")
return StackOfX509(ptr=certstack, disposable=True) | def certs(self) | List of the certificates contained in the structure | 11.313892 | 10.811486 | 1.04647 |
recp = StackOfX509(recipients)
bio = Membio(data)
cms_ptr = libcrypto.CMS_encrypt(recp.ptr, bio.bio, cipher.cipher,
flags)
if cms_ptr is None:
raise CMSError("encrypt EnvelopedData")
return EnvelopedData(cms_ptr) | def create(recipients, data, cipher, flags=0) | Creates and encrypts message
@param recipients - list of X509 objects
@param data - contents of the message
@param cipher - CipherType object
@param flags - flag | 9.308041 | 9.898903 | 0.94031 |
if not pkey.cansign:
raise ValueError("Specified keypair has no private part")
if pkey != cert.pubkey:
raise ValueError("Certificate doesn't match private key")
bio = Membio()
res = libcrypto.CMS_decrypt(self.ptr, pkey.key, cert.cert, None,
... | def decrypt(self, pkey, cert, flags=0) | Decrypts message
@param pkey - private key to decrypt
@param cert - certificate of this private key (to find
neccessary RecipientInfo
@param flags - flags
@returns - decrypted data | 6.055532 | 6.637949 | 0.912259 |
bio = Membio(data)
ptr = libcrypto.CMS_EncryptedData_encrypt(bio.bio, cipher.cipher,
key, len(key), flags)
if ptr is None:
raise CMSError("encrypt data")
return EncryptedData(ptr) | def create(data, cipher, key, flags=0) | Creates an EncryptedData message.
@param data data to encrypt
@param cipher cipher.CipherType object represening required
cipher type
@param key - byte array used as simmetic key
@param flags - OR-ed combination of Flags constant | 6.903261 | 8.093798 | 0.852907 |
bio = Membio()
if libcrypto.CMS_EncryptedData_decrypt(self.ptr, key, len(key), None,
bio.bio, flags) <= 0:
raise CMSError("decrypt data")
return str(bio) | def decrypt(self, key, flags=0) | Decrypts encrypted data message
@param key - symmetic key to decrypt
@param flags - OR-ed combination of Flags constant | 9.4286 | 13.094158 | 0.720062 |
if not hasattr(self, 'digest_name'):
self.digest_name = Oid(libcrypto.EVP_MD_type(self.digest)
).longname()
return self.digest_name | def name(self) | Returns name of the digest | 9.134337 | 6.61802 | 1.380222 |
if self.digest_finalized:
raise DigestError("No updates allowed")
if not isinstance(data, bintype):
raise TypeError("A byte string is expected")
if length is None:
length = len(data)
elif length > len(data):
raise ValueError("Speci... | def update(self, data, length=None) | Hashes given byte string
@param data - string to hash
@param length - if not specifed, entire string is hashed,
otherwise only first length bytes | 3.452281 | 3.760109 | 0.918133 |
if self.digest_finalized:
return self.digest_out.raw[:self.digest_size]
if data is not None:
self.update(data)
self.digest_out = create_string_buffer(256)
length = c_long(0)
result = libcrypto.EVP_DigestFinal_ex(self.ctx, self.digest_out,
... | def digest(self, data=None) | Finalizes digest operation and return digest value
Optionally hashes more data before finalizing | 2.674368 | 2.586697 | 1.033893 |
new_digest = Digest(self.digest_type)
libcrypto.EVP_MD_CTX_copy(new_digest.ctx, self.ctx)
return new_digest | def copy(self) | Creates copy of the digest CTX to allow to compute digest
while being able to hash more data | 6.29072 | 4.022554 | 1.563862 |
try:
if self.ctx is not None:
libcrypto.EVP_MD_CTX_free(self.ctx)
del self.ctx
except AttributeError:
pass
self.digest_out = None
self.digest_finalized = False | def _clean_ctx(self) | Clears and deallocates context | 4.681402 | 4.271739 | 1.095901 |
from base64 import b16encode
if pyver == 2:
return b16encode(self.digest(data))
else:
return b16encode(self.digest(data)).decode('us-ascii') | def hexdigest(self, data=None) | Returns digest in the hexadecimal form. For compatibility
with hashlib | 3.184853 | 3.259773 | 0.977017 |
bio = Membio()
libcrypto.ASN1_TIME_print(bio.bio, asn1date)
pydate = datetime.strptime(str(bio), "%b %d %H:%M:%S %Y %Z")
return pydate.replace(tzinfo=utc) | def _X509__asn1date_to_datetime(asn1date) | Converts openssl ASN1_TIME object to python datetime.datetime | 4.747884 | 4.128294 | 1.150084 |
if not isinstance(oid, Oid):
raise TypeError("Need crytypescrypto.oid.Oid as argument")
found = []
index = -1
end = len(self)
while True:
index = libcrypto.X509_get_ext_by_NID(self.cert.cert, oid.nid,
... | def find(self, oid) | Return list of extensions with given Oid | 5.775084 | 5.127653 | 1.126263 |
if crit:
flag = 1
else:
flag = 0
found = []
end = len(self)
index = -1
while True:
index = libcrypto.X509_get_ext_by_critical(self.cert.cert, flag,
index)
if in... | def find_critical(self, crit=True) | Return list of critical extensions (or list of non-cricital, if
optional second argument is False | 4.097452 | 3.948108 | 1.037827 |
bio = Membio()
if libcrypto.PEM_write_bio_X509(bio.bio, self.cert) == 0:
raise X509Error("error serializing certificate")
return str(bio) | def pem(self) | Returns PEM represntation of the certificate | 5.885978 | 5.242909 | 1.122655 |
if store is not None and key is not None:
raise X509Error("key and store cannot be specified simultaneously")
if store is not None:
ctx = libcrypto.X509_STORE_CTX_new()
if ctx is None:
raise X509Error("Error allocating X509_STORE_CTX")
... | def verify(self, store=None, chain=None, key=None) | Verify self. Supports verification on both X509 store object
or just public issuer key
@param store X509Store object.
@param chain - list of X509 objects to add into verification
context.These objects are untrusted, but can be used to
build certificate chain up to trusted... | 2.341517 | 2.311318 | 1.013065 |
asnint = libcrypto.X509_get_serialNumber(self.cert)
bio = Membio()
libcrypto.i2a_ASN1_INTEGER(bio.bio, asnint)
return int(str(bio), 16) | def serial(self) | Serial number of certificate as integer | 7.823794 | 5.970435 | 1.310423 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.