repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
genialis/resolwe
resolwe/flow/executors/run.py
BaseFlowExecutor._run
async def _run(self, data_id, script): """Execute the script and save results.""" self.data_id = data_id # Fetch data instance to get any executor requirements. self.process = PROCESS requirements = self.process['requirements'] self.requirements = requirements.get('execu...
python
async def _run(self, data_id, script): """Execute the script and save results.""" self.data_id = data_id # Fetch data instance to get any executor requirements. self.process = PROCESS requirements = self.process['requirements'] self.requirements = requirements.get('execu...
[ "async", "def", "_run", "(", "self", ",", "data_id", ",", "script", ")", ":", "self", ".", "data_id", "=", "data_id", "# Fetch data instance to get any executor requirements.", "self", ".", "process", "=", "PROCESS", "requirements", "=", "self", ".", "process", ...
Execute the script and save results.
[ "Execute", "the", "script", "and", "save", "results", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/executors/run.py#L134-L279
DataONEorg/d1_python
gmn/src/d1_gmn/app/local_replica.py
get_total_size_of_queued_replicas
def get_total_size_of_queued_replicas(): """Return the total number of bytes of requested, unprocessed replicas.""" return ( d1_gmn.app.models.ReplicationQueue.objects.filter( local_replica__info__status__status='queued' ).aggregate(Sum('size'))['size__sum'] or 0 )
python
def get_total_size_of_queued_replicas(): """Return the total number of bytes of requested, unprocessed replicas.""" 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", "(", "d1_gmn", ".", "app", ".", "models", ".", "ReplicationQueue", ".", "objects", ".", "filter", "(", "local_replica__info__status__status", "=", "'queued'", ")", ".", "aggregate", "(", "Sum", ...
Return the total number of bytes of requested, unprocessed replicas.
[ "Return", "the", "total", "number", "of", "bytes", "of", "requested", "unprocessed", "replicas", "." ]
train
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/gmn/src/d1_gmn/app/local_replica.py#L48-L55
DataONEorg/d1_python
gmn/src/d1_gmn/app/local_replica.py
add_to_replication_queue
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). Pos...
python
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). Pos...
[ "def", "add_to_replication_queue", "(", "source_node_urn", ",", "sysmeta_pyxb", ")", ":", "replica_info_model", "=", "d1_gmn", ".", "app", ".", "models", ".", "replica_info", "(", "status_str", "=", "'queued'", ",", "source_node_urn", "=", "source_node_urn", ")", ...
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...
[ "Add", "a", "replication", "request", "issued", "by", "a", "CN", "to", "a", "queue", "that", "is", "processed", "asynchronously", "." ]
train
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/gmn/src/d1_gmn/app/local_replica.py#L58-L80
DataONEorg/d1_python
gmn/src/d1_gmn/app/management/commands/util/standard_args.py
add_arguments
def add_arguments(parser, doc_str, add_base_url=True): """Add standard arguments for DataONE utilities to a command line parser.""" parser.description = doc_str parser.formatter_class = argparse.RawDescriptionHelpFormatter parser.add_argument("--debug", action="store_true", help="Debug level logging") ...
python
def add_arguments(parser, doc_str, add_base_url=True): """Add standard arguments for DataONE utilities to a command line parser.""" parser.description = doc_str parser.formatter_class = argparse.RawDescriptionHelpFormatter parser.add_argument("--debug", action="store_true", help="Debug level logging") ...
[ "def", "add_arguments", "(", "parser", ",", "doc_str", ",", "add_base_url", "=", "True", ")", ":", "parser", ".", "description", "=", "doc_str", "parser", ".", "formatter_class", "=", "argparse", ".", "RawDescriptionHelpFormatter", "parser", ".", "add_argument", ...
Add standard arguments for DataONE utilities to a command line parser.
[ "Add", "standard", "arguments", "for", "DataONE", "utilities", "to", "a", "command", "line", "parser", "." ]
train
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/gmn/src/d1_gmn/app/management/commands/util/standard_args.py#L29-L98
DataONEorg/d1_python
lib_common/src/d1_common/iter/path.py
path_generator
def path_generator( path_list, include_glob_list=None, exclude_glob_list=None, recursive=True, ignore_invalid=False, default_excludes=True, return_dir_paths=False, ): """# language=rst. Args: path_list: list of str List of file- and dir paths. File paths are used dire...
python
def path_generator( path_list, include_glob_list=None, exclude_glob_list=None, recursive=True, ignore_invalid=False, default_excludes=True, return_dir_paths=False, ): """# language=rst. Args: path_list: list of str List of file- and dir paths. File paths are used dire...
[ "def", "path_generator", "(", "path_list", ",", "include_glob_list", "=", "None", ",", "exclude_glob_list", "=", "None", ",", "recursive", "=", "True", ",", "ignore_invalid", "=", "False", ",", "default_excludes", "=", "True", ",", "return_dir_paths", "=", "Fals...
# language=rst. Args: path_list: list of str List of file- and dir paths. File paths are used directly and dirs are searched for files. ``path_list`` does not accept glob patterns, as it's more convenient to let the shell expand glob patterns to directly specified files and ...
[ "#", "language", "=", "rst", "." ]
train
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/iter/path.py#L44-L217
DataONEorg/d1_python
gmn/src/d1_gmn/app/resource_map.py
get_resource_map_members
def get_resource_map_members(pid): """``pid`` is the PID of a Resource Map or the PID of a member of a Resource Map.""" 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_m...
python
def get_resource_map_members(pid): """``pid`` is the PID of a Resource Map or the PID of a member of a Resource Map.""" 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_m...
[ "def", "get_resource_map_members", "(", "pid", ")", ":", "if", "d1_gmn", ".", "app", ".", "did", ".", "is_resource_map_db", "(", "pid", ")", ":", "return", "get_resource_map_members_by_map", "(", "pid", ")", "elif", "d1_gmn", ".", "app", ".", "did", ".", "...
``pid`` is the PID of a Resource Map or the PID of a member of a Resource Map.
[ "pid", "is", "the", "PID", "of", "a", "Resource", "Map", "or", "the", "PID", "of", "a", "member", "of", "a", "Resource", "Map", "." ]
train
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/gmn/src/d1_gmn/app/resource_map.py#L97-L106
DataONEorg/d1_python
client_cli/src/d1_cli/impl/session.py
Session.set_with_conversion
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...
python
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...
[ "def", "set_with_conversion", "(", "self", ",", "variable", ",", "value_string", ")", ":", "self", ".", "_assert_valid_variable", "(", "variable", ")", "try", ":", "v", "=", "ast", ".", "literal_eval", "(", "value_string", ")", "except", "(", "ValueError", "...
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.
[ "Convert", "user", "supplied", "string", "to", "Python", "type", "." ]
train
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/client_cli/src/d1_cli/impl/session.py#L160-L186
DataONEorg/d1_python
lib_common/src/d1_common/util.py
log_setup
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...
python
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...
[ "def", "log_setup", "(", "is_debug", "=", "False", ",", "is_multiprocess", "=", "False", ")", ":", "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...
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.
[ "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"...
train
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/util.py#L32-L52
DataONEorg/d1_python
lib_common/src/d1_common/util.py
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: Stri...
python
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: Stri...
[ "def", "get_content_type", "(", "content_type", ")", ":", "m", "=", "email", ".", "message", ".", "Message", "(", ")", "m", "[", "'Content-Type'", "]", "=", "content_type", "return", "m", ".", "get_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: ...
[ "Extract", "the", "MIME", "type", "value", "from", "a", "content", "type", "string", "." ]
train
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/util.py#L55-L77
DataONEorg/d1_python
lib_common/src/d1_common/util.py
nested_update
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...
python
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...
[ "def", "nested_update", "(", "d", ",", "u", ")", ":", "for", "k", ",", "v", "in", "list", "(", "u", ".", "items", "(", ")", ")", ":", "if", "isinstance", "(", "v", ",", "collections", ".", "Mapping", ")", ":", "r", "=", "nested_update", "(", "d...
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...
[ "Merge", "two", "nested", "dicts", "." ]
train
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/util.py#L80-L102
DataONEorg/d1_python
lib_common/src/d1_common/util.py
print_logging
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 an...
python
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 an...
[ "def", "print_logging", "(", ")", ":", "root_logger", "=", "logging", ".", "getLogger", "(", ")", "old_level_list", "=", "[", "h", ".", "level", "for", "h", "in", "root_logger", ".", "handlers", "]", "for", "h", "in", "root_logger", ".", "handlers", ":",...
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...
[ "Context", "manager", "to", "temporarily", "suppress", "additional", "information", "such", "as", "timestamps", "when", "writing", "to", "loggers", "." ]
train
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/util.py#L198-L230
DataONEorg/d1_python
lib_common/src/d1_common/util.py
save_json
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 ...
python
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 ...
[ "def", "save_json", "(", "py_obj", ",", "json_path", ")", ":", "with", "open", "(", "json_path", ",", "'w'", ",", "encoding", "=", "'utf-8'", ")", "as", "f", ":", "f", ".", "write", "(", "serialize_to_normalized_pretty_json", "(", "py_obj", ")", ")" ]
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. ...
[ "Serialize", "a", "native", "object", "to", "JSON", "and", "save", "it", "normalized", "pretty", "printed", "to", "a", "file", "." ]
train
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/util.py#L233-L253
DataONEorg/d1_python
lib_common/src/d1_common/util.py
serialize_to_normalized_pretty_json
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 automatic...
python
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 automatic...
[ "def", "serialize_to_normalized_pretty_json", "(", "py_obj", ")", ":", "return", "json", ".", "dumps", "(", "py_obj", ",", "sort_keys", "=", "True", ",", "indent", "=", "2", ",", "cls", "=", "ToJsonCompatibleTypes", ")" ]
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...
[ "Serialize", "a", "native", "object", "to", "normalized", "pretty", "printed", "JSON", "." ]
train
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/util.py#L287-L301
DataONEorg/d1_python
lib_common/src/d1_common/util.py
serialize_to_normalized_compact_json
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 represent...
python
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 represent...
[ "def", "serialize_to_normalized_compact_json", "(", "py_obj", ")", ":", "return", "json", ".", "dumps", "(", "py_obj", ",", "sort_keys", "=", "True", ",", "separators", "=", "(", "','", ",", "':'", ")", ",", "cls", "=", "ToJsonCompatibleTypes", ")" ]
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...
[ "Serialize", "a", "native", "object", "to", "normalized", "compact", "JSON", "." ]
train
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/util.py#L304-L321
DataONEorg/d1_python
lib_common/src/d1_common/util.py
format_sec_to_dhm
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``. """ rem_int, s_int = divmod(int(sec), 60) rem_int, m_int, = divm...
python
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``. """ rem_int, s_int = divmod(int(sec), 60) rem_int, m_int, = divm...
[ "def", "format_sec_to_dhm", "(", "sec", ")", ":", "rem_int", ",", "s_int", "=", "divmod", "(", "int", "(", "sec", ")", ",", "60", ")", "rem_int", ",", "m_int", ",", "=", "divmod", "(", "rem_int", ",", "60", ")", "d_int", ",", "h_int", ",", "=", "...
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``.
[ "Format", "seconds", "to", "days", "hours", "minutes", "." ]
train
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/util.py#L347-L361
DataONEorg/d1_python
lib_common/src/d1_common/util.py
EventCounter.count
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 th...
python
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 th...
[ "def", "count", "(", "self", ",", "event_str", ",", "inc_int", "=", "1", ")", ":", "self", ".", "_event_dict", ".", "setdefault", "(", "event_str", ",", "0", ")", "self", ".", "_event_dict", "[", "event_str", "]", "+=", "inc_int" ]
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.
[ "Count", "an", "event", "." ]
train
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/util.py#L141-L154
DataONEorg/d1_python
lib_common/src/d1_common/util.py
EventCounter.log_and_count
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 o...
python
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 o...
[ "def", "log_and_count", "(", "self", ",", "event_str", ",", "msg_str", "=", "None", ",", "inc_int", "=", "None", ")", ":", "logger", ".", "info", "(", "' - '", ".", "join", "(", "map", "(", "str", ",", "[", "v", "for", "v", "in", "(", "event_str", ...
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 ...
[ "Count", "an", "event", "and", "write", "a", "message", "to", "a", "logger", "." ]
train
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/util.py#L156-L177
DataONEorg/d1_python
lib_common/src/d1_common/util.py
EventCounter.dump_to_log
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. """ if self._event_dict: logger.info('Events:') for event_str...
python
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. """ if self._event_dict: logger.info('Events:') for event_str...
[ "def", "dump_to_log", "(", "self", ")", ":", "if", "self", ".", "_event_dict", ":", "logger", ".", "info", "(", "'Events:'", ")", "for", "event_str", ",", "count_int", "in", "sorted", "(", "self", ".", "_event_dict", ".", "items", "(", ")", ")", ":", ...
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.
[ "Write", "summary", "to", "logger", "with", "the", "name", "and", "number", "of", "times", "each", "event", "has", "been", "counted", "." ]
train
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/util.py#L179-L191
DataONEorg/d1_python
gmn/src/d1_gmn/app/delete.py
delete_all_from_db
def delete_all_from_db(): """Clear the database. Used for testing and debugging. """ # 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().dele...
python
def delete_all_from_db(): """Clear the database. Used for testing and debugging. """ # 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().dele...
[ "def", "delete_all_from_db", "(", ")", ":", "# 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", "(", ")", ":", "...
Clear the database. Used for testing and debugging.
[ "Clear", "the", "database", "." ]
train
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/gmn/src/d1_gmn/app/delete.py#L44-L53
genialis/resolwe
resolwe/elastic/pagination.py
get_query_param
def get_query_param(request, key): """Get query parameter uniformly for GET and POST requests.""" value = request.query_params.get(key) or request.data.get(key) if value is None: raise KeyError() return value
python
def get_query_param(request, key): """Get query parameter uniformly for GET and POST requests.""" 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", ")", ":", "value", "=", "request", ".", "query_params", ".", "get", "(", "key", ")", "or", "request", ".", "data", ".", "get", "(", "key", ")", "if", "value", "is", "None", ":", "raise", "KeyError...
Get query parameter uniformly for GET and POST requests.
[ "Get", "query", "parameter", "uniformly", "for", "GET", "and", "POST", "requests", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/elastic/pagination.py#L16-L21
genialis/resolwe
resolwe/elastic/pagination.py
LimitOffsetPostPagination.get_limit
def get_limit(self, request): """Return limit parameter.""" if self.limit_query_param: try: return _positive_int( get_query_param(request, self.limit_query_param), strict=True, cutoff=self.max_limit )...
python
def get_limit(self, request): """Return limit parameter.""" if self.limit_query_param: try: return _positive_int( get_query_param(request, self.limit_query_param), strict=True, cutoff=self.max_limit )...
[ "def", "get_limit", "(", "self", ",", "request", ")", ":", "if", "self", ".", "limit_query_param", ":", "try", ":", "return", "_positive_int", "(", "get_query_param", "(", "request", ",", "self", ".", "limit_query_param", ")", ",", "strict", "=", "True", "...
Return limit parameter.
[ "Return", "limit", "parameter", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/elastic/pagination.py#L33-L45
genialis/resolwe
resolwe/elastic/pagination.py
LimitOffsetPostPagination.get_offset
def get_offset(self, request): """Return offset parameter.""" try: return _positive_int( get_query_param(request, self.offset_query_param), ) except (KeyError, ValueError): return 0
python
def get_offset(self, request): """Return offset parameter.""" try: return _positive_int( get_query_param(request, self.offset_query_param), ) except (KeyError, ValueError): return 0
[ "def", "get_offset", "(", "self", ",", "request", ")", ":", "try", ":", "return", "_positive_int", "(", "get_query_param", "(", "request", ",", "self", ".", "offset_query_param", ")", ",", ")", "except", "(", "KeyError", ",", "ValueError", ")", ":", "retur...
Return offset parameter.
[ "Return", "offset", "parameter", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/elastic/pagination.py#L47-L54
DataONEorg/d1_python
dev_tools/src/d1_dev/src-cleanup.py
futurize_module
def futurize_module(module_path, show_diff, write_update): """2to3 uses AST, not Baron.""" 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 ...
python
def futurize_module(module_path, show_diff, write_update): """2to3 uses AST, not Baron.""" 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", ")", ":", "logging", ".", "info", "(", "'Futurizing module... path=\"{}\"'", ".", "format", "(", "module_path", ")", ")", "ast_tree", "=", "back_to_the_futurize", "(", "module_path"...
2to3 uses AST, not Baron.
[ "2to3", "uses", "AST", "not", "Baron", "." ]
train
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/dev_tools/src/d1_dev/src-cleanup.py#L159-L165
DataONEorg/d1_python
dev_tools/src/d1_dev/src-cleanup.py
_remove_single_line_import_comments
def _remove_single_line_import_comments(r): """We previously used more groups for the import statements and named each group.""" 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): ...
python
def _remove_single_line_import_comments(r): """We previously used more groups for the import statements and named each group.""" 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): ...
[ "def", "_remove_single_line_import_comments", "(", "r", ")", ":", "logging", ".", "info", "(", "'Removing single line import comments'", ")", "import_r", ",", "remaining_r", "=", "split_by_last_import", "(", "r", ")", "new_import_r", "=", "redbaron", ".", "NodeList", ...
We previously used more groups for the import statements and named each group.
[ "We", "previously", "used", "more", "groups", "for", "the", "import", "statements", "and", "named", "each", "group", "." ]
train
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/dev_tools/src/d1_dev/src-cleanup.py#L171-L186
DataONEorg/d1_python
dev_tools/src/d1_dev/src-cleanup.py
_update_init_all
def _update_init_all(module_path, r): """Add or update __all__ in __init__.py file.""" 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...
python
def _update_init_all(module_path, r): """Add or update __all__ in __init__.py file.""" 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...
[ "def", "_update_init_all", "(", "module_path", ",", "r", ")", ":", "module_dir_path", "=", "os", ".", "path", ".", "split", "(", "module_path", ")", "[", "0", "]", "module_list", "=", "[", "]", "for", "item_name", "in", "os", ".", "listdir", "(", "modu...
Add or update __all__ in __init__.py file.
[ "Add", "or", "update", "__all__", "in", "__init__", ".", "py", "file", "." ]
train
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/dev_tools/src/d1_dev/src-cleanup.py#L301-L329
DataONEorg/d1_python
dev_tools/src/d1_dev/src-cleanup.py
_remove_init_all
def _remove_init_all(r): """Remove any __all__ in __init__.py file.""" 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
python
def _remove_init_all(r): """Remove any __all__ in __init__.py file.""" 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", ")", ":", "new_r", "=", "redbaron", ".", "NodeList", "(", ")", "for", "n", "in", "r", ".", "node_list", ":", "if", "n", ".", "type", "==", "'assignment'", "and", "n", ".", "target", ".", "value", "==", "'__all__'"...
Remove any __all__ in __init__.py file.
[ "Remove", "any", "__all__", "in", "__init__", ".", "py", "file", "." ]
train
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/dev_tools/src/d1_dev/src-cleanup.py#L332-L340
DataONEorg/d1_python
gmn/src/d1_gmn/app/views/gmn.py
get_object_list_json
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. """ # TODO: Add to documentation ...
python
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. """ # TODO: Add to documentation ...
[ "def", "get_object_list_json", "(", "request", ")", ":", "# TODO: Add to documentation", "if", "\"f\"", "in", "request", ".", "GET", ":", "field_list", "=", "request", ".", "GET", ".", "getlist", "(", "\"f\"", ")", "else", ":", "field_list", "=", "None", "re...
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.
[ "gmn", ".", "listObjects", "(", "session", "[", "fromDate", "]", "[", "toDate", "]", "[", "formatId", "]" ]
train
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/gmn/src/d1_gmn/app/views/gmn.py#L34-L59
genialis/resolwe
resolwe/flow/executors/logger.py
configure_logging
def configure_logging(emit_list): """Configure logging to send log records to the master.""" if 'sphinx' in sys.modules: module_base = 'resolwe.flow.executors' else: module_base = 'executors' logging_config = dict( version=1, formatters={ 'json_formatter': { ...
python
def configure_logging(emit_list): """Configure logging to send log records to the master.""" if 'sphinx' in sys.modules: module_base = 'resolwe.flow.executors' else: module_base = 'executors' logging_config = dict( version=1, formatters={ 'json_formatter': { ...
[ "def", "configure_logging", "(", "emit_list", ")", ":", "if", "'sphinx'", "in", "sys", ".", "modules", ":", "module_base", "=", "'resolwe.flow.executors'", "else", ":", "module_base", "=", "'executors'", "logging_config", "=", "dict", "(", "version", "=", "1", ...
Configure logging to send log records to the master.
[ "Configure", "logging", "to", "send", "log", "records", "to", "the", "master", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/executors/logger.py#L62-L102
genialis/resolwe
resolwe/flow/executors/logger.py
JSONFormatter.format
def format(self, record): """Dump the record to JSON.""" 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 ac...
python
def format(self, record): """Dump the record to JSON.""" 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 ac...
[ "def", "format", "(", "self", ",", "record", ")", ":", "data", "=", "record", ".", "__dict__", ".", "copy", "(", ")", "data", "[", "'data_id'", "]", "=", "DATA", "[", "'id'", "]", "data", "[", "'data_location_id'", "]", "=", "DATA_LOCATION", "[", "'i...
Dump the record to JSON.
[ "Dump", "the", "record", "to", "JSON", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/executors/logger.py#L18-L35
genialis/resolwe
resolwe/flow/executors/logger.py
RedisHandler.emit
def emit(self, record): """Send log message to the listener.""" future = asyncio.ensure_future(send_manager_command( ExecutorProtocol.LOG, extra_fields={ ExecutorProtocol.LOG_MESSAGE: self.format(record), }, expect_reply=False )) ...
python
def emit(self, record): """Send log message to the listener.""" future = asyncio.ensure_future(send_manager_command( ExecutorProtocol.LOG, extra_fields={ ExecutorProtocol.LOG_MESSAGE: self.format(record), }, expect_reply=False )) ...
[ "def", "emit", "(", "self", ",", "record", ")", ":", "future", "=", "asyncio", ".", "ensure_future", "(", "send_manager_command", "(", "ExecutorProtocol", ".", "LOG", ",", "extra_fields", "=", "{", "ExecutorProtocol", ".", "LOG_MESSAGE", ":", "self", ".", "f...
Send log message to the listener.
[ "Send", "log", "message", "to", "the", "listener", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/executors/logger.py#L50-L59
DataONEorg/d1_python
gmn/src/d1_gmn/app/management/commands/sync.py
Command.is_object_synced_to_cn
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 ...
python
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 ...
[ "async", "def", "is_object_synced_to_cn", "(", "self", ",", "client", ",", "pid", ")", ":", "status", "=", "await", "client", ".", "describe", "(", "pid", ")", "if", "status", "==", "200", ":", "self", ".", "progress_logger", ".", "event", "(", "\"SciObj...
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.
[ "Check", "if", "object", "with", "{", "pid", "}", "has", "successfully", "synced", "to", "the", "CN", "." ]
train
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/gmn/src/d1_gmn/app/management/commands/sync.py#L147-L168
DataONEorg/d1_python
gmn/src/d1_gmn/app/management/commands/sync.py
Command.send_synchronization_request
async def send_synchronization_request(self, client, pid): """Issue a notification and request for sync for object with {pid} to the CN.""" # Skip CN call for debugging # status = 200 status = await client.synchronize(pid) if status == 200: self.progress_logger.event(...
python
async def send_synchronization_request(self, client, pid): """Issue a notification and request for sync for object with {pid} to the CN.""" # Skip CN call for debugging # status = 200 status = await client.synchronize(pid) if status == 200: self.progress_logger.event(...
[ "async", "def", "send_synchronization_request", "(", "self", ",", "client", ",", "pid", ")", ":", "# Skip CN call for debugging", "# status = 200", "status", "=", "await", "client", ".", "synchronize", "(", "pid", ")", "if", "status", "==", "200", ":", "self", ...
Issue a notification and request for sync for object with {pid} to the CN.
[ "Issue", "a", "notification", "and", "request", "for", "sync", "for", "object", "with", "{", "pid", "}", "to", "the", "CN", "." ]
train
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/gmn/src/d1_gmn/app/management/commands/sync.py#L170-L181
genialis/resolwe
resolwe/flow/models/secret.py
SecretManager.create_secret
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...
python
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...
[ "def", "create_secret", "(", "self", ",", "value", ",", "contributor", ",", "metadata", "=", "None", ",", "expires", "=", "None", ")", ":", "if", "metadata", "is", "None", ":", "metadata", "=", "{", "}", "secret", "=", "self", ".", "create", "(", "va...
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 ...
[ "Create", "a", "new", "secret", "returning", "its", "handle", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/models/secret.py#L14-L33
genialis/resolwe
resolwe/flow/models/secret.py
SecretManager.get_secret
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. """ ...
python
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. """ ...
[ "def", "get_secret", "(", "self", ",", "handle", ",", "contributor", ")", ":", "queryset", "=", "self", ".", "all", "(", ")", "if", "contributor", "is", "not", "None", ":", "queryset", "=", "queryset", ".", "filter", "(", "contributor", "=", "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.
[ "Retrieve", "an", "existing", "secret", "s", "value", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/models/secret.py#L35-L47
genialis/resolwe
resolwe/flow/models/utils.py
validation_schema
def validation_schema(name): """Return json schema for json validation.""" schemas = { 'processor': 'processSchema.json', 'descriptor': 'descriptorSchema.json', 'field': 'fieldSchema.json', 'type': 'typeSchema.json', } if name not in schemas: raise ValueError() ...
python
def validation_schema(name): """Return json schema for json validation.""" schemas = { 'processor': 'processSchema.json', 'descriptor': 'descriptorSchema.json', 'field': 'fieldSchema.json', 'type': 'typeSchema.json', } if name not in schemas: raise ValueError() ...
[ "def", "validation_schema", "(", "name", ")", ":", "schemas", "=", "{", "'processor'", ":", "'processSchema.json'", ",", "'descriptor'", ":", "'descriptorSchema.json'", ",", "'field'", ":", "'fieldSchema.json'", ",", "'type'", ":", "'typeSchema.json'", ",", "}", "...
Return json schema for json validation.
[ "Return", "json", "schema", "for", "json", "validation", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/models/utils.py#L19-L42
genialis/resolwe
resolwe/flow/models/utils.py
validate_schema
def validate_schema(instance, schema, test_required=True, data_location=None, skip_missing_data=False): """Check if DictField values are consistent with our data types. Perform basic JSON schema validation and our custom validations: * check that required fields are given (if `test_r...
python
def validate_schema(instance, schema, test_required=True, data_location=None, skip_missing_data=False): """Check if DictField values are consistent with our data types. Perform basic JSON schema validation and our custom validations: * check that required fields are given (if `test_r...
[ "def", "validate_schema", "(", "instance", ",", "schema", ",", "test_required", "=", "True", ",", "data_location", "=", "None", ",", "skip_missing_data", "=", "False", ")", ":", "from", ".", "storage", "import", "Storage", "# Prevent circular import.", "path_prefi...
Check if DictField values are consistent with our data types. Perform basic JSON schema validation and our custom validations: * check that required fields are given (if `test_required` is set to ``True``) * check if ``basic:file:`` and ``list:basic:file`` fields match regex given in s...
[ "Check", "if", "DictField", "values", "are", "consistent", "with", "our", "data", "types", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/models/utils.py#L48-L232
genialis/resolwe
resolwe/flow/models/utils.py
_hydrate_values
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. """ def hydrate_path(file_name): """Hydrate file paths...
python
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. """ def hydrate_path(file_name): """Hydrate file paths...
[ "def", "_hydrate_values", "(", "output", ",", "output_schema", ",", "data", ")", ":", "def", "hydrate_path", "(", "file_name", ")", ":", "\"\"\"Hydrate file paths.\"\"\"", "from", "resolwe", ".", "flow", ".", "managers", "import", "manager", "class", "HydratedPath...
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.
[ "Hydrate", "basic", ":", "file", "and", "basic", ":", "json", "values", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/models/utils.py#L235-L292
genialis/resolwe
resolwe/flow/models/utils.py
hydrate_input_references
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. """ from .data import Data # prevent circular import for fi...
python
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. """ from .data import Data # prevent circular import for fi...
[ "def", "hydrate_input_references", "(", "input_", ",", "input_schema", ",", "hydrate_values", "=", "True", ")", ":", "from", ".", "data", "import", "Data", "# prevent circular import", "for", "field_schema", ",", "fields", "in", "iterate_fields", "(", "input_", ",...
Hydrate ``input_`` with linked data. Find fields with complex data:<...> types in ``input_``. Assign an output of corresponding data object to those fields.
[ "Hydrate", "input_", "with", "linked", "data", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/models/utils.py#L295-L360
genialis/resolwe
resolwe/flow/models/utils.py
hydrate_input_uploads
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. """ from resolwe.flow.managers import manager files = [] for field_schema, fields ...
python
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. """ from resolwe.flow.managers import manager files = [] for field_schema, fields ...
[ "def", "hydrate_input_uploads", "(", "input_", ",", "input_schema", ",", "hydrate_values", "=", "True", ")", ":", "from", "resolwe", ".", "flow", ".", "managers", "import", "manager", "files", "=", "[", "]", "for", "field_schema", ",", "fields", "in", "itera...
Hydrate input basic:upload types with upload location. Find basic:upload fields in input. Add the upload location for relative paths.
[ "Hydrate", "input", "basic", ":", "upload", "types", "with", "upload", "location", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/models/utils.py#L363-L392
genialis/resolwe
resolwe/flow/models/utils.py
hydrate_size
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. """ from...
python
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. """ from...
[ "def", "hydrate_size", "(", "data", ",", "force", "=", "False", ")", ":", "from", ".", "data", "import", "Data", "# prevent circular import", "def", "get_dir_size", "(", "path", ")", ":", "\"\"\"Get directory size.\"\"\"", "total_size", "=", "0", "for", "dirpath...
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.
[ "Add", "file", "and", "dir", "sizes", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/models/utils.py#L395-L482
genialis/resolwe
resolwe/flow/models/utils.py
render_descriptor
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` """ if not data.descriptor_schema: return # Set default values for ...
python
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` """ if not data.descriptor_schema: return # Set default values for ...
[ "def", "render_descriptor", "(", "data", ")", ":", "if", "not", "data", ".", "descriptor_schema", ":", "return", "# Set default values", "for", "field_schema", ",", "field", ",", "path", "in", "iterate_schema", "(", "data", ".", "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`
[ "Render", "data", "descriptor", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/models/utils.py#L485-L500
genialis/resolwe
resolwe/flow/models/utils.py
render_template
def render_template(process, template_string, context): """Render template using the specified expression engine.""" 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...
python
def render_template(process, template_string, context): """Render template using the specified expression engine.""" 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...
[ "def", "render_template", "(", "process", ",", "template_string", ",", "context", ")", ":", "from", "resolwe", ".", "flow", ".", "managers", "import", "manager", "# Get the appropriate expression engine. If none is defined, do not evaluate", "# any expressions.", "expression_...
Render template using the specified expression engine.
[ "Render", "template", "using", "the", "specified", "expression", "engine", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/models/utils.py#L503-L513
genialis/resolwe
resolwe/flow/models/utils.py
json_path_components
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 """ if isinstance(path, str): path = path.split('.') retur...
python
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 """ if isinstance(path, str): path = path.split('.') retur...
[ "def", "json_path_components", "(", "path", ")", ":", "if", "isinstance", "(", "path", ",", "str", ")", ":", "path", "=", "path", ".", "split", "(", "'.'", ")", "return", "list", "(", "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
[ "Convert", "JSON", "path", "to", "individual", "path", "components", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/models/utils.py#L516-L526
genialis/resolwe
resolwe/flow/models/utils.py
validate_process_subtype
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 st...
python
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 st...
[ "def", "validate_process_subtype", "(", "supertype_name", ",", "supertype", ",", "subtype_name", ",", "subtype", ")", ":", "errors", "=", "[", "]", "for", "item", "in", "supertype", ":", "# Ensure that the item exists in subtype and has the same schema.", "for", "subite...
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
[ "Perform", "process", "subtype", "validation", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/models/utils.py#L529-L576
genialis/resolwe
resolwe/flow/models/utils.py
validate_process_types
def validate_process_types(queryset=None): """Perform process type validation. :param queryset: Optional process queryset to validate :return: A list of validation error strings """ if not queryset: from .process import Process queryset = Process.objects.all() processes = {} ...
python
def validate_process_types(queryset=None): """Perform process type validation. :param queryset: Optional process queryset to validate :return: A list of validation error strings """ if not queryset: from .process import Process queryset = Process.objects.all() processes = {} ...
[ "def", "validate_process_types", "(", "queryset", "=", "None", ")", ":", "if", "not", "queryset", ":", "from", ".", "process", "import", "Process", "queryset", "=", "Process", ".", "objects", ".", "all", "(", ")", "processes", "=", "{", "}", "for", "proc...
Perform process type validation. :param queryset: Optional process queryset to validate :return: A list of validation error strings
[ "Perform", "process", "type", "validation", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/models/utils.py#L579-L617
genialis/resolwe
resolwe/flow/models/utils.py
fill_with_defaults
def fill_with_defaults(process_input, input_schema): """Fill empty optional fields in input with default values.""" 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...
python
def fill_with_defaults(process_input, input_schema): """Fill empty optional fields in input with default values.""" 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...
[ "def", "fill_with_defaults", "(", "process_input", ",", "input_schema", ")", ":", "for", "field_schema", ",", "fields", ",", "path", "in", "iterate_schema", "(", "process_input", ",", "input_schema", ")", ":", "if", "'default'", "in", "field_schema", "and", "fie...
Fill empty optional fields in input with default values.
[ "Fill", "empty", "optional", "fields", "in", "input", "with", "default", "values", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/models/utils.py#L620-L624
genialis/resolwe
resolwe/flow/serializers/contributor.py
ContributorSerializer.to_internal_value
def to_internal_value(self, data): """Format the internal value.""" # 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...
python
def to_internal_value(self, data): """Format the internal value.""" # 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...
[ "def", "to_internal_value", "(", "self", ",", "data", ")", ":", "# When setting the contributor, it may be passed as an integer.", "if", "isinstance", "(", "data", ",", "dict", ")", "and", "isinstance", "(", "data", ".", "get", "(", "'id'", ",", "None", ")", ","...
Format the internal value.
[ "Format", "the", "internal", "value", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/serializers/contributor.py#L35-L45
genialis/resolwe
resolwe/flow/elastic_indexes/collection.py
CollectionIndexMixin.extract_descriptor
def extract_descriptor(self, obj): """Extract data from the descriptor.""" descriptor = [] def flatten(current): """Flatten descriptor.""" if isinstance(current, dict): for key in current: flatten(current[key]) elif isinsta...
python
def extract_descriptor(self, obj): """Extract data from the descriptor.""" descriptor = [] def flatten(current): """Flatten descriptor.""" if isinstance(current, dict): for key in current: flatten(current[key]) elif isinsta...
[ "def", "extract_descriptor", "(", "self", ",", "obj", ")", ":", "descriptor", "=", "[", "]", "def", "flatten", "(", "current", ")", ":", "\"\"\"Flatten descriptor.\"\"\"", "if", "isinstance", "(", "current", ",", "dict", ")", ":", "for", "key", "in", "curr...
Extract data from the descriptor.
[ "Extract", "data", "from", "the", "descriptor", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/elastic_indexes/collection.py#L26-L43
genialis/resolwe
resolwe/flow/serializers/data.py
DataSerializer._serialize_items
def _serialize_items(self, serializer, kind, items): """Return serialized items or list of ids, depending on `hydrate_XXX` query param.""" if self.request and self.request.query_params.get('hydrate_{}'.format(kind), False): serializer = serializer(items, many=True, read_only=True) ...
python
def _serialize_items(self, serializer, kind, items): """Return serialized items or list of ids, depending on `hydrate_XXX` query param.""" if self.request and self.request.query_params.get('hydrate_{}'.format(kind), False): serializer = serializer(items, many=True, read_only=True) ...
[ "def", "_serialize_items", "(", "self", ",", "serializer", ",", "kind", ",", "items", ")", ":", "if", "self", ".", "request", "and", "self", ".", "request", ".", "query_params", ".", "get", "(", "'hydrate_{}'", ".", "format", "(", "kind", ")", ",", "Fa...
Return serialized items or list of ids, depending on `hydrate_XXX` query param.
[ "Return", "serialized", "items", "or", "list", "of", "ids", "depending", "on", "hydrate_XXX", "query", "param", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/serializers/data.py#L91-L98
genialis/resolwe
resolwe/flow/serializers/data.py
DataSerializer.get_entity_names
def get_entity_names(self, data): """Return serialized list of entity names on data that user has `view` permission on.""" entities = self._filter_queryset('view_entity', data.entity_set.all()) return list(entities.values_list('name', flat=True))
python
def get_entity_names(self, data): """Return serialized list of entity names on data that user has `view` permission on.""" entities = self._filter_queryset('view_entity', data.entity_set.all()) return list(entities.values_list('name', flat=True))
[ "def", "get_entity_names", "(", "self", ",", "data", ")", ":", "entities", "=", "self", ".", "_filter_queryset", "(", "'view_entity'", ",", "data", ".", "entity_set", ".", "all", "(", ")", ")", "return", "list", "(", "entities", ".", "values_list", "(", ...
Return serialized list of entity names on data that user has `view` permission on.
[ "Return", "serialized", "list", "of", "entity", "names", "on", "data", "that", "user", "has", "view", "permission", "on", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/serializers/data.py#L105-L108
genialis/resolwe
resolwe/flow/serializers/data.py
DataSerializer.get_collections
def get_collections(self, data): """Return serialized list of collection objects on data that user has `view` permission on.""" collections = self._filter_queryset('view_collection', data.collection_set.all()) from .collection import CollectionSerializer class CollectionWithoutDataSeri...
python
def get_collections(self, data): """Return serialized list of collection objects on data that user has `view` permission on.""" collections = self._filter_queryset('view_collection', data.collection_set.all()) from .collection import CollectionSerializer class CollectionWithoutDataSeri...
[ "def", "get_collections", "(", "self", ",", "data", ")", ":", "collections", "=", "self", ".", "_filter_queryset", "(", "'view_collection'", ",", "data", ".", "collection_set", ".", "all", "(", ")", ")", "from", ".", "collection", "import", "CollectionSerializ...
Return serialized list of collection objects on data that user has `view` permission on.
[ "Return", "serialized", "list", "of", "collection", "objects", "on", "data", "that", "user", "has", "view", "permission", "on", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/serializers/data.py#L110-L119
genialis/resolwe
resolwe/flow/serializers/data.py
DataSerializer.get_entities
def get_entities(self, data): """Return serialized list of entity objects on data that user has `view` permission on.""" entities = self._filter_queryset('view_entity', data.entity_set.all()) from .entity import EntitySerializer class EntityWithoutDataSerializer(WithoutDataSerializerMi...
python
def get_entities(self, data): """Return serialized list of entity objects on data that user has `view` permission on.""" entities = self._filter_queryset('view_entity', data.entity_set.all()) from .entity import EntitySerializer class EntityWithoutDataSerializer(WithoutDataSerializerMi...
[ "def", "get_entities", "(", "self", ",", "data", ")", ":", "entities", "=", "self", ".", "_filter_queryset", "(", "'view_entity'", ",", "data", ".", "entity_set", ".", "all", "(", ")", ")", "from", ".", "entity", "import", "EntitySerializer", "class", "Ent...
Return serialized list of entity objects on data that user has `view` permission on.
[ "Return", "serialized", "list", "of", "entity", "objects", "on", "data", "that", "user", "has", "view", "permission", "on", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/serializers/data.py#L121-L130
genialis/resolwe
resolwe/flow/serializers/data.py
DataSerializer.get_fields
def get_fields(self): """Dynamically adapt fields based on the current request.""" 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'] ...
python
def get_fields(self): """Dynamically adapt fields based on the current request.""" 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'] ...
[ "def", "get_fields", "(", "self", ")", ":", "fields", "=", "super", "(", "DataSerializer", ",", "self", ")", ".", "get_fields", "(", ")", "# Hide collections/entities fields on list views as fetching them may be expensive.", "if", "self", ".", "parent", "is", "not", ...
Dynamically adapt fields based on the current request.
[ "Dynamically", "adapt", "fields", "based", "on", "the", "current", "request", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/serializers/data.py#L132-L141
genialis/resolwe
resolwe/flow/management/commands/list_docker_images.py
Command.handle
def handle(self, *args, **options): """Handle command list_docker_images.""" 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...
python
def handle(self, *args, **options): """Handle command list_docker_images.""" 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...
[ "def", "handle", "(", "self", ",", "*", "args", ",", "*", "*", "options", ")", ":", "verbosity", "=", "int", "(", "options", ".", "get", "(", "'verbosity'", ")", ")", "# Check that the specified output format is valid", "if", "options", "[", "'format'", "]",...
Handle command list_docker_images.
[ "Handle", "command", "list_docker_images", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/management/commands/list_docker_images.py#L48-L129
genialis/resolwe
resolwe/flow/views/data.py
DataViewSet.create
def create(self, request, *args, **kwargs): """Create a resource.""" 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: coll...
python
def create(self, request, *args, **kwargs): """Create a resource.""" 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: coll...
[ "def", "create", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "collections", "=", "request", ".", "data", ".", "get", "(", "'collections'", ",", "[", "]", ")", "# check that user has permissions on all collections that Data...
Create a resource.
[ "Create", "a", "resource", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/views/data.py#L108-L138
genialis/resolwe
resolwe/flow/views/data.py
DataViewSet.get_or_create
def get_or_create(self, request, *args, **kwargs): """Get ``Data`` object if similar already exists, otherwise create it.""" kwargs['get_or_create'] = True return self.create(request, *args, **kwargs)
python
def get_or_create(self, request, *args, **kwargs): """Get ``Data`` object if similar already exists, otherwise create it.""" kwargs['get_or_create'] = True return self.create(request, *args, **kwargs)
[ "def", "get_or_create", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'get_or_create'", "]", "=", "True", "return", "self", ".", "create", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ...
Get ``Data`` object if similar already exists, otherwise create it.
[ "Get", "Data", "object", "if", "similar", "already", "exists", "otherwise", "create", "it", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/views/data.py#L162-L165
genialis/resolwe
resolwe/flow/views/data.py
DataViewSet.perform_get_or_create
def perform_get_or_create(self, request, *args, **kwargs): """Perform "get_or_create" - return existing object if found.""" serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) process = serializer.validated_data.get('process') process_inp...
python
def perform_get_or_create(self, request, *args, **kwargs): """Perform "get_or_create" - return existing object if found.""" serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) process = serializer.validated_data.get('process') process_inp...
[ "def", "perform_get_or_create", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "serializer", "=", "self", ".", "get_serializer", "(", "data", "=", "request", ".", "data", ")", "serializer", ".", "is_valid", "(", "raise_...
Perform "get_or_create" - return existing object if found.
[ "Perform", "get_or_create", "-", "return", "existing", "object", "if", "found", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/views/data.py#L167-L185
genialis/resolwe
resolwe/flow/views/data.py
DataViewSet.perform_create
def perform_create(self, serializer): """Create a resource.""" 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) ...
python
def perform_create(self, serializer): """Create a resource.""" 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) ...
[ "def", "perform_create", "(", "self", ",", "serializer", ")", ":", "process", "=", "serializer", ".", "validated_data", ".", "get", "(", "'process'", ")", "if", "not", "process", ".", "is_active", ":", "raise", "exceptions", ".", "ParseError", "(", "'Process...
Create a resource.
[ "Create", "a", "resource", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/views/data.py#L187-L213
DataONEorg/d1_python
gmn/src/d1_gmn/app/gmn.py
Startup.ready
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. """ # Stop the startup code from runn...
python
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. """ # Stop the startup code from runn...
[ "def", "ready", "(", "self", ")", ":", "# 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'):", ...
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.
[ "Called", "once", "per", "Django", "process", "instance", "." ]
train
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/gmn/src/d1_gmn/app/gmn.py#L49-L75
DataONEorg/d1_python
gmn/src/d1_gmn/app/gmn.py
Startup._assert_dirs_exist
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. """ v = self._get_setting(setting_name) if (not os.path.isdir(os.path.split(v)[0])) or os.path.isdir(v): self.raise_config_...
python
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. """ v = self._get_setting(setting_name) if (not os.path.isdir(os.path.split(v)[0])) or os.path.isdir(v): self.raise_config_...
[ "def", "_assert_dirs_exist", "(", "self", ",", "setting_name", ")", ":", "v", "=", "self", ".", "_get_setting", "(", "setting_name", ")", "if", "(", "not", "os", ".", "path", ".", "isdir", "(", "os", ".", "path", ".", "split", "(", "v", ")", "[", "...
Check that the dirs leading up to the given file path exist. Does not check if the file exists.
[ "Check", "that", "the", "dirs", "leading", "up", "to", "the", "given", "file", "path", "exist", "." ]
train
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/gmn/src/d1_gmn/app/gmn.py#L109-L123
DataONEorg/d1_python
gmn/src/d1_gmn/app/gmn.py
Startup._warn_unsafe_for_prod
def _warn_unsafe_for_prod(self): """Warn on settings that are not safe for production.""" safe_settings_list = [ ('DEBUG', False), ('DEBUG_GMN', False), ('STAND_ALONE', False), ('DATABASES.default.ATOMIC_REQUESTS', True), ('SECRET_KEY', '<Do no...
python
def _warn_unsafe_for_prod(self): """Warn on settings that are not safe for production.""" safe_settings_list = [ ('DEBUG', False), ('DEBUG_GMN', False), ('STAND_ALONE', False), ('DATABASES.default.ATOMIC_REQUESTS', True), ('SECRET_KEY', '<Do no...
[ "def", "_warn_unsafe_for_prod", "(", "self", ")", ":", "safe_settings_list", "=", "[", "(", "'DEBUG'", ",", "False", ")", ",", "(", "'DEBUG_GMN'", ",", "False", ")", ",", "(", "'STAND_ALONE'", ",", "False", ")", ",", "(", "'DATABASES.default.ATOMIC_REQUESTS'",...
Warn on settings that are not safe for production.
[ "Warn", "on", "settings", "that", "are", "not", "safe", "for", "production", "." ]
train
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/gmn/src/d1_gmn/app/gmn.py#L153-L169
DataONEorg/d1_python
gmn/src/d1_gmn/app/gmn.py
Startup._get_setting
def _get_setting(self, setting_dotted_name, default=None): """Return the value of a potentially nested dict setting. E.g., 'DATABASES.default.NAME """ name_list = setting_dotted_name.split('.') setting_obj = getattr(django.conf.settings, name_list[0], default) # if len(...
python
def _get_setting(self, setting_dotted_name, default=None): """Return the value of a potentially nested dict setting. E.g., 'DATABASES.default.NAME """ name_list = setting_dotted_name.split('.') setting_obj = getattr(django.conf.settings, name_list[0], default) # if len(...
[ "def", "_get_setting", "(", "self", ",", "setting_dotted_name", ",", "default", "=", "None", ")", ":", "name_list", "=", "setting_dotted_name", ".", "split", "(", "'.'", ")", "setting_obj", "=", "getattr", "(", "django", ".", "conf", ".", "settings", ",", ...
Return the value of a potentially nested dict setting. E.g., 'DATABASES.default.NAME
[ "Return", "the", "value", "of", "a", "potentially", "nested", "dict", "setting", "." ]
train
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/gmn/src/d1_gmn/app/gmn.py#L244-L257
genialis/resolwe
resolwe/elastic/indices.py
BaseIndex._refresh_connection
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 con...
python
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 con...
[ "def", "_refresh_connection", "(", "self", ")", ":", "# 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", "curre...
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 ...
[ "Refresh", "connection", "to", "Elasticsearch", "when", "worker", "is", "started", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/elastic/indices.py#L138-L154
genialis/resolwe
resolwe/elastic/indices.py
BaseIndex.generate_id
def generate_id(self, obj): """Generate unique document id for ElasticSearch.""" object_type = type(obj).__name__.lower() return '{}_{}'.format(object_type, self.get_object_id(obj))
python
def generate_id(self, obj): """Generate unique document id for ElasticSearch.""" object_type = type(obj).__name__.lower() return '{}_{}'.format(object_type, self.get_object_id(obj))
[ "def", "generate_id", "(", "self", ",", "obj", ")", ":", "object_type", "=", "type", "(", "obj", ")", ".", "__name__", ".", "lower", "(", ")", "return", "'{}_{}'", ".", "format", "(", "object_type", ",", "self", ".", "get_object_id", "(", "obj", ")", ...
Generate unique document id for ElasticSearch.
[ "Generate", "unique", "document", "id", "for", "ElasticSearch", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/elastic/indices.py#L180-L183
genialis/resolwe
resolwe/elastic/indices.py
BaseIndex.process_object
def process_object(self, obj): """Process current object and push it to the ElasticSearch.""" 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', 'group...
python
def process_object(self, obj): """Process current object and push it to the ElasticSearch.""" 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', 'group...
[ "def", "process_object", "(", "self", ",", "obj", ")", ":", "document", "=", "self", ".", "document_class", "(", "meta", "=", "{", "'id'", ":", "self", ".", "generate_id", "(", "obj", ")", "}", ")", "for", "field", "in", "document", ".", "_doc_type", ...
Process current object and push it to the ElasticSearch.
[ "Process", "current", "object", "and", "push", "it", "to", "the", "ElasticSearch", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/elastic/indices.py#L185-L241
genialis/resolwe
resolwe/elastic/indices.py
BaseIndex.create_mapping
def create_mapping(self): """Create the mappings in elasticsearch.""" try: self.document_class.init() self._mapping_created = True except IllegalOperation as error: if error.args[0].startswith('You cannot update analysis configuration'): # Igno...
python
def create_mapping(self): """Create the mappings in elasticsearch.""" try: self.document_class.init() self._mapping_created = True except IllegalOperation as error: if error.args[0].startswith('You cannot update analysis configuration'): # Igno...
[ "def", "create_mapping", "(", "self", ")", ":", "try", ":", "self", ".", "document_class", ".", "init", "(", ")", "self", ".", "_mapping_created", "=", "True", "except", "IllegalOperation", "as", "error", ":", "if", "error", ".", "args", "[", "0", "]", ...
Create the mappings in elasticsearch.
[ "Create", "the", "mappings", "in", "elasticsearch", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/elastic/indices.py#L243-L255
genialis/resolwe
resolwe/elastic/indices.py
BaseIndex.build
def build(self, obj=None, queryset=None, push=True): """Build indexes.""" 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 ...
python
def build(self, obj=None, queryset=None, push=True): """Build indexes.""" 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 ...
[ "def", "build", "(", "self", ",", "obj", "=", "None", ",", "queryset", "=", "None", ",", "push", "=", "True", ")", ":", "if", "obj", "is", "not", "None", "and", "queryset", "is", "not", "None", ":", "raise", "ValueError", "(", "\"Only one of 'obj' and ...
Build indexes.
[ "Build", "indexes", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/elastic/indices.py#L257-L323
genialis/resolwe
resolwe/elastic/indices.py
BaseIndex._build
def _build(self, obj=None, queryset=None, push=True): """Build indexes.""" 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(que...
python
def _build(self, obj=None, queryset=None, push=True): """Build indexes.""" 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(que...
[ "def", "_build", "(", "self", ",", "obj", "=", "None", ",", "queryset", "=", "None", ",", "push", "=", "True", ")", ":", "logger", ".", "debug", "(", "\"Building '%s' Elasticsearch index...\"", ",", "self", ".", "__class__", ".", "__name__", ")", "if", "...
Build indexes.
[ "Build", "indexes", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/elastic/indices.py#L325-L367
genialis/resolwe
resolwe/elastic/indices.py
BaseIndex.push
def push(self): """Push built documents to ElasticSearch.""" 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 #...
python
def push(self): """Push built documents to ElasticSearch.""" 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 #...
[ "def", "push", "(", "self", ")", ":", "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 ...
Push built documents to ElasticSearch.
[ "Push", "built", "documents", "to", "ElasticSearch", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/elastic/indices.py#L369-L390
genialis/resolwe
resolwe/elastic/indices.py
BaseIndex.destroy
def destroy(self): """Destroy an index.""" 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 = Fal...
python
def destroy(self): """Destroy an index.""" 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 = Fal...
[ "def", "destroy", "(", "self", ")", ":", "self", ".", "_refresh_connection", "(", ")", "self", ".", "push_queue", "=", "[", "]", "index_name", "=", "self", ".", "document_class", "(", ")", ".", "_get_index", "(", ")", "# pylint: disable=protected-access", "c...
Destroy an index.
[ "Destroy", "an", "index", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/elastic/indices.py#L392-L400
genialis/resolwe
resolwe/elastic/indices.py
BaseIndex.get_permissions
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. """ # TODO: Optimize this for bulk running ...
python
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. """ # TODO: Optimize this for bulk running ...
[ "def", "get_permissions", "(", "self", ",", "obj", ")", ":", "# TODO: Optimize this for bulk running", "filters", "=", "{", "'object_pk'", ":", "obj", ".", "id", ",", "'content_type'", ":", "ContentType", ".", "objects", ".", "get_for_model", "(", "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.
[ "Return", "users", "and", "groups", "with", "view", "permission", "on", "the", "current", "object", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/elastic/indices.py#L402-L422
genialis/resolwe
resolwe/elastic/indices.py
BaseIndex.remove_object
def remove_object(self, obj): """Remove current object from the ElasticSearch.""" 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)
python
def remove_object(self, obj): """Remove current object from the ElasticSearch.""" 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", ")", ":", "obj_id", "=", "self", ".", "generate_id", "(", "obj", ")", "es_obj", "=", "self", ".", "document_class", ".", "get", "(", "obj_id", ",", "ignore", "=", "[", "404", "]", ")", "# Object may not ...
Remove current object from the ElasticSearch.
[ "Remove", "current", "object", "from", "the", "ElasticSearch", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/elastic/indices.py#L428-L434
DataONEorg/d1_python
lib_common/src/d1_common/types/scripts/pyxbgen_all.py
GenerateBindings.generate_pyxb_binding
def generate_pyxb_binding(self, args): """Args: args: """ pyxbgen_args = [] pyxbgen_args.append('--schema-root=\'{}\''.format(self.schema_dir)) pyxbgen_args.append('--binding-root=\'{}\''.format(self.binding_dir)) pyxbgen_args.append( '--schema-strip...
python
def generate_pyxb_binding(self, args): """Args: args: """ pyxbgen_args = [] pyxbgen_args.append('--schema-root=\'{}\''.format(self.schema_dir)) pyxbgen_args.append('--binding-root=\'{}\''.format(self.binding_dir)) pyxbgen_args.append( '--schema-strip...
[ "def", "generate_pyxb_binding", "(", "self", ",", "args", ")", ":", "pyxbgen_args", "=", "[", "]", "pyxbgen_args", ".", "append", "(", "'--schema-root=\\'{}\\''", ".", "format", "(", "self", ".", "schema_dir", ")", ")", "pyxbgen_args", ".", "append", "(", "'...
Args: args:
[ "Args", ":" ]
train
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/types/scripts/pyxbgen_all.py#L132-L147
DataONEorg/d1_python
lib_common/src/d1_common/types/scripts/pyxbgen_all.py
GenerateBindings.run_pyxbgen
def run_pyxbgen(self, args): """Args: args: """ cmd = 'pyxbgen {}'.format(' '.join(args)) print(cmd) os.system(cmd)
python
def run_pyxbgen(self, args): """Args: args: """ cmd = 'pyxbgen {}'.format(' '.join(args)) print(cmd) os.system(cmd)
[ "def", "run_pyxbgen", "(", "self", ",", "args", ")", ":", "cmd", "=", "'pyxbgen {}'", ".", "format", "(", "' '", ".", "join", "(", "args", ")", ")", "print", "(", "cmd", ")", "os", ".", "system", "(", "cmd", ")" ]
Args: args:
[ "Args", ":" ]
train
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/types/scripts/pyxbgen_all.py#L149-L157
DataONEorg/d1_python
lib_common/src/d1_common/types/scripts/pyxbgen_all.py
GenerateVersionFile.generate_version_file
def generate_version_file(self, schema_filename, binding_filename): """Given a DataONE schema, generates a file that contains version information about the schema.""" version_filename = binding_filename + '_version.txt' version_path = os.path.join(self.binding_dir, version_filename) ...
python
def generate_version_file(self, schema_filename, binding_filename): """Given a DataONE schema, generates a file that contains version information about the schema.""" version_filename = binding_filename + '_version.txt' version_path = os.path.join(self.binding_dir, version_filename) ...
[ "def", "generate_version_file", "(", "self", ",", "schema_filename", ",", "binding_filename", ")", ":", "version_filename", "=", "binding_filename", "+", "'_version.txt'", "version_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "binding_dir", ",", ...
Given a DataONE schema, generates a file that contains version information about the schema.
[ "Given", "a", "DataONE", "schema", "generates", "a", "file", "that", "contains", "version", "information", "about", "the", "schema", "." ]
train
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/types/scripts/pyxbgen_all.py#L170-L183
DataONEorg/d1_python
lib_common/src/d1_common/types/scripts/pyxbgen_all.py
GenerateVersionFile.write_version_file
def write_version_file(self, version_file_path, tstamp, svnpath, svnrev, version): """Args: version_file_path: tstamp: svnpath: svnrev: version: """ txt = """# This file is automatically generated. Manual edits will be erased. # When this file was generated TIMESTAMP="{}" # Path of t...
python
def write_version_file(self, version_file_path, tstamp, svnpath, svnrev, version): """Args: version_file_path: tstamp: svnpath: svnrev: version: """ txt = """# This file is automatically generated. Manual edits will be erased. # When this file was generated TIMESTAMP="{}" # Path of t...
[ "def", "write_version_file", "(", "self", ",", "version_file_path", ",", "tstamp", ",", "svnpath", ",", "svnrev", ",", "version", ")", ":", "txt", "=", "\"\"\"# This file is automatically generated. Manual edits will be erased.\n\n# When this file was generated\nTIMESTAMP=\"{}\"\...
Args: version_file_path: tstamp: svnpath: svnrev: version:
[ "Args", ":" ]
train
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/types/scripts/pyxbgen_all.py#L185-L209
DataONEorg/d1_python
lib_client/src/d1_client/baseclient_2_0.py
DataONEBaseClient_2_0.updateSystemMetadataResponse
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: ...
python
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: ...
[ "def", "updateSystemMetadataResponse", "(", "self", ",", "pid", ",", "sysmeta_pyxb", ",", "vendorSpecific", "=", "None", ")", ":", "mmp_dict", "=", "{", "'pid'", ":", "pid", ".", "encode", "(", "'utf-8'", ")", ",", "'sysmeta'", ":", "(", "'sysmeta.xml'", "...
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:
[ "MNStorage", ".", "updateSystemMetadata", "(", "session", "pid", "sysmeta", ")", "→", "boolean", "http", ":", "//", "jenkins", "-", "1", ".", "dataone", ".", "org", "/", "documentation", "/", "unstable", "/", "API", "-", "Documentation", "-", "development", ...
train
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_client/src/d1_client/baseclient_2_0.py#L56-L73
genialis/resolwe
resolwe/flow/migrations/0028_add_data_location.py
set_data_location
def set_data_location(apps, schema_editor): """Create DataLocation for each Data.""" 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))): ...
python
def set_data_location(apps, schema_editor): """Create DataLocation for each Data.""" 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))): ...
[ "def", "set_data_location", "(", "apps", ",", "schema_editor", ")", ":", "Data", "=", "apps", ".", "get_model", "(", "'flow'", ",", "'Data'", ")", "DataLocation", "=", "apps", ".", "get_model", "(", "'flow'", ",", "'DataLocation'", ")", "for", "data", "in"...
Create DataLocation for each Data.
[ "Create", "DataLocation", "for", "each", "Data", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/migrations/0028_add_data_location.py#L12-L30
DataONEorg/d1_python
lib_client/src/d1_client/iter/objectlist.py
ObjectListIterator._loadMore
def _loadMore(self, start=0, trys=0, validation=True): """Retrieves the next page of results.""" self._log.debug("Loading page starting from %d" % start) self._czero = start self._pageoffs = 0 try: pyxb.RequireValidWhenParsing(validation) self._object_list...
python
def _loadMore(self, start=0, trys=0, validation=True): """Retrieves the next page of results.""" self._log.debug("Loading page starting from %d" % start) self._czero = start self._pageoffs = 0 try: pyxb.RequireValidWhenParsing(validation) self._object_list...
[ "def", "_loadMore", "(", "self", ",", "start", "=", "0", ",", "trys", "=", "0", ",", "validation", "=", "True", ")", ":", "self", ".", "_log", ".", "debug", "(", "\"Loading page starting from %d\"", "%", "start", ")", "self", ".", "_czero", "=", "start...
Retrieves the next page of results.
[ "Retrieves", "the", "next", "page", "of", "results", "." ]
train
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_client/src/d1_client/iter/objectlist.py#L188-L213
DataONEorg/d1_python
lib_common/src/d1_common/ext/mimeparser.py
parse_mime_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'}) ...
python
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'}) ...
[ "def", "parse_mime_type", "(", "mime_type", ")", ":", "parts", "=", "mime_type", ".", "split", "(", "\";\"", ")", "params", "=", "dict", "(", "[", "tuple", "(", "[", "s", ".", "strip", "(", ")", "for", "s", "in", "param", ".", "split", "(", "\"=\""...
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'})
[ "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", "exa...
train
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/ext/mimeparser.py#L50-L66
DataONEorg/d1_python
lib_common/src/d1_common/ext/mimeparser.py
best_match
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([...
python
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([...
[ "def", "best_match", "(", "supported", ",", "header", ")", ":", "parsed_header", "=", "[", "parse_media_range", "(", "r", ")", "for", "r", "in", "header", ".", "split", "(", "\",\"", ")", "]", "weighted_matches", "=", "[", "(", "fitness_and_quality_parsed", ...
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...
[ "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", "con...
train
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/ext/mimeparser.py#L153-L168
genialis/resolwe
resolwe/flow/models/data.py
DataQuerySet._delete_chunked
def _delete_chunked(queryset, chunk_size=500): """Chunked delete, which should be used if deleting many objects. The reason why this method is needed is that deleting a lot of Data objects requires Django to fetch all of them into memory (fast path is not used) and this causes huge memo...
python
def _delete_chunked(queryset, chunk_size=500): """Chunked delete, which should be used if deleting many objects. The reason why this method is needed is that deleting a lot of Data objects requires Django to fetch all of them into memory (fast path is not used) and this causes huge memo...
[ "def", "_delete_chunked", "(", "queryset", ",", "chunk_size", "=", "500", ")", ":", "while", "True", ":", "# Discover primary key to limit the current chunk. This is required because delete", "# cannot be called on a sliced queryset due to ordering requirement.", "with", "transaction...
Chunked delete, which should be used if deleting many objects. The reason why this method is needed is that deleting a lot of Data objects requires Django to fetch all of them into memory (fast path is not used) and this causes huge memory usage (and possibly OOM). :param chunk_size: O...
[ "Chunked", "delete", "which", "should", "be", "used", "if", "deleting", "many", "objects", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/models/data.py#L40-L60
genialis/resolwe
resolwe/flow/models/data.py
DataQuerySet.duplicate
def duplicate(self, contributor=None): """Duplicate (make a copy) ``Data`` objects. :param contributor: Duplication user """ bundle = [ {'original': data, 'copy': data.duplicate(contributor=contributor)} for data in self ] bundle = rewire_inputs(...
python
def duplicate(self, contributor=None): """Duplicate (make a copy) ``Data`` objects. :param contributor: Duplication user """ bundle = [ {'original': data, 'copy': data.duplicate(contributor=contributor)} for data in self ] bundle = rewire_inputs(...
[ "def", "duplicate", "(", "self", ",", "contributor", "=", "None", ")", ":", "bundle", "=", "[", "{", "'original'", ":", "data", ",", "'copy'", ":", "data", ".", "duplicate", "(", "contributor", "=", "contributor", ")", "}", "for", "data", "in", "self",...
Duplicate (make a copy) ``Data`` objects. :param contributor: Duplication user
[ "Duplicate", "(", "make", "a", "copy", ")", "Data", "objects", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/models/data.py#L74-L87
genialis/resolwe
resolwe/flow/models/data.py
Data.save_storage
def save_storage(self, instance, schema): """Save basic:json values to a Storage collection.""" for field_schema, fields in iterate_fields(instance, schema): name = field_schema['name'] value = fields[name] if field_schema.get('type', '').startswith('basic:json:'): ...
python
def save_storage(self, instance, schema): """Save basic:json values to a Storage collection.""" for field_schema, fields in iterate_fields(instance, schema): name = field_schema['name'] value = fields[name] if field_schema.get('type', '').startswith('basic:json:'): ...
[ "def", "save_storage", "(", "self", ",", "instance", ",", "schema", ")", ":", "for", "field_schema", ",", "fields", "in", "iterate_fields", "(", "instance", ",", "schema", ")", ":", "name", "=", "field_schema", "[", "'name'", "]", "value", "=", "fields", ...
Save basic:json values to a Storage collection.
[ "Save", "basic", ":", "json", "values", "to", "a", "Storage", "collection", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/models/data.py#L236-L271
genialis/resolwe
resolwe/flow/models/data.py
Data.resolve_secrets
def resolve_secrets(self): """Retrieve handles for all basic:secret: fields on input. The process must have the ``secrets`` resource requirement specified in order to access any secrets. Otherwise this method will raise a ``PermissionDenied`` exception. :return: A dictionary of...
python
def resolve_secrets(self): """Retrieve handles for all basic:secret: fields on input. The process must have the ``secrets`` resource requirement specified in order to access any secrets. Otherwise this method will raise a ``PermissionDenied`` exception. :return: A dictionary of...
[ "def", "resolve_secrets", "(", "self", ")", ":", "secrets", "=", "{", "}", "for", "field_schema", ",", "fields", "in", "iterate_fields", "(", "self", ".", "input", ",", "self", ".", "process", ".", "input_schema", ")", ":", "# pylint: disable=no-member", "if...
Retrieve handles for all basic:secret: fields on input. The process must have the ``secrets`` resource requirement specified in order to access any secrets. Otherwise this method will raise a ``PermissionDenied`` exception. :return: A dictionary of secrets where key is the secret handl...
[ "Retrieve", "handles", "for", "all", "basic", ":", "secret", ":", "fields", "on", "input", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/models/data.py#L273-L313
genialis/resolwe
resolwe/flow/models/data.py
Data.save_dependencies
def save_dependencies(self, instance, schema): """Save data: and list:data: references as parents.""" def add_dependency(value): """Add parent Data dependency.""" try: DataDependency.objects.update_or_create( parent=Data.objects.get(pk=value), ...
python
def save_dependencies(self, instance, schema): """Save data: and list:data: references as parents.""" def add_dependency(value): """Add parent Data dependency.""" try: DataDependency.objects.update_or_create( parent=Data.objects.get(pk=value), ...
[ "def", "save_dependencies", "(", "self", ",", "instance", ",", "schema", ")", ":", "def", "add_dependency", "(", "value", ")", ":", "\"\"\"Add parent Data dependency.\"\"\"", "try", ":", "DataDependency", ".", "objects", ".", "update_or_create", "(", "parent", "="...
Save data: and list:data: references as parents.
[ "Save", "data", ":", "and", "list", ":", "data", ":", "references", "as", "parents", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/models/data.py#L315-L336
genialis/resolwe
resolwe/flow/models/data.py
Data.create_entity
def create_entity(self): """Create entity if `flow_collection` is defined in process. Following rules applies for adding `Data` object to `Entity`: * Only add `Data object` to `Entity` if process has defined `flow_collection` field * Add object to existing `Entity`, if all paren...
python
def create_entity(self): """Create entity if `flow_collection` is defined in process. Following rules applies for adding `Data` object to `Entity`: * Only add `Data object` to `Entity` if process has defined `flow_collection` field * Add object to existing `Entity`, if all paren...
[ "def", "create_entity", "(", "self", ")", ":", "entity_type", "=", "self", ".", "process", ".", "entity_type", "# pylint: disable=no-member", "entity_descriptor_schema", "=", "self", ".", "process", ".", "entity_descriptor_schema", "# pylint: disable=no-member", "entity_i...
Create entity if `flow_collection` is defined in process. Following rules applies for adding `Data` object to `Entity`: * Only add `Data object` to `Entity` if process has defined `flow_collection` field * Add object to existing `Entity`, if all parents that are part of it (but ...
[ "Create", "entity", "if", "flow_collection", "is", "defined", "in", "process", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/models/data.py#L338-L401
genialis/resolwe
resolwe/flow/models/data.py
Data.save
def save(self, render_name=False, *args, **kwargs): # pylint: disable=keyword-arg-before-vararg """Save the data model.""" if self.name != self._original_name: self.named_by_user = True create = self.pk is None if create: fill_with_defaults(self.input, self.proc...
python
def save(self, render_name=False, *args, **kwargs): # pylint: disable=keyword-arg-before-vararg """Save the data model.""" if self.name != self._original_name: self.named_by_user = True create = self.pk is None if create: fill_with_defaults(self.input, self.proc...
[ "def", "save", "(", "self", ",", "render_name", "=", "False", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=keyword-arg-before-vararg", "if", "self", ".", "name", "!=", "self", ".", "_original_name", ":", "self", ".", "named_by_user...
Save the data model.
[ "Save", "the", "data", "model", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/models/data.py#L403-L466
genialis/resolwe
resolwe/flow/models/data.py
Data.delete
def delete(self, *args, **kwargs): """Delete the data model.""" # Store ids in memory as relations are also deleted with the Data object. storage_ids = list(self.storages.values_list('pk', flat=True)) # pylint: disable=no-member super().delete(*args, **kwargs) Storage.objects....
python
def delete(self, *args, **kwargs): """Delete the data model.""" # Store ids in memory as relations are also deleted with the Data object. storage_ids = list(self.storages.values_list('pk', flat=True)) # pylint: disable=no-member super().delete(*args, **kwargs) Storage.objects....
[ "def", "delete", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Store ids in memory as relations are also deleted with the Data object.", "storage_ids", "=", "list", "(", "self", ".", "storages", ".", "values_list", "(", "'pk'", ",", "flat", ...
Delete the data model.
[ "Delete", "the", "data", "model", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/models/data.py#L472-L479
genialis/resolwe
resolwe/flow/models/data.py
Data.duplicate
def duplicate(self, contributor=None): """Duplicate (make a copy).""" if self.status not in [self.STATUS_DONE, self.STATUS_ERROR]: raise ValidationError('Data object must have done or error status to be duplicated') duplicate = Data.objects.get(id=self.id) duplicate.pk = Non...
python
def duplicate(self, contributor=None): """Duplicate (make a copy).""" if self.status not in [self.STATUS_DONE, self.STATUS_ERROR]: raise ValidationError('Data object must have done or error status to be duplicated') duplicate = Data.objects.get(id=self.id) duplicate.pk = Non...
[ "def", "duplicate", "(", "self", ",", "contributor", "=", "None", ")", ":", "if", "self", ".", "status", "not", "in", "[", "self", ".", "STATUS_DONE", ",", "self", ".", "STATUS_ERROR", "]", ":", "raise", "ValidationError", "(", "'Data object must have done o...
Duplicate (make a copy).
[ "Duplicate", "(", "make", "a", "copy", ")", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/models/data.py#L485-L527
genialis/resolwe
resolwe/flow/models/data.py
Data._render_name
def _render_name(self): """Render data name. The rendering is based on name template (`process.data_name`) and input context. """ if not self.process.data_name or self.named_by_user: # pylint: disable=no-member return inputs = copy.deepcopy(self.input) ...
python
def _render_name(self): """Render data name. The rendering is based on name template (`process.data_name`) and input context. """ if not self.process.data_name or self.named_by_user: # pylint: disable=no-member return inputs = copy.deepcopy(self.input) ...
[ "def", "_render_name", "(", "self", ")", ":", "if", "not", "self", ".", "process", ".", "data_name", "or", "self", ".", "named_by_user", ":", "# pylint: disable=no-member", "return", "inputs", "=", "copy", ".", "deepcopy", "(", "self", ".", "input", ")", "...
Render data name. The rendering is based on name template (`process.data_name`) and input context.
[ "Render", "data", "name", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/models/data.py#L529-L552
genialis/resolwe
resolwe/flow/models/data.py
DataLocation.get_path
def get_path(self, prefix=None, filename=None): """Compose data location path.""" prefix = prefix or settings.FLOW_EXECUTOR['DATA_DIR'] path = os.path.join(prefix, self.subpath) if filename: path = os.path.join(path, filename) return path
python
def get_path(self, prefix=None, filename=None): """Compose data location path.""" prefix = prefix or settings.FLOW_EXECUTOR['DATA_DIR'] path = os.path.join(prefix, self.subpath) if filename: path = os.path.join(path, filename) return path
[ "def", "get_path", "(", "self", ",", "prefix", "=", "None", ",", "filename", "=", "None", ")", ":", "prefix", "=", "prefix", "or", "settings", ".", "FLOW_EXECUTOR", "[", "'DATA_DIR'", "]", "path", "=", "os", ".", "path", ".", "join", "(", "prefix", "...
Compose data location path.
[ "Compose", "data", "location", "path", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/models/data.py#L584-L592
genialis/resolwe
resolwe/flow/models/data.py
DataLocation.get_runtime_path
def get_runtime_path(self, filename=None): """Compose data runtime location path.""" return self.get_path(prefix=settings.FLOW_EXECUTOR['RUNTIME_DIR'], filename=filename)
python
def get_runtime_path(self, filename=None): """Compose data runtime location path.""" return self.get_path(prefix=settings.FLOW_EXECUTOR['RUNTIME_DIR'], filename=filename)
[ "def", "get_runtime_path", "(", "self", ",", "filename", "=", "None", ")", ":", "return", "self", ".", "get_path", "(", "prefix", "=", "settings", ".", "FLOW_EXECUTOR", "[", "'RUNTIME_DIR'", "]", ",", "filename", "=", "filename", ")" ]
Compose data runtime location path.
[ "Compose", "data", "runtime", "location", "path", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/models/data.py#L594-L596
genialis/resolwe
resolwe/flow/serializers/entity.py
EntitySerializer.get_data
def get_data(self, entity): """Return serialized list of data objects on entity that user has `view` permission on.""" data = self._filter_queryset('view_data', entity.data.all()) return self._serialize_data(data)
python
def get_data(self, entity): """Return serialized list of data objects on entity that user has `view` permission on.""" data = self._filter_queryset('view_data', entity.data.all()) return self._serialize_data(data)
[ "def", "get_data", "(", "self", ",", "entity", ")", ":", "data", "=", "self", ".", "_filter_queryset", "(", "'view_data'", ",", "entity", ".", "data", ".", "all", "(", ")", ")", "return", "self", ".", "_serialize_data", "(", "data", ")" ]
Return serialized list of data objects on entity that user has `view` permission on.
[ "Return", "serialized", "list", "of", "data", "objects", "on", "entity", "that", "user", "has", "view", "permission", "on", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/serializers/entity.py#L25-L29
genialis/resolwe
resolwe/process/descriptor.py
ProcessDescriptor.validate
def validate(self): """Validate process descriptor.""" required_fields = ('slug', 'name', 'process_type', 'version') for field in required_fields: if getattr(self.metadata, field, None) is None: raise ValidationError("process '{}' is missing required meta attribute: {...
python
def validate(self): """Validate process descriptor.""" required_fields = ('slug', 'name', 'process_type', 'version') for field in required_fields: if getattr(self.metadata, field, None) is None: raise ValidationError("process '{}' is missing required meta attribute: {...
[ "def", "validate", "(", "self", ")", ":", "required_fields", "=", "(", "'slug'", ",", "'name'", ",", "'process_type'", ",", "'version'", ")", "for", "field", "in", "required_fields", ":", "if", "getattr", "(", "self", ".", "metadata", ",", "field", ",", ...
Validate process descriptor.
[ "Validate", "process", "descriptor", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/process/descriptor.py#L61-L71
genialis/resolwe
resolwe/process/descriptor.py
ProcessDescriptor.to_schema
def to_schema(self): """Return process schema for this process.""" process_type = self.metadata.process_type if not process_type.endswith(':'): process_type = '{}:'.format(process_type) schema = { 'slug': self.metadata.slug, 'name': self.metadata.name...
python
def to_schema(self): """Return process schema for this process.""" process_type = self.metadata.process_type if not process_type.endswith(':'): process_type = '{}:'.format(process_type) schema = { 'slug': self.metadata.slug, 'name': self.metadata.name...
[ "def", "to_schema", "(", "self", ")", ":", "process_type", "=", "self", ".", "metadata", ".", "process_type", "if", "not", "process_type", ".", "endswith", "(", "':'", ")", ":", "process_type", "=", "'{}:'", ".", "format", "(", "process_type", ")", "schema...
Return process schema for this process.
[ "Return", "process", "schema", "for", "this", "process", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/process/descriptor.py#L73-L124
genialis/resolwe
resolwe/flow/executors/docker/prepare.py
FlowExecutorPreparer.post_register_hook
def post_register_hook(self, verbosity=1): """Pull Docker images needed by processes after registering.""" if not getattr(settings, 'FLOW_DOCKER_DONT_PULL', False): call_command('list_docker_images', pull=True, verbosity=verbosity)
python
def post_register_hook(self, verbosity=1): """Pull Docker images needed by processes after registering.""" if not getattr(settings, 'FLOW_DOCKER_DONT_PULL', False): call_command('list_docker_images', pull=True, verbosity=verbosity)
[ "def", "post_register_hook", "(", "self", ",", "verbosity", "=", "1", ")", ":", "if", "not", "getattr", "(", "settings", ",", "'FLOW_DOCKER_DONT_PULL'", ",", "False", ")", ":", "call_command", "(", "'list_docker_images'", ",", "pull", "=", "True", ",", "verb...
Pull Docker images needed by processes after registering.
[ "Pull", "Docker", "images", "needed", "by", "processes", "after", "registering", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/executors/docker/prepare.py#L24-L27
genialis/resolwe
resolwe/flow/executors/docker/prepare.py
FlowExecutorPreparer.resolve_data_path
def resolve_data_path(self, data=None, filename=None): """Resolve data path for use with the executor. :param data: Data object instance :param filename: Filename to resolve :return: Resolved filename, which can be used to access the given data file in programs executed usin...
python
def resolve_data_path(self, data=None, filename=None): """Resolve data path for use with the executor. :param data: Data object instance :param filename: Filename to resolve :return: Resolved filename, which can be used to access the given data file in programs executed usin...
[ "def", "resolve_data_path", "(", "self", ",", "data", "=", "None", ",", "filename", "=", "None", ")", ":", "if", "data", "is", "None", ":", "return", "constants", ".", "DATA_ALL_VOLUME", "# Prefix MUST be set because ``get_path`` uses Django's settings,", "# if prefix...
Resolve data path for use with the executor. :param data: Data object instance :param filename: Filename to resolve :return: Resolved filename, which can be used to access the given data file in programs executed using this executor
[ "Resolve", "data", "path", "for", "use", "with", "the", "executor", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/executors/docker/prepare.py#L29-L44
genialis/resolwe
resolwe/flow/executors/docker/prepare.py
FlowExecutorPreparer.resolve_upload_path
def resolve_upload_path(self, filename=None): """Resolve upload path for use with the executor. :param filename: Filename to resolve :return: Resolved filename, which can be used to access the given uploaded file in programs executed using this executor """ ...
python
def resolve_upload_path(self, filename=None): """Resolve upload path for use with the executor. :param filename: Filename to resolve :return: Resolved filename, which can be used to access the given uploaded file in programs executed using this executor """ ...
[ "def", "resolve_upload_path", "(", "self", ",", "filename", "=", "None", ")", ":", "if", "filename", "is", "None", ":", "return", "constants", ".", "UPLOAD_VOLUME", "return", "os", ".", "path", ".", "join", "(", "constants", ".", "UPLOAD_VOLUME", ",", "fil...
Resolve upload path for use with the executor. :param filename: Filename to resolve :return: Resolved filename, which can be used to access the given uploaded file in programs executed using this executor
[ "Resolve", "upload", "path", "for", "use", "with", "the", "executor", "." ]
train
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/executors/docker/prepare.py#L46-L57
DataONEorg/d1_python
lib_common/src/d1_common/date_time.py
are_equal
def are_equal(a_dt, b_dt, round_sec=1): """Determine if two datetimes are equal with fuzz factor. A naive datetime (no timezone information) is assumed to be in in UTC. Args: a_dt: datetime Timestamp to compare. b_dt: datetime Timestamp to compare. round_sec: int or flo...
python
def are_equal(a_dt, b_dt, round_sec=1): """Determine if two datetimes are equal with fuzz factor. A naive datetime (no timezone information) is assumed to be in in UTC. Args: a_dt: datetime Timestamp to compare. b_dt: datetime Timestamp to compare. round_sec: int or flo...
[ "def", "are_equal", "(", "a_dt", ",", "b_dt", ",", "round_sec", "=", "1", ")", ":", "ra_dt", "=", "round_to_nearest", "(", "a_dt", ",", "round_sec", ")", "rb_dt", "=", "round_to_nearest", "(", "b_dt", ",", "round_sec", ")", "logger", ".", "debug", "(", ...
Determine if two datetimes are equal with fuzz factor. A naive datetime (no timezone information) is assumed to be in in UTC. Args: a_dt: datetime Timestamp to compare. b_dt: datetime Timestamp to compare. round_sec: int or float Round the timestamps to the closest ...
[ "Determine", "if", "two", "datetimes", "are", "equal", "with", "fuzz", "factor", "." ]
train
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/date_time.py#L191-L238