code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
if not program:
return
logger.debug(__("Manager preparing Data with id {} for processing.", data.id))
# Prepare the executor's environment.
try:
executor_env_vars = self.get_executor().get_environment_variables()
program = self._include_envi... | def _data_execute(self, data, program, executor) | Execute the Data object.
The activities carried out here include target directory
preparation, executor copying, setting serialization and actual
execution of the object.
:param data: The :class:`~resolwe.flow.models.Data` object to
execute.
:param program: The proc... | 5.663836 | 5.238901 | 1.081111 |
try:
return self.expression_engines[name]
except KeyError:
raise InvalidEngineError("Unsupported expression engine: {}".format(name)) | def get_expression_engine(self, name) | Return an expression engine instance. | 3.873278 | 3.700777 | 1.046612 |
try:
return self.execution_engines[name]
except KeyError:
raise InvalidEngineError("Unsupported execution engine: {}".format(name)) | def get_execution_engine(self, name) | Return an execution engine instance. | 3.999652 | 3.510249 | 1.139421 |
executor_name = executor_name + '.prepare'
module = import_module(executor_name)
return module.FlowExecutorPreparer() | def load_executor(self, executor_name) | Load process executor. | 7.866609 | 7.906034 | 0.995013 |
primary_str, subject_info_xml = d1_common.cert.x509.extract_subjects(cert_pem)
equivalent_set = {
primary_str,
d1_common.const.SUBJECT_AUTHENTICATED,
d1_common.const.SUBJECT_PUBLIC,
}
if subject_info_xml is not None:
equivalent_set |= d1_common.cert.subject_info.extr... | def extract_subjects(cert_pem) | Extract subjects from a DataONE PEM (Base64) encoded X.509 v3 certificate.
Args:
cert_pem: str or bytes
PEM (Base64) encoded X.509 v3 certificate
Returns:
2-tuple:
- The primary subject string, extracted from the certificate DN.
- A set of equivalent identities, group membe... | 3.530231 | 3.139306 | 1.124526 |
return self.queryset.prefetch_related('data__entity_set')
return self.queryset | def get_queryset(self): # pylint: disable=method-hidden
if self.request and self.request.query_params.get('hydrate_data', False) | Return queryset. | 10.936346 | 7.496906 | 1.458781 |
collection_query = Collection.objects.filter(pk=collection_id)
if not collection_query.exists():
raise exceptions.ValidationError('Collection id does not exist')
collection = collection_query.first()
if not user.has_perm('add_collection', obj=collection):
... | def _get_collection_for_user(self, collection_id, user) | Check that collection exists and user has `add` permission. | 2.704395 | 2.244545 | 1.204874 |
queryset = get_objects_for_user(user, 'view_entity', Entity.objects.filter(id__in=ids))
actual_ids = queryset.values_list('id', flat=True)
missing_ids = list(set(ids) - set(actual_ids))
if missing_ids:
raise exceptions.ParseError(
"Entities with the f... | def _get_entities(self, user, ids) | Return entities queryset based on provided entity ids. | 2.582822 | 2.429928 | 1.062921 |
# Data doesn't have "ADD" permission, so it has to be removed
payload = remove_permission(payload, 'add')
for data in obj.data.all():
if user.has_perm('share_data', data):
update_permission(data, payload) | def set_content_permissions(self, user, obj, payload) | Apply permissions to data objects in ``Entity``. | 7.696474 | 7.273768 | 1.058114 |
obj = self.get_object()
user = request.user
if strtobool(request.query_params.get('delete_content', 'false')):
for data in obj.data.all():
if user.has_perm('edit_data', data):
data.delete()
# If all data objects in an entity ... | def destroy(self, request, *args, **kwargs) | Destroy a model instance.
If ``delete_content`` flag is set in query parameters, also all
Data objects contained in entity will be deleted. | 4.699571 | 4.023273 | 1.168096 |
entity = self.get_object()
# TODO use `self.get_ids` (and elsewhere). Backwards
# incompatible because raised error's response contains
# ``detail`` instead of ``error``).
if 'ids' not in request.data:
return Response({"error": "`ids` parameter is required"}... | def add_to_collection(self, request, pk=None) | Add Entity to a collection. | 4.619638 | 4.443323 | 1.039681 |
# add data to entity
resp = super().add_data(request, pk)
# add data to collections in which entity is
entity = self.get_object()
for collection in entity.collections.all():
collection.data.add(*request.data['ids'])
return resp | def add_data(self, request, pk=None) | Add data to Entity and it's collection. | 4.612302 | 3.581828 | 1.287695 |
ids = self.get_ids(request.data)
src_collection_id = self.get_id(request.data, 'source_collection')
dst_collection_id = self.get_id(request.data, 'destination_collection')
src_collection = self._get_collection_for_user(src_collection_id, request.user)
dst_collection = s... | def move_to_collection(self, request, *args, **kwargs) | Move samples from source to destination collection. | 2.16564 | 2.028842 | 1.067427 |
orig_get_queryset = self.get_queryset
def patched_get_queryset():
entity_ids = orig_get_queryset().values_list('id', flat=True)
return Entity.objects.filter(id__in=entity_ids)
self.get_queryset = patched_get_queryset
resp = super().update(r... | def update(self, request, *args, **kwargs) | Update an entity.
Original queryset produces a temporary database table whose rows
cannot be selected for an update. As a workaround, we patch
get_queryset function to return only Entity objects without
additional data that is not needed for the update. | 2.423624 | 1.816605 | 1.334151 |
# Create a Bash command to add all the tools to PATH.
tools_paths = ':'.join([map_["dest"] for map_ in self.tools_volumes])
add_tools_path = 'export PATH=$PATH:{}'.format(tools_paths)
# Spawn another child bash, to avoid running anything as PID 1, which has special
# sig... | async def run_script(self, script) | Execute the script and save results. | 6.571987 | 6.571919 | 1.00001 |
try:
await self.proc.wait()
finally:
# Cleanup temporary files.
for temporary_file in self.temporary_files:
temporary_file.close()
self.temporary_files = []
return self.proc.returncode | async def end(self) | End process execution. | 3.701837 | 3.059397 | 1.209989 |
# Workaround for pylint issue #1469
# (https://github.com/PyCQA/pylint/issues/1469).
cmd = await subprocess.create_subprocess_exec( # pylint: disable=no-member
*shlex.split('{} rm -f {}'.format(self.command, self._generate_container_name()))
)
await cmd.wait... | async def terminate(self) | Terminate a running script. | 4.890079 | 4.576603 | 1.068495 |
decoder = json.JSONDecoder()
while text:
obj, ndx = decoder.raw_decode(text)
if not isinstance(obj, dict):
raise ValueError()
text = text[ndx:].lstrip('\r\n')
yield obj | def iterjson(text) | Decode JSON stream. | 3.664171 | 3.658075 | 1.001666 |
resp = await send_manager_command(*args, **kwargs)
if resp is False:
await self.terminate() | async def _send_manager_command(self, *args, **kwargs) | Send an update to manager and terminate the process if it fails. | 6.654241 | 4.365381 | 1.524321 |
await self._send_manager_command(ExecutorProtocol.UPDATE, extra_fields={
ExecutorProtocol.UPDATE_CHANGESET: kwargs
}) | async def update_data_status(self, **kwargs) | Update (PATCH) Data object.
:param kwargs: The dictionary of
:class:`~resolwe.flow.models.Data` attributes to be changed. | 23.390137 | 25.656322 | 0.911671 |
logger.debug("Executor for Data with id {} has started.".format(data_id))
try:
finish_fields = await self._run(data_id, script)
except SystemExit as ex:
raise ex
except Exception as error: # pylint: disable=broad-except
logger.exception("Unha... | async def run(self, data_id, script) | Execute the script and save results. | 5.784435 | 5.686894 | 1.017152 |
file_descriptor = os.open(filename, os.O_WRONLY | os.O_CREAT | os.O_EXCL)
return os.fdopen(file_descriptor, 'w') | def _create_file(self, filename) | Ensure a new file is created and opened for writing. | 2.310292 | 2.086065 | 1.107488 |
return (
d1_gmn.app.models.ReplicationQueue.objects.filter(
local_replica__info__status__status='queued'
).aggregate(Sum('size'))['size__sum']
or 0
) | def get_total_size_of_queued_replicas() | Return the total number of bytes of requested, unprocessed replicas. | 5.633567 | 5.324271 | 1.058092 |
replica_info_model = d1_gmn.app.models.replica_info(
status_str='queued', source_node_urn=source_node_urn
)
local_replica_model = d1_gmn.app.models.local_replica(
pid=d1_common.xml.get_req_val(sysmeta_pyxb.identifier),
replica_info_model=replica_info_model,
)
d1_gmn.app.... | def add_to_replication_queue(source_node_urn, sysmeta_pyxb) | Add a replication request issued by a CN to a queue that is processed
asynchronously.
Preconditions:
- sysmeta_pyxb.identifier is verified to be available for create. E.g., with
d1_gmn.app.views.is_valid_pid_for_create(pid).
Postconditions:
- The database is set up to track a new replica, wi... | 2.798134 | 2.707047 | 1.033648 |
parser.description = doc_str
parser.formatter_class = argparse.RawDescriptionHelpFormatter
parser.add_argument("--debug", action="store_true", help="Debug level logging")
parser.add_argument(
"--cert-pub",
dest="cert_pem_path",
action="store",
default=django.conf.set... | def add_arguments(parser, doc_str, add_base_url=True) | Add standard arguments for DataONE utilities to a command line parser. | 2.526642 | 2.420996 | 1.043638 |
if d1_gmn.app.did.is_resource_map_db(pid):
return get_resource_map_members_by_map(pid)
elif d1_gmn.app.did.is_resource_map_member(pid):
return get_resource_map_members_by_member(pid)
else:
raise d1_common.types.exceptions.InvalidRequest(
0, 'Not a Resource Map or Res... | def get_resource_map_members(pid) | ``pid`` is the PID of a Resource Map or the PID of a member of a Resource Map. | 2.50827 | 2.351249 | 1.066782 |
self._assert_valid_variable(variable)
try:
v = ast.literal_eval(value_string)
except (ValueError, SyntaxError):
v = value_string
if v is None or v == "none":
self._variables[variable] = None
else:
try:
type_... | def set_with_conversion(self, variable, value_string) | Convert user supplied string to Python type.
Lets user use values such as True, False and integers. All variables can be set
to None, regardless of type. Handle the case where a string is typed by the user
and is not quoted, as a string literal. | 2.612398 | 2.577029 | 1.013724 |
format_str = (
'%(asctime)s %(name)s %(module)s:%(lineno)d %(process)4d %(levelname)-8s %(message)s'
if is_multiprocess
else '%(asctime)s %(name)s %(module)s:%(lineno)d %(levelname)-8s %(message)s'
)
formatter = logging.Formatter(format_str, '%Y-%m-%d %H:%M:%S')
console_logg... | def log_setup(is_debug=False, is_multiprocess=False) | Set up a standardized log format for the DataONE Python stack. All Python
components should use this function. If ``is_multiprocess`` is True, include process
ID in the log so that logs can be separated for each process.
Output only to stdout and stderr. | 1.790523 | 1.753888 | 1.020888 |
m = email.message.Message()
m['Content-Type'] = content_type
return m.get_content_type() | def get_content_type(content_type) | Extract the MIME type value from a content type string.
Removes any subtype and parameter values that may be present in the string.
Args:
content_type: str
String with content type and optional subtype and parameter fields.
Returns:
str: String with only content type
Example:
... | 4.497364 | 6.357736 | 0.707385 |
for k, v in list(u.items()):
if isinstance(v, collections.Mapping):
r = nested_update(d.get(k, {}), v)
d[k] = r
else:
d[k] = u[k]
return d | def nested_update(d, u) | Merge two nested dicts.
Nested dicts are sometimes used for representing various recursive structures. When
updating such a structure, it may be convenient to present the updated data as a
corresponding recursive structure. This function will then apply the update.
Args:
d: dict
dict tha... | 1.468592 | 2.079453 | 0.70624 |
root_logger = logging.getLogger()
old_level_list = [h.level for h in root_logger.handlers]
for h in root_logger.handlers:
h.setLevel(logging.WARN)
log_format = logging.Formatter('%(message)s')
stream_handler = logging.StreamHandler(sys.stdout)
stream_handler.setFormatter(log_format)... | def print_logging() | Context manager to temporarily suppress additional information such as timestamps
when writing to loggers.
This makes logging look like ``print()``. The main use case is in scripts that mix
logging and ``print()``, as Python uses separate streams for those, and output can
and does end up getting shuffl... | 1.769789 | 1.889577 | 0.936606 |
with open(json_path, 'w', encoding='utf-8') as f:
f.write(serialize_to_normalized_pretty_json(py_obj)) | def save_json(py_obj, json_path) | Serialize a native object to JSON and save it normalized, pretty printed to a
file.
The JSON string is normalized by sorting any dictionary keys.
Args:
py_obj: object
Any object that can be represented in JSON. Some types, such as datetimes are
automatically converted to strings.
... | 3.529927 | 3.877597 | 0.910339 |
return json.dumps(py_obj, sort_keys=True, indent=2, cls=ToJsonCompatibleTypes) | def serialize_to_normalized_pretty_json(py_obj) | Serialize a native object to normalized, pretty printed JSON.
The JSON string is normalized by sorting any dictionary keys.
Args:
py_obj: object
Any object that can be represented in JSON. Some types, such as datetimes are
automatically converted to strings.
Returns:
str: norm... | 7.032175 | 11.303913 | 0.622101 |
return json.dumps(
py_obj, sort_keys=True, separators=(',', ':'), cls=ToJsonCompatibleTypes
) | def serialize_to_normalized_compact_json(py_obj) | Serialize a native object to normalized, compact JSON.
The JSON string is normalized by sorting any dictionary keys. It will be on a single
line without whitespace between elements.
Args:
py_obj: object
Any object that can be represented in JSON. Some types, such as datetimes are
aut... | 6.436495 | 9.583061 | 0.671653 |
rem_int, s_int = divmod(int(sec), 60)
rem_int, m_int, = divmod(rem_int, 60)
d_int, h_int, = divmod(rem_int, 24)
return '{}d{:02d}h{:02d}m'.format(d_int, h_int, m_int) | def format_sec_to_dhm(sec) | Format seconds to days, hours, minutes.
Args:
sec: float or int
Number of seconds in a period of time
Returns:
Period of time represented as a string on the form ``0d:00h:00m``. | 2.422955 | 2.437807 | 0.993908 |
self._event_dict.setdefault(event_str, 0)
self._event_dict[event_str] += inc_int | def count(self, event_str, inc_int=1) | Count an event.
Args:
event_str:
The name of an event to count. Used as a key in the event dict. The same
name will also be used in the summary.
inc_int: int
Optional argument to increase the count for the event by more than 1. | 2.648235 | 2.936604 | 0.901802 |
logger.info(
' - '.join(map(str, [v for v in (event_str, msg_str, inc_int) if v]))
)
self.count(event_str, inc_int or 1) | def log_and_count(self, event_str, msg_str=None, inc_int=None) | Count an event and write a message to a logger.
Args:
event_str: str
The name of an event to count. Used as a key in the event dict. The same
name will be used in the summary. This also becomes a part of the message
logged by this function.
msg_str: str
... | 3.78602 | 5.041463 | 0.750976 |
if self._event_dict:
logger.info('Events:')
for event_str, count_int in sorted(self._event_dict.items()):
logger.info(' {}: {}'.format(event_str, count_int))
else:
logger.info('No Events') | def dump_to_log(self) | Write summary to logger with the name and number of times each event has been
counted.
This function may be called at any point in the process. Counts are not zeroed. | 3.413284 | 2.988885 | 1.141992 |
# The models.CASCADE property is set on all ForeignKey fields, so tables can
# be deleted in any order without breaking constraints.
for model in django.apps.apps.get_models():
model.objects.all().delete() | def delete_all_from_db() | Clear the database.
Used for testing and debugging. | 7.146218 | 7.492031 | 0.953843 |
value = request.query_params.get(key) or request.data.get(key)
if value is None:
raise KeyError()
return value | def get_query_param(request, key) | Get query parameter uniformly for GET and POST requests. | 3.405268 | 2.933526 | 1.160811 |
if self.limit_query_param:
try:
return _positive_int(
get_query_param(request, self.limit_query_param),
strict=True,
cutoff=self.max_limit
)
except (KeyError, ValueError):
... | def get_limit(self, request) | Return limit parameter. | 3.032226 | 2.86148 | 1.05967 |
try:
return _positive_int(
get_query_param(request, self.offset_query_param),
)
except (KeyError, ValueError):
return 0 | def get_offset(self, request) | Return offset parameter. | 4.777648 | 4.190809 | 1.14003 |
logging.info('Futurizing module... path="{}"'.format(module_path))
ast_tree = back_to_the_futurize(module_path)
return d1_dev.util.update_module_file_ast(
ast_tree, module_path, show_diff, write_update
) | def futurize_module(module_path, show_diff, write_update) | 2to3 uses AST, not Baron. | 5.840361 | 5.331527 | 1.095439 |
logging.info('Removing single line import comments')
import_r, remaining_r = split_by_last_import(r)
new_import_r = redbaron.NodeList()
for i, v in enumerate(import_r):
if 1 < i < len(import_r) - 2:
if not (
import_r[i - 2].type != 'comment'
and v... | def _remove_single_line_import_comments(r) | We previously used more groups for the import statements and named each group. | 3.473412 | 3.396156 | 1.022748 |
module_dir_path = os.path.split(module_path)[0]
module_list = []
for item_name in os.listdir(module_dir_path):
item_path = os.path.join(module_dir_path, item_name)
if os.path.isfile(item_path) and item_name in ('__init__.py', 'setup.py'):
continue
if os.path.isfile(i... | def _update_init_all(module_path, r) | Add or update __all__ in __init__.py file. | 2.61573 | 2.560322 | 1.021641 |
new_r = redbaron.NodeList()
for n in r.node_list:
if n.type == 'assignment' and n.target.value == '__all__':
pass
else:
new_r.append(n)
return new_r | def _remove_init_all(r) | Remove any __all__ in __init__.py file. | 3.97277 | 3.737493 | 1.06295 |
# TODO: Add to documentation
if "f" in request.GET:
field_list = request.GET.getlist("f")
else:
field_list = None
result_dict = d1_gmn.app.views.util.query_object_list(request, "object_list_json")
result_dict["fields"] = field_list
result_dict["objects"] = d1_gmn.app.sysmet... | def get_object_list_json(request) | gmn.listObjects(session[, fromDate][, toDate][, formatId]
[, identifier][, replicaStatus][, start=0][, count=1000]
[, f=sysmetaField ...]) → ObjectListJson
GMN specific API for fast retrieval of object sysmeta elements. | 3.784775 | 3.595567 | 1.052623 |
if 'sphinx' in sys.modules:
module_base = 'resolwe.flow.executors'
else:
module_base = 'executors'
logging_config = dict(
version=1,
formatters={
'json_formatter': {
'()': JSONFormatter
},
},
handlers={
... | def configure_logging(emit_list) | Configure logging to send log records to the master. | 2.920756 | 2.906108 | 1.00504 |
data = record.__dict__.copy()
data['data_id'] = DATA['id']
data['data_location_id'] = DATA_LOCATION['id']
data['hostname'] = socket.gethostname()
# Get relative path, so listener can reconstruct the path to the actual code.
data['pathname'] = os.path.relpath(da... | def format(self, record) | Dump the record to JSON. | 5.735252 | 5.579453 | 1.027924 |
future = asyncio.ensure_future(send_manager_command(
ExecutorProtocol.LOG,
extra_fields={
ExecutorProtocol.LOG_MESSAGE: self.format(record),
},
expect_reply=False
))
self.emit_list.append(future) | def emit(self, record) | Send log message to the listener. | 9.029936 | 8.181479 | 1.103705 |
status = await client.describe(pid)
if status == 200:
self.progress_logger.event("SciObj already synced on CN")
return True
elif status == 404:
self.progress_logger.event("SciObj has not synced to CN")
return False
self.progress_lo... | async def is_object_synced_to_cn(self, client, pid) | Check if object with {pid} has successfully synced to the CN.
CNRead.describe() is used as it's a light-weight HTTP HEAD request.
This assumes that the call is being made over a connection that has
been authenticated and has read or better access on the given object if
it exists. | 5.325142 | 3.908457 | 1.362467 |
# Skip CN call for debugging
# status = 200
status = await client.synchronize(pid)
if status == 200:
self.progress_logger.event("Issued sync request, CN accepted")
else:
self.progress_logger.event(
"CNRead.synchronize() returned un... | async def send_synchronization_request(self, client, pid) | Issue a notification and request for sync for object with {pid} to the CN. | 9.090468 | 7.981263 | 1.138976 |
if metadata is None:
metadata = {}
secret = self.create(
value=value,
contributor=contributor,
metadata=metadata,
expires=expires,
)
return str(secret.handle) | def create_secret(self, value, contributor, metadata=None, expires=None) | Create a new secret, returning its handle.
:param value: Secret value to store
:param contributor: User owning the secret
:param metadata: Optional metadata dictionary (must be JSON serializable)
:param expires: Optional date/time of expiry (defaults to None, which means that
... | 3.206603 | 3.369872 | 0.95155 |
queryset = self.all()
if contributor is not None:
queryset = queryset.filter(contributor=contributor)
secret = queryset.get(handle=handle)
return secret.value | def get_secret(self, handle, contributor) | Retrieve an existing secret's value.
:param handle: Secret handle
:param contributor: User instance to perform contributor validation,
which means that only secrets for the given contributor will be
looked up. | 3.238845 | 3.447683 | 0.939427 |
schemas = {
'processor': 'processSchema.json',
'descriptor': 'descriptorSchema.json',
'field': 'fieldSchema.json',
'type': 'typeSchema.json',
}
if name not in schemas:
raise ValueError()
field_schema_file = finders.find('flow/{}'.format(schemas['field']), a... | def validation_schema(name) | Return json schema for json validation. | 3.121339 | 3.046761 | 1.024478 |
def hydrate_path(file_name):
from resolwe.flow.managers import manager
class HydratedPath(str):
__slots__ = ('data_id', 'file_name')
def __new__(cls, value=''):
hydrated = str.__new__(cls, value)
h... | def _hydrate_values(output, output_schema, data) | Hydrate basic:file and basic:json values.
Find fields with basic:file type and assign a full path to the file.
Find fields with basic:json type and assign a JSON object from storage. | 2.224251 | 2.165978 | 1.026904 |
from .data import Data # prevent circular import
for field_schema, fields in iterate_fields(input_, input_schema):
name = field_schema['name']
value = fields[name]
if 'type' in field_schema:
if field_schema['type'].startswith('data:'):
if value is None:... | def hydrate_input_references(input_, input_schema, hydrate_values=True) | Hydrate ``input_`` with linked data.
Find fields with complex data:<...> types in ``input_``.
Assign an output of corresponding data object to those fields. | 2.009108 | 1.999251 | 1.00493 |
from resolwe.flow.managers import manager
files = []
for field_schema, fields in iterate_fields(input_, input_schema):
name = field_schema['name']
value = fields[name]
if 'type' in field_schema:
if field_schema['type'] == 'basic:file:':
files.append(... | def hydrate_input_uploads(input_, input_schema, hydrate_values=True) | Hydrate input basic:upload types with upload location.
Find basic:upload fields in input.
Add the upload location for relative paths. | 3.296574 | 3.316443 | 0.994009 |
from .data import Data # prevent circular import
def get_dir_size(path):
total_size = 0
for dirpath, _, filenames in os.walk(path):
for file_name in filenames:
file_path = os.path.join(dirpath, file_name)
if not os.path.isfile(file_path... | def hydrate_size(data, force=False) | Add file and dir sizes.
Add sizes to ``basic:file:``, ``list:basic:file``, ``basic:dir:``
and ``list:basic:dir:`` fields.
``force`` parameter is used to recompute file sizes also on objects
that already have these values, e.g. in migrations. | 2.11977 | 2.052983 | 1.032532 |
if not data.descriptor_schema:
return
# Set default values
for field_schema, field, path in iterate_schema(data.descriptor, data.descriptor_schema.schema, 'descriptor'):
if 'default' in field_schema and field_schema['name'] not in field:
dict_dot(data, path, field_schema['d... | def render_descriptor(data) | Render data descriptor.
The rendering is based on descriptor schema and input context.
:param data: data instance
:type data: :class:`resolwe.flow.models.Data` or :class:`dict` | 5.978258 | 6.564325 | 0.910719 |
from resolwe.flow.managers import manager
# Get the appropriate expression engine. If none is defined, do not evaluate
# any expressions.
expression_engine = process.requirements.get('expression-engine', None)
if not expression_engine:
return template_string
return manager.get_exp... | def render_template(process, template_string, context) | Render template using the specified expression engine. | 4.909544 | 4.318193 | 1.136944 |
if isinstance(path, str):
path = path.split('.')
return list(path) | def json_path_components(path) | Convert JSON path to individual path components.
:param path: JSON path, which can be either an iterable of path
components or a dot-separated string
:return: A list of path components | 5.472625 | 5.903756 | 0.926973 |
errors = []
for item in supertype:
# Ensure that the item exists in subtype and has the same schema.
for subitem in subtype:
if item['name'] != subitem['name']:
continue
for key in set(item.keys()) | set(subitem.keys()):
if key in ('l... | def validate_process_subtype(supertype_name, supertype, subtype_name, subtype) | Perform process subtype validation.
:param supertype_name: Supertype name
:param supertype: Supertype schema
:param subtype_name: Subtype name
:param subtype: Subtype schema
:return: A list of validation error strings | 2.724917 | 2.738954 | 0.994875 |
if not queryset:
from .process import Process
queryset = Process.objects.all()
processes = {}
for process in queryset:
dict_dot(
processes,
process.type.replace(':', '.') + '__schema__',
process.output_schema
)
errors = []
fo... | def validate_process_types(queryset=None) | Perform process type validation.
:param queryset: Optional process queryset to validate
:return: A list of validation error strings | 3.925624 | 3.957855 | 0.991856 |
for field_schema, fields, path in iterate_schema(process_input, input_schema):
if 'default' in field_schema and field_schema['name'] not in fields:
dict_dot(process_input, path, field_schema['default']) | def fill_with_defaults(process_input, input_schema) | Fill empty optional fields in input with default values. | 4.089462 | 3.926057 | 1.041621 |
# When setting the contributor, it may be passed as an integer.
if isinstance(data, dict) and isinstance(data.get('id', None), int):
data = data['id']
elif isinstance(data, int):
pass
else:
raise ValidationError("Contributor must be an integer... | def to_internal_value(self, data) | Format the internal value. | 3.812046 | 3.665266 | 1.040046 |
descriptor = []
def flatten(current):
if isinstance(current, dict):
for key in current:
flatten(current[key])
elif isinstance(current, list):
for val in current:
flatten(val)
... | def extract_descriptor(self, obj) | Extract data from the descriptor. | 2.906159 | 2.801485 | 1.037364 |
if self.request and self.request.query_params.get('hydrate_{}'.format(kind), False):
serializer = serializer(items, many=True, read_only=True)
serializer.bind(kind, self)
return serializer.data
else:
return [item.id for item in items] | def _serialize_items(self, serializer, kind, items) | Return serialized items or list of ids, depending on `hydrate_XXX` query param. | 4.570233 | 2.80734 | 1.627959 |
entities = self._filter_queryset('view_entity', data.entity_set.all())
return list(entities.values_list('name', flat=True)) | def get_entity_names(self, data) | Return serialized list of entity names on data that user has `view` permission on. | 7.809424 | 5.084302 | 1.535988 |
collections = self._filter_queryset('view_collection', data.collection_set.all())
from .collection import CollectionSerializer
class CollectionWithoutDataSerializer(WithoutDataSerializerMixin, CollectionSerializer):
return self._serialize_items(CollectionWithoutD... | def get_collections(self, data) | Return serialized list of collection objects on data that user has `view` permission on. | 11.694564 | 9.400019 | 1.2441 |
entities = self._filter_queryset('view_entity', data.entity_set.all())
from .entity import EntitySerializer
class EntityWithoutDataSerializer(WithoutDataSerializerMixin, EntitySerializer):
return self._serialize_items(EntityWithoutDataSerializer, 'entities', enti... | def get_entities(self, data) | Return serialized list of entity objects on data that user has `view` permission on. | 13.545596 | 10.268117 | 1.31919 |
fields = super(DataSerializer, self).get_fields()
# Hide collections/entities fields on list views as fetching them may be expensive.
if self.parent is not None:
del fields['collections']
del fields['entities']
return fields | def get_fields(self) | Dynamically adapt fields based on the current request. | 8.419699 | 7.45458 | 1.129466 |
verbosity = int(options.get('verbosity'))
# Check that the specified output format is valid
if options['format'] != 'plain' and options['format'] != 'yaml':
raise CommandError("Unknown output format: %s" % options['format'])
# Gather only unique latest custom Docke... | def handle(self, *args, **options) | Handle command list_docker_images. | 3.247071 | 3.174239 | 1.022945 |
collections = request.data.get('collections', [])
# check that user has permissions on all collections that Data
# object will be added to
for collection_id in collections:
try:
collection = Collection.objects.get(pk=collection_id)
except... | def create(self, request, *args, **kwargs) | Create a resource. | 2.912113 | 2.80144 | 1.039506 |
kwargs['get_or_create'] = True
return self.create(request, *args, **kwargs) | def get_or_create(self, request, *args, **kwargs) | Get ``Data`` object if similar already exists, otherwise create it. | 3.610625 | 3.184697 | 1.133742 |
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
process = serializer.validated_data.get('process')
process_input = request.data.get('input', {})
fill_with_defaults(process_input, process.input_schema)
checksum = get... | def perform_get_or_create(self, request, *args, **kwargs) | Perform "get_or_create" - return existing object if found. | 2.795228 | 2.777429 | 1.006409 |
process = serializer.validated_data.get('process')
if not process.is_active:
raise exceptions.ParseError(
'Process retired (id: {}, slug: {}/{}).'.format(process.id, process.slug, process.version)
)
with transaction.atomic():
instance... | def perform_create(self, serializer) | Create a resource. | 4.446248 | 4.46892 | 0.994927 |
# Stop the startup code from running automatically from pytest unit tests.
# When running tests in parallel with xdist, an instance of GMN is launched
# before thread specific settings have been applied.
# if hasattr(sys, '_launched_by_pytest'):
# return
self._... | def ready(self) | Called once per Django process instance.
If the filesystem setup fails or if an error is found in settings.py,
django.core.exceptions.ImproperlyConfigured is raised, causing Django not to
launch the main GMN app. | 8.550137 | 7.472405 | 1.144228 |
v = self._get_setting(setting_name)
if (not os.path.isdir(os.path.split(v)[0])) or os.path.isdir(v):
self.raise_config_error(
setting_name,
v,
str,
'a file path in an existing directory',
is_none_allowed... | def _assert_dirs_exist(self, setting_name) | Check that the dirs leading up to the given file path exist.
Does not check if the file exists. | 5.248017 | 5.015557 | 1.046348 |
safe_settings_list = [
('DEBUG', False),
('DEBUG_GMN', False),
('STAND_ALONE', False),
('DATABASES.default.ATOMIC_REQUESTS', True),
('SECRET_KEY', '<Do not modify this placeholder value>'),
('STATIC_SERVER', False),
]
... | def _warn_unsafe_for_prod(self) | Warn on settings that are not safe for production. | 4.405641 | 3.940895 | 1.117929 |
name_list = setting_dotted_name.split('.')
setting_obj = getattr(django.conf.settings, name_list[0], default)
# if len(name_list) == 1:
# return setting_obj
return functools.reduce(
lambda o, a: o.get(a, default), [setting_obj] + name_list[1:]
) | def _get_setting(self, setting_dotted_name, default=None) | Return the value of a potentially nested dict setting.
E.g., 'DATABASES.default.NAME | 3.283865 | 3.469815 | 0.946409 |
# Thread with same id can be created when one terminates, but it
# is ok, as we are only concerned about concurent pushes.
current_thread_id = threading.current_thread().ident
if current_thread_id != self.connection_thread_id:
prepare_connection()
self.... | def _refresh_connection(self) | Refresh connection to Elasticsearch when worker is started.
File descriptors (sockets) can be shared between multiple
threads. If same connection is used by multiple threads at the
same time, this can cause timeouts in some of the pushes. So
connection needs to be reestablished in each ... | 9.103851 | 7.308899 | 1.245585 |
object_type = type(obj).__name__.lower()
return '{}_{}'.format(object_type, self.get_object_id(obj)) | def generate_id(self, obj) | Generate unique document id for ElasticSearch. | 3.749917 | 3.266778 | 1.147895 |
document = self.document_class(meta={'id': self.generate_id(obj)})
for field in document._doc_type.mapping: # pylint: disable=protected-access
if field in ['users_with_permissions', 'groups_with_permissions', 'public_permission']:
continue # These fields are handl... | def process_object(self, obj) | Process current object and push it to the ElasticSearch. | 2.987866 | 2.883895 | 1.036052 |
try:
self.document_class.init()
self._mapping_created = True
except IllegalOperation as error:
if error.args[0].startswith('You cannot update analysis configuration'):
# Ignore mapping update errors, which are thrown even when the analysis
... | def create_mapping(self) | Create the mappings in elasticsearch. | 8.154918 | 6.88549 | 1.184363 |
if obj is not None and queryset is not None:
raise ValueError(
"Only one of 'obj' and 'queryset' parameters can be passed to the build method."
)
if obj is not None:
if self.queryset.model != obj._meta.model: # pylint: disable=protected-acce... | def build(self, obj=None, queryset=None, push=True) | Build indexes. | 3.076803 | 3.031751 | 1.01486 |
logger.debug("Building '%s' Elasticsearch index...", self.__class__.__name__)
if obj is not None:
build_list = [obj]
elif queryset is not None:
build_list = self.queryset.intersection(queryset)
logger.debug("Found %s elements to build.", build_list... | def _build(self, obj=None, queryset=None, push=True) | Build indexes. | 2.141955 | 2.099021 | 1.020454 |
self._refresh_connection()
# Check if we need to update mappings as this needs to be done
# before we push anything to the Elasticsearch server.
# This must be done even if the queue is empty, as otherwise ES
# will fail when retrieving data.
if not self._mappin... | def push(self) | Push built documents to ElasticSearch. | 5.076881 | 4.484911 | 1.131992 |
self._refresh_connection()
self.push_queue = []
index_name = self.document_class()._get_index() # pylint: disable=protected-access
connections.get_connection().indices.delete(index_name, ignore=404)
self._mapping_created = False | def destroy(self) | Destroy an index. | 8.283643 | 7.50182 | 1.104218 |
# TODO: Optimize this for bulk running
filters = {
'object_pk': obj.id,
'content_type': ContentType.objects.get_for_model(obj),
'permission__codename__startswith': 'view',
}
return {
'users': list(
UserObjectPermiss... | def get_permissions(self, obj) | Return users and groups with ``view`` permission on the current object.
Return a dict with two keys - ``users`` and ``groups`` - which
contain list of ids of users/groups with ``view`` permission. | 2.701371 | 2.54065 | 1.06326 |
obj_id = self.generate_id(obj)
es_obj = self.document_class.get(obj_id, ignore=[404])
# Object may not exist in this index.
if es_obj:
es_obj.delete(refresh=True) | def remove_object(self, obj) | Remove current object from the ElasticSearch. | 4.785374 | 4.015764 | 1.191647 |
pyxbgen_args = []
pyxbgen_args.append('--schema-root=\'{}\''.format(self.schema_dir))
pyxbgen_args.append('--binding-root=\'{}\''.format(self.binding_dir))
pyxbgen_args.append(
'--schema-stripped-prefix='
'\'https://repository.dataone.org/software/cicore/... | def generate_pyxb_binding(self, args) | Args:
args: | 4.128136 | 4.10323 | 1.00607 |
cmd = 'pyxbgen {}'.format(' '.join(args))
print(cmd)
os.system(cmd) | def run_pyxbgen(self, args) | Args:
args: | 3.082314 | 3.221979 | 0.956653 |
version_filename = binding_filename + '_version.txt'
version_path = os.path.join(self.binding_dir, version_filename)
schema_path = os.path.join(self.schema_dir, schema_filename)
try:
tstamp, svnpath, svnrev, version = self.get_version_info_from_svn(
s... | def generate_version_file(self, schema_filename, binding_filename) | Given a DataONE schema, generates a file that contains version information
about the schema. | 2.964211 | 2.940199 | 1.008167 |
txt = .format(
tstamp, svnpath, svnrev, version
)
with open(version_file_path, 'w') as f:
f.write(txt) | def write_version_file(self, version_file_path, tstamp, svnpath, svnrev, version) | Args:
version_file_path: tstamp: svnpath: svnrev: version: | 3.36863 | 2.646972 | 1.272636 |
mmp_dict = {
'pid': pid.encode('utf-8'),
'sysmeta': ('sysmeta.xml', sysmeta_pyxb.toxml('utf-8')),
}
return self.PUT('meta', fields=mmp_dict, headers=vendorSpecific) | def updateSystemMetadataResponse(self, pid, sysmeta_pyxb, vendorSpecific=None) | MNStorage.updateSystemMetadata(session, pid, sysmeta) → boolean
http://jenkins-1.dataone.org/documentation/unstable/API-Documentation-
development/apis/MN_APIs.html#MNStorage.updateSystemMetadata.
Args:
pid:
sysmeta_pyxb:
vendorSpecific:
Returns: | 4.936457 | 7.738906 | 0.637875 |
Data = apps.get_model('flow', 'Data')
DataLocation = apps.get_model('flow', 'DataLocation')
for data in Data.objects.all():
if os.path.isdir(os.path.join(settings.FLOW_EXECUTOR['DATA_DIR'], str(data.id))):
with transaction.atomic():
# Manually set DataLocation id to... | def set_data_location(apps, schema_editor) | Create DataLocation for each Data. | 2.895321 | 2.750806 | 1.052536 |
self._log.debug("Loading page starting from %d" % start)
self._czero = start
self._pageoffs = 0
try:
pyxb.RequireValidWhenParsing(validation)
self._object_list = self._client.listObjects(
start=start,
count=self._pagesize,
... | def _loadMore(self, start=0, trys=0, validation=True) | Retrieves the next page of results. | 3.549445 | 3.451316 | 1.028432 |
parts = mime_type.split(";")
params = dict([tuple([s.strip() for s in param.split("=")]) for param in parts[1:]])
full_type = parts[0].strip()
# Java URLConnection class sends an Accept header that includes a single "*"
# Turn it into a legal wildcard.
if full_type == '*':
full_type... | def parse_mime_type(mime_type) | Carves up a mime-type and returns a tuple of the (type, subtype, params) where
'params' is a dictionary of all the parameters for the media range. For example, the
media range 'application/xhtml;q=0.5' would get parsed into:
('application', 'xhtml', {'q', '0.5'}) | 4.461722 | 4.199406 | 1.062465 |
parsed_header = [parse_media_range(r) for r in header.split(",")]
weighted_matches = [
(fitness_and_quality_parsed(mime_type, parsed_header), mime_type)
for mime_type in supported
]
weighted_matches.sort()
return weighted_matches[-1][0][1] and weighted_matches[-1][1] or '' | def best_match(supported, header) | Takes a list of supported mime-types and finds the best match for all the media-
ranges listed in header. The value of header must be a string that conforms to the
format of the HTTP Accept: header. The value of 'supported' is a list of mime-types.
>>> best_match(['application/xbel+xml', 'text/xml'], 'text... | 5.006983 | 4.560815 | 1.097826 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.