repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
DataONEorg/d1_python
gmn/src/d1_gmn/app/middleware/response_handler.py
ResponseHandler._debug_mode_responses
def _debug_mode_responses(self, request, response): """Extra functionality available in debug mode. - If pretty printed output was requested, force the content type to text. This causes the browser to not try to format the output in any way. - If SQL profiling is turned on, return a page with SQL query timing information instead of the actual response. """ if django.conf.settings.DEBUG_GMN: if 'pretty' in request.GET: response['Content-Type'] = d1_common.const.CONTENT_TYPE_TEXT if ( 'HTTP_VENDOR_PROFILE_SQL' in request.META or django.conf.settings.DEBUG_PROFILE_SQL ): response_list = [] for query in django.db.connection.queries: response_list.append('{}\n{}'.format(query['time'], query['sql'])) return django.http.HttpResponse( '\n\n'.join(response_list), d1_common.const.CONTENT_TYPE_TEXT ) return response
python
def _debug_mode_responses(self, request, response): """Extra functionality available in debug mode. - If pretty printed output was requested, force the content type to text. This causes the browser to not try to format the output in any way. - If SQL profiling is turned on, return a page with SQL query timing information instead of the actual response. """ if django.conf.settings.DEBUG_GMN: if 'pretty' in request.GET: response['Content-Type'] = d1_common.const.CONTENT_TYPE_TEXT if ( 'HTTP_VENDOR_PROFILE_SQL' in request.META or django.conf.settings.DEBUG_PROFILE_SQL ): response_list = [] for query in django.db.connection.queries: response_list.append('{}\n{}'.format(query['time'], query['sql'])) return django.http.HttpResponse( '\n\n'.join(response_list), d1_common.const.CONTENT_TYPE_TEXT ) return response
[ "def", "_debug_mode_responses", "(", "self", ",", "request", ",", "response", ")", ":", "if", "django", ".", "conf", ".", "settings", ".", "DEBUG_GMN", ":", "if", "'pretty'", "in", "request", ".", "GET", ":", "response", "[", "'Content-Type'", "]", "=", ...
Extra functionality available in debug mode. - If pretty printed output was requested, force the content type to text. This causes the browser to not try to format the output in any way. - If SQL profiling is turned on, return a page with SQL query timing information instead of the actual response.
[ "Extra", "functionality", "available", "in", "debug", "mode", "." ]
3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/gmn/src/d1_gmn/app/middleware/response_handler.py#L74-L96
train
45,500
genialis/resolwe
resolwe/elastic/builder.py
BuildArgumentsCache._get_cache_key
def _get_cache_key(self, obj): """Derive cache key for given object.""" if obj is not None: # Make sure that key is REALLY unique. return '{}-{}'.format(id(self), obj.pk) return "{}-None".format(id(self))
python
def _get_cache_key(self, obj): """Derive cache key for given object.""" if obj is not None: # Make sure that key is REALLY unique. return '{}-{}'.format(id(self), obj.pk) return "{}-None".format(id(self))
[ "def", "_get_cache_key", "(", "self", ",", "obj", ")", ":", "if", "obj", "is", "not", "None", ":", "# Make sure that key is REALLY unique.", "return", "'{}-{}'", ".", "format", "(", "id", "(", "self", ")", ",", "obj", ".", "pk", ")", "return", "\"{}-None\"...
Derive cache key for given object.
[ "Derive", "cache", "key", "for", "given", "object", "." ]
f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/elastic/builder.py#L45-L51
train
45,501
genialis/resolwe
resolwe/elastic/builder.py
BuildArgumentsCache.set
def set(self, obj, build_kwargs): """Set cached value.""" if build_kwargs is None: build_kwargs = {} cached = {} if 'queryset' in build_kwargs: cached = { 'model': build_kwargs['queryset'].model, 'pks': list(build_kwargs['queryset'].values_list('pk', flat=True)), } elif 'obj' in build_kwargs: cached = { 'obj': build_kwargs['obj'], } if not hasattr(self._thread_local, 'cache'): self._thread_local.cache = {} self._thread_local.cache[self._get_cache_key(obj)] = cached
python
def set(self, obj, build_kwargs): """Set cached value.""" if build_kwargs is None: build_kwargs = {} cached = {} if 'queryset' in build_kwargs: cached = { 'model': build_kwargs['queryset'].model, 'pks': list(build_kwargs['queryset'].values_list('pk', flat=True)), } elif 'obj' in build_kwargs: cached = { 'obj': build_kwargs['obj'], } if not hasattr(self._thread_local, 'cache'): self._thread_local.cache = {} self._thread_local.cache[self._get_cache_key(obj)] = cached
[ "def", "set", "(", "self", ",", "obj", ",", "build_kwargs", ")", ":", "if", "build_kwargs", "is", "None", ":", "build_kwargs", "=", "{", "}", "cached", "=", "{", "}", "if", "'queryset'", "in", "build_kwargs", ":", "cached", "=", "{", "'model'", ":", ...
Set cached value.
[ "Set", "cached", "value", "." ]
f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/elastic/builder.py#L57-L76
train
45,502
genialis/resolwe
resolwe/elastic/builder.py
BuildArgumentsCache.take
def take(self, obj): """Get cached value and clean cache.""" cached = self._thread_local.cache[self._get_cache_key(obj)] build_kwargs = {} if 'model' in cached and 'pks' in cached: build_kwargs['queryset'] = cached['model'].objects.filter(pk__in=cached['pks']) elif 'obj' in cached: if cached['obj'].__class__.objects.filter(pk=cached['obj'].pk).exists(): build_kwargs['obj'] = cached['obj'] else: # Object was deleted in the meantime. build_kwargs['queryset'] = cached['obj'].__class__.objects.none() self._clean_cache(obj) return build_kwargs
python
def take(self, obj): """Get cached value and clean cache.""" cached = self._thread_local.cache[self._get_cache_key(obj)] build_kwargs = {} if 'model' in cached and 'pks' in cached: build_kwargs['queryset'] = cached['model'].objects.filter(pk__in=cached['pks']) elif 'obj' in cached: if cached['obj'].__class__.objects.filter(pk=cached['obj'].pk).exists(): build_kwargs['obj'] = cached['obj'] else: # Object was deleted in the meantime. build_kwargs['queryset'] = cached['obj'].__class__.objects.none() self._clean_cache(obj) return build_kwargs
[ "def", "take", "(", "self", ",", "obj", ")", ":", "cached", "=", "self", ".", "_thread_local", ".", "cache", "[", "self", ".", "_get_cache_key", "(", "obj", ")", "]", "build_kwargs", "=", "{", "}", "if", "'model'", "in", "cached", "and", "'pks'", "in...
Get cached value and clean cache.
[ "Get", "cached", "value", "and", "clean", "cache", "." ]
f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/elastic/builder.py#L78-L95
train
45,503
genialis/resolwe
resolwe/elastic/builder.py
ElasticSignal.connect
def connect(self, signal, **kwargs): """Connect a specific signal type to this receiver.""" signal.connect(self, **kwargs) self.connections.append((signal, kwargs))
python
def connect(self, signal, **kwargs): """Connect a specific signal type to this receiver.""" signal.connect(self, **kwargs) self.connections.append((signal, kwargs))
[ "def", "connect", "(", "self", ",", "signal", ",", "*", "*", "kwargs", ")", ":", "signal", ".", "connect", "(", "self", ",", "*", "*", "kwargs", ")", "self", ".", "connections", ".", "append", "(", "(", "signal", ",", "kwargs", ")", ")" ]
Connect a specific signal type to this receiver.
[ "Connect", "a", "specific", "signal", "type", "to", "this", "receiver", "." ]
f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/elastic/builder.py#L121-L124
train
45,504
genialis/resolwe
resolwe/elastic/builder.py
ElasticSignal.disconnect
def disconnect(self): """Disconnect all connected signal types from this receiver.""" for signal, kwargs in self.connections: signal.disconnect(self, **kwargs)
python
def disconnect(self): """Disconnect all connected signal types from this receiver.""" for signal, kwargs in self.connections: signal.disconnect(self, **kwargs)
[ "def", "disconnect", "(", "self", ")", ":", "for", "signal", ",", "kwargs", "in", "self", ".", "connections", ":", "signal", ".", "disconnect", "(", "self", ",", "*", "*", "kwargs", ")" ]
Disconnect all connected signal types from this receiver.
[ "Disconnect", "all", "connected", "signal", "types", "from", "this", "receiver", "." ]
f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/elastic/builder.py#L126-L129
train
45,505
genialis/resolwe
resolwe/elastic/builder.py
ManyToManyDependency._filter
def _filter(self, objects, **kwargs): """Determine if dependent object should be processed.""" for obj in objects: if self.filter(obj, **kwargs) is False: return False return True
python
def _filter(self, objects, **kwargs): """Determine if dependent object should be processed.""" for obj in objects: if self.filter(obj, **kwargs) is False: return False return True
[ "def", "_filter", "(", "self", ",", "objects", ",", "*", "*", "kwargs", ")", ":", "for", "obj", "in", "objects", ":", "if", "self", ".", "filter", "(", "obj", ",", "*", "*", "kwargs", ")", "is", "False", ":", "return", "False", "return", "True" ]
Determine if dependent object should be processed.
[ "Determine", "if", "dependent", "object", "should", "be", "processed", "." ]
f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/elastic/builder.py#L257-L263
train
45,506
genialis/resolwe
resolwe/elastic/builder.py
ManyToManyDependency._get_build_kwargs
def _get_build_kwargs(self, obj, pk_set=None, action=None, update_fields=None, reverse=None, **kwargs): """Prepare arguments for rebuilding indices.""" if action is None: # Check filter before rebuilding index. if not self._filter([obj], update_fields=update_fields): return queryset = getattr(obj, self.accessor).all() # Special handling for relations to self. if self.field.rel.model == self.field.rel.related_model: queryset = queryset.union(getattr(obj, self.field.rel.get_accessor_name()).all()) return {'queryset': queryset} else: # Update to relation itself, only update the object in question. if self.field.rel.model == self.field.rel.related_model: # Special case, self-reference, update both ends of the relation. pks = set() if self._filter(self.model.objects.filter(pk__in=pk_set)): pks.add(obj.pk) if self._filter(self.model.objects.filter(pk__in=[obj.pk])): pks.update(pk_set) return {'queryset': self.index.object_type.objects.filter(pk__in=pks)} elif isinstance(obj, self.model): # Need to switch the role of object and pk_set. result = {'queryset': self.index.object_type.objects.filter(pk__in=pk_set)} pk_set = {obj.pk} else: result = {'obj': obj} if action != 'post_clear': # Check filter before rebuilding index. if not self._filter(self.model.objects.filter(pk__in=pk_set)): return return result
python
def _get_build_kwargs(self, obj, pk_set=None, action=None, update_fields=None, reverse=None, **kwargs): """Prepare arguments for rebuilding indices.""" if action is None: # Check filter before rebuilding index. if not self._filter([obj], update_fields=update_fields): return queryset = getattr(obj, self.accessor).all() # Special handling for relations to self. if self.field.rel.model == self.field.rel.related_model: queryset = queryset.union(getattr(obj, self.field.rel.get_accessor_name()).all()) return {'queryset': queryset} else: # Update to relation itself, only update the object in question. if self.field.rel.model == self.field.rel.related_model: # Special case, self-reference, update both ends of the relation. pks = set() if self._filter(self.model.objects.filter(pk__in=pk_set)): pks.add(obj.pk) if self._filter(self.model.objects.filter(pk__in=[obj.pk])): pks.update(pk_set) return {'queryset': self.index.object_type.objects.filter(pk__in=pks)} elif isinstance(obj, self.model): # Need to switch the role of object and pk_set. result = {'queryset': self.index.object_type.objects.filter(pk__in=pk_set)} pk_set = {obj.pk} else: result = {'obj': obj} if action != 'post_clear': # Check filter before rebuilding index. if not self._filter(self.model.objects.filter(pk__in=pk_set)): return return result
[ "def", "_get_build_kwargs", "(", "self", ",", "obj", ",", "pk_set", "=", "None", ",", "action", "=", "None", ",", "update_fields", "=", "None", ",", "reverse", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "action", "is", "None", ":", "# Chec...
Prepare arguments for rebuilding indices.
[ "Prepare", "arguments", "for", "rebuilding", "indices", "." ]
f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/elastic/builder.py#L265-L303
train
45,507
genialis/resolwe
resolwe/elastic/builder.py
ManyToManyDependency.process_predelete
def process_predelete(self, obj, pk_set=None, action=None, update_fields=None, **kwargs): """Render the queryset of influenced objects and cache it.""" build_kwargs = self._get_build_kwargs(obj, pk_set, action, update_fields, **kwargs) self.delete_cache.set(obj, build_kwargs)
python
def process_predelete(self, obj, pk_set=None, action=None, update_fields=None, **kwargs): """Render the queryset of influenced objects and cache it.""" build_kwargs = self._get_build_kwargs(obj, pk_set, action, update_fields, **kwargs) self.delete_cache.set(obj, build_kwargs)
[ "def", "process_predelete", "(", "self", ",", "obj", ",", "pk_set", "=", "None", ",", "action", "=", "None", ",", "update_fields", "=", "None", ",", "*", "*", "kwargs", ")", ":", "build_kwargs", "=", "self", ".", "_get_build_kwargs", "(", "obj", ",", "...
Render the queryset of influenced objects and cache it.
[ "Render", "the", "queryset", "of", "influenced", "objects", "and", "cache", "it", "." ]
f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/elastic/builder.py#L305-L308
train
45,508
genialis/resolwe
resolwe/elastic/builder.py
ManyToManyDependency.process_delete
def process_delete(self, obj, pk_set=None, action=None, update_fields=None, **kwargs): """Recreate queryset from the index and rebuild the index.""" build_kwargs = self.delete_cache.take(obj) if build_kwargs: self.index.build(**build_kwargs)
python
def process_delete(self, obj, pk_set=None, action=None, update_fields=None, **kwargs): """Recreate queryset from the index and rebuild the index.""" build_kwargs = self.delete_cache.take(obj) if build_kwargs: self.index.build(**build_kwargs)
[ "def", "process_delete", "(", "self", ",", "obj", ",", "pk_set", "=", "None", ",", "action", "=", "None", ",", "update_fields", "=", "None", ",", "*", "*", "kwargs", ")", ":", "build_kwargs", "=", "self", ".", "delete_cache", ".", "take", "(", "obj", ...
Recreate queryset from the index and rebuild the index.
[ "Recreate", "queryset", "from", "the", "index", "and", "rebuild", "the", "index", "." ]
f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/elastic/builder.py#L310-L315
train
45,509
genialis/resolwe
resolwe/elastic/builder.py
ManyToManyDependency._process_m2m_through
def _process_m2m_through(self, obj, action): """Process custom M2M through model actions.""" source = getattr(obj, self.field.rel.field.m2m_field_name()) target = getattr(obj, self.field.rel.field.m2m_reverse_field_name()) pk_set = set() if target: pk_set.add(target.pk) self.process_m2m(source, pk_set, action=action, reverse=False, cache_key=obj)
python
def _process_m2m_through(self, obj, action): """Process custom M2M through model actions.""" source = getattr(obj, self.field.rel.field.m2m_field_name()) target = getattr(obj, self.field.rel.field.m2m_reverse_field_name()) pk_set = set() if target: pk_set.add(target.pk) self.process_m2m(source, pk_set, action=action, reverse=False, cache_key=obj)
[ "def", "_process_m2m_through", "(", "self", ",", "obj", ",", "action", ")", ":", "source", "=", "getattr", "(", "obj", ",", "self", ".", "field", ".", "rel", ".", "field", ".", "m2m_field_name", "(", ")", ")", "target", "=", "getattr", "(", "obj", ",...
Process custom M2M through model actions.
[ "Process", "custom", "M2M", "through", "model", "actions", "." ]
f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/elastic/builder.py#L338-L347
train
45,510
genialis/resolwe
resolwe/elastic/builder.py
ManyToManyDependency.process_m2m_through_save
def process_m2m_through_save(self, obj, created=False, **kwargs): """Process M2M post save for custom through model.""" # We are only interested in signals that establish relations. if not created: return self._process_m2m_through(obj, 'post_add')
python
def process_m2m_through_save(self, obj, created=False, **kwargs): """Process M2M post save for custom through model.""" # We are only interested in signals that establish relations. if not created: return self._process_m2m_through(obj, 'post_add')
[ "def", "process_m2m_through_save", "(", "self", ",", "obj", ",", "created", "=", "False", ",", "*", "*", "kwargs", ")", ":", "# We are only interested in signals that establish relations.", "if", "not", "created", ":", "return", "self", ".", "_process_m2m_through", ...
Process M2M post save for custom through model.
[ "Process", "M2M", "post", "save", "for", "custom", "through", "model", "." ]
f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/elastic/builder.py#L349-L355
train
45,511
genialis/resolwe
resolwe/elastic/builder.py
IndexBuilder._connect_signal
def _connect_signal(self, index): """Create signals for building indexes.""" post_save_signal = ElasticSignal(index, 'build') post_save_signal.connect(post_save, sender=index.object_type) self.signals.append(post_save_signal) post_delete_signal = ElasticSignal(index, 'remove_object') post_delete_signal.connect(post_delete, sender=index.object_type) self.signals.append(post_delete_signal) # Connect signals for all dependencies. for dependency in index.get_dependencies(): # Automatically convert m2m fields to dependencies. if isinstance(dependency, (models.ManyToManyField, ManyToManyDescriptor)): dependency = ManyToManyDependency(dependency) elif not isinstance(dependency, Dependency): raise TypeError("Unsupported dependency type: {}".format(repr(dependency))) signal = dependency.connect(index) self.signals.extend(signal)
python
def _connect_signal(self, index): """Create signals for building indexes.""" post_save_signal = ElasticSignal(index, 'build') post_save_signal.connect(post_save, sender=index.object_type) self.signals.append(post_save_signal) post_delete_signal = ElasticSignal(index, 'remove_object') post_delete_signal.connect(post_delete, sender=index.object_type) self.signals.append(post_delete_signal) # Connect signals for all dependencies. for dependency in index.get_dependencies(): # Automatically convert m2m fields to dependencies. if isinstance(dependency, (models.ManyToManyField, ManyToManyDescriptor)): dependency = ManyToManyDependency(dependency) elif not isinstance(dependency, Dependency): raise TypeError("Unsupported dependency type: {}".format(repr(dependency))) signal = dependency.connect(index) self.signals.extend(signal)
[ "def", "_connect_signal", "(", "self", ",", "index", ")", ":", "post_save_signal", "=", "ElasticSignal", "(", "index", ",", "'build'", ")", "post_save_signal", ".", "connect", "(", "post_save", ",", "sender", "=", "index", ".", "object_type", ")", "self", "....
Create signals for building indexes.
[ "Create", "signals", "for", "building", "indexes", "." ]
f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/elastic/builder.py#L397-L416
train
45,512
genialis/resolwe
resolwe/elastic/builder.py
IndexBuilder.register_signals
def register_signals(self): """Register signals for all indexes.""" for index in self.indexes: if index.object_type: self._connect_signal(index)
python
def register_signals(self): """Register signals for all indexes.""" for index in self.indexes: if index.object_type: self._connect_signal(index)
[ "def", "register_signals", "(", "self", ")", ":", "for", "index", "in", "self", ".", "indexes", ":", "if", "index", ".", "object_type", ":", "self", ".", "_connect_signal", "(", "index", ")" ]
Register signals for all indexes.
[ "Register", "signals", "for", "all", "indexes", "." ]
f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/elastic/builder.py#L424-L428
train
45,513
genialis/resolwe
resolwe/elastic/builder.py
IndexBuilder.discover_indexes
def discover_indexes(self): """Save list of index builders into ``_index_builders``.""" self.indexes = [] for app_config in apps.get_app_configs(): indexes_path = '{}.elastic_indexes'.format(app_config.name) try: indexes_module = import_module(indexes_path) for attr_name in dir(indexes_module): attr = getattr(indexes_module, attr_name) if inspect.isclass(attr) and issubclass(attr, BaseIndex) and attr is not BaseIndex: # Make sure that parallel tests have different indices. if is_testing(): index = attr.document_class._index._name # pylint: disable=protected-access testing_postfix = '_test_{}_{}'.format(TESTING_UUID, os.getpid()) if not index.endswith(testing_postfix): # Replace current postfix with the new one. if attr.testing_postfix: index = index[:-len(attr.testing_postfix)] index = index + testing_postfix attr.testing_postfix = testing_postfix attr.document_class._index._name = index # pylint: disable=protected-access index = attr() # Apply any extensions defined for the given index. Currently index extensions are # limited to extending "mappings". for extension in composer.get_extensions(attr): mapping = getattr(extension, 'mapping', {}) index.mapping.update(mapping) self.indexes.append(index) except ImportError as ex: if not re.match('No module named .*elastic_indexes.*', str(ex)): raise
python
def discover_indexes(self): """Save list of index builders into ``_index_builders``.""" self.indexes = [] for app_config in apps.get_app_configs(): indexes_path = '{}.elastic_indexes'.format(app_config.name) try: indexes_module = import_module(indexes_path) for attr_name in dir(indexes_module): attr = getattr(indexes_module, attr_name) if inspect.isclass(attr) and issubclass(attr, BaseIndex) and attr is not BaseIndex: # Make sure that parallel tests have different indices. if is_testing(): index = attr.document_class._index._name # pylint: disable=protected-access testing_postfix = '_test_{}_{}'.format(TESTING_UUID, os.getpid()) if not index.endswith(testing_postfix): # Replace current postfix with the new one. if attr.testing_postfix: index = index[:-len(attr.testing_postfix)] index = index + testing_postfix attr.testing_postfix = testing_postfix attr.document_class._index._name = index # pylint: disable=protected-access index = attr() # Apply any extensions defined for the given index. Currently index extensions are # limited to extending "mappings". for extension in composer.get_extensions(attr): mapping = getattr(extension, 'mapping', {}) index.mapping.update(mapping) self.indexes.append(index) except ImportError as ex: if not re.match('No module named .*elastic_indexes.*', str(ex)): raise
[ "def", "discover_indexes", "(", "self", ")", ":", "self", ".", "indexes", "=", "[", "]", "for", "app_config", "in", "apps", ".", "get_app_configs", "(", ")", ":", "indexes_path", "=", "'{}.elastic_indexes'", ".", "format", "(", "app_config", ".", "name", "...
Save list of index builders into ``_index_builders``.
[ "Save", "list", "of", "index", "builders", "into", "_index_builders", "." ]
f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/elastic/builder.py#L435-L472
train
45,514
genialis/resolwe
resolwe/elastic/builder.py
IndexBuilder.build
def build(self, obj=None, queryset=None, push=True): """Trigger building of the indexes. Support passing ``obj`` parameter to the indexes, so we can trigger build only for one object. """ for index in self.indexes: index.build(obj, queryset, push)
python
def build(self, obj=None, queryset=None, push=True): """Trigger building of the indexes. Support passing ``obj`` parameter to the indexes, so we can trigger build only for one object. """ for index in self.indexes: index.build(obj, queryset, push)
[ "def", "build", "(", "self", ",", "obj", "=", "None", ",", "queryset", "=", "None", ",", "push", "=", "True", ")", ":", "for", "index", "in", "self", ".", "indexes", ":", "index", ".", "build", "(", "obj", ",", "queryset", ",", "push", ")" ]
Trigger building of the indexes. Support passing ``obj`` parameter to the indexes, so we can trigger build only for one object.
[ "Trigger", "building", "of", "the", "indexes", "." ]
f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/elastic/builder.py#L474-L481
train
45,515
genialis/resolwe
resolwe/elastic/builder.py
IndexBuilder.delete
def delete(self, skip_mapping=False): """Delete all entries from ElasticSearch.""" for index in self.indexes: index.destroy() if not skip_mapping: index.create_mapping()
python
def delete(self, skip_mapping=False): """Delete all entries from ElasticSearch.""" for index in self.indexes: index.destroy() if not skip_mapping: index.create_mapping()
[ "def", "delete", "(", "self", ",", "skip_mapping", "=", "False", ")", ":", "for", "index", "in", "self", ".", "indexes", ":", "index", ".", "destroy", "(", ")", "if", "not", "skip_mapping", ":", "index", ".", "create_mapping", "(", ")" ]
Delete all entries from ElasticSearch.
[ "Delete", "all", "entries", "from", "ElasticSearch", "." ]
f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/elastic/builder.py#L493-L498
train
45,516
genialis/resolwe
resolwe/elastic/builder.py
IndexBuilder.destroy
def destroy(self): """Delete all indexes from Elasticsearch and index builder.""" self.unregister_signals() for index in self.indexes: index.destroy() self.indexes = []
python
def destroy(self): """Delete all indexes from Elasticsearch and index builder.""" self.unregister_signals() for index in self.indexes: index.destroy() self.indexes = []
[ "def", "destroy", "(", "self", ")", ":", "self", ".", "unregister_signals", "(", ")", "for", "index", "in", "self", ".", "indexes", ":", "index", ".", "destroy", "(", ")", "self", ".", "indexes", "=", "[", "]" ]
Delete all indexes from Elasticsearch and index builder.
[ "Delete", "all", "indexes", "from", "Elasticsearch", "and", "index", "builder", "." ]
f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/elastic/builder.py#L505-L510
train
45,517
wilson-eft/wilson
wilson/run/smeft/classes.py
SMEFT._set_initial
def _set_initial(self, C_in, scale_in): r"""Set the initial values for parameters and Wilson coefficients at the scale `scale_in`.""" self.C_in = C_in self.scale_in = scale_in
python
def _set_initial(self, C_in, scale_in): r"""Set the initial values for parameters and Wilson coefficients at the scale `scale_in`.""" self.C_in = C_in self.scale_in = scale_in
[ "def", "_set_initial", "(", "self", ",", "C_in", ",", "scale_in", ")", ":", "self", ".", "C_in", "=", "C_in", "self", ".", "scale_in", "=", "scale_in" ]
r"""Set the initial values for parameters and Wilson coefficients at the scale `scale_in`.
[ "r", "Set", "the", "initial", "values", "for", "parameters", "and", "Wilson", "coefficients", "at", "the", "scale", "scale_in", "." ]
4164f55ff663d4f668c6e2b4575fd41562662cc9
https://github.com/wilson-eft/wilson/blob/4164f55ff663d4f668c6e2b4575fd41562662cc9/wilson/run/smeft/classes.py#L37-L41
train
45,518
wilson-eft/wilson
wilson/run/smeft/classes.py
SMEFT._rgevolve_leadinglog
def _rgevolve_leadinglog(self, scale_out): """Compute the leading logarithmic approximation to the solution of the SMEFT RGEs from the initial scale to `scale_out`. Returns a dictionary with parameters and Wilson coefficients. Much faster but less precise that `rgevolve`. """ self._check_initial() return rge.smeft_evolve_leadinglog(C_in=self.C_in, scale_in=self.scale_in, scale_out=scale_out)
python
def _rgevolve_leadinglog(self, scale_out): """Compute the leading logarithmic approximation to the solution of the SMEFT RGEs from the initial scale to `scale_out`. Returns a dictionary with parameters and Wilson coefficients. Much faster but less precise that `rgevolve`. """ self._check_initial() return rge.smeft_evolve_leadinglog(C_in=self.C_in, scale_in=self.scale_in, scale_out=scale_out)
[ "def", "_rgevolve_leadinglog", "(", "self", ",", "scale_out", ")", ":", "self", ".", "_check_initial", "(", ")", "return", "rge", ".", "smeft_evolve_leadinglog", "(", "C_in", "=", "self", ".", "C_in", ",", "scale_in", "=", "self", ".", "scale_in", ",", "sc...
Compute the leading logarithmic approximation to the solution of the SMEFT RGEs from the initial scale to `scale_out`. Returns a dictionary with parameters and Wilson coefficients. Much faster but less precise that `rgevolve`.
[ "Compute", "the", "leading", "logarithmic", "approximation", "to", "the", "solution", "of", "the", "SMEFT", "RGEs", "from", "the", "initial", "scale", "to", "scale_out", ".", "Returns", "a", "dictionary", "with", "parameters", "and", "Wilson", "coefficients", "....
4164f55ff663d4f668c6e2b4575fd41562662cc9
https://github.com/wilson-eft/wilson/blob/4164f55ff663d4f668c6e2b4575fd41562662cc9/wilson/run/smeft/classes.py#L106-L115
train
45,519
wilson-eft/wilson
wilson/run/smeft/classes.py
SMEFT.get_smpar
def get_smpar(self, accuracy='integrate', scale_sm=91.1876): """Compute the SM MS-bar parameters at the electroweak scale. This method can be used to validate the accuracy of the iterative extraction of SM parameters. If successful, the values returned by this method should agree with the values in the dictionary `wilson.run.smeft.smpar.p`.""" if accuracy == 'integrate': C_out = self._rgevolve(scale_sm) elif accuracy == 'leadinglog': C_out = self._rgevolve_leadinglog(scale_sm) else: raise ValueError("'{}' is not a valid value of 'accuracy' (must be either 'integrate' or 'leadinglog').".format(accuracy)) return smpar.smpar(C_out)
python
def get_smpar(self, accuracy='integrate', scale_sm=91.1876): """Compute the SM MS-bar parameters at the electroweak scale. This method can be used to validate the accuracy of the iterative extraction of SM parameters. If successful, the values returned by this method should agree with the values in the dictionary `wilson.run.smeft.smpar.p`.""" if accuracy == 'integrate': C_out = self._rgevolve(scale_sm) elif accuracy == 'leadinglog': C_out = self._rgevolve_leadinglog(scale_sm) else: raise ValueError("'{}' is not a valid value of 'accuracy' (must be either 'integrate' or 'leadinglog').".format(accuracy)) return smpar.smpar(C_out)
[ "def", "get_smpar", "(", "self", ",", "accuracy", "=", "'integrate'", ",", "scale_sm", "=", "91.1876", ")", ":", "if", "accuracy", "==", "'integrate'", ":", "C_out", "=", "self", ".", "_rgevolve", "(", "scale_sm", ")", "elif", "accuracy", "==", "'leadinglo...
Compute the SM MS-bar parameters at the electroweak scale. This method can be used to validate the accuracy of the iterative extraction of SM parameters. If successful, the values returned by this method should agree with the values in the dictionary `wilson.run.smeft.smpar.p`.
[ "Compute", "the", "SM", "MS", "-", "bar", "parameters", "at", "the", "electroweak", "scale", "." ]
4164f55ff663d4f668c6e2b4575fd41562662cc9
https://github.com/wilson-eft/wilson/blob/4164f55ff663d4f668c6e2b4575fd41562662cc9/wilson/run/smeft/classes.py#L164-L177
train
45,520
wilson-eft/wilson
wilson/run/smeft/classes.py
SMEFT.run_continuous
def run_continuous(self, scale): """Return a continuous solution to the RGE as `RGsolution` instance.""" if scale == self.scale_in: raise ValueError("The scale must be different from the input scale") elif scale < self.scale_in: scale_min = scale scale_max = self.scale_in elif scale > self.scale_in: scale_max = scale scale_min = self.scale_in fun = rge.smeft_evolve_continuous(C_in=self.C_in, scale_in=self.scale_in, scale_out=scale) return wilson.classes.RGsolution(fun, scale_min, scale_max)
python
def run_continuous(self, scale): """Return a continuous solution to the RGE as `RGsolution` instance.""" if scale == self.scale_in: raise ValueError("The scale must be different from the input scale") elif scale < self.scale_in: scale_min = scale scale_max = self.scale_in elif scale > self.scale_in: scale_max = scale scale_min = self.scale_in fun = rge.smeft_evolve_continuous(C_in=self.C_in, scale_in=self.scale_in, scale_out=scale) return wilson.classes.RGsolution(fun, scale_min, scale_max)
[ "def", "run_continuous", "(", "self", ",", "scale", ")", ":", "if", "scale", "==", "self", ".", "scale_in", ":", "raise", "ValueError", "(", "\"The scale must be different from the input scale\"", ")", "elif", "scale", "<", "self", ".", "scale_in", ":", "scale_m...
Return a continuous solution to the RGE as `RGsolution` instance.
[ "Return", "a", "continuous", "solution", "to", "the", "RGE", "as", "RGsolution", "instance", "." ]
4164f55ff663d4f668c6e2b4575fd41562662cc9
https://github.com/wilson-eft/wilson/blob/4164f55ff663d4f668c6e2b4575fd41562662cc9/wilson/run/smeft/classes.py#L216-L229
train
45,521
genialis/resolwe
resolwe/flow/models/fields.py
ResolweSlugField.deconstruct
def deconstruct(self): """Deconstruct method.""" name, path, args, kwargs = super().deconstruct() if self.populate_from is not None: kwargs['populate_from'] = self.populate_from if self.unique_with != (): kwargs['unique_with'] = self.unique_with kwargs.pop('unique', None) return name, path, args, kwargs
python
def deconstruct(self): """Deconstruct method.""" name, path, args, kwargs = super().deconstruct() if self.populate_from is not None: kwargs['populate_from'] = self.populate_from if self.unique_with != (): kwargs['unique_with'] = self.unique_with kwargs.pop('unique', None) return name, path, args, kwargs
[ "def", "deconstruct", "(", "self", ")", ":", "name", ",", "path", ",", "args", ",", "kwargs", "=", "super", "(", ")", ".", "deconstruct", "(", ")", "if", "self", ".", "populate_from", "is", "not", "None", ":", "kwargs", "[", "'populate_from'", "]", "...
Deconstruct method.
[ "Deconstruct", "method", "." ]
f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/models/fields.py#L30-L41
train
45,522
genialis/resolwe
resolwe/flow/models/fields.py
ResolweSlugField._get_unique_constraints
def _get_unique_constraints(self, instance): """Return SQL filter for filtering by fields in ``unique_with`` attribute. Filter is returned as tuple of two elements where first one is placeholder which is safe to insert into SQL query and second one may include potentially dangerous values and must be passed to SQL query in ``params`` attribute to make sure it is properly escaped. """ constraints_expression = [] constraints_values = {} for field_name in self.unique_with: if constants.LOOKUP_SEP in field_name: raise NotImplementedError( '`unique_with` constraint does not support lookups by related models.' ) field = instance._meta.get_field(field_name) # pylint: disable=protected-access field_value = getattr(instance, field_name) # Convert value to the database representation. field_db_value = field.get_prep_value(field_value) constraint_key = 'unique_' + field_name constraints_expression.append("{} = %({})s".format( connection.ops.quote_name(field.column), constraint_key )) constraints_values[constraint_key] = field_db_value if not constraints_expression: return '', [] constraints_expression = 'AND ' + ' AND '.join(constraints_expression) return constraints_expression, constraints_values
python
def _get_unique_constraints(self, instance): """Return SQL filter for filtering by fields in ``unique_with`` attribute. Filter is returned as tuple of two elements where first one is placeholder which is safe to insert into SQL query and second one may include potentially dangerous values and must be passed to SQL query in ``params`` attribute to make sure it is properly escaped. """ constraints_expression = [] constraints_values = {} for field_name in self.unique_with: if constants.LOOKUP_SEP in field_name: raise NotImplementedError( '`unique_with` constraint does not support lookups by related models.' ) field = instance._meta.get_field(field_name) # pylint: disable=protected-access field_value = getattr(instance, field_name) # Convert value to the database representation. field_db_value = field.get_prep_value(field_value) constraint_key = 'unique_' + field_name constraints_expression.append("{} = %({})s".format( connection.ops.quote_name(field.column), constraint_key )) constraints_values[constraint_key] = field_db_value if not constraints_expression: return '', [] constraints_expression = 'AND ' + ' AND '.join(constraints_expression) return constraints_expression, constraints_values
[ "def", "_get_unique_constraints", "(", "self", ",", "instance", ")", ":", "constraints_expression", "=", "[", "]", "constraints_values", "=", "{", "}", "for", "field_name", "in", "self", ".", "unique_with", ":", "if", "constants", ".", "LOOKUP_SEP", "in", "fie...
Return SQL filter for filtering by fields in ``unique_with`` attribute. Filter is returned as tuple of two elements where first one is placeholder which is safe to insert into SQL query and second one may include potentially dangerous values and must be passed to SQL query in ``params`` attribute to make sure it is properly escaped.
[ "Return", "SQL", "filter", "for", "filtering", "by", "fields", "in", "unique_with", "attribute", "." ]
f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/models/fields.py#L43-L77
train
45,523
genialis/resolwe
resolwe/flow/models/fields.py
ResolweSlugField._get_populate_from_value
def _get_populate_from_value(self, instance): """Get the value from ``populate_from`` attribute.""" if hasattr(self.populate_from, '__call__'): # ResolweSlugField(populate_from=lambda instance: ...) return self.populate_from(instance) else: # ResolweSlugField(populate_from='foo') attr = getattr(instance, self.populate_from) return attr() if callable(attr) else attr
python
def _get_populate_from_value(self, instance): """Get the value from ``populate_from`` attribute.""" if hasattr(self.populate_from, '__call__'): # ResolweSlugField(populate_from=lambda instance: ...) return self.populate_from(instance) else: # ResolweSlugField(populate_from='foo') attr = getattr(instance, self.populate_from) return attr() if callable(attr) else attr
[ "def", "_get_populate_from_value", "(", "self", ",", "instance", ")", ":", "if", "hasattr", "(", "self", ".", "populate_from", ",", "'__call__'", ")", ":", "# ResolweSlugField(populate_from=lambda instance: ...)", "return", "self", ".", "populate_from", "(", "instance...
Get the value from ``populate_from`` attribute.
[ "Get", "the", "value", "from", "populate_from", "attribute", "." ]
f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/models/fields.py#L79-L87
train
45,524
genialis/resolwe
resolwe/flow/execution_engines/workflow/__init__.py
ExecutionEngine._evaluate_expressions
def _evaluate_expressions(self, expression_engine, step_id, values, context): """Recursively evaluate expressions in a dictionary of values.""" if expression_engine is None: return values processed = {} for name, value in values.items(): if isinstance(value, str): value = value.strip() try: expression = expression_engine.get_inline_expression(value) if expression is not None: # Inline expression. value = expression_engine.evaluate_inline(expression, context) else: # Block expression. value = expression_engine.evaluate_block(value, context) except EvaluationError as error: raise ExecutionError('Error while evaluating expression for step "{}":\n{}'.format( step_id, error )) elif isinstance(value, dict): value = self._evaluate_expressions(expression_engine, step_id, value, context) processed[name] = value return processed
python
def _evaluate_expressions(self, expression_engine, step_id, values, context): """Recursively evaluate expressions in a dictionary of values.""" if expression_engine is None: return values processed = {} for name, value in values.items(): if isinstance(value, str): value = value.strip() try: expression = expression_engine.get_inline_expression(value) if expression is not None: # Inline expression. value = expression_engine.evaluate_inline(expression, context) else: # Block expression. value = expression_engine.evaluate_block(value, context) except EvaluationError as error: raise ExecutionError('Error while evaluating expression for step "{}":\n{}'.format( step_id, error )) elif isinstance(value, dict): value = self._evaluate_expressions(expression_engine, step_id, value, context) processed[name] = value return processed
[ "def", "_evaluate_expressions", "(", "self", ",", "expression_engine", ",", "step_id", ",", "values", ",", "context", ")", ":", "if", "expression_engine", "is", "None", ":", "return", "values", "processed", "=", "{", "}", "for", "name", ",", "value", "in", ...
Recursively evaluate expressions in a dictionary of values.
[ "Recursively", "evaluate", "expressions", "in", "a", "dictionary", "of", "values", "." ]
f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/execution_engines/workflow/__init__.py#L56-L82
train
45,525
genialis/resolwe
resolwe/flow/executors/manager_commands.py
init
async def init(): """Create a connection to the Redis server.""" global redis_conn # pylint: disable=global-statement,invalid-name conn = await aioredis.create_connection( 'redis://{}:{}'.format( SETTINGS.get('FLOW_EXECUTOR', {}).get('REDIS_CONNECTION', {}).get('host', 'localhost'), SETTINGS.get('FLOW_EXECUTOR', {}).get('REDIS_CONNECTION', {}).get('port', 56379) ), db=int(SETTINGS.get('FLOW_EXECUTOR', {}).get('REDIS_CONNECTION', {}).get('db', 1)) ) redis_conn = aioredis.Redis(conn)
python
async def init(): """Create a connection to the Redis server.""" global redis_conn # pylint: disable=global-statement,invalid-name conn = await aioredis.create_connection( 'redis://{}:{}'.format( SETTINGS.get('FLOW_EXECUTOR', {}).get('REDIS_CONNECTION', {}).get('host', 'localhost'), SETTINGS.get('FLOW_EXECUTOR', {}).get('REDIS_CONNECTION', {}).get('port', 56379) ), db=int(SETTINGS.get('FLOW_EXECUTOR', {}).get('REDIS_CONNECTION', {}).get('db', 1)) ) redis_conn = aioredis.Redis(conn)
[ "async", "def", "init", "(", ")", ":", "global", "redis_conn", "# pylint: disable=global-statement,invalid-name", "conn", "=", "await", "aioredis", ".", "create_connection", "(", "'redis://{}:{}'", ".", "format", "(", "SETTINGS", ".", "get", "(", "'FLOW_EXECUTOR'", ...
Create a connection to the Redis server.
[ "Create", "a", "connection", "to", "the", "Redis", "server", "." ]
f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/executors/manager_commands.py#L25-L35
train
45,526
genialis/resolwe
resolwe/flow/executors/manager_commands.py
send_manager_command
async def send_manager_command(cmd, expect_reply=True, extra_fields={}): """Send a properly formatted command to the manager. :param cmd: The command to send (:class:`str`). :param expect_reply: If ``True``, wait for the manager to reply with an acknowledgement packet. :param extra_fields: A dictionary of extra information that's merged into the packet body (i.e. not under an extra key). """ packet = { ExecutorProtocol.DATA_ID: DATA['id'], ExecutorProtocol.COMMAND: cmd, } packet.update(extra_fields) logger.debug("Sending command to listener: {}".format(json.dumps(packet))) # TODO what happens here if the push fails? we don't have any realistic recourse, # so just let it explode and stop processing queue_channel = EXECUTOR_SETTINGS['REDIS_CHANNEL_PAIR'][0] try: await redis_conn.rpush(queue_channel, json.dumps(packet)) except Exception: logger.error("Error sending command to manager:\n\n{}".format(traceback.format_exc())) raise if not expect_reply: return for _ in range(_REDIS_RETRIES): response = await redis_conn.blpop(QUEUE_RESPONSE_CHANNEL, timeout=1) if response: break else: # NOTE: If there's still no response after a few seconds, the system is broken # enough that it makes sense to give up; we're isolated here, so if the manager # doesn't respond, we can't really do much more than just crash raise RuntimeError("No response from the manager after {} retries.".format(_REDIS_RETRIES)) _, item = response result = json.loads(item.decode('utf-8'))[ExecutorProtocol.RESULT] assert result in [ExecutorProtocol.RESULT_OK, ExecutorProtocol.RESULT_ERROR] if result == ExecutorProtocol.RESULT_OK: return True return False
python
async def send_manager_command(cmd, expect_reply=True, extra_fields={}): """Send a properly formatted command to the manager. :param cmd: The command to send (:class:`str`). :param expect_reply: If ``True``, wait for the manager to reply with an acknowledgement packet. :param extra_fields: A dictionary of extra information that's merged into the packet body (i.e. not under an extra key). """ packet = { ExecutorProtocol.DATA_ID: DATA['id'], ExecutorProtocol.COMMAND: cmd, } packet.update(extra_fields) logger.debug("Sending command to listener: {}".format(json.dumps(packet))) # TODO what happens here if the push fails? we don't have any realistic recourse, # so just let it explode and stop processing queue_channel = EXECUTOR_SETTINGS['REDIS_CHANNEL_PAIR'][0] try: await redis_conn.rpush(queue_channel, json.dumps(packet)) except Exception: logger.error("Error sending command to manager:\n\n{}".format(traceback.format_exc())) raise if not expect_reply: return for _ in range(_REDIS_RETRIES): response = await redis_conn.blpop(QUEUE_RESPONSE_CHANNEL, timeout=1) if response: break else: # NOTE: If there's still no response after a few seconds, the system is broken # enough that it makes sense to give up; we're isolated here, so if the manager # doesn't respond, we can't really do much more than just crash raise RuntimeError("No response from the manager after {} retries.".format(_REDIS_RETRIES)) _, item = response result = json.loads(item.decode('utf-8'))[ExecutorProtocol.RESULT] assert result in [ExecutorProtocol.RESULT_OK, ExecutorProtocol.RESULT_ERROR] if result == ExecutorProtocol.RESULT_OK: return True return False
[ "async", "def", "send_manager_command", "(", "cmd", ",", "expect_reply", "=", "True", ",", "extra_fields", "=", "{", "}", ")", ":", "packet", "=", "{", "ExecutorProtocol", ".", "DATA_ID", ":", "DATA", "[", "'id'", "]", ",", "ExecutorProtocol", ".", "COMMAN...
Send a properly formatted command to the manager. :param cmd: The command to send (:class:`str`). :param expect_reply: If ``True``, wait for the manager to reply with an acknowledgement packet. :param extra_fields: A dictionary of extra information that's merged into the packet body (i.e. not under an extra key).
[ "Send", "a", "properly", "formatted", "command", "to", "the", "manager", "." ]
f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/executors/manager_commands.py#L44-L90
train
45,527
DataONEorg/d1_python
gmn/src/d1_gmn/app/sysmeta_extract.py
_annotate_query
def _annotate_query(query, generate_dict): """Add annotations to the query to retrieve values required by field value generate functions.""" annotate_key_list = [] for field_name, annotate_dict in generate_dict.items(): for annotate_name, annotate_func in annotate_dict["annotate_dict"].items(): query = annotate_func(query) annotate_key_list.append(annotate_name) return query, annotate_key_list
python
def _annotate_query(query, generate_dict): """Add annotations to the query to retrieve values required by field value generate functions.""" annotate_key_list = [] for field_name, annotate_dict in generate_dict.items(): for annotate_name, annotate_func in annotate_dict["annotate_dict"].items(): query = annotate_func(query) annotate_key_list.append(annotate_name) return query, annotate_key_list
[ "def", "_annotate_query", "(", "query", ",", "generate_dict", ")", ":", "annotate_key_list", "=", "[", "]", "for", "field_name", ",", "annotate_dict", "in", "generate_dict", ".", "items", "(", ")", ":", "for", "annotate_name", ",", "annotate_func", "in", "anno...
Add annotations to the query to retrieve values required by field value generate functions.
[ "Add", "annotations", "to", "the", "query", "to", "retrieve", "values", "required", "by", "field", "value", "generate", "functions", "." ]
3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/gmn/src/d1_gmn/app/sysmeta_extract.py#L163-L171
train
45,528
DataONEorg/d1_python
gmn/src/d1_gmn/app/sysmeta_extract.py
_value_list_to_sciobj_dict
def _value_list_to_sciobj_dict( sciobj_value_list, lookup_list, lookup_dict, generate_dict ): """Create a dict where the keys are the requested field names, from the values returned by Django.""" sciobj_dict = {} # for sciobj_value, lookup_str in zip(sciobj_value_list, lookup_list): lookup_to_value_dict = {k: v for k, v in zip(lookup_list, sciobj_value_list)} for field_name, r_dict in lookup_dict.items(): if r_dict["lookup_str"] in lookup_to_value_dict.keys(): sciobj_dict[field_name] = lookup_to_value_dict[r_dict["lookup_str"]] for field_name, annotate_dict in generate_dict.items(): for final_name, generate_func in annotate_dict["generate_dict"].items(): sciobj_dict[field_name] = generate_func(lookup_to_value_dict) return sciobj_dict
python
def _value_list_to_sciobj_dict( sciobj_value_list, lookup_list, lookup_dict, generate_dict ): """Create a dict where the keys are the requested field names, from the values returned by Django.""" sciobj_dict = {} # for sciobj_value, lookup_str in zip(sciobj_value_list, lookup_list): lookup_to_value_dict = {k: v for k, v in zip(lookup_list, sciobj_value_list)} for field_name, r_dict in lookup_dict.items(): if r_dict["lookup_str"] in lookup_to_value_dict.keys(): sciobj_dict[field_name] = lookup_to_value_dict[r_dict["lookup_str"]] for field_name, annotate_dict in generate_dict.items(): for final_name, generate_func in annotate_dict["generate_dict"].items(): sciobj_dict[field_name] = generate_func(lookup_to_value_dict) return sciobj_dict
[ "def", "_value_list_to_sciobj_dict", "(", "sciobj_value_list", ",", "lookup_list", ",", "lookup_dict", ",", "generate_dict", ")", ":", "sciobj_dict", "=", "{", "}", "# for sciobj_value, lookup_str in zip(sciobj_value_list, lookup_list):", "lookup_to_value_dict", "=", "{", "k"...
Create a dict where the keys are the requested field names, from the values returned by Django.
[ "Create", "a", "dict", "where", "the", "keys", "are", "the", "requested", "field", "names", "from", "the", "values", "returned", "by", "Django", "." ]
3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/gmn/src/d1_gmn/app/sysmeta_extract.py#L174-L193
train
45,529
DataONEorg/d1_python
gmn/src/d1_gmn/app/sysmeta_extract.py
_split_field_list
def _split_field_list(field_list): """Split the list of fields for which to extract values into lists by extraction methods. - Remove any duplicated field names. - Raises ValueError with list of any invalid field names in ``field_list``. """ lookup_dict = {} generate_dict = {} for field_name in field_list or FIELD_NAME_TO_EXTRACT_DICT.keys(): try: extract_dict = FIELD_NAME_TO_EXTRACT_DICT[field_name] except KeyError: assert_invalid_field_list(field_list) else: if "lookup_str" in extract_dict: lookup_dict[field_name] = extract_dict else: generate_dict[field_name] = extract_dict return lookup_dict, generate_dict
python
def _split_field_list(field_list): """Split the list of fields for which to extract values into lists by extraction methods. - Remove any duplicated field names. - Raises ValueError with list of any invalid field names in ``field_list``. """ lookup_dict = {} generate_dict = {} for field_name in field_list or FIELD_NAME_TO_EXTRACT_DICT.keys(): try: extract_dict = FIELD_NAME_TO_EXTRACT_DICT[field_name] except KeyError: assert_invalid_field_list(field_list) else: if "lookup_str" in extract_dict: lookup_dict[field_name] = extract_dict else: generate_dict[field_name] = extract_dict return lookup_dict, generate_dict
[ "def", "_split_field_list", "(", "field_list", ")", ":", "lookup_dict", "=", "{", "}", "generate_dict", "=", "{", "}", "for", "field_name", "in", "field_list", "or", "FIELD_NAME_TO_EXTRACT_DICT", ".", "keys", "(", ")", ":", "try", ":", "extract_dict", "=", "...
Split the list of fields for which to extract values into lists by extraction methods. - Remove any duplicated field names. - Raises ValueError with list of any invalid field names in ``field_list``.
[ "Split", "the", "list", "of", "fields", "for", "which", "to", "extract", "values", "into", "lists", "by", "extraction", "methods", "." ]
3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/gmn/src/d1_gmn/app/sysmeta_extract.py#L196-L218
train
45,530
DataONEorg/d1_python
gmn/src/d1_gmn/app/views/util.py
dataoneTypes
def dataoneTypes(request): """Return the PyXB binding to use when handling a request.""" if is_v1_api(request): return d1_common.types.dataoneTypes_v1_1 elif is_v2_api(request) or is_diag_api(request): return d1_common.types.dataoneTypes_v2_0 else: raise d1_common.types.exceptions.ServiceFailure( 0, 'Unknown version designator in URL. url="{}"'.format(request.path) )
python
def dataoneTypes(request): """Return the PyXB binding to use when handling a request.""" if is_v1_api(request): return d1_common.types.dataoneTypes_v1_1 elif is_v2_api(request) or is_diag_api(request): return d1_common.types.dataoneTypes_v2_0 else: raise d1_common.types.exceptions.ServiceFailure( 0, 'Unknown version designator in URL. url="{}"'.format(request.path) )
[ "def", "dataoneTypes", "(", "request", ")", ":", "if", "is_v1_api", "(", "request", ")", ":", "return", "d1_common", ".", "types", ".", "dataoneTypes_v1_1", "elif", "is_v2_api", "(", "request", ")", "or", "is_diag_api", "(", "request", ")", ":", "return", ...
Return the PyXB binding to use when handling a request.
[ "Return", "the", "PyXB", "binding", "to", "use", "when", "handling", "a", "request", "." ]
3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/gmn/src/d1_gmn/app/views/util.py#L46-L55
train
45,531
DataONEorg/d1_python
gmn/src/d1_gmn/app/views/util.py
parse_and_normalize_url_date
def parse_and_normalize_url_date(date_str): """Parse a ISO 8601 date-time with optional timezone. - Return as datetime with timezone adjusted to UTC. - Return naive date-time set to UTC. """ if date_str is None: return None try: return d1_common.date_time.dt_from_iso8601_str(date_str) except d1_common.date_time.iso8601.ParseError as e: raise d1_common.types.exceptions.InvalidRequest( 0, 'Invalid date format for URL parameter. date="{}" error="{}"'.format( date_str, str(e) ), )
python
def parse_and_normalize_url_date(date_str): """Parse a ISO 8601 date-time with optional timezone. - Return as datetime with timezone adjusted to UTC. - Return naive date-time set to UTC. """ if date_str is None: return None try: return d1_common.date_time.dt_from_iso8601_str(date_str) except d1_common.date_time.iso8601.ParseError as e: raise d1_common.types.exceptions.InvalidRequest( 0, 'Invalid date format for URL parameter. date="{}" error="{}"'.format( date_str, str(e) ), )
[ "def", "parse_and_normalize_url_date", "(", "date_str", ")", ":", "if", "date_str", "is", "None", ":", "return", "None", "try", ":", "return", "d1_common", ".", "date_time", ".", "dt_from_iso8601_str", "(", "date_str", ")", "except", "d1_common", ".", "date_time...
Parse a ISO 8601 date-time with optional timezone. - Return as datetime with timezone adjusted to UTC. - Return naive date-time set to UTC.
[ "Parse", "a", "ISO", "8601", "date", "-", "time", "with", "optional", "timezone", "." ]
3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/gmn/src/d1_gmn/app/views/util.py#L179-L196
train
45,532
DataONEorg/d1_python
lib_client/src/d1_client/solr_client.py
SolrClient.get
def get(self, doc_id): """Retrieve the specified document.""" resp_dict = self._get_query(q='id:{}'.format(doc_id)) if resp_dict['response']['numFound'] > 0: return resp_dict['response']['docs'][0]
python
def get(self, doc_id): """Retrieve the specified document.""" resp_dict = self._get_query(q='id:{}'.format(doc_id)) if resp_dict['response']['numFound'] > 0: return resp_dict['response']['docs'][0]
[ "def", "get", "(", "self", ",", "doc_id", ")", ":", "resp_dict", "=", "self", ".", "_get_query", "(", "q", "=", "'id:{}'", ".", "format", "(", "doc_id", ")", ")", "if", "resp_dict", "[", "'response'", "]", "[", "'numFound'", "]", ">", "0", ":", "re...
Retrieve the specified document.
[ "Retrieve", "the", "specified", "document", "." ]
3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_client/src/d1_client/solr_client.py#L178-L182
train
45,533
DataONEorg/d1_python
lib_client/src/d1_client/solr_client.py
SolrClient.get_ids
def get_ids(self, start=0, rows=1000, **query_dict): """Retrieve a list of identifiers for documents matching the query.""" resp_dict = self._get_query(start=start, rows=rows, **query_dict) return { 'matches': resp_dict['response']['numFound'], 'start': start, 'ids': [d['id'] for d in resp_dict['response']['docs']], }
python
def get_ids(self, start=0, rows=1000, **query_dict): """Retrieve a list of identifiers for documents matching the query.""" resp_dict = self._get_query(start=start, rows=rows, **query_dict) return { 'matches': resp_dict['response']['numFound'], 'start': start, 'ids': [d['id'] for d in resp_dict['response']['docs']], }
[ "def", "get_ids", "(", "self", ",", "start", "=", "0", ",", "rows", "=", "1000", ",", "*", "*", "query_dict", ")", ":", "resp_dict", "=", "self", ".", "_get_query", "(", "start", "=", "start", ",", "rows", "=", "rows", ",", "*", "*", "query_dict", ...
Retrieve a list of identifiers for documents matching the query.
[ "Retrieve", "a", "list", "of", "identifiers", "for", "documents", "matching", "the", "query", "." ]
3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_client/src/d1_client/solr_client.py#L185-L192
train
45,534
DataONEorg/d1_python
lib_client/src/d1_client/solr_client.py
SolrClient.get_field_values
def get_field_values(self, name, maxvalues=-1, sort=True, **query_dict): """Retrieve the unique values for a field, along with their usage counts. :param name: Name of field for which to retrieve values :type name: string :param sort: Sort the result :param maxvalues: Maximum number of values to retrieve. Default is -1, which causes retrieval of all values. :type maxvalues: int :returns: dict of {fieldname: [[value, count], ... ], } """ param_dict = query_dict.copy() param_dict.update( { 'rows': '0', 'facet': 'true', 'facet.field': name, 'facet.limit': str(maxvalues), 'facet.zeros': 'false', 'facet.sort': str(sort).lower(), } ) resp_dict = self._post_query(**param_dict) result_dict = resp_dict['facet_counts']['facet_fields'] result_dict['numFound'] = resp_dict['response']['numFound'] return result_dict
python
def get_field_values(self, name, maxvalues=-1, sort=True, **query_dict): """Retrieve the unique values for a field, along with their usage counts. :param name: Name of field for which to retrieve values :type name: string :param sort: Sort the result :param maxvalues: Maximum number of values to retrieve. Default is -1, which causes retrieval of all values. :type maxvalues: int :returns: dict of {fieldname: [[value, count], ... ], } """ param_dict = query_dict.copy() param_dict.update( { 'rows': '0', 'facet': 'true', 'facet.field': name, 'facet.limit': str(maxvalues), 'facet.zeros': 'false', 'facet.sort': str(sort).lower(), } ) resp_dict = self._post_query(**param_dict) result_dict = resp_dict['facet_counts']['facet_fields'] result_dict['numFound'] = resp_dict['response']['numFound'] return result_dict
[ "def", "get_field_values", "(", "self", ",", "name", ",", "maxvalues", "=", "-", "1", ",", "sort", "=", "True", ",", "*", "*", "query_dict", ")", ":", "param_dict", "=", "query_dict", ".", "copy", "(", ")", "param_dict", ".", "update", "(", "{", "'ro...
Retrieve the unique values for a field, along with their usage counts. :param name: Name of field for which to retrieve values :type name: string :param sort: Sort the result :param maxvalues: Maximum number of values to retrieve. Default is -1, which causes retrieval of all values. :type maxvalues: int :returns: dict of {fieldname: [[value, count], ... ], }
[ "Retrieve", "the", "unique", "values", "for", "a", "field", "along", "with", "their", "usage", "counts", "." ]
3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_client/src/d1_client/solr_client.py#L201-L230
train
45,535
DataONEorg/d1_python
lib_client/src/d1_client/solr_client.py
SolrClient._get_solr_type
def _get_solr_type(self, field): """Returns the Solr type of the specified field name. Assumes the convention of dynamic fields using an underscore + type character code for the field name. """ field_type = 'string' try: field_type = FIELD_TYPE_CONVERSION_MAP[field] return field_type except: pass fta = field.split('_') if len(fta) > 1: ft = fta[len(fta) - 1] try: field_type = FIELD_TYPE_CONVERSION_MAP[ft] # cache the type so it's used next time FIELD_TYPE_CONVERSION_MAP[field] = field_type except: pass return field_type
python
def _get_solr_type(self, field): """Returns the Solr type of the specified field name. Assumes the convention of dynamic fields using an underscore + type character code for the field name. """ field_type = 'string' try: field_type = FIELD_TYPE_CONVERSION_MAP[field] return field_type except: pass fta = field.split('_') if len(fta) > 1: ft = fta[len(fta) - 1] try: field_type = FIELD_TYPE_CONVERSION_MAP[ft] # cache the type so it's used next time FIELD_TYPE_CONVERSION_MAP[field] = field_type except: pass return field_type
[ "def", "_get_solr_type", "(", "self", ",", "field", ")", ":", "field_type", "=", "'string'", "try", ":", "field_type", "=", "FIELD_TYPE_CONVERSION_MAP", "[", "field", "]", "return", "field_type", "except", ":", "pass", "fta", "=", "field", ".", "split", "(",...
Returns the Solr type of the specified field name. Assumes the convention of dynamic fields using an underscore + type character code for the field name.
[ "Returns", "the", "Solr", "type", "of", "the", "specified", "field", "name", "." ]
3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_client/src/d1_client/solr_client.py#L453-L475
train
45,536
DataONEorg/d1_python
lib_client/src/d1_client/solr_client.py
SolrClient._get_query
def _get_query(self, **query_dict): """Perform a GET query against Solr and return the response as a Python dict.""" param_dict = query_dict.copy() return self._send_query(do_post=False, **param_dict)
python
def _get_query(self, **query_dict): """Perform a GET query against Solr and return the response as a Python dict.""" param_dict = query_dict.copy() return self._send_query(do_post=False, **param_dict)
[ "def", "_get_query", "(", "self", ",", "*", "*", "query_dict", ")", ":", "param_dict", "=", "query_dict", ".", "copy", "(", ")", "return", "self", ".", "_send_query", "(", "do_post", "=", "False", ",", "*", "*", "param_dict", ")" ]
Perform a GET query against Solr and return the response as a Python dict.
[ "Perform", "a", "GET", "query", "against", "Solr", "and", "return", "the", "response", "as", "a", "Python", "dict", "." ]
3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_client/src/d1_client/solr_client.py#L501-L504
train
45,537
DataONEorg/d1_python
lib_client/src/d1_client/solr_client.py
SolrClient._post_query
def _post_query(self, **query_dict): """Perform a POST query against Solr and return the response as a Python dict.""" param_dict = query_dict.copy() return self._send_query(do_post=True, **param_dict)
python
def _post_query(self, **query_dict): """Perform a POST query against Solr and return the response as a Python dict.""" param_dict = query_dict.copy() return self._send_query(do_post=True, **param_dict)
[ "def", "_post_query", "(", "self", ",", "*", "*", "query_dict", ")", ":", "param_dict", "=", "query_dict", ".", "copy", "(", ")", "return", "self", ".", "_send_query", "(", "do_post", "=", "True", ",", "*", "*", "param_dict", ")" ]
Perform a POST query against Solr and return the response as a Python dict.
[ "Perform", "a", "POST", "query", "against", "Solr", "and", "return", "the", "response", "as", "a", "Python", "dict", "." ]
3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_client/src/d1_client/solr_client.py#L506-L510
train
45,538
DataONEorg/d1_python
lib_client/src/d1_client/solr_client.py
SolrClient._send_query
def _send_query(self, do_post=False, **query_dict): """Perform a query against Solr and return the response as a Python dict.""" # self._prepare_query_term() param_dict = query_dict.copy() param_dict.setdefault('wt', 'json') param_dict.setdefault('q', '*.*') param_dict.setdefault('fl', '*') return self.query('solr', '', do_post=do_post, query=param_dict)
python
def _send_query(self, do_post=False, **query_dict): """Perform a query against Solr and return the response as a Python dict.""" # self._prepare_query_term() param_dict = query_dict.copy() param_dict.setdefault('wt', 'json') param_dict.setdefault('q', '*.*') param_dict.setdefault('fl', '*') return self.query('solr', '', do_post=do_post, query=param_dict)
[ "def", "_send_query", "(", "self", ",", "do_post", "=", "False", ",", "*", "*", "query_dict", ")", ":", "# self._prepare_query_term()", "param_dict", "=", "query_dict", ".", "copy", "(", ")", "param_dict", ".", "setdefault", "(", "'wt'", ",", "'json'", ")", ...
Perform a query against Solr and return the response as a Python dict.
[ "Perform", "a", "query", "against", "Solr", "and", "return", "the", "response", "as", "a", "Python", "dict", "." ]
3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_client/src/d1_client/solr_client.py#L512-L519
train
45,539
DataONEorg/d1_python
lib_client/src/d1_client/solr_client.py
SolrClient._escape_query_term
def _escape_query_term(self, term): """Escape a query term for inclusion in a query. - Also see: prepare_query_term(). """ term = term.replace('\\', '\\\\') for c in RESERVED_CHAR_LIST: term = term.replace(c, r'\{}'.format(c)) return term
python
def _escape_query_term(self, term): """Escape a query term for inclusion in a query. - Also see: prepare_query_term(). """ term = term.replace('\\', '\\\\') for c in RESERVED_CHAR_LIST: term = term.replace(c, r'\{}'.format(c)) return term
[ "def", "_escape_query_term", "(", "self", ",", "term", ")", ":", "term", "=", "term", ".", "replace", "(", "'\\\\'", ",", "'\\\\\\\\'", ")", "for", "c", "in", "RESERVED_CHAR_LIST", ":", "term", "=", "term", ".", "replace", "(", "c", ",", "r'\\{}'", "."...
Escape a query term for inclusion in a query. - Also see: prepare_query_term().
[ "Escape", "a", "query", "term", "for", "inclusion", "in", "a", "query", "." ]
3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_client/src/d1_client/solr_client.py#L542-L551
train
45,540
genialis/resolwe
resolwe/flow/migrations/0023_process_entity_2.py
migrate_flow_collection
def migrate_flow_collection(apps, schema_editor): """Migrate 'flow_collection' field to 'entity_type'.""" Process = apps.get_model('flow', 'Process') DescriptorSchema = apps.get_model('flow', 'DescriptorSchema') for process in Process.objects.all(): process.entity_type = process.flow_collection process.entity_descriptor_schema = process.flow_collection if (process.entity_descriptor_schema is not None and not DescriptorSchema.objects.filter(slug=process.entity_descriptor_schema).exists()): raise LookupError( "Descriptow schema '{}' referenced in 'entity_descriptor_schema' not " "found.".format(process.entity_descriptor_schema) ) process.save()
python
def migrate_flow_collection(apps, schema_editor): """Migrate 'flow_collection' field to 'entity_type'.""" Process = apps.get_model('flow', 'Process') DescriptorSchema = apps.get_model('flow', 'DescriptorSchema') for process in Process.objects.all(): process.entity_type = process.flow_collection process.entity_descriptor_schema = process.flow_collection if (process.entity_descriptor_schema is not None and not DescriptorSchema.objects.filter(slug=process.entity_descriptor_schema).exists()): raise LookupError( "Descriptow schema '{}' referenced in 'entity_descriptor_schema' not " "found.".format(process.entity_descriptor_schema) ) process.save()
[ "def", "migrate_flow_collection", "(", "apps", ",", "schema_editor", ")", ":", "Process", "=", "apps", ".", "get_model", "(", "'flow'", ",", "'Process'", ")", "DescriptorSchema", "=", "apps", ".", "get_model", "(", "'flow'", ",", "'DescriptorSchema'", ")", "fo...
Migrate 'flow_collection' field to 'entity_type'.
[ "Migrate", "flow_collection", "field", "to", "entity_type", "." ]
f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/migrations/0023_process_entity_2.py#L8-L24
train
45,541
DataONEorg/d1_python
lib_common/src/d1_common/type_conversions.py
get_pyxb_binding_by_api_version
def get_pyxb_binding_by_api_version(api_major, api_minor=0): """Map DataONE API version tag to PyXB binding. Given a DataONE API major version number, return PyXB binding that can serialize and deserialize DataONE XML docs of that version. Args: api_major, api_minor: str or int DataONE API major and minor version numbers. - If ``api_major`` is an integer, it is combined with ``api_minor`` to form an exact version. - If ``api_major`` is a string of ``v1`` or ``v2``, ``api_minor`` is ignored and the latest PyXB bindingavailable for the ``api_major`` version is returned. Returns: PyXB binding: E.g., ``d1_common.types.dataoneTypes_v1_1``. """ try: return VERSION_TO_BINDING_DICT[api_major, api_minor] except KeyError: raise ValueError( 'Unknown DataONE API version: {}.{}'.format(api_major, api_minor) )
python
def get_pyxb_binding_by_api_version(api_major, api_minor=0): """Map DataONE API version tag to PyXB binding. Given a DataONE API major version number, return PyXB binding that can serialize and deserialize DataONE XML docs of that version. Args: api_major, api_minor: str or int DataONE API major and minor version numbers. - If ``api_major`` is an integer, it is combined with ``api_minor`` to form an exact version. - If ``api_major`` is a string of ``v1`` or ``v2``, ``api_minor`` is ignored and the latest PyXB bindingavailable for the ``api_major`` version is returned. Returns: PyXB binding: E.g., ``d1_common.types.dataoneTypes_v1_1``. """ try: return VERSION_TO_BINDING_DICT[api_major, api_minor] except KeyError: raise ValueError( 'Unknown DataONE API version: {}.{}'.format(api_major, api_minor) )
[ "def", "get_pyxb_binding_by_api_version", "(", "api_major", ",", "api_minor", "=", "0", ")", ":", "try", ":", "return", "VERSION_TO_BINDING_DICT", "[", "api_major", ",", "api_minor", "]", "except", "KeyError", ":", "raise", "ValueError", "(", "'Unknown DataONE API v...
Map DataONE API version tag to PyXB binding. Given a DataONE API major version number, return PyXB binding that can serialize and deserialize DataONE XML docs of that version. Args: api_major, api_minor: str or int DataONE API major and minor version numbers. - If ``api_major`` is an integer, it is combined with ``api_minor`` to form an exact version. - If ``api_major`` is a string of ``v1`` or ``v2``, ``api_minor`` is ignored and the latest PyXB bindingavailable for the ``api_major`` version is returned. Returns: PyXB binding: E.g., ``d1_common.types.dataoneTypes_v1_1``.
[ "Map", "DataONE", "API", "version", "tag", "to", "PyXB", "binding", "." ]
3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/type_conversions.py#L119-L145
train
45,542
DataONEorg/d1_python
lib_common/src/d1_common/type_conversions.py
extract_version_tag_from_url
def extract_version_tag_from_url(url): """Extract a DataONE API version tag from a MN or CN service endpoint URL. Args: url : str Service endpoint URL. E.g.: ``https://mn.example.org/path/v2/object/pid``. Returns: str : Valid version tags are currently ``v1`` or ``v2``. """ m = re.match(r'(/|^)(v\d)(/|$)', url) if not m: return None return m.group(2)
python
def extract_version_tag_from_url(url): """Extract a DataONE API version tag from a MN or CN service endpoint URL. Args: url : str Service endpoint URL. E.g.: ``https://mn.example.org/path/v2/object/pid``. Returns: str : Valid version tags are currently ``v1`` or ``v2``. """ m = re.match(r'(/|^)(v\d)(/|$)', url) if not m: return None return m.group(2)
[ "def", "extract_version_tag_from_url", "(", "url", ")", ":", "m", "=", "re", ".", "match", "(", "r'(/|^)(v\\d)(/|$)'", ",", "url", ")", "if", "not", "m", ":", "return", "None", "return", "m", ".", "group", "(", "2", ")" ]
Extract a DataONE API version tag from a MN or CN service endpoint URL. Args: url : str Service endpoint URL. E.g.: ``https://mn.example.org/path/v2/object/pid``. Returns: str : Valid version tags are currently ``v1`` or ``v2``.
[ "Extract", "a", "DataONE", "API", "version", "tag", "from", "a", "MN", "or", "CN", "service", "endpoint", "URL", "." ]
3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/type_conversions.py#L159-L173
train
45,543
DataONEorg/d1_python
lib_common/src/d1_common/type_conversions.py
str_to_v1_str
def str_to_v1_str(xml_str): """Convert a API v2 XML doc to v1 XML doc. Removes elements that are only valid for v2 and changes namespace to v1. If doc is already v1, it is returned unchanged. Args: xml_str : str API v2 XML doc. E.g.: ``SystemMetadata v2``. Returns: str : API v1 XML doc. E.g.: ``SystemMetadata v1``. """ if str_is_v1(xml_str): return xml_str etree_obj = str_to_etree(xml_str) strip_v2_elements(etree_obj) etree_replace_namespace(etree_obj, d1_common.types.dataoneTypes_v1.Namespace) return etree_to_str(etree_obj)
python
def str_to_v1_str(xml_str): """Convert a API v2 XML doc to v1 XML doc. Removes elements that are only valid for v2 and changes namespace to v1. If doc is already v1, it is returned unchanged. Args: xml_str : str API v2 XML doc. E.g.: ``SystemMetadata v2``. Returns: str : API v1 XML doc. E.g.: ``SystemMetadata v1``. """ if str_is_v1(xml_str): return xml_str etree_obj = str_to_etree(xml_str) strip_v2_elements(etree_obj) etree_replace_namespace(etree_obj, d1_common.types.dataoneTypes_v1.Namespace) return etree_to_str(etree_obj)
[ "def", "str_to_v1_str", "(", "xml_str", ")", ":", "if", "str_is_v1", "(", "xml_str", ")", ":", "return", "xml_str", "etree_obj", "=", "str_to_etree", "(", "xml_str", ")", "strip_v2_elements", "(", "etree_obj", ")", "etree_replace_namespace", "(", "etree_obj", ",...
Convert a API v2 XML doc to v1 XML doc. Removes elements that are only valid for v2 and changes namespace to v1. If doc is already v1, it is returned unchanged. Args: xml_str : str API v2 XML doc. E.g.: ``SystemMetadata v2``. Returns: str : API v1 XML doc. E.g.: ``SystemMetadata v1``.
[ "Convert", "a", "API", "v2", "XML", "doc", "to", "v1", "XML", "doc", "." ]
3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/type_conversions.py#L190-L210
train
45,544
DataONEorg/d1_python
lib_common/src/d1_common/type_conversions.py
str_to_v2_str
def str_to_v2_str(xml_str): """Convert a API v1 XML doc to v2 XML doc. All v1 elements are valid for v2, so only changes namespace. Args: xml_str : str API v1 XML doc. E.g.: ``SystemMetadata v1``. Returns: str : API v2 XML doc. E.g.: ``SystemMetadata v2``. """ if str_is_v2(xml_str): return xml_str etree_obj = str_to_etree(xml_str) etree_replace_namespace(etree_obj, d1_common.types.dataoneTypes_v2_0.Namespace) return etree_to_str(etree_obj)
python
def str_to_v2_str(xml_str): """Convert a API v1 XML doc to v2 XML doc. All v1 elements are valid for v2, so only changes namespace. Args: xml_str : str API v1 XML doc. E.g.: ``SystemMetadata v1``. Returns: str : API v2 XML doc. E.g.: ``SystemMetadata v2``. """ if str_is_v2(xml_str): return xml_str etree_obj = str_to_etree(xml_str) etree_replace_namespace(etree_obj, d1_common.types.dataoneTypes_v2_0.Namespace) return etree_to_str(etree_obj)
[ "def", "str_to_v2_str", "(", "xml_str", ")", ":", "if", "str_is_v2", "(", "xml_str", ")", ":", "return", "xml_str", "etree_obj", "=", "str_to_etree", "(", "xml_str", ")", "etree_replace_namespace", "(", "etree_obj", ",", "d1_common", ".", "types", ".", "dataon...
Convert a API v1 XML doc to v2 XML doc. All v1 elements are valid for v2, so only changes namespace. Args: xml_str : str API v1 XML doc. E.g.: ``SystemMetadata v1``. Returns: str : API v2 XML doc. E.g.: ``SystemMetadata v2``.
[ "Convert", "a", "API", "v1", "XML", "doc", "to", "v2", "XML", "doc", "." ]
3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/type_conversions.py#L250-L267
train
45,545
DataONEorg/d1_python
lib_common/src/d1_common/type_conversions.py
str_to_etree
def str_to_etree(xml_str, encoding='utf-8'): """Deserialize API XML doc to an ElementTree. Args: xml_str: bytes DataONE API XML doc encoding: str Decoder to use when converting the XML doc ``bytes`` to a Unicode str. Returns: ElementTree: Matching the API version of the XML doc. """ parser = xml.etree.ElementTree.XMLParser(encoding=encoding) return xml.etree.ElementTree.fromstring(xml_str, parser=parser)
python
def str_to_etree(xml_str, encoding='utf-8'): """Deserialize API XML doc to an ElementTree. Args: xml_str: bytes DataONE API XML doc encoding: str Decoder to use when converting the XML doc ``bytes`` to a Unicode str. Returns: ElementTree: Matching the API version of the XML doc. """ parser = xml.etree.ElementTree.XMLParser(encoding=encoding) return xml.etree.ElementTree.fromstring(xml_str, parser=parser)
[ "def", "str_to_etree", "(", "xml_str", ",", "encoding", "=", "'utf-8'", ")", ":", "parser", "=", "xml", ".", "etree", ".", "ElementTree", ".", "XMLParser", "(", "encoding", "=", "encoding", ")", "return", "xml", ".", "etree", ".", "ElementTree", ".", "fr...
Deserialize API XML doc to an ElementTree. Args: xml_str: bytes DataONE API XML doc encoding: str Decoder to use when converting the XML doc ``bytes`` to a Unicode str. Returns: ElementTree: Matching the API version of the XML doc.
[ "Deserialize", "API", "XML", "doc", "to", "an", "ElementTree", "." ]
3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/type_conversions.py#L506-L521
train
45,546
DataONEorg/d1_python
lib_common/src/d1_common/type_conversions.py
etree_replace_namespace
def etree_replace_namespace(etree_obj, ns_str): """In-place change the namespace of elements in an ElementTree. Args: etree_obj: ElementTree ns_str : str The namespace to set. E.g.: ``http://ns.dataone.org/service/types/v1``. """ def _replace_recursive(el, n): el.tag = re.sub(r'{.*\}', '{{{}}}'.format(n), el.tag) el.text = el.text.strip() if el.text else None el.tail = el.tail.strip() if el.tail else None for child_el in el: _replace_recursive(child_el, n) _replace_recursive(etree_obj, ns_str)
python
def etree_replace_namespace(etree_obj, ns_str): """In-place change the namespace of elements in an ElementTree. Args: etree_obj: ElementTree ns_str : str The namespace to set. E.g.: ``http://ns.dataone.org/service/types/v1``. """ def _replace_recursive(el, n): el.tag = re.sub(r'{.*\}', '{{{}}}'.format(n), el.tag) el.text = el.text.strip() if el.text else None el.tail = el.tail.strip() if el.tail else None for child_el in el: _replace_recursive(child_el, n) _replace_recursive(etree_obj, ns_str)
[ "def", "etree_replace_namespace", "(", "etree_obj", ",", "ns_str", ")", ":", "def", "_replace_recursive", "(", "el", ",", "n", ")", ":", "el", ".", "tag", "=", "re", ".", "sub", "(", "r'{.*\\}'", ",", "'{{{}}}'", ".", "format", "(", "n", ")", ",", "e...
In-place change the namespace of elements in an ElementTree. Args: etree_obj: ElementTree ns_str : str The namespace to set. E.g.: ``http://ns.dataone.org/service/types/v1``.
[ "In", "-", "place", "change", "the", "namespace", "of", "elements", "in", "an", "ElementTree", "." ]
3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/type_conversions.py#L612-L630
train
45,547
DataONEorg/d1_python
lib_common/src/d1_common/type_conversions.py
strip_v2_elements
def strip_v2_elements(etree_obj): """In-place remove elements and attributes that are only valid in v2 types. Args: etree_obj: ElementTree ElementTree holding one of the DataONE API types that changed between v1 and v2. """ if etree_obj.tag == v2_0_tag('logEntry'): strip_logEntry(etree_obj) elif etree_obj.tag == v2_0_tag('log'): strip_log(etree_obj) elif etree_obj.tag == v2_0_tag('node'): strip_node(etree_obj) elif etree_obj.tag == v2_0_tag('nodeList'): strip_node_list(etree_obj) elif etree_obj.tag == v2_0_tag('systemMetadata'): strip_system_metadata(etree_obj) else: raise ValueError('Unknown root element. tag="{}"'.format(etree_obj.tag))
python
def strip_v2_elements(etree_obj): """In-place remove elements and attributes that are only valid in v2 types. Args: etree_obj: ElementTree ElementTree holding one of the DataONE API types that changed between v1 and v2. """ if etree_obj.tag == v2_0_tag('logEntry'): strip_logEntry(etree_obj) elif etree_obj.tag == v2_0_tag('log'): strip_log(etree_obj) elif etree_obj.tag == v2_0_tag('node'): strip_node(etree_obj) elif etree_obj.tag == v2_0_tag('nodeList'): strip_node_list(etree_obj) elif etree_obj.tag == v2_0_tag('systemMetadata'): strip_system_metadata(etree_obj) else: raise ValueError('Unknown root element. tag="{}"'.format(etree_obj.tag))
[ "def", "strip_v2_elements", "(", "etree_obj", ")", ":", "if", "etree_obj", ".", "tag", "==", "v2_0_tag", "(", "'logEntry'", ")", ":", "strip_logEntry", "(", "etree_obj", ")", "elif", "etree_obj", ".", "tag", "==", "v2_0_tag", "(", "'log'", ")", ":", "strip...
In-place remove elements and attributes that are only valid in v2 types. Args: etree_obj: ElementTree ElementTree holding one of the DataONE API types that changed between v1 and v2.
[ "In", "-", "place", "remove", "elements", "and", "attributes", "that", "are", "only", "valid", "in", "v2", "types", "." ]
3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/type_conversions.py#L633-L651
train
45,548
DataONEorg/d1_python
lib_common/src/d1_common/type_conversions.py
strip_system_metadata
def strip_system_metadata(etree_obj): """In-place remove elements and attributes that are only valid in v2 types from v1 System Metadata. Args: etree_obj: ElementTree ElementTree holding a v1 SystemMetadata. """ for series_id_el in etree_obj.findall('seriesId'): etree_obj.remove(series_id_el) for media_type_el in etree_obj.findall('mediaType'): etree_obj.remove(media_type_el) for file_name_el in etree_obj.findall('fileName'): etree_obj.remove(file_name_el)
python
def strip_system_metadata(etree_obj): """In-place remove elements and attributes that are only valid in v2 types from v1 System Metadata. Args: etree_obj: ElementTree ElementTree holding a v1 SystemMetadata. """ for series_id_el in etree_obj.findall('seriesId'): etree_obj.remove(series_id_el) for media_type_el in etree_obj.findall('mediaType'): etree_obj.remove(media_type_el) for file_name_el in etree_obj.findall('fileName'): etree_obj.remove(file_name_el)
[ "def", "strip_system_metadata", "(", "etree_obj", ")", ":", "for", "series_id_el", "in", "etree_obj", ".", "findall", "(", "'seriesId'", ")", ":", "etree_obj", ".", "remove", "(", "series_id_el", ")", "for", "media_type_el", "in", "etree_obj", ".", "findall", ...
In-place remove elements and attributes that are only valid in v2 types from v1 System Metadata. Args: etree_obj: ElementTree ElementTree holding a v1 SystemMetadata.
[ "In", "-", "place", "remove", "elements", "and", "attributes", "that", "are", "only", "valid", "in", "v2", "types", "from", "v1", "System", "Metadata", "." ]
3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/type_conversions.py#L654-L666
train
45,549
DataONEorg/d1_python
gmn/src/d1_gmn/app/management/commands/process_replication_queue.py
ReplicationQueueProcessor._create_replica
def _create_replica(self, sysmeta_pyxb, sciobj_bytestream): """GMN handles replicas differently from native objects, with the main differences being related to handling of restrictions related to revision chains and SIDs. So this create sequence differs significantly from the regular one that is accessed through MNStorage.create(). """ pid = d1_common.xml.get_req_val(sysmeta_pyxb.identifier) self._assert_is_pid_of_local_unprocessed_replica(pid) self._check_and_create_replica_revision(sysmeta_pyxb, "obsoletes") self._check_and_create_replica_revision(sysmeta_pyxb, "obsoletedBy") sciobj_url = d1_gmn.app.sciobj_store.get_rel_sciobj_file_url_by_pid(pid) sciobj_model = d1_gmn.app.sysmeta.create_or_update(sysmeta_pyxb, sciobj_url) self._store_science_object_bytes(pid, sciobj_bytestream) d1_gmn.app.event_log.create_log_entry( sciobj_model, "create", "0.0.0.0", "[replica]", "[replica]" )
python
def _create_replica(self, sysmeta_pyxb, sciobj_bytestream): """GMN handles replicas differently from native objects, with the main differences being related to handling of restrictions related to revision chains and SIDs. So this create sequence differs significantly from the regular one that is accessed through MNStorage.create(). """ pid = d1_common.xml.get_req_val(sysmeta_pyxb.identifier) self._assert_is_pid_of_local_unprocessed_replica(pid) self._check_and_create_replica_revision(sysmeta_pyxb, "obsoletes") self._check_and_create_replica_revision(sysmeta_pyxb, "obsoletedBy") sciobj_url = d1_gmn.app.sciobj_store.get_rel_sciobj_file_url_by_pid(pid) sciobj_model = d1_gmn.app.sysmeta.create_or_update(sysmeta_pyxb, sciobj_url) self._store_science_object_bytes(pid, sciobj_bytestream) d1_gmn.app.event_log.create_log_entry( sciobj_model, "create", "0.0.0.0", "[replica]", "[replica]" )
[ "def", "_create_replica", "(", "self", ",", "sysmeta_pyxb", ",", "sciobj_bytestream", ")", ":", "pid", "=", "d1_common", ".", "xml", ".", "get_req_val", "(", "sysmeta_pyxb", ".", "identifier", ")", "self", ".", "_assert_is_pid_of_local_unprocessed_replica", "(", "...
GMN handles replicas differently from native objects, with the main differences being related to handling of restrictions related to revision chains and SIDs. So this create sequence differs significantly from the regular one that is accessed through MNStorage.create().
[ "GMN", "handles", "replicas", "differently", "from", "native", "objects", "with", "the", "main", "differences", "being", "related", "to", "handling", "of", "restrictions", "related", "to", "revision", "chains", "and", "SIDs", "." ]
3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/gmn/src/d1_gmn/app/management/commands/process_replication_queue.py#L228-L246
train
45,550
DataONEorg/d1_python
gmn/src/d1_gmn/app/management/commands/import.py
Command.restricted_import
async def restricted_import(self, async_client, node_type): """Import only the Science Objects specified by a text file. The file must be UTF-8 encoded and contain one PIDs or SIDs per line. """ item_task_name = "Importing objects" pid_path = self.options['pid_path'] if not os.path.exists(pid_path): raise ConnectionError('File does not exist: {}'.format(pid_path)) with open(pid_path, encoding='UTF-8') as pid_file: self.progress_logger.start_task_type( item_task_name, len(pid_file.readlines()) ) pid_file.seek(0) for pid in pid_file.readlines(): pid = pid.strip() self.progress_logger.start_task(item_task_name) # Ignore any blank lines in the file if not pid: continue await self.import_aggregated(async_client, pid) self.progress_logger.end_task_type(item_task_name)
python
async def restricted_import(self, async_client, node_type): """Import only the Science Objects specified by a text file. The file must be UTF-8 encoded and contain one PIDs or SIDs per line. """ item_task_name = "Importing objects" pid_path = self.options['pid_path'] if not os.path.exists(pid_path): raise ConnectionError('File does not exist: {}'.format(pid_path)) with open(pid_path, encoding='UTF-8') as pid_file: self.progress_logger.start_task_type( item_task_name, len(pid_file.readlines()) ) pid_file.seek(0) for pid in pid_file.readlines(): pid = pid.strip() self.progress_logger.start_task(item_task_name) # Ignore any blank lines in the file if not pid: continue await self.import_aggregated(async_client, pid) self.progress_logger.end_task_type(item_task_name)
[ "async", "def", "restricted_import", "(", "self", ",", "async_client", ",", "node_type", ")", ":", "item_task_name", "=", "\"Importing objects\"", "pid_path", "=", "self", ".", "options", "[", "'pid_path'", "]", "if", "not", "os", ".", "path", ".", "exists", ...
Import only the Science Objects specified by a text file. The file must be UTF-8 encoded and contain one PIDs or SIDs per line.
[ "Import", "only", "the", "Science", "Objects", "specified", "by", "a", "text", "file", "." ]
3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/gmn/src/d1_gmn/app/management/commands/import.py#L261-L289
train
45,551
DataONEorg/d1_python
gmn/src/d1_gmn/app/management/commands/import.py
Command.get_object_proxy_location
async def get_object_proxy_location(self, client, pid): """If object is proxied, return the proxy location URL. If object is local, return None. """ try: return (await client.describe(pid)).get("DataONE-Proxy") except d1_common.types.exceptions.DataONEException: # Workaround for older GMNs that return 500 instead of 404 for describe() pass
python
async def get_object_proxy_location(self, client, pid): """If object is proxied, return the proxy location URL. If object is local, return None. """ try: return (await client.describe(pid)).get("DataONE-Proxy") except d1_common.types.exceptions.DataONEException: # Workaround for older GMNs that return 500 instead of 404 for describe() pass
[ "async", "def", "get_object_proxy_location", "(", "self", ",", "client", ",", "pid", ")", ":", "try", ":", "return", "(", "await", "client", ".", "describe", "(", "pid", ")", ")", ".", "get", "(", "\"DataONE-Proxy\"", ")", "except", "d1_common", ".", "ty...
If object is proxied, return the proxy location URL. If object is local, return None.
[ "If", "object", "is", "proxied", "return", "the", "proxy", "location", "URL", "." ]
3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/gmn/src/d1_gmn/app/management/commands/import.py#L447-L457
train
45,552
DataONEorg/d1_python
gmn/src/d1_gmn/app/management/commands/import.py
Command.probe_node_type_major
async def probe_node_type_major(self, client): """Determine if import source node is a CN or MN and which major version API to use.""" try: node_pyxb = await self.get_node_doc(client) except d1_common.types.exceptions.DataONEException as e: raise django.core.management.base.CommandError( "Could not find a functional CN or MN at the provided BaseURL. " 'base_url="{}" error="{}"'.format( self.options["baseurl"], e.friendly_format() ) ) is_cn = d1_common.type_conversions.pyxb_get_type_name(node_pyxb) == "NodeList" if is_cn: self.assert_is_known_node_id( node_pyxb, django.conf.settings.NODE_IDENTIFIER ) self._logger.info( "Importing from CN: {}. filtered on MN: {}".format( d1_common.xml.get_req_val( self.find_node(node_pyxb, self.options["baseurl"]).identifier ), django.conf.settings.NODE_IDENTIFIER, ) ) return "cn", "v2" else: self._logger.info( "Importing from MN: {}".format( d1_common.xml.get_req_val(node_pyxb.identifier) ) ) return "mn", self.find_node_api_version(node_pyxb)
python
async def probe_node_type_major(self, client): """Determine if import source node is a CN or MN and which major version API to use.""" try: node_pyxb = await self.get_node_doc(client) except d1_common.types.exceptions.DataONEException as e: raise django.core.management.base.CommandError( "Could not find a functional CN or MN at the provided BaseURL. " 'base_url="{}" error="{}"'.format( self.options["baseurl"], e.friendly_format() ) ) is_cn = d1_common.type_conversions.pyxb_get_type_name(node_pyxb) == "NodeList" if is_cn: self.assert_is_known_node_id( node_pyxb, django.conf.settings.NODE_IDENTIFIER ) self._logger.info( "Importing from CN: {}. filtered on MN: {}".format( d1_common.xml.get_req_val( self.find_node(node_pyxb, self.options["baseurl"]).identifier ), django.conf.settings.NODE_IDENTIFIER, ) ) return "cn", "v2" else: self._logger.info( "Importing from MN: {}".format( d1_common.xml.get_req_val(node_pyxb.identifier) ) ) return "mn", self.find_node_api_version(node_pyxb)
[ "async", "def", "probe_node_type_major", "(", "self", ",", "client", ")", ":", "try", ":", "node_pyxb", "=", "await", "self", ".", "get_node_doc", "(", "client", ")", "except", "d1_common", ".", "types", ".", "exceptions", ".", "DataONEException", "as", "e",...
Determine if import source node is a CN or MN and which major version API to use.
[ "Determine", "if", "import", "source", "node", "is", "a", "CN", "or", "MN", "and", "which", "major", "version", "API", "to", "use", "." ]
3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/gmn/src/d1_gmn/app/management/commands/import.py#L583-L617
train
45,553
DataONEorg/d1_python
gmn/src/d1_gmn/app/management/commands/import.py
Command.assert_is_known_node_id
def assert_is_known_node_id(self, node_list_pyxb, node_id): """When importing from a CN, ensure that the NodeID which the ObjectList will be filtered by is known to the CN.""" node_pyxb = self.find_node_by_id(node_list_pyxb, node_id) assert node_pyxb is not None, ( "The NodeID of this GMN instance is unknown to the CN at the provided BaseURL. " 'node_id="{}" base_url="{}"'.format(node_id, self.options["baseurl"]) )
python
def assert_is_known_node_id(self, node_list_pyxb, node_id): """When importing from a CN, ensure that the NodeID which the ObjectList will be filtered by is known to the CN.""" node_pyxb = self.find_node_by_id(node_list_pyxb, node_id) assert node_pyxb is not None, ( "The NodeID of this GMN instance is unknown to the CN at the provided BaseURL. " 'node_id="{}" base_url="{}"'.format(node_id, self.options["baseurl"]) )
[ "def", "assert_is_known_node_id", "(", "self", ",", "node_list_pyxb", ",", "node_id", ")", ":", "node_pyxb", "=", "self", ".", "find_node_by_id", "(", "node_list_pyxb", ",", "node_id", ")", "assert", "node_pyxb", "is", "not", "None", ",", "(", "\"The NodeID of t...
When importing from a CN, ensure that the NodeID which the ObjectList will be filtered by is known to the CN.
[ "When", "importing", "from", "a", "CN", "ensure", "that", "the", "NodeID", "which", "the", "ObjectList", "will", "be", "filtered", "by", "is", "known", "to", "the", "CN", "." ]
3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/gmn/src/d1_gmn/app/management/commands/import.py#L629-L636
train
45,554
DataONEorg/d1_python
gmn/src/d1_gmn/app/management/commands/import.py
Command.find_node_api_version
def find_node_api_version(self, node_pyxb): """Find the highest API major version supported by node.""" max_major = 0 for s in node_pyxb.services.service: max_major = max(max_major, int(s.version[1:])) return max_major
python
def find_node_api_version(self, node_pyxb): """Find the highest API major version supported by node.""" max_major = 0 for s in node_pyxb.services.service: max_major = max(max_major, int(s.version[1:])) return max_major
[ "def", "find_node_api_version", "(", "self", ",", "node_pyxb", ")", ":", "max_major", "=", "0", "for", "s", "in", "node_pyxb", ".", "services", ".", "service", ":", "max_major", "=", "max", "(", "max_major", ",", "int", "(", "s", ".", "version", "[", "...
Find the highest API major version supported by node.
[ "Find", "the", "highest", "API", "major", "version", "supported", "by", "node", "." ]
3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/gmn/src/d1_gmn/app/management/commands/import.py#L638-L643
train
45,555
genialis/resolwe
resolwe/flow/tasks.py
celery_run
def celery_run(data_id, runtime_dir, argv): """Run process executor. :param data_id: The id of the :class:`~resolwe.flow.models.Data` object to be processed. :param runtime_dir: The directory from which to run the executor. :param argv: The argument vector used to run the executor. :param verbosity: The logging verbosity level. """ subprocess.Popen( argv, cwd=runtime_dir, stdin=subprocess.DEVNULL ).wait()
python
def celery_run(data_id, runtime_dir, argv): """Run process executor. :param data_id: The id of the :class:`~resolwe.flow.models.Data` object to be processed. :param runtime_dir: The directory from which to run the executor. :param argv: The argument vector used to run the executor. :param verbosity: The logging verbosity level. """ subprocess.Popen( argv, cwd=runtime_dir, stdin=subprocess.DEVNULL ).wait()
[ "def", "celery_run", "(", "data_id", ",", "runtime_dir", ",", "argv", ")", ":", "subprocess", ".", "Popen", "(", "argv", ",", "cwd", "=", "runtime_dir", ",", "stdin", "=", "subprocess", ".", "DEVNULL", ")", ".", "wait", "(", ")" ]
Run process executor. :param data_id: The id of the :class:`~resolwe.flow.models.Data` object to be processed. :param runtime_dir: The directory from which to run the executor. :param argv: The argument vector used to run the executor. :param verbosity: The logging verbosity level.
[ "Run", "process", "executor", "." ]
f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/tasks.py#L22-L35
train
45,556
DataONEorg/d1_python
gmn/src/d1_gmn/app/sysmeta.py
archive_sciobj
def archive_sciobj(pid): """Set the status of an object to archived. Preconditions: - The object with the pid is verified to exist. - The object is not a replica. - The object is not archived. """ sciobj_model = d1_gmn.app.model_util.get_sci_model(pid) sciobj_model.is_archived = True sciobj_model.save() _update_modified_timestamp(sciobj_model)
python
def archive_sciobj(pid): """Set the status of an object to archived. Preconditions: - The object with the pid is verified to exist. - The object is not a replica. - The object is not archived. """ sciobj_model = d1_gmn.app.model_util.get_sci_model(pid) sciobj_model.is_archived = True sciobj_model.save() _update_modified_timestamp(sciobj_model)
[ "def", "archive_sciobj", "(", "pid", ")", ":", "sciobj_model", "=", "d1_gmn", ".", "app", ".", "model_util", ".", "get_sci_model", "(", "pid", ")", "sciobj_model", ".", "is_archived", "=", "True", "sciobj_model", ".", "save", "(", ")", "_update_modified_timest...
Set the status of an object to archived. Preconditions: - The object with the pid is verified to exist. - The object is not a replica. - The object is not archived.
[ "Set", "the", "status", "of", "an", "object", "to", "archived", "." ]
3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/gmn/src/d1_gmn/app/sysmeta.py#L48-L60
train
45,557
DataONEorg/d1_python
gmn/src/d1_gmn/app/sysmeta.py
create_or_update
def create_or_update(sysmeta_pyxb, sciobj_url=None): """Create or update database representation of a System Metadata object and closely related internal state. - If ``sciobj_url`` is not passed on create, storage in the internal sciobj store is assumed - If ``sciobj_url`` is passed on create, it can reference a location in the internal sciobj store, or an arbitrary location on disk, or a remote web server. See the sciobj_store module for more information - if ``sciobj_url`` is not passed on update, the sciobj location remains unchanged - If ``sciobj_url`` is passed on update, the sciobj location is updated Preconditions: - All values in ``sysmeta_pyxb`` must be valid for the operation being performed """ # TODO: Make sure that old sections are removed if not included in update. pid = d1_common.xml.get_req_val(sysmeta_pyxb.identifier) if sciobj_url is None: sciobj_url = d1_gmn.app.sciobj_store.get_rel_sciobj_file_url_by_pid(pid) try: sci_model = d1_gmn.app.model_util.get_sci_model(pid) except d1_gmn.app.models.ScienceObject.DoesNotExist: sci_model = d1_gmn.app.models.ScienceObject() sci_model.pid = d1_gmn.app.did.get_or_create_did(pid) sci_model.url = sciobj_url sci_model.serial_version = sysmeta_pyxb.serialVersion sci_model.uploaded_timestamp = d1_common.date_time.normalize_datetime_to_utc( sysmeta_pyxb.dateUploaded ) _base_pyxb_to_model(sci_model, sysmeta_pyxb) sci_model.save() if _has_media_type_pyxb(sysmeta_pyxb): _media_type_pyxb_to_model(sci_model, sysmeta_pyxb) _access_policy_pyxb_to_model(sci_model, sysmeta_pyxb) if _has_replication_policy_pyxb(sysmeta_pyxb): _replication_policy_pyxb_to_model(sci_model, sysmeta_pyxb) replica_pyxb_to_model(sci_model, sysmeta_pyxb) revision_pyxb_to_model(sci_model, sysmeta_pyxb, pid) sci_model.save() return sci_model
python
def create_or_update(sysmeta_pyxb, sciobj_url=None): """Create or update database representation of a System Metadata object and closely related internal state. - If ``sciobj_url`` is not passed on create, storage in the internal sciobj store is assumed - If ``sciobj_url`` is passed on create, it can reference a location in the internal sciobj store, or an arbitrary location on disk, or a remote web server. See the sciobj_store module for more information - if ``sciobj_url`` is not passed on update, the sciobj location remains unchanged - If ``sciobj_url`` is passed on update, the sciobj location is updated Preconditions: - All values in ``sysmeta_pyxb`` must be valid for the operation being performed """ # TODO: Make sure that old sections are removed if not included in update. pid = d1_common.xml.get_req_val(sysmeta_pyxb.identifier) if sciobj_url is None: sciobj_url = d1_gmn.app.sciobj_store.get_rel_sciobj_file_url_by_pid(pid) try: sci_model = d1_gmn.app.model_util.get_sci_model(pid) except d1_gmn.app.models.ScienceObject.DoesNotExist: sci_model = d1_gmn.app.models.ScienceObject() sci_model.pid = d1_gmn.app.did.get_or_create_did(pid) sci_model.url = sciobj_url sci_model.serial_version = sysmeta_pyxb.serialVersion sci_model.uploaded_timestamp = d1_common.date_time.normalize_datetime_to_utc( sysmeta_pyxb.dateUploaded ) _base_pyxb_to_model(sci_model, sysmeta_pyxb) sci_model.save() if _has_media_type_pyxb(sysmeta_pyxb): _media_type_pyxb_to_model(sci_model, sysmeta_pyxb) _access_policy_pyxb_to_model(sci_model, sysmeta_pyxb) if _has_replication_policy_pyxb(sysmeta_pyxb): _replication_policy_pyxb_to_model(sci_model, sysmeta_pyxb) replica_pyxb_to_model(sci_model, sysmeta_pyxb) revision_pyxb_to_model(sci_model, sysmeta_pyxb, pid) sci_model.save() return sci_model
[ "def", "create_or_update", "(", "sysmeta_pyxb", ",", "sciobj_url", "=", "None", ")", ":", "# TODO: Make sure that old sections are removed if not included in update.", "pid", "=", "d1_common", ".", "xml", ".", "get_req_val", "(", "sysmeta_pyxb", ".", "identifier", ")", ...
Create or update database representation of a System Metadata object and closely related internal state. - If ``sciobj_url`` is not passed on create, storage in the internal sciobj store is assumed - If ``sciobj_url`` is passed on create, it can reference a location in the internal sciobj store, or an arbitrary location on disk, or a remote web server. See the sciobj_store module for more information - if ``sciobj_url`` is not passed on update, the sciobj location remains unchanged - If ``sciobj_url`` is passed on update, the sciobj location is updated Preconditions: - All values in ``sysmeta_pyxb`` must be valid for the operation being performed
[ "Create", "or", "update", "database", "representation", "of", "a", "System", "Metadata", "object", "and", "closely", "related", "internal", "state", "." ]
3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/gmn/src/d1_gmn/app/sysmeta.py#L78-L129
train
45,558
DataONEorg/d1_python
gmn/src/d1_gmn/app/sysmeta.py
_access_policy_pyxb_to_model
def _access_policy_pyxb_to_model(sci_model, sysmeta_pyxb): """Create or update the database representation of the sysmeta_pyxb access policy. If called without an access policy, any existing permissions on the object are removed and the access policy for the rights holder is recreated. Preconditions: - Each subject has been verified to a valid DataONE account. - Subject has changePermission for object. Postconditions: - The Permission and related tables contain the new access policy. Notes: - There can be multiple rules in a policy and each rule can contain multiple subjects. So there are two ways that the same subject can be specified multiple times in a policy. If this happens, multiple, conflicting action levels may be provided for the subject. This is handled by checking for an existing row for the subject for this object and updating it if it contains a lower action level. The end result is that there is one row for each subject, for each object and this row contains the highest action level. """ _delete_existing_access_policy(sysmeta_pyxb) # Add an implicit allow rule with all permissions for the rights holder. allow_rights_holder = d1_common.types.dataoneTypes.AccessRule() permission = d1_common.types.dataoneTypes.Permission( d1_gmn.app.auth.CHANGEPERMISSION_STR ) allow_rights_holder.permission.append(permission) allow_rights_holder.subject.append( d1_common.xml.get_req_val(sysmeta_pyxb.rightsHolder) ) top_level = _get_highest_level_action_for_rule(allow_rights_holder) _insert_permission_rows(sci_model, allow_rights_holder, top_level) # Create db entries for all subjects for which permissions have been granted. if _has_access_policy_pyxb(sysmeta_pyxb): for allow_rule in sysmeta_pyxb.accessPolicy.allow: top_level = _get_highest_level_action_for_rule(allow_rule) _insert_permission_rows(sci_model, allow_rule, top_level)
python
def _access_policy_pyxb_to_model(sci_model, sysmeta_pyxb): """Create or update the database representation of the sysmeta_pyxb access policy. If called without an access policy, any existing permissions on the object are removed and the access policy for the rights holder is recreated. Preconditions: - Each subject has been verified to a valid DataONE account. - Subject has changePermission for object. Postconditions: - The Permission and related tables contain the new access policy. Notes: - There can be multiple rules in a policy and each rule can contain multiple subjects. So there are two ways that the same subject can be specified multiple times in a policy. If this happens, multiple, conflicting action levels may be provided for the subject. This is handled by checking for an existing row for the subject for this object and updating it if it contains a lower action level. The end result is that there is one row for each subject, for each object and this row contains the highest action level. """ _delete_existing_access_policy(sysmeta_pyxb) # Add an implicit allow rule with all permissions for the rights holder. allow_rights_holder = d1_common.types.dataoneTypes.AccessRule() permission = d1_common.types.dataoneTypes.Permission( d1_gmn.app.auth.CHANGEPERMISSION_STR ) allow_rights_holder.permission.append(permission) allow_rights_holder.subject.append( d1_common.xml.get_req_val(sysmeta_pyxb.rightsHolder) ) top_level = _get_highest_level_action_for_rule(allow_rights_holder) _insert_permission_rows(sci_model, allow_rights_holder, top_level) # Create db entries for all subjects for which permissions have been granted. if _has_access_policy_pyxb(sysmeta_pyxb): for allow_rule in sysmeta_pyxb.accessPolicy.allow: top_level = _get_highest_level_action_for_rule(allow_rule) _insert_permission_rows(sci_model, allow_rule, top_level)
[ "def", "_access_policy_pyxb_to_model", "(", "sci_model", ",", "sysmeta_pyxb", ")", ":", "_delete_existing_access_policy", "(", "sysmeta_pyxb", ")", "# Add an implicit allow rule with all permissions for the rights holder.", "allow_rights_holder", "=", "d1_common", ".", "types", "...
Create or update the database representation of the sysmeta_pyxb access policy. If called without an access policy, any existing permissions on the object are removed and the access policy for the rights holder is recreated. Preconditions: - Each subject has been verified to a valid DataONE account. - Subject has changePermission for object. Postconditions: - The Permission and related tables contain the new access policy. Notes: - There can be multiple rules in a policy and each rule can contain multiple subjects. So there are two ways that the same subject can be specified multiple times in a policy. If this happens, multiple, conflicting action levels may be provided for the subject. This is handled by checking for an existing row for the subject for this object and updating it if it contains a lower action level. The end result is that there is one row for each subject, for each object and this row contains the highest action level.
[ "Create", "or", "update", "the", "database", "representation", "of", "the", "sysmeta_pyxb", "access", "policy", "." ]
3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/gmn/src/d1_gmn/app/sysmeta.py#L282-L321
train
45,559
DataONEorg/d1_python
lib_common/src/d1_common/cert/view_subject_info.py
deserialize_subject_info
def deserialize_subject_info(subject_info_xml_path): """Deserialize a SubjectInfo XML file to a PyXB object.""" try: with open(subject_info_xml_path) as f: return d1_common.xml.deserialize(f.read()) except ValueError as e: raise d1_common.types.exceptions.InvalidToken( 0, 'Could not deserialize SubjectInfo. subject_info="{}", error="{}"'.format( subject_info_xml_path, str(e) ), )
python
def deserialize_subject_info(subject_info_xml_path): """Deserialize a SubjectInfo XML file to a PyXB object.""" try: with open(subject_info_xml_path) as f: return d1_common.xml.deserialize(f.read()) except ValueError as e: raise d1_common.types.exceptions.InvalidToken( 0, 'Could not deserialize SubjectInfo. subject_info="{}", error="{}"'.format( subject_info_xml_path, str(e) ), )
[ "def", "deserialize_subject_info", "(", "subject_info_xml_path", ")", ":", "try", ":", "with", "open", "(", "subject_info_xml_path", ")", "as", "f", ":", "return", "d1_common", ".", "xml", ".", "deserialize", "(", "f", ".", "read", "(", ")", ")", "except", ...
Deserialize a SubjectInfo XML file to a PyXB object.
[ "Deserialize", "a", "SubjectInfo", "XML", "file", "to", "a", "PyXB", "object", "." ]
3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/cert/view_subject_info.py#L47-L58
train
45,560
DataONEorg/d1_python
lib_client/src/d1_client/session.py
Session.HEAD
def HEAD(self, rest_path_list, **kwargs): """Send a HEAD request. See requests.sessions.request for optional parameters. :returns: Response object """ kwargs.setdefault("allow_redirects", False) return self._request("HEAD", rest_path_list, **kwargs)
python
def HEAD(self, rest_path_list, **kwargs): """Send a HEAD request. See requests.sessions.request for optional parameters. :returns: Response object """ kwargs.setdefault("allow_redirects", False) return self._request("HEAD", rest_path_list, **kwargs)
[ "def", "HEAD", "(", "self", ",", "rest_path_list", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "\"allow_redirects\"", ",", "False", ")", "return", "self", ".", "_request", "(", "\"HEAD\"", ",", "rest_path_list", ",", "*", "*", "k...
Send a HEAD request. See requests.sessions.request for optional parameters. :returns: Response object
[ "Send", "a", "HEAD", "request", ".", "See", "requests", ".", "sessions", ".", "request", "for", "optional", "parameters", "." ]
3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_client/src/d1_client/session.py#L191-L198
train
45,561
DataONEorg/d1_python
lib_client/src/d1_client/session.py
Session.get_curl_command_line
def get_curl_command_line(self, method, url, **kwargs): """Get request as cURL command line for debugging.""" if kwargs.get("query"): url = "{}?{}".format(url, d1_common.url.urlencode(kwargs["query"])) curl_list = ["curl"] if method.lower() == "head": curl_list.append("--head") else: curl_list.append("-X {}".format(method)) for k, v in sorted(list(kwargs["headers"].items())): curl_list.append('-H "{}: {}"'.format(k, v)) curl_list.append("{}".format(url)) return " ".join(curl_list)
python
def get_curl_command_line(self, method, url, **kwargs): """Get request as cURL command line for debugging.""" if kwargs.get("query"): url = "{}?{}".format(url, d1_common.url.urlencode(kwargs["query"])) curl_list = ["curl"] if method.lower() == "head": curl_list.append("--head") else: curl_list.append("-X {}".format(method)) for k, v in sorted(list(kwargs["headers"].items())): curl_list.append('-H "{}: {}"'.format(k, v)) curl_list.append("{}".format(url)) return " ".join(curl_list)
[ "def", "get_curl_command_line", "(", "self", ",", "method", ",", "url", ",", "*", "*", "kwargs", ")", ":", "if", "kwargs", ".", "get", "(", "\"query\"", ")", ":", "url", "=", "\"{}?{}\"", ".", "format", "(", "url", ",", "d1_common", ".", "url", ".", ...
Get request as cURL command line for debugging.
[ "Get", "request", "as", "cURL", "command", "line", "for", "debugging", "." ]
3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_client/src/d1_client/session.py#L252-L264
train
45,562
DataONEorg/d1_python
lib_client/src/d1_client/session.py
Session.dump_request_and_response
def dump_request_and_response(self, response): """Return a string containing a nicely formatted representation of the request and response objects for logging and debugging. - Note: Does not work if the request or response body is a MultipartEncoder object. """ if response.reason is None: response.reason = "<unknown>" return d1_client.util.normalize_request_response_dump( requests_toolbelt.utils.dump.dump_response(response) )
python
def dump_request_and_response(self, response): """Return a string containing a nicely formatted representation of the request and response objects for logging and debugging. - Note: Does not work if the request or response body is a MultipartEncoder object. """ if response.reason is None: response.reason = "<unknown>" return d1_client.util.normalize_request_response_dump( requests_toolbelt.utils.dump.dump_response(response) )
[ "def", "dump_request_and_response", "(", "self", ",", "response", ")", ":", "if", "response", ".", "reason", "is", "None", ":", "response", ".", "reason", "=", "\"<unknown>\"", "return", "d1_client", ".", "util", ".", "normalize_request_response_dump", "(", "req...
Return a string containing a nicely formatted representation of the request and response objects for logging and debugging. - Note: Does not work if the request or response body is a MultipartEncoder object.
[ "Return", "a", "string", "containing", "a", "nicely", "formatted", "representation", "of", "the", "request", "and", "response", "objects", "for", "logging", "and", "debugging", "." ]
3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_client/src/d1_client/session.py#L266-L278
train
45,563
DataONEorg/d1_python
lib_client/src/d1_client/session.py
Session._timeout_to_float
def _timeout_to_float(self, timeout): """Convert timeout to float. Return None if timeout is None, 0 or 0.0. timeout=None disables timeouts in Requests. """ if timeout is not None: try: timeout_float = float(timeout) except ValueError: raise ValueError( 'timeout_sec must be a valid number or None. timeout="{}"'.format( timeout ) ) if timeout_float: return timeout_float
python
def _timeout_to_float(self, timeout): """Convert timeout to float. Return None if timeout is None, 0 or 0.0. timeout=None disables timeouts in Requests. """ if timeout is not None: try: timeout_float = float(timeout) except ValueError: raise ValueError( 'timeout_sec must be a valid number or None. timeout="{}"'.format( timeout ) ) if timeout_float: return timeout_float
[ "def", "_timeout_to_float", "(", "self", ",", "timeout", ")", ":", "if", "timeout", "is", "not", "None", ":", "try", ":", "timeout_float", "=", "float", "(", "timeout", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'timeout_sec must be a valid...
Convert timeout to float. Return None if timeout is None, 0 or 0.0. timeout=None disables timeouts in Requests.
[ "Convert", "timeout", "to", "float", "." ]
3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_client/src/d1_client/session.py#L350-L367
train
45,564
DataONEorg/d1_python
dev_tools/src/d1_dev/src-print-redbaron-tree.py
main
def main(): """Print the RedBaron syntax tree for a Python module.""" parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter ) parser.add_argument("path", help="Python module path") args = parser.parse_args() r = d1_dev.util.redbaron_module_path_to_tree(args.path) print(r.help(True))
python
def main(): """Print the RedBaron syntax tree for a Python module.""" parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter ) parser.add_argument("path", help="Python module path") args = parser.parse_args() r = d1_dev.util.redbaron_module_path_to_tree(args.path) print(r.help(True))
[ "def", "main", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "__doc__", ",", "formatter_class", "=", "argparse", ".", "RawDescriptionHelpFormatter", ")", "parser", ".", "add_argument", "(", "\"path\"", ",", "help", "...
Print the RedBaron syntax tree for a Python module.
[ "Print", "the", "RedBaron", "syntax", "tree", "for", "a", "Python", "module", "." ]
3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/dev_tools/src/d1_dev/src-print-redbaron-tree.py#L27-L36
train
45,565
DataONEorg/d1_python
lib_common/src/d1_common/utils/filesystem.py
abs_path_from_base
def abs_path_from_base(base_path, rel_path): """Join a base and a relative path and return an absolute path to the resulting location. Args: base_path: str Relative or absolute path to prepend to ``rel_path``. rel_path: str Path relative to the location of the module file from which this function is called. Returns: str : Absolute path to the location specified by ``rel_path``. """ # noinspection PyProtectedMember return os.path.abspath( os.path.join( os.path.dirname(sys._getframe(1).f_code.co_filename), base_path, rel_path ) )
python
def abs_path_from_base(base_path, rel_path): """Join a base and a relative path and return an absolute path to the resulting location. Args: base_path: str Relative or absolute path to prepend to ``rel_path``. rel_path: str Path relative to the location of the module file from which this function is called. Returns: str : Absolute path to the location specified by ``rel_path``. """ # noinspection PyProtectedMember return os.path.abspath( os.path.join( os.path.dirname(sys._getframe(1).f_code.co_filename), base_path, rel_path ) )
[ "def", "abs_path_from_base", "(", "base_path", ",", "rel_path", ")", ":", "# noinspection PyProtectedMember", "return", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "sys", ".", "_getfr...
Join a base and a relative path and return an absolute path to the resulting location. Args: base_path: str Relative or absolute path to prepend to ``rel_path``. rel_path: str Path relative to the location of the module file from which this function is called. Returns: str : Absolute path to the location specified by ``rel_path``.
[ "Join", "a", "base", "and", "a", "relative", "path", "and", "return", "an", "absolute", "path", "to", "the", "resulting", "location", "." ]
3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/utils/filesystem.py#L92-L112
train
45,566
DataONEorg/d1_python
lib_common/src/d1_common/utils/filesystem.py
abs_path
def abs_path(rel_path): """Convert a path that is relative to the module from which this function is called, to an absolute path. Args: rel_path: str Path relative to the location of the module file from which this function is called. Returns: str : Absolute path to the location specified by ``rel_path``. """ # noinspection PyProtectedMember return os.path.abspath( os.path.join(os.path.dirname(sys._getframe(1).f_code.co_filename), rel_path) )
python
def abs_path(rel_path): """Convert a path that is relative to the module from which this function is called, to an absolute path. Args: rel_path: str Path relative to the location of the module file from which this function is called. Returns: str : Absolute path to the location specified by ``rel_path``. """ # noinspection PyProtectedMember return os.path.abspath( os.path.join(os.path.dirname(sys._getframe(1).f_code.co_filename), rel_path) )
[ "def", "abs_path", "(", "rel_path", ")", ":", "# noinspection PyProtectedMember", "return", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "sys", ".", "_getframe", "(", "1", ")", "."...
Convert a path that is relative to the module from which this function is called, to an absolute path. Args: rel_path: str Path relative to the location of the module file from which this function is called. Returns: str : Absolute path to the location specified by ``rel_path``.
[ "Convert", "a", "path", "that", "is", "relative", "to", "the", "module", "from", "which", "this", "function", "is", "called", "to", "an", "absolute", "path", "." ]
3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/utils/filesystem.py#L115-L130
train
45,567
DataONEorg/d1_python
lib_common/src/d1_common/wrap/simple_xml.py
SimpleXMLWrapper.get_attr_value
def get_attr_value(self, attr_key, el_idx=0): """Return the value of the selected attribute in the selected element. Args: attr_key : str Name of attribute for which to search el_idx : int Index of element to use in the event that there are multiple sibling elements with the same name. Returns: str : Value of the selected attribute in the selected element. """ return self.get_element_by_attr_key(attr_key, el_idx).attrib[attr_key]
python
def get_attr_value(self, attr_key, el_idx=0): """Return the value of the selected attribute in the selected element. Args: attr_key : str Name of attribute for which to search el_idx : int Index of element to use in the event that there are multiple sibling elements with the same name. Returns: str : Value of the selected attribute in the selected element. """ return self.get_element_by_attr_key(attr_key, el_idx).attrib[attr_key]
[ "def", "get_attr_value", "(", "self", ",", "attr_key", ",", "el_idx", "=", "0", ")", ":", "return", "self", ".", "get_element_by_attr_key", "(", "attr_key", ",", "el_idx", ")", ".", "attrib", "[", "attr_key", "]" ]
Return the value of the selected attribute in the selected element. Args: attr_key : str Name of attribute for which to search el_idx : int Index of element to use in the event that there are multiple sibling elements with the same name. Returns: str : Value of the selected attribute in the selected element.
[ "Return", "the", "value", "of", "the", "selected", "attribute", "in", "the", "selected", "element", "." ]
3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/wrap/simple_xml.py#L308-L323
train
45,568
DataONEorg/d1_python
lib_common/src/d1_common/wrap/simple_xml.py
SimpleXMLWrapper.set_attr_text
def set_attr_text(self, attr_key, attr_val, el_idx=0): """Set the value of the selected attribute of the selected element. Args: attr_key : str Name of attribute for which to search attr_val : str Text to set for the attribute. el_idx : int Index of element to use in the event that there are multiple sibling elements with the same name. """ self.get_element_by_attr_key(attr_key, el_idx).attrib[attr_key] = attr_val
python
def set_attr_text(self, attr_key, attr_val, el_idx=0): """Set the value of the selected attribute of the selected element. Args: attr_key : str Name of attribute for which to search attr_val : str Text to set for the attribute. el_idx : int Index of element to use in the event that there are multiple sibling elements with the same name. """ self.get_element_by_attr_key(attr_key, el_idx).attrib[attr_key] = attr_val
[ "def", "set_attr_text", "(", "self", ",", "attr_key", ",", "attr_val", ",", "el_idx", "=", "0", ")", ":", "self", ".", "get_element_by_attr_key", "(", "attr_key", ",", "el_idx", ")", ".", "attrib", "[", "attr_key", "]", "=", "attr_val" ]
Set the value of the selected attribute of the selected element. Args: attr_key : str Name of attribute for which to search attr_val : str Text to set for the attribute. el_idx : int Index of element to use in the event that there are multiple sibling elements with the same name.
[ "Set", "the", "value", "of", "the", "selected", "attribute", "of", "the", "selected", "element", "." ]
3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/wrap/simple_xml.py#L325-L340
train
45,569
DataONEorg/d1_python
lib_common/src/d1_common/wrap/simple_xml.py
SimpleXMLWrapper.get_element_dt
def get_element_dt(self, el_name, tz=None, el_idx=0): """Return the text of the selected element as a ``datetime.datetime`` object. The element text must be a ISO8601 formatted datetime Args: el_name : str Name of element to use. tz : datetime.tzinfo Timezone in which to return the datetime. - Without a timezone, other contextual information is required in order to determine the exact represented time. - If dt has timezone: The ``tz`` parameter is ignored. - If dt is naive (without timezone): The timezone is set to ``tz``. - ``tz=None``: Prevent naive dt from being set to a timezone. Without a timezone, other contextual information is required in order to determine the exact represented time. - ``tz=d1_common.date_time.UTC()``: Set naive dt to UTC. el_idx : int Index of element to use in the event that there are multiple sibling elements with the same name. Returns: datetime.datetime """ return iso8601.parse_date(self.get_element_by_name(el_name, el_idx).text, tz)
python
def get_element_dt(self, el_name, tz=None, el_idx=0): """Return the text of the selected element as a ``datetime.datetime`` object. The element text must be a ISO8601 formatted datetime Args: el_name : str Name of element to use. tz : datetime.tzinfo Timezone in which to return the datetime. - Without a timezone, other contextual information is required in order to determine the exact represented time. - If dt has timezone: The ``tz`` parameter is ignored. - If dt is naive (without timezone): The timezone is set to ``tz``. - ``tz=None``: Prevent naive dt from being set to a timezone. Without a timezone, other contextual information is required in order to determine the exact represented time. - ``tz=d1_common.date_time.UTC()``: Set naive dt to UTC. el_idx : int Index of element to use in the event that there are multiple sibling elements with the same name. Returns: datetime.datetime """ return iso8601.parse_date(self.get_element_by_name(el_name, el_idx).text, tz)
[ "def", "get_element_dt", "(", "self", ",", "el_name", ",", "tz", "=", "None", ",", "el_idx", "=", "0", ")", ":", "return", "iso8601", ".", "parse_date", "(", "self", ".", "get_element_by_name", "(", "el_name", ",", "el_idx", ")", ".", "text", ",", "tz"...
Return the text of the selected element as a ``datetime.datetime`` object. The element text must be a ISO8601 formatted datetime Args: el_name : str Name of element to use. tz : datetime.tzinfo Timezone in which to return the datetime. - Without a timezone, other contextual information is required in order to determine the exact represented time. - If dt has timezone: The ``tz`` parameter is ignored. - If dt is naive (without timezone): The timezone is set to ``tz``. - ``tz=None``: Prevent naive dt from being set to a timezone. Without a timezone, other contextual information is required in order to determine the exact represented time. - ``tz=d1_common.date_time.UTC()``: Set naive dt to UTC. el_idx : int Index of element to use in the event that there are multiple sibling elements with the same name. Returns: datetime.datetime
[ "Return", "the", "text", "of", "the", "selected", "element", "as", "a", "datetime", ".", "datetime", "object", "." ]
3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/wrap/simple_xml.py#L344-L373
train
45,570
DataONEorg/d1_python
lib_common/src/d1_common/wrap/simple_xml.py
SimpleXMLWrapper.set_element_dt
def set_element_dt(self, el_name, dt, tz=None, el_idx=0): """Set the text of the selected element to an ISO8601 formatted datetime. Args: el_name : str Name of element to update. dt : datetime.datetime Date and time to set tz : datetime.tzinfo Timezone to set - Without a timezone, other contextual information is required in order to determine the exact represented time. - If dt has timezone: The ``tz`` parameter is ignored. - If dt is naive (without timezone): The timezone is set to ``tz``. - ``tz=None``: Prevent naive dt from being set to a timezone. Without a timezone, other contextual information is required in order to determine the exact represented time. - ``tz=d1_common.date_time.UTC()``: Set naive dt to UTC. el_idx : int Index of element to use in the event that there are multiple sibling elements with the same name. """ dt = d1_common.date_time.cast_naive_datetime_to_tz(dt, tz) self.get_element_by_name(el_name, el_idx).text = dt.isoformat()
python
def set_element_dt(self, el_name, dt, tz=None, el_idx=0): """Set the text of the selected element to an ISO8601 formatted datetime. Args: el_name : str Name of element to update. dt : datetime.datetime Date and time to set tz : datetime.tzinfo Timezone to set - Without a timezone, other contextual information is required in order to determine the exact represented time. - If dt has timezone: The ``tz`` parameter is ignored. - If dt is naive (without timezone): The timezone is set to ``tz``. - ``tz=None``: Prevent naive dt from being set to a timezone. Without a timezone, other contextual information is required in order to determine the exact represented time. - ``tz=d1_common.date_time.UTC()``: Set naive dt to UTC. el_idx : int Index of element to use in the event that there are multiple sibling elements with the same name. """ dt = d1_common.date_time.cast_naive_datetime_to_tz(dt, tz) self.get_element_by_name(el_name, el_idx).text = dt.isoformat()
[ "def", "set_element_dt", "(", "self", ",", "el_name", ",", "dt", ",", "tz", "=", "None", ",", "el_idx", "=", "0", ")", ":", "dt", "=", "d1_common", ".", "date_time", ".", "cast_naive_datetime_to_tz", "(", "dt", ",", "tz", ")", "self", ".", "get_element...
Set the text of the selected element to an ISO8601 formatted datetime. Args: el_name : str Name of element to update. dt : datetime.datetime Date and time to set tz : datetime.tzinfo Timezone to set - Without a timezone, other contextual information is required in order to determine the exact represented time. - If dt has timezone: The ``tz`` parameter is ignored. - If dt is naive (without timezone): The timezone is set to ``tz``. - ``tz=None``: Prevent naive dt from being set to a timezone. Without a timezone, other contextual information is required in order to determine the exact represented time. - ``tz=d1_common.date_time.UTC()``: Set naive dt to UTC. el_idx : int Index of element to use in the event that there are multiple sibling elements with the same name.
[ "Set", "the", "text", "of", "the", "selected", "element", "to", "an", "ISO8601", "formatted", "datetime", "." ]
3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/wrap/simple_xml.py#L375-L403
train
45,571
genialis/resolwe
resolwe/flow/models/functions.py
JsonGetPath.as_sql
def as_sql(self, compiler, connection): # pylint: disable=arguments-differ """Compile SQL for this function.""" sql, params = super().as_sql(compiler, connection) params.append(self.path) return sql, params
python
def as_sql(self, compiler, connection): # pylint: disable=arguments-differ """Compile SQL for this function.""" sql, params = super().as_sql(compiler, connection) params.append(self.path) return sql, params
[ "def", "as_sql", "(", "self", ",", "compiler", ",", "connection", ")", ":", "# pylint: disable=arguments-differ", "sql", ",", "params", "=", "super", "(", ")", ".", "as_sql", "(", "compiler", ",", "connection", ")", "params", ".", "append", "(", "self", "....
Compile SQL for this function.
[ "Compile", "SQL", "for", "this", "function", "." ]
f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/models/functions.py#L26-L30
train
45,572
genialis/resolwe
resolwe/flow/models/storage.py
StorageManager.with_json_path
def with_json_path(self, path, field=None): """Annotate Storage objects with a specific JSON path. :param path: Path to get inside the stored object, which can be either a list of path components or a comma-separated string :param field: Optional output field name """ if field is None: field = '_'.join(['json'] + json_path_components(path)) kwargs = {field: JsonGetPath('json', path)} return self.defer('json').annotate(**kwargs)
python
def with_json_path(self, path, field=None): """Annotate Storage objects with a specific JSON path. :param path: Path to get inside the stored object, which can be either a list of path components or a comma-separated string :param field: Optional output field name """ if field is None: field = '_'.join(['json'] + json_path_components(path)) kwargs = {field: JsonGetPath('json', path)} return self.defer('json').annotate(**kwargs)
[ "def", "with_json_path", "(", "self", ",", "path", ",", "field", "=", "None", ")", ":", "if", "field", "is", "None", ":", "field", "=", "'_'", ".", "join", "(", "[", "'json'", "]", "+", "json_path_components", "(", "path", ")", ")", "kwargs", "=", ...
Annotate Storage objects with a specific JSON path. :param path: Path to get inside the stored object, which can be either a list of path components or a comma-separated string :param field: Optional output field name
[ "Annotate", "Storage", "objects", "with", "a", "specific", "JSON", "path", "." ]
f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/models/storage.py#L13-L25
train
45,573
genialis/resolwe
resolwe/flow/models/storage.py
StorageManager.get_json_path
def get_json_path(self, path): """Return only a specific JSON path of Storage objects. :param path: Path to get inside the stored object, which can be either a list of path components or a comma-separated string """ return self.with_json_path(path, field='result').values_list('result', flat=True)
python
def get_json_path(self, path): """Return only a specific JSON path of Storage objects. :param path: Path to get inside the stored object, which can be either a list of path components or a comma-separated string """ return self.with_json_path(path, field='result').values_list('result', flat=True)
[ "def", "get_json_path", "(", "self", ",", "path", ")", ":", "return", "self", ".", "with_json_path", "(", "path", ",", "field", "=", "'result'", ")", ".", "values_list", "(", "'result'", ",", "flat", "=", "True", ")" ]
Return only a specific JSON path of Storage objects. :param path: Path to get inside the stored object, which can be either a list of path components or a comma-separated string
[ "Return", "only", "a", "specific", "JSON", "path", "of", "Storage", "objects", "." ]
f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/models/storage.py#L27-L34
train
45,574
genialis/resolwe
resolwe/flow/models/storage.py
LazyStorageJSON._get_storage
def _get_storage(self): """Load `json` field from `Storage` object.""" if self._json is None: self._json = Storage.objects.get(**self._kwargs).json
python
def _get_storage(self): """Load `json` field from `Storage` object.""" if self._json is None: self._json = Storage.objects.get(**self._kwargs).json
[ "def", "_get_storage", "(", "self", ")", ":", "if", "self", ".", "_json", "is", "None", ":", "self", ".", "_json", "=", "Storage", ".", "objects", ".", "get", "(", "*", "*", "self", ".", "_kwargs", ")", ".", "json" ]
Load `json` field from `Storage` object.
[ "Load", "json", "field", "from", "Storage", "object", "." ]
f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/models/storage.py#L58-L61
train
45,575
wilson-eft/wilson
wilson/run/smeft/smpar.py
m2Lambda_to_vMh2
def m2Lambda_to_vMh2(m2, Lambda, C): """Function to numerically determine the physical Higgs VEV and mass given the parameters of the Higgs potential.""" try: v = (sqrt(2 * m2 / Lambda) + 3 * m2**(3 / 2) / (sqrt(2) * Lambda**(5 / 2)) * C['phi']) except ValueError: v = 0 Mh2 = 2 * m2 * (1 - m2 / Lambda * (3 * C['phi'] - 4 * Lambda * C['phiBox'] + Lambda * C['phiD'])) return {'v': v, 'Mh2': Mh2}
python
def m2Lambda_to_vMh2(m2, Lambda, C): """Function to numerically determine the physical Higgs VEV and mass given the parameters of the Higgs potential.""" try: v = (sqrt(2 * m2 / Lambda) + 3 * m2**(3 / 2) / (sqrt(2) * Lambda**(5 / 2)) * C['phi']) except ValueError: v = 0 Mh2 = 2 * m2 * (1 - m2 / Lambda * (3 * C['phi'] - 4 * Lambda * C['phiBox'] + Lambda * C['phiD'])) return {'v': v, 'Mh2': Mh2}
[ "def", "m2Lambda_to_vMh2", "(", "m2", ",", "Lambda", ",", "C", ")", ":", "try", ":", "v", "=", "(", "sqrt", "(", "2", "*", "m2", "/", "Lambda", ")", "+", "3", "*", "m2", "**", "(", "3", "/", "2", ")", "/", "(", "sqrt", "(", "2", ")", "*",...
Function to numerically determine the physical Higgs VEV and mass given the parameters of the Higgs potential.
[ "Function", "to", "numerically", "determine", "the", "physical", "Higgs", "VEV", "and", "mass", "given", "the", "parameters", "of", "the", "Higgs", "potential", "." ]
4164f55ff663d4f668c6e2b4575fd41562662cc9
https://github.com/wilson-eft/wilson/blob/4164f55ff663d4f668c6e2b4575fd41562662cc9/wilson/run/smeft/smpar.py#L38-L48
train
45,576
wilson-eft/wilson
wilson/run/smeft/smpar.py
smeftpar
def smeftpar(scale, C, basis): """Get the running parameters in SMEFT.""" # start with a zero dict and update it with the input values MW = p['m_W'] # MZ = p['m_Z'] GF = p['GF'] Mh = p['m_h'] vb = sqrt(1 / sqrt(2) / GF) v = vb # TODO _d = vMh2_to_m2Lambda(v=v, Mh2=Mh**2, C=C) m2 = _d['m2'].real Lambda = _d['Lambda'].real gsbar = sqrt(4 * pi * p['alpha_s']) gs = (1 - C['phiG'] * (v**2)) * gsbar gbar = 2 * MW / v g = gbar * (1 - C['phiW'] * (v**2)) ebar = sqrt(4 * pi * p['alpha_e']) gp = get_gpbar(ebar, gbar, v, C) c = {} c['m2'] = m2 c['Lambda'] = Lambda c['g'] = g c['gp'] = gp c['gs'] = gs K = ckmutil.ckm.ckm_tree(p['Vus'], p['Vub'], p['Vcb'], p['delta']) if basis == 'Warsaw': Mu = K.conj().T @ np.diag([p['m_u'], p['m_c'], p['m_t']]) Md = np.diag([p['m_d'], p['m_s'], p['m_b']]) elif basis == 'Warsaw up': Mu = np.diag([p['m_u'], p['m_c'], p['m_t']]) Md = K @ np.diag([p['m_d'], p['m_s'], p['m_b']]) else: raise ValueError("Basis '{}' not supported".format(basis)) Me = np.diag([p['m_e'], p['m_mu'], p['m_tau']]) c['Gd'] = Md / (v / sqrt(2)) + C['dphi'] * (v**2) / 2 c['Gu'] = Mu / (v / sqrt(2)) + C['uphi'] * (v**2) / 2 c['Ge'] = Me / (v / sqrt(2)) + C['ephi'] * (v**2) / 2 return c
python
def smeftpar(scale, C, basis): """Get the running parameters in SMEFT.""" # start with a zero dict and update it with the input values MW = p['m_W'] # MZ = p['m_Z'] GF = p['GF'] Mh = p['m_h'] vb = sqrt(1 / sqrt(2) / GF) v = vb # TODO _d = vMh2_to_m2Lambda(v=v, Mh2=Mh**2, C=C) m2 = _d['m2'].real Lambda = _d['Lambda'].real gsbar = sqrt(4 * pi * p['alpha_s']) gs = (1 - C['phiG'] * (v**2)) * gsbar gbar = 2 * MW / v g = gbar * (1 - C['phiW'] * (v**2)) ebar = sqrt(4 * pi * p['alpha_e']) gp = get_gpbar(ebar, gbar, v, C) c = {} c['m2'] = m2 c['Lambda'] = Lambda c['g'] = g c['gp'] = gp c['gs'] = gs K = ckmutil.ckm.ckm_tree(p['Vus'], p['Vub'], p['Vcb'], p['delta']) if basis == 'Warsaw': Mu = K.conj().T @ np.diag([p['m_u'], p['m_c'], p['m_t']]) Md = np.diag([p['m_d'], p['m_s'], p['m_b']]) elif basis == 'Warsaw up': Mu = np.diag([p['m_u'], p['m_c'], p['m_t']]) Md = K @ np.diag([p['m_d'], p['m_s'], p['m_b']]) else: raise ValueError("Basis '{}' not supported".format(basis)) Me = np.diag([p['m_e'], p['m_mu'], p['m_tau']]) c['Gd'] = Md / (v / sqrt(2)) + C['dphi'] * (v**2) / 2 c['Gu'] = Mu / (v / sqrt(2)) + C['uphi'] * (v**2) / 2 c['Ge'] = Me / (v / sqrt(2)) + C['ephi'] * (v**2) / 2 return c
[ "def", "smeftpar", "(", "scale", ",", "C", ",", "basis", ")", ":", "# start with a zero dict and update it with the input values", "MW", "=", "p", "[", "'m_W'", "]", "# MZ = p['m_Z']", "GF", "=", "p", "[", "'GF'", "]", "Mh", "=", "p", "[", "'m_h'", "]", "v...
Get the running parameters in SMEFT.
[ "Get", "the", "running", "parameters", "in", "SMEFT", "." ]
4164f55ff663d4f668c6e2b4575fd41562662cc9
https://github.com/wilson-eft/wilson/blob/4164f55ff663d4f668c6e2b4575fd41562662cc9/wilson/run/smeft/smpar.py#L100-L137
train
45,577
wilson-eft/wilson
wilson/util/smeftutil.py
scale_8
def scale_8(b): """Translations necessary for class-8 coefficients to go from a basis with only non-redundant WCxf operators to a basis where the Wilson coefficients are symmetrized like the operators.""" a = np.array(b, copy=True, dtype=complex) for i in range(3): a[0, 0, 1, i] = 1/2 * b[0, 0, 1, i] a[0, 0, 2, i] = 1/2 * b[0, 0, 2, i] a[0, 1, 1, i] = 1/2 * b[0, 1, 1, i] a[0, 1, 2, i] = 2/3 * b[0, 1, 2, i] - 1/6 * b[0, 2, 1, i] - 1/6 * b[1, 0, 2, i] + 1/6 * b[1, 2, 0, i] a[0, 2, 1, i] = - (1/6) * b[0, 1, 2, i] + 2/3 * b[0, 2, 1, i] + 1/6 * b[1, 0, 2, i] + 1/3 * b[1, 2, 0, i] a[0, 2, 2, i] = 1/2 * b[0, 2, 2, i] a[1, 0, 2, i] = - (1/6) * b[0, 1, 2, i] + 1/6 * b[0, 2, 1, i] + 2/3 * b[1, 0, 2, i] - 1/6 * b[1, 2, 0, i] a[1, 1, 2, i] = 1/2 * b[1, 1, 2, i] a[1, 2, 0, i] = 1/6 * b[0, 1, 2, i] + 1/3 * b[0, 2, 1, i] - 1/6 * b[1, 0, 2, i] + 2/3 * b[1, 2, 0, i] a[1, 2, 2, i] = 1/2 * b[1, 2, 2, i] return a
python
def scale_8(b): """Translations necessary for class-8 coefficients to go from a basis with only non-redundant WCxf operators to a basis where the Wilson coefficients are symmetrized like the operators.""" a = np.array(b, copy=True, dtype=complex) for i in range(3): a[0, 0, 1, i] = 1/2 * b[0, 0, 1, i] a[0, 0, 2, i] = 1/2 * b[0, 0, 2, i] a[0, 1, 1, i] = 1/2 * b[0, 1, 1, i] a[0, 1, 2, i] = 2/3 * b[0, 1, 2, i] - 1/6 * b[0, 2, 1, i] - 1/6 * b[1, 0, 2, i] + 1/6 * b[1, 2, 0, i] a[0, 2, 1, i] = - (1/6) * b[0, 1, 2, i] + 2/3 * b[0, 2, 1, i] + 1/6 * b[1, 0, 2, i] + 1/3 * b[1, 2, 0, i] a[0, 2, 2, i] = 1/2 * b[0, 2, 2, i] a[1, 0, 2, i] = - (1/6) * b[0, 1, 2, i] + 1/6 * b[0, 2, 1, i] + 2/3 * b[1, 0, 2, i] - 1/6 * b[1, 2, 0, i] a[1, 1, 2, i] = 1/2 * b[1, 1, 2, i] a[1, 2, 0, i] = 1/6 * b[0, 1, 2, i] + 1/3 * b[0, 2, 1, i] - 1/6 * b[1, 0, 2, i] + 2/3 * b[1, 2, 0, i] a[1, 2, 2, i] = 1/2 * b[1, 2, 2, i] return a
[ "def", "scale_8", "(", "b", ")", ":", "a", "=", "np", ".", "array", "(", "b", ",", "copy", "=", "True", ",", "dtype", "=", "complex", ")", "for", "i", "in", "range", "(", "3", ")", ":", "a", "[", "0", ",", "0", ",", "1", ",", "i", "]", ...
Translations necessary for class-8 coefficients to go from a basis with only non-redundant WCxf operators to a basis where the Wilson coefficients are symmetrized like the operators.
[ "Translations", "necessary", "for", "class", "-", "8", "coefficients", "to", "go", "from", "a", "basis", "with", "only", "non", "-", "redundant", "WCxf", "operators", "to", "a", "basis", "where", "the", "Wilson", "coefficients", "are", "symmetrized", "like", ...
4164f55ff663d4f668c6e2b4575fd41562662cc9
https://github.com/wilson-eft/wilson/blob/4164f55ff663d4f668c6e2b4575fd41562662cc9/wilson/util/smeftutil.py#L546-L563
train
45,578
wilson-eft/wilson
wilson/util/smeftutil.py
arrays2wcxf
def arrays2wcxf(C): """Convert a dictionary with Wilson coefficient names as keys and numbers or numpy arrays as values to a dictionary with a Wilson coefficient name followed by underscore and numeric indices as keys and numbers as values. This is needed for the output in WCxf format.""" d = {} for k, v in C.items(): if np.shape(v) == () or np.shape(v) == (1,): d[k] = v else: ind = np.indices(v.shape).reshape(v.ndim, v.size).T for i in ind: name = k + '_' + ''.join([str(int(j) + 1) for j in i]) d[name] = v[tuple(i)] return d
python
def arrays2wcxf(C): """Convert a dictionary with Wilson coefficient names as keys and numbers or numpy arrays as values to a dictionary with a Wilson coefficient name followed by underscore and numeric indices as keys and numbers as values. This is needed for the output in WCxf format.""" d = {} for k, v in C.items(): if np.shape(v) == () or np.shape(v) == (1,): d[k] = v else: ind = np.indices(v.shape).reshape(v.ndim, v.size).T for i in ind: name = k + '_' + ''.join([str(int(j) + 1) for j in i]) d[name] = v[tuple(i)] return d
[ "def", "arrays2wcxf", "(", "C", ")", ":", "d", "=", "{", "}", "for", "k", ",", "v", "in", "C", ".", "items", "(", ")", ":", "if", "np", ".", "shape", "(", "v", ")", "==", "(", ")", "or", "np", ".", "shape", "(", "v", ")", "==", "(", "1"...
Convert a dictionary with Wilson coefficient names as keys and numbers or numpy arrays as values to a dictionary with a Wilson coefficient name followed by underscore and numeric indices as keys and numbers as values. This is needed for the output in WCxf format.
[ "Convert", "a", "dictionary", "with", "Wilson", "coefficient", "names", "as", "keys", "and", "numbers", "or", "numpy", "arrays", "as", "values", "to", "a", "dictionary", "with", "a", "Wilson", "coefficient", "name", "followed", "by", "underscore", "and", "nume...
4164f55ff663d4f668c6e2b4575fd41562662cc9
https://github.com/wilson-eft/wilson/blob/4164f55ff663d4f668c6e2b4575fd41562662cc9/wilson/util/smeftutil.py#L623-L637
train
45,579
wilson-eft/wilson
wilson/util/smeftutil.py
wcxf2arrays
def wcxf2arrays(d): """Convert a dictionary with a Wilson coefficient name followed by underscore and numeric indices as keys and numbers as values to a dictionary with Wilson coefficient names as keys and numbers or numpy arrays as values. This is needed for the parsing of input in WCxf format.""" C = {} for k, v in d.items(): name = k.split('_')[0] s = C_keys_shape[name] if s == 1: C[k] = v else: ind = k.split('_')[-1] if name not in C: C[name] = np.zeros(s, dtype=complex) C[name][tuple([int(i) - 1 for i in ind])] = v return C
python
def wcxf2arrays(d): """Convert a dictionary with a Wilson coefficient name followed by underscore and numeric indices as keys and numbers as values to a dictionary with Wilson coefficient names as keys and numbers or numpy arrays as values. This is needed for the parsing of input in WCxf format.""" C = {} for k, v in d.items(): name = k.split('_')[0] s = C_keys_shape[name] if s == 1: C[k] = v else: ind = k.split('_')[-1] if name not in C: C[name] = np.zeros(s, dtype=complex) C[name][tuple([int(i) - 1 for i in ind])] = v return C
[ "def", "wcxf2arrays", "(", "d", ")", ":", "C", "=", "{", "}", "for", "k", ",", "v", "in", "d", ".", "items", "(", ")", ":", "name", "=", "k", ".", "split", "(", "'_'", ")", "[", "0", "]", "s", "=", "C_keys_shape", "[", "name", "]", "if", ...
Convert a dictionary with a Wilson coefficient name followed by underscore and numeric indices as keys and numbers as values to a dictionary with Wilson coefficient names as keys and numbers or numpy arrays as values. This is needed for the parsing of input in WCxf format.
[ "Convert", "a", "dictionary", "with", "a", "Wilson", "coefficient", "name", "followed", "by", "underscore", "and", "numeric", "indices", "as", "keys", "and", "numbers", "as", "values", "to", "a", "dictionary", "with", "Wilson", "coefficient", "names", "as", "k...
4164f55ff663d4f668c6e2b4575fd41562662cc9
https://github.com/wilson-eft/wilson/blob/4164f55ff663d4f668c6e2b4575fd41562662cc9/wilson/util/smeftutil.py#L640-L657
train
45,580
wilson-eft/wilson
wilson/util/smeftutil.py
add_missing
def add_missing(C): """Add arrays with zeros for missing Wilson coefficient keys""" C_out = C.copy() for k in (set(WC_keys) - set(C.keys())): C_out[k] = np.zeros(C_keys_shape[k]) return C_out
python
def add_missing(C): """Add arrays with zeros for missing Wilson coefficient keys""" C_out = C.copy() for k in (set(WC_keys) - set(C.keys())): C_out[k] = np.zeros(C_keys_shape[k]) return C_out
[ "def", "add_missing", "(", "C", ")", ":", "C_out", "=", "C", ".", "copy", "(", ")", "for", "k", "in", "(", "set", "(", "WC_keys", ")", "-", "set", "(", "C", ".", "keys", "(", ")", ")", ")", ":", "C_out", "[", "k", "]", "=", "np", ".", "ze...
Add arrays with zeros for missing Wilson coefficient keys
[ "Add", "arrays", "with", "zeros", "for", "missing", "Wilson", "coefficient", "keys" ]
4164f55ff663d4f668c6e2b4575fd41562662cc9
https://github.com/wilson-eft/wilson/blob/4164f55ff663d4f668c6e2b4575fd41562662cc9/wilson/util/smeftutil.py#L660-L665
train
45,581
wilson-eft/wilson
wilson/util/smeftutil.py
C_array2dict
def C_array2dict(C): """Convert a 1D array containing C values to a dictionary.""" d = OrderedDict() i=0 for k in C_keys: s = C_keys_shape[k] if s == 1: j = i+1 d[k] = C[i] else: j = i \ + reduce(operator.mul, s, 1) d[k] = C[i:j].reshape(s) i = j return d
python
def C_array2dict(C): """Convert a 1D array containing C values to a dictionary.""" d = OrderedDict() i=0 for k in C_keys: s = C_keys_shape[k] if s == 1: j = i+1 d[k] = C[i] else: j = i \ + reduce(operator.mul, s, 1) d[k] = C[i:j].reshape(s) i = j return d
[ "def", "C_array2dict", "(", "C", ")", ":", "d", "=", "OrderedDict", "(", ")", "i", "=", "0", "for", "k", "in", "C_keys", ":", "s", "=", "C_keys_shape", "[", "k", "]", "if", "s", "==", "1", ":", "j", "=", "i", "+", "1", "d", "[", "k", "]", ...
Convert a 1D array containing C values to a dictionary.
[ "Convert", "a", "1D", "array", "containing", "C", "values", "to", "a", "dictionary", "." ]
4164f55ff663d4f668c6e2b4575fd41562662cc9
https://github.com/wilson-eft/wilson/blob/4164f55ff663d4f668c6e2b4575fd41562662cc9/wilson/util/smeftutil.py#L766-L780
train
45,582
wilson-eft/wilson
wilson/util/smeftutil.py
C_dict2array
def C_dict2array(C): """Convert an OrderedDict containing C values to a 1D array.""" return np.hstack([np.asarray(C[k]).ravel() for k in C_keys])
python
def C_dict2array(C): """Convert an OrderedDict containing C values to a 1D array.""" return np.hstack([np.asarray(C[k]).ravel() for k in C_keys])
[ "def", "C_dict2array", "(", "C", ")", ":", "return", "np", ".", "hstack", "(", "[", "np", ".", "asarray", "(", "C", "[", "k", "]", ")", ".", "ravel", "(", ")", "for", "k", "in", "C_keys", "]", ")" ]
Convert an OrderedDict containing C values to a 1D array.
[ "Convert", "an", "OrderedDict", "containing", "C", "values", "to", "a", "1D", "array", "." ]
4164f55ff663d4f668c6e2b4575fd41562662cc9
https://github.com/wilson-eft/wilson/blob/4164f55ff663d4f668c6e2b4575fd41562662cc9/wilson/util/smeftutil.py#L783-L785
train
45,583
wilson-eft/wilson
wilson/util/smeftutil.py
unscale_dict
def unscale_dict(C): """Undo the scaling applied in `scale_dict`.""" C_out = {k: _scale_dict[k] * v for k, v in C.items()} for k in C_symm_keys[8]: C_out['qqql'] = unscale_8(C_out['qqql']) return C_out
python
def unscale_dict(C): """Undo the scaling applied in `scale_dict`.""" C_out = {k: _scale_dict[k] * v for k, v in C.items()} for k in C_symm_keys[8]: C_out['qqql'] = unscale_8(C_out['qqql']) return C_out
[ "def", "unscale_dict", "(", "C", ")", ":", "C_out", "=", "{", "k", ":", "_scale_dict", "[", "k", "]", "*", "v", "for", "k", ",", "v", "in", "C", ".", "items", "(", ")", "}", "for", "k", "in", "C_symm_keys", "[", "8", "]", ":", "C_out", "[", ...
Undo the scaling applied in `scale_dict`.
[ "Undo", "the", "scaling", "applied", "in", "scale_dict", "." ]
4164f55ff663d4f668c6e2b4575fd41562662cc9
https://github.com/wilson-eft/wilson/blob/4164f55ff663d4f668c6e2b4575fd41562662cc9/wilson/util/smeftutil.py#L848-L853
train
45,584
wilson-eft/wilson
wilson/util/smeftutil.py
wcxf2arrays_symmetrized
def wcxf2arrays_symmetrized(d): """Convert a dictionary with a Wilson coefficient name followed by underscore and numeric indices as keys and numbers as values to a dictionary with Wilson coefficient names as keys and numbers or numpy arrays as values. In contrast to `wcxf2arrays`, here the numpy arrays fulfill the same symmetry relations as the operators (i.e. they contain redundant entries) and they do not contain undefined indices. Zero arrays are added for missing coefficients.""" C = wcxf2arrays(d) C = symmetrize_nonred(C) C = add_missing(C) return C
python
def wcxf2arrays_symmetrized(d): """Convert a dictionary with a Wilson coefficient name followed by underscore and numeric indices as keys and numbers as values to a dictionary with Wilson coefficient names as keys and numbers or numpy arrays as values. In contrast to `wcxf2arrays`, here the numpy arrays fulfill the same symmetry relations as the operators (i.e. they contain redundant entries) and they do not contain undefined indices. Zero arrays are added for missing coefficients.""" C = wcxf2arrays(d) C = symmetrize_nonred(C) C = add_missing(C) return C
[ "def", "wcxf2arrays_symmetrized", "(", "d", ")", ":", "C", "=", "wcxf2arrays", "(", "d", ")", "C", "=", "symmetrize_nonred", "(", "C", ")", "C", "=", "add_missing", "(", "C", ")", "return", "C" ]
Convert a dictionary with a Wilson coefficient name followed by underscore and numeric indices as keys and numbers as values to a dictionary with Wilson coefficient names as keys and numbers or numpy arrays as values. In contrast to `wcxf2arrays`, here the numpy arrays fulfill the same symmetry relations as the operators (i.e. they contain redundant entries) and they do not contain undefined indices. Zero arrays are added for missing coefficients.
[ "Convert", "a", "dictionary", "with", "a", "Wilson", "coefficient", "name", "followed", "by", "underscore", "and", "numeric", "indices", "as", "keys", "and", "numbers", "as", "values", "to", "a", "dictionary", "with", "Wilson", "coefficient", "names", "as", "k...
4164f55ff663d4f668c6e2b4575fd41562662cc9
https://github.com/wilson-eft/wilson/blob/4164f55ff663d4f668c6e2b4575fd41562662cc9/wilson/util/smeftutil.py#L856-L871
train
45,585
genialis/resolwe
resolwe/flow/signals.py
commit_signal
def commit_signal(data_id): """Nudge manager at the end of every Data object save event.""" if not getattr(settings, 'FLOW_MANAGER_DISABLE_AUTO_CALLS', False): immediate = getattr(settings, 'FLOW_MANAGER_SYNC_AUTO_CALLS', False) async_to_sync(manager.communicate)(data_id=data_id, save_settings=False, run_sync=immediate)
python
def commit_signal(data_id): """Nudge manager at the end of every Data object save event.""" if not getattr(settings, 'FLOW_MANAGER_DISABLE_AUTO_CALLS', False): immediate = getattr(settings, 'FLOW_MANAGER_SYNC_AUTO_CALLS', False) async_to_sync(manager.communicate)(data_id=data_id, save_settings=False, run_sync=immediate)
[ "def", "commit_signal", "(", "data_id", ")", ":", "if", "not", "getattr", "(", "settings", ",", "'FLOW_MANAGER_DISABLE_AUTO_CALLS'", ",", "False", ")", ":", "immediate", "=", "getattr", "(", "settings", ",", "'FLOW_MANAGER_SYNC_AUTO_CALLS'", ",", "False", ")", "...
Nudge manager at the end of every Data object save event.
[ "Nudge", "manager", "at", "the", "end", "of", "every", "Data", "object", "save", "event", "." ]
f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/signals.py#L21-L25
train
45,586
genialis/resolwe
resolwe/flow/signals.py
delete_entity
def delete_entity(sender, instance, **kwargs): """Delete Entity when last Data object is deleted.""" # 1 means that the last Data object is going to be deleted. Entity.objects.annotate(num_data=Count('data')).filter(data=instance, num_data=1).delete()
python
def delete_entity(sender, instance, **kwargs): """Delete Entity when last Data object is deleted.""" # 1 means that the last Data object is going to be deleted. Entity.objects.annotate(num_data=Count('data')).filter(data=instance, num_data=1).delete()
[ "def", "delete_entity", "(", "sender", ",", "instance", ",", "*", "*", "kwargs", ")", ":", "# 1 means that the last Data object is going to be deleted.", "Entity", ".", "objects", ".", "annotate", "(", "num_data", "=", "Count", "(", "'data'", ")", ")", ".", "fil...
Delete Entity when last Data object is deleted.
[ "Delete", "Entity", "when", "last", "Data", "object", "is", "deleted", "." ]
f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/signals.py#L39-L42
train
45,587
genialis/resolwe
resolwe/flow/signals.py
delete_relation
def delete_relation(sender, instance, **kwargs): """Delete the Relation object when the last Entity is removed.""" def process_signal(relation_id): """Get the relation and delete it if it has no entities left.""" try: relation = Relation.objects.get(pk=relation_id) except Relation.DoesNotExist: return if relation.entities.count() == 0: relation.delete() # Wait for partitions to be recreated. transaction.on_commit(lambda: process_signal(instance.relation_id))
python
def delete_relation(sender, instance, **kwargs): """Delete the Relation object when the last Entity is removed.""" def process_signal(relation_id): """Get the relation and delete it if it has no entities left.""" try: relation = Relation.objects.get(pk=relation_id) except Relation.DoesNotExist: return if relation.entities.count() == 0: relation.delete() # Wait for partitions to be recreated. transaction.on_commit(lambda: process_signal(instance.relation_id))
[ "def", "delete_relation", "(", "sender", ",", "instance", ",", "*", "*", "kwargs", ")", ":", "def", "process_signal", "(", "relation_id", ")", ":", "\"\"\"Get the relation and delete it if it has no entities left.\"\"\"", "try", ":", "relation", "=", "Relation", ".", ...
Delete the Relation object when the last Entity is removed.
[ "Delete", "the", "Relation", "object", "when", "the", "last", "Entity", "is", "removed", "." ]
f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/signals.py#L48-L61
train
45,588
genialis/resolwe
resolwe/flow/executors/__main__.py
run_executor
async def run_executor(): """Start the actual execution; instantiate the executor and run.""" parser = argparse.ArgumentParser(description="Run the specified executor.") parser.add_argument('module', help="The module from which to instantiate the concrete executor.") args = parser.parse_args() module_name = '{}.run'.format(args.module) class_name = 'FlowExecutor' module = import_module(module_name, __package__) executor = getattr(module, class_name)() with open(ExecutorFiles.PROCESS_SCRIPT, 'rt') as script_file: await executor.run(DATA['id'], script_file.read())
python
async def run_executor(): """Start the actual execution; instantiate the executor and run.""" parser = argparse.ArgumentParser(description="Run the specified executor.") parser.add_argument('module', help="The module from which to instantiate the concrete executor.") args = parser.parse_args() module_name = '{}.run'.format(args.module) class_name = 'FlowExecutor' module = import_module(module_name, __package__) executor = getattr(module, class_name)() with open(ExecutorFiles.PROCESS_SCRIPT, 'rt') as script_file: await executor.run(DATA['id'], script_file.read())
[ "async", "def", "run_executor", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "\"Run the specified executor.\"", ")", "parser", ".", "add_argument", "(", "'module'", ",", "help", "=", "\"The module from which to instantiate ...
Start the actual execution; instantiate the executor and run.
[ "Start", "the", "actual", "execution", ";", "instantiate", "the", "executor", "and", "run", "." ]
f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/executors/__main__.py#L39-L51
train
45,589
genialis/resolwe
resolwe/elastic/apps.py
ElasticConfig.ready
def ready(self): """Perform application initialization.""" # Initialize the type extension composer. from . composer import composer composer.discover_extensions() is_migrating = sys.argv[1:2] == ['migrate'] if is_migrating: # Do not register signals and ES indices when: # * migrating - model instances used during migrations do # not contain the full functionality of models and things # like content types don't work correctly and signals are # not versioned so they are guaranteed to work only with # the last version of the model return # Connect all signals from . import signals # pylint: disable=unused-import # Register ES indices from . builder import index_builder
python
def ready(self): """Perform application initialization.""" # Initialize the type extension composer. from . composer import composer composer.discover_extensions() is_migrating = sys.argv[1:2] == ['migrate'] if is_migrating: # Do not register signals and ES indices when: # * migrating - model instances used during migrations do # not contain the full functionality of models and things # like content types don't work correctly and signals are # not versioned so they are guaranteed to work only with # the last version of the model return # Connect all signals from . import signals # pylint: disable=unused-import # Register ES indices from . builder import index_builder
[ "def", "ready", "(", "self", ")", ":", "# Initialize the type extension composer.", "from", ".", "composer", "import", "composer", "composer", ".", "discover_extensions", "(", ")", "is_migrating", "=", "sys", ".", "argv", "[", "1", ":", "2", "]", "==", "[", ...
Perform application initialization.
[ "Perform", "application", "initialization", "." ]
f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/elastic/apps.py#L12-L32
train
45,590
genialis/resolwe
resolwe/flow/serializers/fields.py
ResolweSlugRelatedField.to_internal_value
def to_internal_value(self, data): """Convert to internal value.""" user = getattr(self.context.get('request'), 'user') queryset = self.get_queryset() permission = get_full_perm('view', queryset.model) try: return get_objects_for_user( user, permission, queryset.filter(**{self.slug_field: data}), ).latest() except ObjectDoesNotExist: self.fail( 'does_not_exist', slug_name=self.slug_field, value=smart_text(data), model_name=queryset.model._meta.model_name, # pylint: disable=protected-access ) except (TypeError, ValueError): self.fail('invalid')
python
def to_internal_value(self, data): """Convert to internal value.""" user = getattr(self.context.get('request'), 'user') queryset = self.get_queryset() permission = get_full_perm('view', queryset.model) try: return get_objects_for_user( user, permission, queryset.filter(**{self.slug_field: data}), ).latest() except ObjectDoesNotExist: self.fail( 'does_not_exist', slug_name=self.slug_field, value=smart_text(data), model_name=queryset.model._meta.model_name, # pylint: disable=protected-access ) except (TypeError, ValueError): self.fail('invalid')
[ "def", "to_internal_value", "(", "self", ",", "data", ")", ":", "user", "=", "getattr", "(", "self", ".", "context", ".", "get", "(", "'request'", ")", ",", "'user'", ")", "queryset", "=", "self", ".", "get_queryset", "(", ")", "permission", "=", "get_...
Convert to internal value.
[ "Convert", "to", "internal", "value", "." ]
f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/serializers/fields.py#L38-L57
train
45,591
Alonreznik/dynamodb-json
dynamodb_json/json_util.py
object_hook
def object_hook(dct): """ DynamoDB object hook to return python values """ try: # First - Try to parse the dct as DynamoDB parsed if 'BOOL' in dct: return dct['BOOL'] if 'S' in dct: val = dct['S'] try: return datetime.strptime(val, '%Y-%m-%dT%H:%M:%S.%f') except: return str(val) if 'SS' in dct: return list(dct['SS']) if 'N' in dct: if re.match("^-?\d+?\.\d+?$", dct['N']) is not None: return float(dct['N']) else: try: return int(dct['N']) except: return int(dct['N']) if 'B' in dct: return str(dct['B']) if 'NS' in dct: return set(dct['NS']) if 'BS' in dct: return set(dct['BS']) if 'M' in dct: return dct['M'] if 'L' in dct: return dct['L'] if 'NULL' in dct and dct['NULL'] is True: return None except: return dct # In a Case of returning a regular python dict for key, val in six.iteritems(dct): if isinstance(val, six.string_types): try: dct[key] = datetime.strptime(val, '%Y-%m-%dT%H:%M:%S.%f') except: # This is a regular Basestring object pass if isinstance(val, Decimal): if val % 1 > 0: dct[key] = float(val) elif six.PY3: dct[key] = int(val) elif val < sys.maxsize: dct[key] = int(val) else: dct[key] = long(val) return dct
python
def object_hook(dct): """ DynamoDB object hook to return python values """ try: # First - Try to parse the dct as DynamoDB parsed if 'BOOL' in dct: return dct['BOOL'] if 'S' in dct: val = dct['S'] try: return datetime.strptime(val, '%Y-%m-%dT%H:%M:%S.%f') except: return str(val) if 'SS' in dct: return list(dct['SS']) if 'N' in dct: if re.match("^-?\d+?\.\d+?$", dct['N']) is not None: return float(dct['N']) else: try: return int(dct['N']) except: return int(dct['N']) if 'B' in dct: return str(dct['B']) if 'NS' in dct: return set(dct['NS']) if 'BS' in dct: return set(dct['BS']) if 'M' in dct: return dct['M'] if 'L' in dct: return dct['L'] if 'NULL' in dct and dct['NULL'] is True: return None except: return dct # In a Case of returning a regular python dict for key, val in six.iteritems(dct): if isinstance(val, six.string_types): try: dct[key] = datetime.strptime(val, '%Y-%m-%dT%H:%M:%S.%f') except: # This is a regular Basestring object pass if isinstance(val, Decimal): if val % 1 > 0: dct[key] = float(val) elif six.PY3: dct[key] = int(val) elif val < sys.maxsize: dct[key] = int(val) else: dct[key] = long(val) return dct
[ "def", "object_hook", "(", "dct", ")", ":", "try", ":", "# First - Try to parse the dct as DynamoDB parsed", "if", "'BOOL'", "in", "dct", ":", "return", "dct", "[", "'BOOL'", "]", "if", "'S'", "in", "dct", ":", "val", "=", "dct", "[", "'S'", "]", "try", ...
DynamoDB object hook to return python values
[ "DynamoDB", "object", "hook", "to", "return", "python", "values" ]
f6a5c472fc349f51281fb2ecd4679479f01ee2f3
https://github.com/Alonreznik/dynamodb-json/blob/f6a5c472fc349f51281fb2ecd4679479f01ee2f3/dynamodb_json/json_util.py#L48-L104
train
45,592
geoadmin/lib-gatilegrid
gatilegrid/tilegrids.py
_TileGrid.tileAddress
def tileAddress(self, zoom, point): "Returns a tile address based on a zoom level and \ a point in the tile" [x, y] = point assert x <= self.MAXX and x >= self.MINX assert y <= self.MAXY and y >= self.MINY assert zoom in range(0, len(self.RESOLUTIONS)) tileS = self.tileSize(zoom) offsetX = abs(x - self.MINX) if self.originCorner == 'bottom-left': offsetY = abs(y - self.MINY) elif self.originCorner == 'top-left': offsetY = abs(self.MAXY - y) col = offsetX / tileS row = offsetY / tileS # We are exactly on the edge of a tile and the extent if x in (self.MINX, self.MAXX) and col.is_integer(): col = max(0, col - 1) if y in (self.MINY, self.MAXY) and row.is_integer(): row = max(0, row - 1) return [ int(math.floor(col)), int(math.floor(row)) ]
python
def tileAddress(self, zoom, point): "Returns a tile address based on a zoom level and \ a point in the tile" [x, y] = point assert x <= self.MAXX and x >= self.MINX assert y <= self.MAXY and y >= self.MINY assert zoom in range(0, len(self.RESOLUTIONS)) tileS = self.tileSize(zoom) offsetX = abs(x - self.MINX) if self.originCorner == 'bottom-left': offsetY = abs(y - self.MINY) elif self.originCorner == 'top-left': offsetY = abs(self.MAXY - y) col = offsetX / tileS row = offsetY / tileS # We are exactly on the edge of a tile and the extent if x in (self.MINX, self.MAXX) and col.is_integer(): col = max(0, col - 1) if y in (self.MINY, self.MAXY) and row.is_integer(): row = max(0, row - 1) return [ int(math.floor(col)), int(math.floor(row)) ]
[ "def", "tileAddress", "(", "self", ",", "zoom", ",", "point", ")", ":", "[", "x", ",", "y", "]", "=", "point", "assert", "x", "<=", "self", ".", "MAXX", "and", "x", ">=", "self", ".", "MINX", "assert", "y", "<=", "self", ".", "MAXY", "and", "y"...
Returns a tile address based on a zoom level and \ a point in the tile
[ "Returns", "a", "tile", "address", "based", "on", "a", "zoom", "level", "and", "\\", "a", "point", "in", "the", "tile" ]
28e39cba22451f6ef0ddcb93cbc0838f06815505
https://github.com/geoadmin/lib-gatilegrid/blob/28e39cba22451f6ef0ddcb93cbc0838f06815505/gatilegrid/tilegrids.py#L222-L246
train
45,593
geoadmin/lib-gatilegrid
gatilegrid/tilegrids.py
_TileGrid.intersectsExtent
def intersectsExtent(self, extent): "Determine if an extent intersects this instance extent" return \ self.extent[0] <= extent[2] and self.extent[2] >= extent[0] and \ self.extent[1] <= extent[3] and self.extent[3] >= extent[1]
python
def intersectsExtent(self, extent): "Determine if an extent intersects this instance extent" return \ self.extent[0] <= extent[2] and self.extent[2] >= extent[0] and \ self.extent[1] <= extent[3] and self.extent[3] >= extent[1]
[ "def", "intersectsExtent", "(", "self", ",", "extent", ")", ":", "return", "self", ".", "extent", "[", "0", "]", "<=", "extent", "[", "2", "]", "and", "self", ".", "extent", "[", "2", "]", ">=", "extent", "[", "0", "]", "and", "self", ".", "exten...
Determine if an extent intersects this instance extent
[ "Determine", "if", "an", "extent", "intersects", "this", "instance", "extent" ]
28e39cba22451f6ef0ddcb93cbc0838f06815505
https://github.com/geoadmin/lib-gatilegrid/blob/28e39cba22451f6ef0ddcb93cbc0838f06815505/gatilegrid/tilegrids.py#L248-L252
train
45,594
geoadmin/lib-gatilegrid
gatilegrid/tilegrids.py
_TileGrid.iterGrid
def iterGrid(self, minZoom, maxZoom): "Yields the tileBounds, zoom, tileCol and tileRow" assert minZoom in range(0, len(self.RESOLUTIONS)) assert maxZoom in range(0, len(self.RESOLUTIONS)) assert minZoom <= maxZoom for zoom in xrange(minZoom, maxZoom + 1): [minRow, minCol, maxRow, maxCol] = self.getExtentAddress(zoom) for row in xrange(minRow, maxRow + 1): for col in xrange(minCol, maxCol + 1): tileBounds = self.tileBounds(zoom, col, row) yield (tileBounds, zoom, col, row)
python
def iterGrid(self, minZoom, maxZoom): "Yields the tileBounds, zoom, tileCol and tileRow" assert minZoom in range(0, len(self.RESOLUTIONS)) assert maxZoom in range(0, len(self.RESOLUTIONS)) assert minZoom <= maxZoom for zoom in xrange(minZoom, maxZoom + 1): [minRow, minCol, maxRow, maxCol] = self.getExtentAddress(zoom) for row in xrange(minRow, maxRow + 1): for col in xrange(minCol, maxCol + 1): tileBounds = self.tileBounds(zoom, col, row) yield (tileBounds, zoom, col, row)
[ "def", "iterGrid", "(", "self", ",", "minZoom", ",", "maxZoom", ")", ":", "assert", "minZoom", "in", "range", "(", "0", ",", "len", "(", "self", ".", "RESOLUTIONS", ")", ")", "assert", "maxZoom", "in", "range", "(", "0", ",", "len", "(", "self", "....
Yields the tileBounds, zoom, tileCol and tileRow
[ "Yields", "the", "tileBounds", "zoom", "tileCol", "and", "tileRow" ]
28e39cba22451f6ef0ddcb93cbc0838f06815505
https://github.com/geoadmin/lib-gatilegrid/blob/28e39cba22451f6ef0ddcb93cbc0838f06815505/gatilegrid/tilegrids.py#L254-L265
train
45,595
geoadmin/lib-gatilegrid
gatilegrid/tilegrids.py
_TileGrid.numberOfXTilesAtZoom
def numberOfXTilesAtZoom(self, zoom): "Returns the number of tiles over x at a given zoom level" [minRow, minCol, maxRow, maxCol] = self.getExtentAddress(zoom) return maxCol - minCol + 1
python
def numberOfXTilesAtZoom(self, zoom): "Returns the number of tiles over x at a given zoom level" [minRow, minCol, maxRow, maxCol] = self.getExtentAddress(zoom) return maxCol - minCol + 1
[ "def", "numberOfXTilesAtZoom", "(", "self", ",", "zoom", ")", ":", "[", "minRow", ",", "minCol", ",", "maxRow", ",", "maxCol", "]", "=", "self", ".", "getExtentAddress", "(", "zoom", ")", "return", "maxCol", "-", "minCol", "+", "1" ]
Returns the number of tiles over x at a given zoom level
[ "Returns", "the", "number", "of", "tiles", "over", "x", "at", "a", "given", "zoom", "level" ]
28e39cba22451f6ef0ddcb93cbc0838f06815505
https://github.com/geoadmin/lib-gatilegrid/blob/28e39cba22451f6ef0ddcb93cbc0838f06815505/gatilegrid/tilegrids.py#L267-L270
train
45,596
geoadmin/lib-gatilegrid
gatilegrid/tilegrids.py
_TileGrid.numberOfYTilesAtZoom
def numberOfYTilesAtZoom(self, zoom): "Retruns the number of tiles over y at a given zoom level" [minRow, minCol, maxRow, maxCol] = self.getExtentAddress(zoom) return maxRow - minRow + 1
python
def numberOfYTilesAtZoom(self, zoom): "Retruns the number of tiles over y at a given zoom level" [minRow, minCol, maxRow, maxCol] = self.getExtentAddress(zoom) return maxRow - minRow + 1
[ "def", "numberOfYTilesAtZoom", "(", "self", ",", "zoom", ")", ":", "[", "minRow", ",", "minCol", ",", "maxRow", ",", "maxCol", "]", "=", "self", ".", "getExtentAddress", "(", "zoom", ")", "return", "maxRow", "-", "minRow", "+", "1" ]
Retruns the number of tiles over y at a given zoom level
[ "Retruns", "the", "number", "of", "tiles", "over", "y", "at", "a", "given", "zoom", "level" ]
28e39cba22451f6ef0ddcb93cbc0838f06815505
https://github.com/geoadmin/lib-gatilegrid/blob/28e39cba22451f6ef0ddcb93cbc0838f06815505/gatilegrid/tilegrids.py#L272-L275
train
45,597
geoadmin/lib-gatilegrid
gatilegrid/tilegrids.py
_TileGrid.numberOfTilesAtZoom
def numberOfTilesAtZoom(self, zoom): "Returns the total number of tile at a given zoom level" [minRow, minCol, maxRow, maxCol] = self.getExtentAddress(zoom) return (maxCol - minCol + 1) * (maxRow - minRow + 1)
python
def numberOfTilesAtZoom(self, zoom): "Returns the total number of tile at a given zoom level" [minRow, minCol, maxRow, maxCol] = self.getExtentAddress(zoom) return (maxCol - minCol + 1) * (maxRow - minRow + 1)
[ "def", "numberOfTilesAtZoom", "(", "self", ",", "zoom", ")", ":", "[", "minRow", ",", "minCol", ",", "maxRow", ",", "maxCol", "]", "=", "self", ".", "getExtentAddress", "(", "zoom", ")", "return", "(", "maxCol", "-", "minCol", "+", "1", ")", "*", "("...
Returns the total number of tile at a given zoom level
[ "Returns", "the", "total", "number", "of", "tile", "at", "a", "given", "zoom", "level" ]
28e39cba22451f6ef0ddcb93cbc0838f06815505
https://github.com/geoadmin/lib-gatilegrid/blob/28e39cba22451f6ef0ddcb93cbc0838f06815505/gatilegrid/tilegrids.py#L277-L280
train
45,598
geoadmin/lib-gatilegrid
gatilegrid/tilegrids.py
_TileGrid.totalNumberOfTiles
def totalNumberOfTiles(self, minZoom=None, maxZoom=None): "Return the total number of tiles for this instance extent" nbTiles = 0 minZoom = minZoom or 0 if maxZoom: maxZoom = maxZoom + 1 else: maxZoom = len(self.RESOLUTIONS) for zoom in xrange(minZoom, maxZoom): nbTiles += self.numberOfTilesAtZoom(zoom) return nbTiles
python
def totalNumberOfTiles(self, minZoom=None, maxZoom=None): "Return the total number of tiles for this instance extent" nbTiles = 0 minZoom = minZoom or 0 if maxZoom: maxZoom = maxZoom + 1 else: maxZoom = len(self.RESOLUTIONS) for zoom in xrange(minZoom, maxZoom): nbTiles += self.numberOfTilesAtZoom(zoom) return nbTiles
[ "def", "totalNumberOfTiles", "(", "self", ",", "minZoom", "=", "None", ",", "maxZoom", "=", "None", ")", ":", "nbTiles", "=", "0", "minZoom", "=", "minZoom", "or", "0", "if", "maxZoom", ":", "maxZoom", "=", "maxZoom", "+", "1", "else", ":", "maxZoom", ...
Return the total number of tiles for this instance extent
[ "Return", "the", "total", "number", "of", "tiles", "for", "this", "instance", "extent" ]
28e39cba22451f6ef0ddcb93cbc0838f06815505
https://github.com/geoadmin/lib-gatilegrid/blob/28e39cba22451f6ef0ddcb93cbc0838f06815505/gatilegrid/tilegrids.py#L282-L292
train
45,599