text_prompt
stringlengths 100
17.7k
⌀ | code_prompt
stringlengths 7
9.86k
⌀ |
---|---|
<SYSTEM_TASK:>
Generate an ACL.
<END_TASK>
<USER_TASK:>
Description:
def generate_acl(config, model_cls, raml_resource, es_based=True):
""" Generate an ACL.
Generated ACL class has a `item_model` attribute set to
:model_cls:.
ACLs used for collection and item access control are generated from a
first security scheme with type `x-ACL`.
If :raml_resource: has no x-ACL security schemes defined then ALLOW_ALL
ACL is used.
If the `collection` or `item` settings are empty, then ALLOW_ALL ACL
is used.
:param model_cls: Generated model class
:param raml_resource: Instance of ramlfications.raml.ResourceNode
for which ACL is being generated
:param es_based: Boolean inidicating whether ACL should query ES or
not when getting an object
""" |
schemes = raml_resource.security_schemes or []
schemes = [sch for sch in schemes if sch.type == 'x-ACL']
if not schemes:
collection_acl = item_acl = []
log.debug('No ACL scheme applied. Using ACL: {}'.format(item_acl))
else:
sec_scheme = schemes[0]
log.debug('{} ACL scheme applied'.format(sec_scheme.name))
settings = sec_scheme.settings or {}
collection_acl = parse_acl(acl_string=settings.get('collection'))
item_acl = parse_acl(acl_string=settings.get('item'))
class GeneratedACLBase(object):
item_model = model_cls
def __init__(self, request, es_based=es_based):
super(GeneratedACLBase, self).__init__(request=request)
self.es_based = es_based
self._collection_acl = collection_acl
self._item_acl = item_acl
bases = [GeneratedACLBase]
if config.registry.database_acls:
from nefertari_guards.acl import DatabaseACLMixin as GuardsMixin
bases += [DatabaseACLMixin, GuardsMixin]
bases.append(BaseACL)
return type('GeneratedACL', tuple(bases), {}) |
<SYSTEM_TASK:>
Override to support ACL filtering.
<END_TASK>
<USER_TASK:>
Description:
def getitem_es(self, key):
""" Override to support ACL filtering.
To do so: passes `self.request` to `get_item` and uses
`ACLFilterES`.
""" |
from nefertari_guards.elasticsearch import ACLFilterES
es = ACLFilterES(self.item_model.__name__)
params = {
'id': key,
'request': self.request,
}
obj = es.get_item(**params)
obj.__acl__ = self.item_acl(obj)
obj.__parent__ = self
obj.__name__ = key
return obj |
<SYSTEM_TASK:>
Generate view method names needed for `raml_resource` view.
<END_TASK>
<USER_TASK:>
Description:
def resource_view_attrs(raml_resource, singular=False):
""" Generate view method names needed for `raml_resource` view.
Collects HTTP method names from resource siblings and dynamic children
if exist. Collected methods are then translated to
`nefertari.view.BaseView` method names, each of which is used to
process a particular HTTP method request.
Maps of {HTTP_method: view_method} `collection_methods` and
`item_methods` are used to convert collection and item methods
respectively.
:param raml_resource: Instance of ramlfications.raml.ResourceNode
:param singular: Boolean indicating if resource is singular or not
""" |
from .views import collection_methods, item_methods
# Singular resource doesn't have collection methods though
# it looks like a collection
if singular:
collection_methods = item_methods
siblings = get_resource_siblings(raml_resource)
http_methods = [sibl.method.lower() for sibl in siblings]
attrs = [collection_methods.get(method) for method in http_methods]
# Check if resource has dynamic child resource like collection/{id}
# If dynamic child resource exists, add its siblings' methods to attrs,
# as both resources are handled by a single view
children = get_resource_children(raml_resource)
http_submethods = [child.method.lower() for child in children
if is_dynamic_uri(child.path)]
attrs += [item_methods.get(method) for method in http_submethods]
return set(filter(bool, attrs)) |
<SYSTEM_TASK:>
Prepare map of event subscribers.
<END_TASK>
<USER_TASK:>
Description:
def get_events_map():
""" Prepare map of event subscribers.
* Extends copies of BEFORE_EVENTS and AFTER_EVENTS maps with
'set' action.
* Returns map of {before/after: {action: event class(es)}}
""" |
from nefertari import events
set_keys = ('create', 'update', 'replace', 'update_many', 'register')
before_events = events.BEFORE_EVENTS.copy()
before_events['set'] = [before_events[key] for key in set_keys]
after_events = events.AFTER_EVENTS.copy()
after_events['set'] = [after_events[key] for key in set_keys]
return {
'before': before_events,
'after': after_events,
} |
<SYSTEM_TASK:>
Patches view_cls.Model with model_cls.
<END_TASK>
<USER_TASK:>
Description:
def patch_view_model(view_cls, model_cls):
""" Patches view_cls.Model with model_cls.
:param view_cls: View class "Model" param of which should be
patched
:param model_cls: Model class which should be used to patch
view_cls.Model
""" |
original_model = view_cls.Model
view_cls.Model = model_cls
try:
yield
finally:
view_cls.Model = original_model |
<SYSTEM_TASK:>
Get route name from RAML resource URI.
<END_TASK>
<USER_TASK:>
Description:
def get_route_name(resource_uri):
""" Get route name from RAML resource URI.
:param resource_uri: String representing RAML resource URI.
:returns string: String with route name, which is :resource_uri:
stripped of non-word characters.
""" |
resource_uri = resource_uri.strip('/')
resource_uri = re.sub('\W', '', resource_uri)
return resource_uri |
<SYSTEM_TASK:>
Perform complete one resource configuration process
<END_TASK>
<USER_TASK:>
Description:
def generate_resource(config, raml_resource, parent_resource):
""" Perform complete one resource configuration process
This function generates: ACL, view, route, resource, database
model for a given `raml_resource`. New nefertari resource is
attached to `parent_resource` class which is an instance of
`nefertari.resource.Resource`.
Things to consider:
* Top-level resources must be collection names.
* No resources are explicitly created for dynamic (ending with '}')
RAML resources as they are implicitly processed by parent collection
resources.
* Resource nesting must look like collection/id/collection/id/...
* Only part of resource path after last '/' is taken into account,
thus each level of resource nesting should add one more path
element. E.g. /stories -> /stories/{id} and not
/stories -> /stories/mystories/{id}. Latter route will be generated
at /stories/{id}.
:param raml_resource: Instance of ramlfications.raml.ResourceNode.
:param parent_resource: Parent nefertari resource object.
""" |
from .models import get_existing_model
# Don't generate resources for dynamic routes as they are already
# generated by their parent
resource_uri = get_resource_uri(raml_resource)
if is_dynamic_uri(resource_uri):
if parent_resource.is_root:
raise Exception("Top-level resources can't be dynamic and must "
"represent collections instead")
return
route_name = get_route_name(resource_uri)
log.info('Configuring resource: `{}`. Parent: `{}`'.format(
route_name, parent_resource.uid or 'root'))
# Get DB model. If this is an attribute or singular resource,
# we don't need to get model
is_singular = singular_subresource(raml_resource, route_name)
is_attr_res = attr_subresource(raml_resource, route_name)
if not parent_resource.is_root and (is_attr_res or is_singular):
model_cls = parent_resource.view.Model
else:
model_name = generate_model_name(raml_resource)
model_cls = get_existing_model(model_name)
resource_kwargs = {}
# Generate ACL
log.info('Generating ACL for `{}`'.format(route_name))
resource_kwargs['factory'] = generate_acl(
config,
model_cls=model_cls,
raml_resource=raml_resource)
# Generate dynamic part name
if not is_singular:
resource_kwargs['id_name'] = dynamic_part_name(
raml_resource=raml_resource,
route_name=route_name,
pk_field=model_cls.pk_field())
# Generate REST view
log.info('Generating view for `{}`'.format(route_name))
view_attrs = resource_view_attrs(raml_resource, is_singular)
resource_kwargs['view'] = generate_rest_view(
config,
model_cls=model_cls,
attrs=view_attrs,
attr_view=is_attr_res,
singular=is_singular,
)
# In case of singular resource, model still needs to be generated,
# but we store it on a different view attribute
if is_singular:
model_name = generate_model_name(raml_resource)
view_cls = resource_kwargs['view']
view_cls._parent_model = view_cls.Model
view_cls.Model = get_existing_model(model_name)
# Create new nefertari resource
log.info('Creating new resource for `{}`'.format(route_name))
clean_uri = resource_uri.strip('/')
resource_args = (singularize(clean_uri),)
if not is_singular:
resource_args += (clean_uri,)
return parent_resource.add(*resource_args, **resource_kwargs) |
<SYSTEM_TASK:>
Handle server generation process.
<END_TASK>
<USER_TASK:>
Description:
def generate_server(raml_root, config):
""" Handle server generation process.
:param raml_root: Instance of ramlfications.raml.RootNode.
:param config: Pyramid Configurator instance.
""" |
log.info('Server generation started')
if not raml_root.resources:
return
root_resource = config.get_root_resource()
generated_resources = {}
for raml_resource in raml_root.resources:
if raml_resource.path in generated_resources:
continue
# Get Nefertari parent resource
parent_resource = _get_nefertari_parent_resource(
raml_resource, generated_resources, root_resource)
# Get generated resource and store it
new_resource = generate_resource(
config, raml_resource, parent_resource)
if new_resource is not None:
generated_resources[raml_resource.path] = new_resource |
<SYSTEM_TASK:>
Generate REST view for a model class.
<END_TASK>
<USER_TASK:>
Description:
def generate_rest_view(config, model_cls, attrs=None, es_based=True,
attr_view=False, singular=False):
""" Generate REST view for a model class.
:param model_cls: Generated DB model class.
:param attr: List of strings that represent names of view methods, new
generated view should support. Not supported methods are replaced
with property that raises AttributeError to display MethodNotAllowed
error.
:param es_based: Boolean indicating if generated view should read from
elasticsearch. If True - collection reads are performed from
elasticsearch. Database is used for reads otherwise.
Defaults to True.
:param attr_view: Boolean indicating if ItemAttributeView should be
used as a base class for generated view.
:param singular: Boolean indicating if ItemSingularView should be
used as a base class for generated view.
""" |
valid_attrs = (list(collection_methods.values()) +
list(item_methods.values()))
missing_attrs = set(valid_attrs) - set(attrs)
if singular:
bases = [ItemSingularView]
elif attr_view:
bases = [ItemAttributeView]
elif es_based:
bases = [ESCollectionView]
else:
bases = [CollectionView]
if config.registry.database_acls:
from nefertari_guards.view import ACLFilterViewMixin
bases = [SetObjectACLMixin] + bases + [ACLFilterViewMixin]
bases.append(NefertariBaseView)
RESTView = type('RESTView', tuple(bases), {'Model': model_cls})
def _attr_error(*args, **kwargs):
raise AttributeError
for attr in missing_attrs:
setattr(RESTView, attr, property(_attr_error))
return RESTView |
<SYSTEM_TASK:>
Get location of the `obj`
<END_TASK>
<USER_TASK:>
Description:
def _location(self, obj):
""" Get location of the `obj`
Arguments:
:obj: self.Model instance.
""" |
field_name = self.clean_id_name
return self.request.route_url(
self._resource.uid,
**{self._resource.id_name: getattr(obj, field_name)}) |
<SYSTEM_TASK:>
Get queryset of parent view.
<END_TASK>
<USER_TASK:>
Description:
def _parent_queryset(self):
""" Get queryset of parent view.
Generated queryset is used to run queries in the current level view.
""" |
parent = self._resource.parent
if hasattr(parent, 'view'):
req = self.request.blank(self.request.path)
req.registry = self.request.registry
req.matchdict = {
parent.id_name: self.request.matchdict.get(parent.id_name)}
parent_view = parent.view(parent.view._factory, req)
obj = parent_view.get_item(**req.matchdict)
if isinstance(self, ItemSubresourceBaseView):
return
prop = self._resource.collection_name
return getattr(obj, prop, None) |
<SYSTEM_TASK:>
Get objects collection taking into account generated queryset
<END_TASK>
<USER_TASK:>
Description:
def get_collection(self, **kwargs):
""" Get objects collection taking into account generated queryset
of parent view.
This method allows working with nested resources properly. Thus a
queryset returned by this method will be a subset of its parent
view's queryset, thus filtering out objects that don't belong to
the parent object.
""" |
self._query_params.update(kwargs)
objects = self._parent_queryset()
if objects is not None:
return self.Model.filter_objects(
objects, **self._query_params)
return self.Model.get_collection(**self._query_params) |
<SYSTEM_TASK:>
Get collection item taking into account generated queryset
<END_TASK>
<USER_TASK:>
Description:
def get_item(self, **kwargs):
""" Get collection item taking into account generated queryset
of parent view.
This method allows working with nested resources properly. Thus an item
returned by this method will belong to its parent view's queryset, thus
filtering out objects that don't belong to the parent object.
Returns an object from the applicable ACL. If ACL wasn't applied, it is
applied explicitly.
""" |
if six.callable(self.context):
self.reload_context(es_based=False, **kwargs)
objects = self._parent_queryset()
if objects is not None and self.context not in objects:
raise JHTTPNotFound('{}({}) not found'.format(
self.Model.__name__,
self._get_context_key(**kwargs)))
return self.context |
<SYSTEM_TASK:>
Reload `self.context` object into a DB or ES object.
<END_TASK>
<USER_TASK:>
Description:
def reload_context(self, es_based, **kwargs):
""" Reload `self.context` object into a DB or ES object.
A reload is performed by getting the object ID from :kwargs: and then
getting a context key item from the new instance of `self._factory`
which is an ACL class used by the current view.
Arguments:
:es_based: Boolean. Whether to init ACL ac es-based or not. This
affects the backend which will be queried - either DB or ES
:kwargs: Kwargs that contain value for current resource 'id_name'
key
""" |
from .acl import BaseACL
key = self._get_context_key(**kwargs)
kwargs = {'request': self.request}
if issubclass(self._factory, BaseACL):
kwargs['es_based'] = es_based
acl = self._factory(**kwargs)
if acl.item_model is None:
acl.item_model = self.Model
self.context = acl[key] |
<SYSTEM_TASK:>
Get ES objects collection taking into account the generated
<END_TASK>
<USER_TASK:>
Description:
def get_collection_es(self):
""" Get ES objects collection taking into account the generated
queryset of parent view.
This method allows working with nested resources properly. Thus a
queryset returned by this method will be a subset of its parent view's
queryset, thus filtering out objects that don't belong to the parent
object.
""" |
objects_ids = self._parent_queryset_es()
if objects_ids is not None:
objects_ids = self.get_es_object_ids(objects_ids)
if not objects_ids:
return []
self._query_params['id'] = objects_ids
return super(ESBaseView, self).get_collection_es() |
<SYSTEM_TASK:>
Get ES collection item taking into account generated queryset
<END_TASK>
<USER_TASK:>
Description:
def get_item_es(self, **kwargs):
""" Get ES collection item taking into account generated queryset
of parent view.
This method allows working with nested resources properly. Thus an item
returned by this method will belong to its parent view's queryset, thus
filtering out objects that don't belong to the parent object.
Returns an object retrieved from the applicable ACL. If an ACL wasn't
applied, it is applied explicitly.
""" |
item_id = self._get_context_key(**kwargs)
objects_ids = self._parent_queryset_es()
if objects_ids is not None:
objects_ids = self.get_es_object_ids(objects_ids)
if six.callable(self.context):
self.reload_context(es_based=True, **kwargs)
if (objects_ids is not None) and (item_id not in objects_ids):
raise JHTTPNotFound('{}(id={}) resource not found'.format(
self.Model.__name__, item_id))
return self.context |
<SYSTEM_TASK:>
Delete multiple objects from collection.
<END_TASK>
<USER_TASK:>
Description:
def delete_many(self, **kwargs):
""" Delete multiple objects from collection.
First ES is queried, then the results are used to query the DB.
This is done to make sure deleted objects are those filtered
by ES in the 'index' method (so user deletes what he saw).
""" |
db_objects = self.get_dbcollection_with_es(**kwargs)
return self.Model._delete_many(db_objects, self.request) |
<SYSTEM_TASK:>
Update multiple objects from collection.
<END_TASK>
<USER_TASK:>
Description:
def update_many(self, **kwargs):
""" Update multiple objects from collection.
First ES is queried, then the results are used to query DB.
This is done to make sure updated objects are those filtered
by ES in the 'index' method (so user updates what he saw).
""" |
db_objects = self.get_dbcollection_with_es(**kwargs)
return self.Model._update_many(
db_objects, self._json_params, self.request) |
<SYSTEM_TASK:>
Allow this module to be used as sphinx extension.
<END_TASK>
<USER_TASK:>
Description:
def setup(app):
"""Allow this module to be used as sphinx extension.
This attaches the Sphinx hooks.
:type app: sphinx.application.Sphinx
""" |
import sphinxcontrib_django.docstrings
import sphinxcontrib_django.roles
# Setup both modules at once. They can also be separately imported to
# use only fragments of this package.
sphinxcontrib_django.docstrings.setup(app)
sphinxcontrib_django.roles.setup(app) |
<SYSTEM_TASK:>
Fix the appearance of some classes in autodoc.
<END_TASK>
<USER_TASK:>
Description:
def patch_django_for_autodoc():
"""Fix the appearance of some classes in autodoc.
This avoids query evaluation.
""" |
# Fix Django's manager appearance
ManagerDescriptor.__get__ = lambda self, *args, **kwargs: self.manager
# Stop Django from executing DB queries
models.QuerySet.__repr__ = lambda self: self.__class__.__name__ |
<SYSTEM_TASK:>
Hook that tells autodoc to include or exclude certain fields.
<END_TASK>
<USER_TASK:>
Description:
def autodoc_skip(app, what, name, obj, skip, options):
"""Hook that tells autodoc to include or exclude certain fields.
Sadly, it doesn't give a reference to the parent object,
so only the ``name`` can be used for referencing.
:type app: sphinx.application.Sphinx
:param what: The parent type, ``class`` or ``module``
:type what: str
:param name: The name of the child method/attribute.
:type name: str
:param obj: The child value (e.g. a method, dict, or module reference)
:param options: The current autodoc settings.
:type options: dict
.. seealso:: http://www.sphinx-doc.org/en/stable/ext/autodoc.html#event-autodoc-skip-member
""" |
if name in config.EXCLUDE_MEMBERS:
return True
if name in config.INCLUDE_MEMBERS:
return False
return skip |
<SYSTEM_TASK:>
Hook that improves the autodoc docstrings for Django models.
<END_TASK>
<USER_TASK:>
Description:
def improve_model_docstring(app, what, name, obj, options, lines):
"""Hook that improves the autodoc docstrings for Django models.
:type app: sphinx.application.Sphinx
:param what: The parent type, ``class`` or ``module``
:type what: str
:param name: The dotted path to the child method/attribute.
:type name: str
:param obj: The Python object that i s being documented.
:param options: The current autodoc settings.
:type options: dict
:param lines: The current documentation lines
:type lines: list
""" |
if what == 'class':
_improve_class_docs(app, obj, lines)
elif what == 'attribute':
_improve_attribute_docs(obj, name, lines)
elif what == 'method':
_improve_method_docs(obj, name, lines)
# Return the extended docstring
return lines |
<SYSTEM_TASK:>
Improve the documentation of a class.
<END_TASK>
<USER_TASK:>
Description:
def _improve_class_docs(app, cls, lines):
"""Improve the documentation of a class.""" |
if issubclass(cls, models.Model):
_add_model_fields_as_params(app, cls, lines)
elif issubclass(cls, forms.Form):
_add_form_fields(cls, lines) |
<SYSTEM_TASK:>
Improve the documentation of a Django model subclass.
<END_TASK>
<USER_TASK:>
Description:
def _add_model_fields_as_params(app, obj, lines):
"""Improve the documentation of a Django model subclass.
This adds all model fields as parameters to the ``__init__()`` method.
:type app: sphinx.application.Sphinx
:type lines: list
""" |
for field in obj._meta.get_fields():
try:
help_text = strip_tags(force_text(field.help_text))
verbose_name = force_text(field.verbose_name).capitalize()
except AttributeError:
# e.g. ManyToOneRel
continue
# Add parameter
if help_text:
lines.append(u':param %s: %s' % (field.name, help_text))
else:
lines.append(u':param %s: %s' % (field.name, verbose_name))
# Add type
lines.append(_get_field_type(field))
if 'sphinx.ext.inheritance_diagram' in app.extensions and \
'sphinx.ext.graphviz' in app.extensions and \
not any('inheritance-diagram::' in line for line in lines):
lines.append('.. inheritance-diagram::') |
<SYSTEM_TASK:>
Improve the documentation of a Django Form class.
<END_TASK>
<USER_TASK:>
Description:
def _add_form_fields(obj, lines):
"""Improve the documentation of a Django Form class.
This highlights the available fields in the form.
""" |
lines.append("**Form fields:**")
lines.append("")
for name, field in obj.base_fields.items():
field_type = "{}.{}".format(field.__class__.__module__, field.__class__.__name__)
tpl = "* ``{name}``: {label} (:class:`~{field_type}`)"
lines.append(tpl.format(
name=name,
field=field,
label=field.label or name.replace('_', ' ').title(),
field_type=field_type
)) |
<SYSTEM_TASK:>
Improve the documentation of various attributes.
<END_TASK>
<USER_TASK:>
Description:
def _improve_attribute_docs(obj, name, lines):
"""Improve the documentation of various attributes.
This improves the navigation between related objects.
:param obj: the instance of the object to document.
:param name: full dotted path to the object.
:param lines: expected documentation lines.
""" |
if obj is None:
# Happens with form attributes.
return
if isinstance(obj, DeferredAttribute):
# This only points to a field name, not a field.
# Get the field by importing the name.
cls_path, field_name = name.rsplit('.', 1)
model = import_string(cls_path)
field = model._meta.get_field(obj.field_name)
del lines[:] # lines.clear() is Python 3 only
lines.append("**Model field:** {label}".format(
label=field.verbose_name
))
elif isinstance(obj, _FIELD_DESCRIPTORS):
# These
del lines[:]
lines.append("**Model field:** {label}".format(
label=obj.field.verbose_name
))
if isinstance(obj, FileDescriptor):
lines.append("**Return type:** :class:`~django.db.models.fields.files.FieldFile`")
elif PhoneNumberDescriptor is not None and isinstance(obj, PhoneNumberDescriptor):
lines.append("**Return type:** :class:`~phonenumber_field.phonenumber.PhoneNumber`")
elif isinstance(obj, related_descriptors.ForwardManyToOneDescriptor):
# Display a reasonable output for forward descriptors.
related_model = obj.field.remote_field.model
if isinstance(related_model, str):
cls_path = related_model
else:
cls_path = "{}.{}".format(related_model.__module__, related_model.__name__)
del lines[:]
lines.append("**Model field:** {label}, "
"accesses the :class:`~{cls_path}` model.".format(
label=obj.field.verbose_name, cls_path=cls_path
))
elif isinstance(obj, related_descriptors.ReverseOneToOneDescriptor):
related_model = obj.related.related_model
if isinstance(related_model, str):
cls_path = related_model
else:
cls_path = "{}.{}".format(related_model.__module__, related_model.__name__)
del lines[:]
lines.append("**Model field:** {label}, "
"accesses the :class:`~{cls_path}` model.".format(
label=obj.related.field.verbose_name, cls_path=cls_path
))
elif isinstance(obj, related_descriptors.ReverseManyToOneDescriptor):
related_model = obj.rel.related_model
if isinstance(related_model, str):
cls_path = related_model
else:
cls_path = "{}.{}".format(related_model.__module__, related_model.__name__)
del lines[:]
lines.append("**Model field:** {label}, "
"accesses the M2M :class:`~{cls_path}` model.".format(
label=obj.field.verbose_name, cls_path=cls_path
))
elif isinstance(obj, (models.Manager, ManagerDescriptor)):
# Somehow the 'objects' manager doesn't pass through the docstrings.
module, cls_name, field_name = name.rsplit('.', 2)
lines.append("Django manager to access the ORM")
tpl = "Use ``{cls_name}.objects.all()`` to fetch all objects."
lines.append(tpl.format(cls_name=cls_name)) |
<SYSTEM_TASK:>
Improve the documentation of various methods.
<END_TASK>
<USER_TASK:>
Description:
def _improve_method_docs(obj, name, lines):
"""Improve the documentation of various methods.
:param obj: the instance of the method to document.
:param name: full dotted path to the object.
:param lines: expected documentation lines.
""" |
if not lines:
# Not doing obj.__module__ lookups to avoid performance issues.
if name.endswith('_display'):
match = RE_GET_FOO_DISPLAY.search(name)
if match is not None:
# Django get_..._display method
lines.append("**Autogenerated:** Shows the label of the :attr:`{field}`".format(
field=match.group('field')
))
elif '.get_next_by_' in name:
match = RE_GET_NEXT_BY.search(name)
if match is not None:
lines.append("**Autogenerated:** Finds next instance"
" based on :attr:`{field}`.".format(
field=match.group('field')
))
elif '.get_previous_by_' in name:
match = RE_GET_PREVIOUS_BY.search(name)
if match is not None:
lines.append("**Autogenerated:** Finds previous instance"
" based on :attr:`{field}`.".format(
field=match.group('field')
)) |
<SYSTEM_TASK:>
Calculate elliptical Fourier descriptors for a contour.
<END_TASK>
<USER_TASK:>
Description:
def elliptic_fourier_descriptors(contour, order=10, normalize=False):
"""Calculate elliptical Fourier descriptors for a contour.
:param numpy.ndarray contour: A contour array of size ``[M x 2]``.
:param int order: The order of Fourier coefficients to calculate.
:param bool normalize: If the coefficients should be normalized;
see references for details.
:return: A ``[order x 4]`` array of Fourier coefficients.
:rtype: :py:class:`numpy.ndarray`
""" |
dxy = np.diff(contour, axis=0)
dt = np.sqrt((dxy ** 2).sum(axis=1))
t = np.concatenate([([0., ]), np.cumsum(dt)])
T = t[-1]
phi = (2 * np.pi * t) / T
coeffs = np.zeros((order, 4))
for n in _range(1, order + 1):
const = T / (2 * n * n * np.pi * np.pi)
phi_n = phi * n
d_cos_phi_n = np.cos(phi_n[1:]) - np.cos(phi_n[:-1])
d_sin_phi_n = np.sin(phi_n[1:]) - np.sin(phi_n[:-1])
a_n = const * np.sum((dxy[:, 0] / dt) * d_cos_phi_n)
b_n = const * np.sum((dxy[:, 0] / dt) * d_sin_phi_n)
c_n = const * np.sum((dxy[:, 1] / dt) * d_cos_phi_n)
d_n = const * np.sum((dxy[:, 1] / dt) * d_sin_phi_n)
coeffs[n - 1, :] = a_n, b_n, c_n, d_n
if normalize:
coeffs = normalize_efd(coeffs)
return coeffs |
<SYSTEM_TASK:>
Normalizes an array of Fourier coefficients.
<END_TASK>
<USER_TASK:>
Description:
def normalize_efd(coeffs, size_invariant=True):
"""Normalizes an array of Fourier coefficients.
See [#a]_ and [#b]_ for details.
:param numpy.ndarray coeffs: A ``[n x 4]`` Fourier coefficient array.
:param bool size_invariant: If size invariance normalizing should be done as well.
Default is ``True``.
:return: The normalized ``[n x 4]`` Fourier coefficient array.
:rtype: :py:class:`numpy.ndarray`
""" |
# Make the coefficients have a zero phase shift from
# the first major axis. Theta_1 is that shift angle.
theta_1 = 0.5 * np.arctan2(
2 * ((coeffs[0, 0] * coeffs[0, 1]) + (coeffs[0, 2] * coeffs[0, 3])),
((coeffs[0, 0] ** 2) - (coeffs[0, 1] ** 2) + (coeffs[0, 2] ** 2) - (coeffs[0, 3] ** 2)))
# Rotate all coefficients by theta_1.
for n in _range(1, coeffs.shape[0] + 1):
coeffs[n - 1, :] = np.dot(
np.array([[coeffs[n - 1, 0], coeffs[n - 1, 1]],
[coeffs[n - 1, 2], coeffs[n - 1, 3]]]),
np.array([[np.cos(n * theta_1), -np.sin(n * theta_1)],
[np.sin(n * theta_1), np.cos(n * theta_1)]])).flatten()
# Make the coefficients rotation invariant by rotating so that
# the semi-major axis is parallel to the x-axis.
psi_1 = np.arctan2(coeffs[0, 2], coeffs[0, 0])
psi_rotation_matrix = np.array([[np.cos(psi_1), np.sin(psi_1)],
[-np.sin(psi_1), np.cos(psi_1)]])
# Rotate all coefficients by -psi_1.
for n in _range(1, coeffs.shape[0] + 1):
coeffs[n - 1, :] = psi_rotation_matrix.dot(
np.array([[coeffs[n - 1, 0], coeffs[n - 1, 1]],
[coeffs[n - 1, 2], coeffs[n - 1, 3]]])).flatten()
if size_invariant:
# Obtain size-invariance by normalizing.
coeffs /= np.abs(coeffs[0, 0])
return coeffs |
<SYSTEM_TASK:>
Generate input mask from bytemask
<END_TASK>
<USER_TASK:>
Description:
def _gen_input_mask(mask):
"""Generate input mask from bytemask""" |
return input_mask(
shift=bool(mask & MOD_Shift),
lock=bool(mask & MOD_Lock),
control=bool(mask & MOD_Control),
mod1=bool(mask & MOD_Mod1),
mod2=bool(mask & MOD_Mod2),
mod3=bool(mask & MOD_Mod3),
mod4=bool(mask & MOD_Mod4),
mod5=bool(mask & MOD_Mod5)) |
<SYSTEM_TASK:>
Move the mouse to a specific location.
<END_TASK>
<USER_TASK:>
Description:
def move_mouse(self, x, y, screen=0):
"""
Move the mouse to a specific location.
:param x: the target X coordinate on the screen in pixels.
:param y: the target Y coordinate on the screen in pixels.
:param screen: the screen (number) you want to move on.
""" |
# todo: apparently the "screen" argument is not behaving properly
# and sometimes even making the interpreter crash..
# Figure out why (changed API / using wrong header?)
# >>> xdo.move_mouse(3000,200,1)
# X Error of failed request: BadWindow (invalid Window parameter)
# Major opcode of failed request: 41 (X_WarpPointer)
# Resource id in failed request: 0x2a4fca0
# Serial number of failed request: 25
# Current serial number in output stream: 26
# Just to be safe..
# screen = 0
x = ctypes.c_int(x)
y = ctypes.c_int(y)
screen = ctypes.c_int(screen)
_libxdo.xdo_move_mouse(self._xdo, x, y, screen) |
<SYSTEM_TASK:>
Move the mouse to a specific location relative to the top-left corner
<END_TASK>
<USER_TASK:>
Description:
def move_mouse_relative_to_window(self, window, x, y):
"""
Move the mouse to a specific location relative to the top-left corner
of a window.
:param x: the target X coordinate on the screen in pixels.
:param y: the target Y coordinate on the screen in pixels.
""" |
_libxdo.xdo_move_mouse_relative_to_window(
self._xdo, ctypes.c_ulong(window), x, y) |
<SYSTEM_TASK:>
Move the mouse relative to it's current position.
<END_TASK>
<USER_TASK:>
Description:
def move_mouse_relative(self, x, y):
"""
Move the mouse relative to it's current position.
:param x: the distance in pixels to move on the X axis.
:param y: the distance in pixels to move on the Y axis.
""" |
_libxdo.xdo_move_mouse_relative(self._xdo, x, y) |
<SYSTEM_TASK:>
Get the window the mouse is currently over
<END_TASK>
<USER_TASK:>
Description:
def get_window_at_mouse(self):
"""
Get the window the mouse is currently over
""" |
window_ret = ctypes.c_ulong(0)
_libxdo.xdo_get_window_at_mouse(self._xdo, ctypes.byref(window_ret))
return window_ret.value |
<SYSTEM_TASK:>
Get all mouse location-related data.
<END_TASK>
<USER_TASK:>
Description:
def get_mouse_location2(self):
"""
Get all mouse location-related data.
:return: a namedtuple with ``x``, ``y``, ``screen_num``
and ``window`` fields
""" |
x = ctypes.c_int(0)
y = ctypes.c_int(0)
screen_num_ret = ctypes.c_ulong(0)
window_ret = ctypes.c_ulong(0)
_libxdo.xdo_get_mouse_location2(
self._xdo, ctypes.byref(x), ctypes.byref(y),
ctypes.byref(screen_num_ret), ctypes.byref(window_ret))
return mouse_location2(x.value, y.value, screen_num_ret.value,
window_ret.value) |
<SYSTEM_TASK:>
Wait for the mouse to move from a location. This function will block
<END_TASK>
<USER_TASK:>
Description:
def wait_for_mouse_move_from(self, origin_x, origin_y):
"""
Wait for the mouse to move from a location. This function will block
until the condition has been satisified.
:param origin_x: the X position you expect the mouse to move from
:param origin_y: the Y position you expect the mouse to move from
""" |
_libxdo.xdo_wait_for_mouse_move_from(self._xdo, origin_x, origin_y) |
<SYSTEM_TASK:>
Wait for the mouse to move to a location. This function will block
<END_TASK>
<USER_TASK:>
Description:
def wait_for_mouse_move_to(self, dest_x, dest_y):
"""
Wait for the mouse to move to a location. This function will block
until the condition has been satisified.
:param dest_x: the X position you expect the mouse to move to
:param dest_y: the Y position you expect the mouse to move to
""" |
_libxdo.xdo_wait_for_mouse_move_from(self._xdo, dest_x, dest_y) |
<SYSTEM_TASK:>
Send a click for a specific mouse button at the current mouse location.
<END_TASK>
<USER_TASK:>
Description:
def click_window(self, window, button):
"""
Send a click for a specific mouse button at the current mouse location.
:param window:
The window you want to send the event to or CURRENTWINDOW
:param button:
The mouse button. Generally, 1 is left, 2 is middle, 3 is
right, 4 is wheel up, 5 is wheel down.
""" |
_libxdo.xdo_click_window(self._xdo, window, button) |
<SYSTEM_TASK:>
Send a one or more clicks for a specific mouse button at the
<END_TASK>
<USER_TASK:>
Description:
def click_window_multiple(self, window, button, repeat=2, delay=100000):
"""
Send a one or more clicks for a specific mouse button at the
current mouse location.
:param window:
The window you want to send the event to or CURRENTWINDOW
:param button:
The mouse button. Generally, 1 is left, 2 is middle, 3 is
right, 4 is wheel up, 5 is wheel down.
:param repeat: number of repetitions (default: 2)
:param delay: delay between clicks, in microseconds (default: 100k)
""" |
_libxdo.xdo_click_window_multiple(
self._xdo, window, button, repeat, delay) |
<SYSTEM_TASK:>
Type a string to the specified window.
<END_TASK>
<USER_TASK:>
Description:
def enter_text_window(self, window, string, delay=12000):
"""
Type a string to the specified window.
If you want to send a specific key or key sequence, such as
"alt+l", you want instead ``send_keysequence_window(...)``.
:param window:
The window you want to send keystrokes to or CURRENTWINDOW
:param string:
The string to type, like "Hello world!"
:param delay:
The delay between keystrokes in microseconds.
12000 is a decent choice if you don't have other plans.
""" |
return _libxdo.xdo_enter_text_window(self._xdo, window, string, delay) |
<SYSTEM_TASK:>
Send a keysequence to the specified window.
<END_TASK>
<USER_TASK:>
Description:
def send_keysequence_window(self, window, keysequence, delay=12000):
"""
Send a keysequence to the specified window.
This allows you to send keysequences by symbol name. Any combination
of X11 KeySym names separated by '+' are valid. Single KeySym names
are valid, too.
Examples:
"l"
"semicolon"
"alt+Return"
"Alt_L+Tab"
If you want to type a string, such as "Hello world." you want to
instead use xdo_enter_text_window.
:param window: The window you want to send the keysequence to or
CURRENTWINDOW
:param keysequence: The string keysequence to send.
:param delay: The delay between keystrokes in microseconds.
""" |
_libxdo.xdo_send_keysequence_window(
self._xdo, window, keysequence, delay) |
<SYSTEM_TASK:>
Send a series of keystrokes.
<END_TASK>
<USER_TASK:>
Description:
def send_keysequence_window_list_do(
self, window, keys, pressed=1, modifier=None, delay=120000):
"""
Send a series of keystrokes.
:param window: The window to send events to or CURRENTWINDOW
:param keys: The array of charcodemap_t entities to send.
:param pressed: 1 for key press, 0 for key release.
:param modifier:
Pointer to integer to record the modifiers
activated by the keys being pressed. If NULL, we don't save
the modifiers.
:param delay:
The delay between keystrokes in microseconds.
""" |
# todo: how to properly use charcodes_t in a nice way?
_libxdo.xdo_send_keysequence_window_list_do(
self._xdo, window, keys, len(keys), pressed, modifier, delay) |
<SYSTEM_TASK:>
Wait for a window to have a specific map state.
<END_TASK>
<USER_TASK:>
Description:
def wait_for_window_map_state(self, window, state):
"""
Wait for a window to have a specific map state.
State possibilities:
IsUnmapped - window is not displayed.
IsViewable - window is mapped and shown (though may be
clipped by windows on top of it)
IsUnviewable - window is mapped but a parent window is unmapped.
:param window: the window you want to wait for.
:param state: the state to wait for.
""" |
_libxdo.xdo_wait_for_window_map_state(self._xdo, window, state) |
<SYSTEM_TASK:>
Move a window to a specific location.
<END_TASK>
<USER_TASK:>
Description:
def move_window(self, window, x, y):
"""
Move a window to a specific location.
The top left corner of the window will be moved to the x,y coordinate.
:param wid: the window to move
:param x: the X coordinate to move to.
:param y: the Y coordinate to move to.
""" |
_libxdo.xdo_move_window(self._xdo, window, x, y) |
<SYSTEM_TASK:>
Change the window size.
<END_TASK>
<USER_TASK:>
Description:
def set_window_size(self, window, w, h, flags=0):
"""
Change the window size.
:param wid: the window to resize
:param w: the new desired width
:param h: the new desired height
:param flags: if 0, use pixels for units. If SIZE_USEHINTS, then
the units will be relative to the window size hints.
""" |
_libxdo.xdo_set_window_size(self._xdo, window, w, h, flags) |
<SYSTEM_TASK:>
Change a window property.
<END_TASK>
<USER_TASK:>
Description:
def set_window_property(self, window, name, value):
"""
Change a window property.
Example properties you can change are WM_NAME, WM_ICON_NAME, etc.
:param wid: The window to change a property of.
:param name: the string name of the property.
:param value: the string value of the property.
""" |
_libxdo.xdo_set_window_property(self._xdo, window, name, value) |
<SYSTEM_TASK:>
Change the window's classname and or class.
<END_TASK>
<USER_TASK:>
Description:
def set_window_class(self, window, name, class_):
"""
Change the window's classname and or class.
:param name: The new class name. If ``None``, no change.
:param class_: The new class. If ``None``, no change.
""" |
_libxdo.xdo_set_window_class(self._xdo, window, name, class_) |
<SYSTEM_TASK:>
Set the override_redirect value for a window. This generally means
<END_TASK>
<USER_TASK:>
Description:
def set_window_override_redirect(self, window, override_redirect):
"""
Set the override_redirect value for a window. This generally means
whether or not a window manager will manage this window.
If you set it to 1, the window manager will usually not draw
borders on the window, etc. If you set it to 0, the window manager
will see it like a normal application window.
""" |
_libxdo.xdo_set_window_override_redirect(
self._xdo, window, override_redirect) |
<SYSTEM_TASK:>
Get the window currently having focus.
<END_TASK>
<USER_TASK:>
Description:
def get_focused_window(self):
"""
Get the window currently having focus.
:param window_ret:
Pointer to a window where the currently-focused window
will be stored.
""" |
window_ret = window_t(0)
_libxdo.xdo_get_focused_window(self._xdo, ctypes.byref(window_ret))
return window_ret.value |
<SYSTEM_TASK:>
Wait for a window to have or lose focus.
<END_TASK>
<USER_TASK:>
Description:
def wait_for_window_focus(self, window, want_focus):
"""
Wait for a window to have or lose focus.
:param window: The window to wait on
:param want_focus: If 1, wait for focus. If 0, wait for loss of focus.
""" |
_libxdo.xdo_wait_for_window_focus(self._xdo, window, want_focus) |
<SYSTEM_TASK:>
Wait for a window to be active or not active.
<END_TASK>
<USER_TASK:>
Description:
def wait_for_window_active(self, window, active=1):
"""
Wait for a window to be active or not active.
Requires your window manager to support this.
Uses _NET_ACTIVE_WINDOW from the EWMH spec.
:param window: the window to wait on
:param active: If 1, wait for active. If 0, wait for inactive.
""" |
_libxdo.xdo_wait_for_window_active(self._xdo, window, active) |
<SYSTEM_TASK:>
Reparents a window
<END_TASK>
<USER_TASK:>
Description:
def reparent_window(self, window_source, window_target):
"""
Reparents a window
:param wid_source: the window to reparent
:param wid_target: the new parent window
""" |
_libxdo.xdo_reparent_window(self._xdo, window_source, window_target) |
<SYSTEM_TASK:>
Get the currently-active window.
<END_TASK>
<USER_TASK:>
Description:
def get_active_window(self):
"""
Get the currently-active window.
Requires your window manager to support this.
Uses ``_NET_ACTIVE_WINDOW`` from the EWMH spec.
""" |
window_ret = window_t(0)
_libxdo.xdo_get_active_window(self._xdo, ctypes.byref(window_ret))
return window_ret.value |
<SYSTEM_TASK:>
Get a window ID by clicking on it.
<END_TASK>
<USER_TASK:>
Description:
def select_window_with_click(self):
"""
Get a window ID by clicking on it.
This function blocks until a selection is made.
""" |
window_ret = window_t(0)
_libxdo.xdo_select_window_with_click(
self._xdo, ctypes.byref(window_ret))
return window_ret.value |
<SYSTEM_TASK:>
Get the current number of desktops.
<END_TASK>
<USER_TASK:>
Description:
def get_number_of_desktops(self):
"""
Get the current number of desktops.
Uses ``_NET_NUMBER_OF_DESKTOPS`` of the EWMH spec.
:param ndesktops:
pointer to long where the current number of desktops is stored
""" |
ndesktops = ctypes.c_long(0)
_libxdo.xdo_get_number_of_desktops(self._xdo, ctypes.byref(ndesktops))
return ndesktops.value |
<SYSTEM_TASK:>
Move a window to another desktop
<END_TASK>
<USER_TASK:>
Description:
def set_desktop_for_window(self, window, desktop):
"""
Move a window to another desktop
Uses _NET_WM_DESKTOP of the EWMH spec.
:param wid: the window to move
:param desktop: the desktop destination for the window
""" |
_libxdo.xdo_set_desktop_for_window(self._xdo, window, desktop) |
<SYSTEM_TASK:>
Get the desktop a window is on.
<END_TASK>
<USER_TASK:>
Description:
def get_desktop_for_window(self, window):
"""
Get the desktop a window is on.
Uses _NET_WM_DESKTOP of the EWMH spec.
If your desktop does not support ``_NET_WM_DESKTOP``, then '*desktop'
remains unmodified.
:param wid: the window to query
""" |
desktop = ctypes.c_long(0)
_libxdo.xdo_get_desktop_for_window(
self._xdo, window, ctypes.byref(desktop))
return desktop.value |
<SYSTEM_TASK:>
Search for windows.
<END_TASK>
<USER_TASK:>
Description:
def search_windows(
self, winname=None, winclass=None, winclassname=None,
pid=None, only_visible=False, screen=None, require=False,
searchmask=0, desktop=None, limit=0, max_depth=-1):
"""
Search for windows.
:param winname:
Regexp to be matched against window name
:param winclass:
Regexp to be matched against window class
:param winclassname:
Regexp to be matched against window class name
:param pid:
Only return windows from this PID
:param only_visible:
If True, only return visible windows
:param screen:
Search only windows on this screen
:param require:
If True, will match ALL conditions. Otherwise, windows matching
ANY condition will be returned.
:param searchmask:
Search mask, for advanced usage. Leave this alone if you
don't kwnow what you are doing.
:param limit:
Maximum number of windows to list. Zero means no limit.
:param max_depth:
Maximum depth to return. Defaults to -1, meaning "no limit".
:return:
A list of window ids matching query.
""" |
windowlist_ret = ctypes.pointer(window_t(0))
nwindows_ret = ctypes.c_uint(0)
search = xdo_search_t(searchmask=searchmask)
if winname is not None:
search.winname = winname
search.searchmask |= SEARCH_NAME
if winclass is not None:
search.winclass = winclass
search.searchmask |= SEARCH_CLASS
if winclassname is not None:
search.winclassname = winclassname
search.searchmask |= SEARCH_CLASSNAME
if pid is not None:
search.pid = pid
search.searchmask |= SEARCH_PID
if only_visible:
search.only_visible = True
search.searchmask |= SEARCH_ONLYVISIBLE
if screen is not None:
search.screen = screen
search.searchmask |= SEARCH_SCREEN
if screen is not None:
search.screen = desktop
search.searchmask |= SEARCH_DESKTOP
search.limit = limit
search.max_depth = max_depth
_libxdo.xdo_search_windows(
self._xdo, search,
ctypes.byref(windowlist_ret),
ctypes.byref(nwindows_ret))
return [windowlist_ret[i] for i in range(nwindows_ret.value)] |
<SYSTEM_TASK:>
If you need the symbol map, use this method.
<END_TASK>
<USER_TASK:>
Description:
def get_symbol_map(self):
"""
If you need the symbol map, use this method.
The symbol map is an array of string pairs mapping common tokens
to X Keysym strings, such as "alt" to "Alt_L"
:return: array of strings.
""" |
# todo: make sure we return a list of strings!
sm = _libxdo.xdo_get_symbol_map()
# Return value is like:
# ['alt', 'Alt_L', ..., None, None, None, ...]
# We want to return only values up to the first None.
# todo: any better solution than this?
i = 0
ret = []
while True:
c = sm[i]
if c is None:
return ret
ret.append(c)
i += 1 |
<SYSTEM_TASK:>
Get a list of active keys. Uses XQueryKeymap.
<END_TASK>
<USER_TASK:>
Description:
def get_active_modifiers(self):
"""
Get a list of active keys. Uses XQueryKeymap.
:return: list of charcodemap_t instances
""" |
keys = ctypes.pointer(charcodemap_t())
nkeys = ctypes.c_int(0)
_libxdo.xdo_get_active_modifiers(
self._xdo, ctypes.byref(keys), ctypes.byref(nkeys))
return [keys[i] for i in range(nkeys.value)] |
<SYSTEM_TASK:>
Attempts to cast given value to an integer, return the original value if failed or the default if one provided.
<END_TASK>
<USER_TASK:>
Description:
def coerce_to_int(val, default=0xDEADBEEF):
"""Attempts to cast given value to an integer, return the original value if failed or the default if one provided.""" |
try:
return int(val)
except (TypeError, ValueError):
if default != 0xDEADBEEF:
return default
return val |
<SYSTEM_TASK:>
Given year, month and day numeric values and a timezone
<END_TASK>
<USER_TASK:>
Description:
def date_struct(year, month, day, tz = "UTC"):
"""
Given year, month and day numeric values and a timezone
convert to structured date object
""" |
ymdtz = (year, month, day, tz)
if None in ymdtz:
#logger.debug("a year, month, day or tz value was empty: %s" % str(ymdtz))
return None # return early if we have a bad value
try:
return time.strptime("%s-%s-%s %s" % ymdtz, "%Y-%m-%d %Z")
except(TypeError, ValueError):
#logger.debug("date failed to convert: %s" % str(ymdtz))
pass |
<SYSTEM_TASK:>
Assemble a date object but if day or month is none set them to 1
<END_TASK>
<USER_TASK:>
Description:
def date_struct_nn(year, month, day, tz="UTC"):
"""
Assemble a date object but if day or month is none set them to 1
to make it easier to deal with partial dates
""" |
if not day:
day = 1
if not month:
month = 1
return date_struct(year, month, day, tz) |
<SYSTEM_TASK:>
Only intended for use in getting components, look for tag name of fig-group
<END_TASK>
<USER_TASK:>
Description:
def component_acting_parent_tag(parent_tag, tag):
"""
Only intended for use in getting components, look for tag name of fig-group
and if so, find the first fig tag inside it as the acting parent tag
""" |
if parent_tag.name == "fig-group":
if (len(tag.find_previous_siblings("fig")) > 0):
acting_parent_tag = first(extract_nodes(parent_tag, "fig"))
else:
# Do not return the first fig as parent of itself
return None
else:
acting_parent_tag = parent_tag
return acting_parent_tag |
<SYSTEM_TASK:>
Given a beautiful soup tag, look at its parents and return the first
<END_TASK>
<USER_TASK:>
Description:
def first_parent(tag, nodename):
"""
Given a beautiful soup tag, look at its parents and return the first
tag name that matches nodename or the list nodename
""" |
if nodename is not None and type(nodename) == str:
nodename = [nodename]
return first(list(filter(lambda tag: tag.name in nodename, tag.parents))) |
<SYSTEM_TASK:>
Meant for finding the position of fig tags with respect to whether
<END_TASK>
<USER_TASK:>
Description:
def tag_fig_ordinal(tag):
"""
Meant for finding the position of fig tags with respect to whether
they are for a main figure or a child figure
""" |
tag_count = 0
if 'specific-use' not in tag.attrs:
# Look for tags with no "specific-use" attribute
return len(list(filter(lambda tag: 'specific-use' not in tag.attrs,
tag.find_all_previous(tag.name)))) + 1 |
<SYSTEM_TASK:>
Count previous tags of the same name until it
<END_TASK>
<USER_TASK:>
Description:
def tag_limit_sibling_ordinal(tag, stop_tag_name):
"""
Count previous tags of the same name until it
reaches a tag name of type stop_tag, then stop counting
""" |
tag_count = 1
for prev_tag in tag.previous_elements:
if prev_tag.name == tag.name:
tag_count += 1
if prev_tag.name == stop_tag_name:
break
return tag_count |
<SYSTEM_TASK:>
Count sibling ordinal differently depending on if the
<END_TASK>
<USER_TASK:>
Description:
def tag_media_sibling_ordinal(tag):
"""
Count sibling ordinal differently depending on if the
mimetype is video or not
""" |
if hasattr(tag, 'name') and tag.name != 'media':
return None
nodenames = ['fig','supplementary-material','sub-article']
first_parent_tag = first_parent(tag, nodenames)
sibling_ordinal = None
if first_parent_tag:
# Start counting at 0
sibling_ordinal = 0
for media_tag in first_parent_tag.find_all(tag.name):
if 'mimetype' in tag.attrs and tag['mimetype'] == 'video':
# Count all video type media tags
if 'mimetype' in media_tag.attrs and tag['mimetype'] == 'video':
sibling_ordinal += 1
if media_tag == tag:
break
else:
# Count all non-video type media tags
if (('mimetype' not in media_tag.attrs)
or ('mimetype' in media_tag.attrs and tag['mimetype'] != 'video')):
sibling_ordinal += 1
if media_tag == tag:
break
else:
# Start counting at 1
sibling_ordinal = 1
for prev_tag in tag.find_all_previous(tag.name):
if not first_parent(prev_tag, nodenames):
if 'mimetype' in tag.attrs and tag['mimetype'] == 'video':
# Count all video type media tags
if supp_asset(prev_tag) == supp_asset(tag) and 'mimetype' in prev_tag.attrs:
sibling_ordinal += 1
else:
if supp_asset(prev_tag) == supp_asset(tag) and 'mimetype' not in prev_tag.attrs:
sibling_ordinal += 1
return sibling_ordinal |
<SYSTEM_TASK:>
Strategy is to count the previous supplementary-material tags
<END_TASK>
<USER_TASK:>
Description:
def tag_supplementary_material_sibling_ordinal(tag):
"""
Strategy is to count the previous supplementary-material tags
having the same asset value to get its sibling ordinal.
The result is its position inside any parent tag that
are the same asset type
""" |
if hasattr(tag, 'name') and tag.name != 'supplementary-material':
return None
nodenames = ['fig','media','sub-article']
first_parent_tag = first_parent(tag, nodenames)
sibling_ordinal = 1
if first_parent_tag:
# Within the parent tag of interest, count the tags
# having the same asset value
for supp_tag in first_parent_tag.find_all(tag.name):
if tag == supp_tag:
# Stop once we reach the same tag we are checking
break
if supp_asset(supp_tag) == supp_asset(tag):
sibling_ordinal += 1
else:
# Look in all previous elements that do not have a parent
# and count the tags having the same asset value
for prev_tag in tag.find_all_previous(tag.name):
if not first_parent(prev_tag, nodenames):
if supp_asset(prev_tag) == supp_asset(tag):
sibling_ordinal += 1
return sibling_ordinal |
<SYSTEM_TASK:>
when a title is required, generate one from the value
<END_TASK>
<USER_TASK:>
Description:
def text_to_title(value):
"""when a title is required, generate one from the value""" |
title = None
if not value:
return title
words = value.split(" ")
keep_words = []
for word in words:
if word.endswith(".") or word.endswith(":"):
keep_words.append(word)
if len(word) > 1 and "<italic>" not in word and "<i>" not in word:
break
else:
keep_words.append(word)
if len(keep_words) > 0:
title = " ".join(keep_words)
if title.split(" ")[-1] != "spp.":
title = title.rstrip(" .:")
return title |
<SYSTEM_TASK:>
Quick convert unicode ampersand characters not associated with
<END_TASK>
<USER_TASK:>
Description:
def escape_ampersand(string):
"""
Quick convert unicode ampersand characters not associated with
a numbered entity or not starting with allowed characters to a plain &
""" |
if not string:
return string
start_with_match = r"(\#x(....);|lt;|gt;|amp;)"
# The pattern below is match & that is not immediately followed by #
string = re.sub(r"&(?!" + start_with_match + ")", '&', string)
return string |
<SYSTEM_TASK:>
to extract the doctype details from the file when parsed and return the data
<END_TASK>
<USER_TASK:>
Description:
def parse(filename, return_doctype_dict=False):
"""
to extract the doctype details from the file when parsed and return the data
for later use, set return_doctype_dict to True
""" |
doctype_dict = {}
# check for python version, doctype in ElementTree is deprecated 3.2 and above
if sys.version_info < (3,2):
parser = CustomXMLParser(html=0, target=None, encoding='utf-8')
else:
# Assume greater than Python 3.2, get the doctype from the TreeBuilder
tree_builder = CustomTreeBuilder()
parser = ElementTree.XMLParser(html=0, target=tree_builder, encoding='utf-8')
tree = ElementTree.parse(filename, parser)
root = tree.getroot()
if sys.version_info < (3,2):
doctype_dict = parser.doctype_dict
else:
doctype_dict = tree_builder.doctype_dict
if return_doctype_dict is True:
return root, doctype_dict
else:
return root |
<SYSTEM_TASK:>
Helper function to refactor the adding of new tags
<END_TASK>
<USER_TASK:>
Description:
def add_tag_before(tag_name, tag_text, parent_tag, before_tag_name):
"""
Helper function to refactor the adding of new tags
especially for when converting text to role tags
""" |
new_tag = Element(tag_name)
new_tag.text = tag_text
if get_first_element_index(parent_tag, before_tag_name):
parent_tag.insert( get_first_element_index(parent_tag, before_tag_name) - 1, new_tag)
return parent_tag |
<SYSTEM_TASK:>
Instantiate an ElifeDocumentType, a subclass of minidom.DocumentType, with
<END_TASK>
<USER_TASK:>
Description:
def build_doctype(qualifiedName, publicId=None, systemId=None, internalSubset=None):
"""
Instantiate an ElifeDocumentType, a subclass of minidom.DocumentType, with
some properties so it is more testable
""" |
doctype = ElifeDocumentType(qualifiedName)
doctype._identified_mixin_init(publicId, systemId)
if internalSubset:
doctype.internalSubset = internalSubset
return doctype |
<SYSTEM_TASK:>
Due to XML content that will not conform with the strict JSON schema validation rules,
<END_TASK>
<USER_TASK:>
Description:
def rewrite_json(rewrite_type, soup, json_content):
"""
Due to XML content that will not conform with the strict JSON schema validation rules,
for elife articles only, rewrite the JSON to make it valid
""" |
if not soup:
return json_content
if not elifetools.rawJATS.doi(soup) or not elifetools.rawJATS.journal_id(soup):
return json_content
# Hook only onto elife articles for rewriting currently
journal_id_tag = elifetools.rawJATS.journal_id(soup)
doi_tag = elifetools.rawJATS.doi(soup)
journal_id = elifetools.utils.node_text(journal_id_tag)
doi = elifetools.utils.doi_uri_to_doi(elifetools.utils.node_text(doi_tag))
if journal_id.lower() == "elife":
function_name = rewrite_function_name(journal_id, rewrite_type)
if function_name:
try:
json_content = globals()[function_name](json_content, doi)
except KeyError:
pass
return json_content |
<SYSTEM_TASK:>
this does the work of rewriting elife references json
<END_TASK>
<USER_TASK:>
Description:
def rewrite_elife_references_json(json_content, doi):
""" this does the work of rewriting elife references json """ |
references_rewrite_json = elife_references_rewrite_json()
if doi in references_rewrite_json:
json_content = rewrite_references_json(json_content, references_rewrite_json[doi])
# Edge case delete one reference
if doi == "10.7554/eLife.12125":
for i, ref in enumerate(json_content):
if ref.get("id") and ref.get("id") == "bib11":
del json_content[i]
return json_content |
<SYSTEM_TASK:>
general purpose references json rewriting by matching the id value
<END_TASK>
<USER_TASK:>
Description:
def rewrite_references_json(json_content, rewrite_json):
""" general purpose references json rewriting by matching the id value """ |
for ref in json_content:
if ref.get("id") and ref.get("id") in rewrite_json:
for key, value in iteritems(rewrite_json.get(ref.get("id"))):
ref[key] = value
return json_content |
<SYSTEM_TASK:>
rewrite elife funding awards
<END_TASK>
<USER_TASK:>
Description:
def rewrite_elife_funding_awards(json_content, doi):
""" rewrite elife funding awards """ |
# remove a funding award
if doi == "10.7554/eLife.00801":
for i, award in enumerate(json_content):
if "id" in award and award["id"] == "par-2":
del json_content[i]
# add funding award recipient
if doi == "10.7554/eLife.04250":
recipients_for_04250 = [{"type": "person", "name": {"preferred": "Eric Jonas", "index": "Jonas, Eric"}}]
for i, award in enumerate(json_content):
if "id" in award and award["id"] in ["par-2", "par-3", "par-4"]:
if "recipients" not in award:
json_content[i]["recipients"] = recipients_for_04250
# add funding award recipient
if doi == "10.7554/eLife.06412":
recipients_for_06412 = [{"type": "person", "name": {"preferred": "Adam J Granger", "index": "Granger, Adam J"}}]
for i, award in enumerate(json_content):
if "id" in award and award["id"] == "par-1":
if "recipients" not in award:
json_content[i]["recipients"] = recipients_for_06412
return json_content |
<SYSTEM_TASK:>
Run the linter over the new metadata, comparing to the old.
<END_TASK>
<USER_TASK:>
Description:
def metadata_lint(old, new, locations):
"""Run the linter over the new metadata, comparing to the old.""" |
# ensure we don't modify the metadata
old = old.copy()
new = new.copy()
# remove version info
old.pop('$version', None)
new.pop('$version', None)
for old_group_name in old:
if old_group_name not in new:
yield LintError('', 'api group removed', api_name=old_group_name)
for group_name, new_group in new.items():
old_group = old.get(group_name, {'apis': {}})
for name, api in new_group['apis'].items():
old_api = old_group['apis'].get(name, {})
api_locations = locations[name]
for message in lint_api(name, old_api, api, api_locations):
message.api_name = name
if message.location is None:
message.location = api_locations['api']
yield message |
<SYSTEM_TASK:>
Serialize into JSONable dict, and associated locations data.
<END_TASK>
<USER_TASK:>
Description:
def serialize(self):
"""Serialize into JSONable dict, and associated locations data.""" |
api_metadata = OrderedDict()
# $ char makes this come first in sort ordering
api_metadata['$version'] = self.current_version
locations = {}
for svc_name, group in self.groups():
group_apis = OrderedDict()
group_metadata = OrderedDict()
group_metadata['apis'] = group_apis
group_metadata['title'] = group.title
api_metadata[group.name] = group_metadata
if group.docs is not None:
group_metadata['docs'] = group.docs
for name, api in group.items():
group_apis[name] = OrderedDict()
group_apis[name]['service'] = svc_name
group_apis[name]['api_group'] = group.name
group_apis[name]['api_name'] = api.name
group_apis[name]['introduced_at'] = api.introduced_at
group_apis[name]['methods'] = api.methods
group_apis[name]['request_schema'] = api.request_schema
group_apis[name]['response_schema'] = api.response_schema
group_apis[name]['doc'] = api.docs
group_apis[name]['changelog'] = api._changelog
if api.title:
group_apis[name]['title'] = api.title
else:
title = name.replace('-', ' ').replace('_', ' ').title()
group_apis[name]['title'] = title
group_apis[name]['url'] = api.resolve_url()
if api.undocumented:
group_apis[name]['undocumented'] = True
if api.deprecated_at is not None:
group_apis[name]['deprecated_at'] = api.deprecated_at
locations[name] = {
'api': api.location,
'request_schema': api._request_schema_location,
'response_schema': api._response_schema_location,
'changelog': api._changelog_locations,
'view': api.view_fn_location,
}
return api_metadata, locations |
<SYSTEM_TASK:>
Add an API to the service.
<END_TASK>
<USER_TASK:>
Description:
def api(self,
url,
name,
introduced_at=None,
undocumented=False,
deprecated_at=None,
title=None,
**options):
"""Add an API to the service.
:param url: This is the url that the API should be registered at.
:param name: This is the name of the api, and will be registered with
flask apps under.
Other keyword arguments may be used, and they will be passed to the
flask application when initialised. Of particular interest is the
'methods' keyword argument, which can be used to specify the HTTP
method the URL will be added for.
""" |
location = get_callsite_location()
api = AcceptableAPI(
self,
name,
url,
introduced_at,
options,
undocumented=undocumented,
deprecated_at=deprecated_at,
title=title,
location=location,
)
self.metadata.register_api(self.name, self.group, api)
return api |
<SYSTEM_TASK:>
Add a django API handler to the service.
<END_TASK>
<USER_TASK:>
Description:
def django_api(
self,
name,
introduced_at,
undocumented=False,
deprecated_at=None,
title=None,
**options):
"""Add a django API handler to the service.
:param name: This is the name of the django url to use.
The 'methods' paramater can be supplied as normal, you can also user
the @api.handler decorator to link this API to its handler.
""" |
from acceptable.djangoutil import DjangoAPI
location = get_callsite_location()
api = DjangoAPI(
self,
name,
introduced_at,
options,
location=location,
undocumented=undocumented,
deprecated_at=deprecated_at,
title=title,
)
self.metadata.register_api(self.name, self.group, api)
return api |
<SYSTEM_TASK:>
Add a changelog entry for this api.
<END_TASK>
<USER_TASK:>
Description:
def changelog(self, api_version, doc):
"""Add a changelog entry for this api.""" |
doc = textwrap.dedent(doc).strip()
self._changelog[api_version] = doc
self._changelog_locations[api_version] = get_callsite_location() |
<SYSTEM_TASK:>
Find the keywords from the set of kwd-group tags
<END_TASK>
<USER_TASK:>
Description:
def keywords(soup):
"""
Find the keywords from the set of kwd-group tags
which are typically labelled as the author keywords
""" |
if not raw_parser.author_keywords(soup):
return []
return list(map(node_text, raw_parser.author_keywords(soup))) |
<SYSTEM_TASK:>
return a list of article-id data
<END_TASK>
<USER_TASK:>
Description:
def article_id_list(soup):
"""return a list of article-id data""" |
id_list = []
for article_id_tag in raw_parser.article_id(soup):
id_details = OrderedDict()
set_if_value(id_details, "type", article_id_tag.get("pub-id-type"))
set_if_value(id_details, "value", article_id_tag.text)
set_if_value(id_details, "assigning-authority", article_id_tag.get("assigning-authority"))
id_list.append(id_details)
return id_list |
<SYSTEM_TASK:>
Find the subject areas from article-categories subject tags
<END_TASK>
<USER_TASK:>
Description:
def subject_area(soup):
"""
Find the subject areas from article-categories subject tags
""" |
subject_area = []
tags = raw_parser.subject_area(soup)
for tag in tags:
subject_area.append(node_text(tag))
return subject_area |
<SYSTEM_TASK:>
Find the subject areas of type display-channel
<END_TASK>
<USER_TASK:>
Description:
def display_channel(soup):
"""
Find the subject areas of type display-channel
""" |
display_channel = []
tags = raw_parser.display_channel(soup)
for tag in tags:
display_channel.append(node_text(tag))
return display_channel |
<SYSTEM_TASK:>
Find the category from subject areas
<END_TASK>
<USER_TASK:>
Description:
def category(soup):
"""
Find the category from subject areas
""" |
category = []
tags = raw_parser.category(soup)
for tag in tags:
category.append(node_text(tag))
return category |
<SYSTEM_TASK:>
Get the year, month and day from child tags
<END_TASK>
<USER_TASK:>
Description:
def ymd(soup):
"""
Get the year, month and day from child tags
""" |
day = node_text(raw_parser.day(soup))
month = node_text(raw_parser.month(soup))
year = node_text(raw_parser.year(soup))
return (day, month, year) |
<SYSTEM_TASK:>
Return the publishing date in struct format
<END_TASK>
<USER_TASK:>
Description:
def pub_date(soup):
"""
Return the publishing date in struct format
pub_date_date, pub_date_day, pub_date_month, pub_date_year, pub_date_timestamp
Default date_type is pub
""" |
pub_date = first(raw_parser.pub_date(soup, date_type="pub"))
if pub_date is None:
pub_date = first(raw_parser.pub_date(soup, date_type="publication"))
if pub_date is None:
return None
(day, month, year) = ymd(pub_date)
return date_struct(year, month, day) |
<SYSTEM_TASK:>
return a list of all the pub dates
<END_TASK>
<USER_TASK:>
Description:
def pub_dates(soup):
"""
return a list of all the pub dates
""" |
pub_dates = []
tags = raw_parser.pub_date(soup)
for tag in tags:
pub_date = OrderedDict()
copy_attribute(tag.attrs, 'publication-format', pub_date)
copy_attribute(tag.attrs, 'date-type', pub_date)
copy_attribute(tag.attrs, 'pub-type', pub_date)
for tag_attr in ["date-type", "pub-type"]:
if tag_attr in tag.attrs:
(day, month, year) = ymd(tag)
pub_date['day'] = day
pub_date['month'] = month
pub_date['year'] = year
pub_date['date'] = date_struct_nn(year, month, day)
pub_dates.append(pub_date)
return pub_dates |
<SYSTEM_TASK:>
Pub date of type collection will hold a year element for VOR articles
<END_TASK>
<USER_TASK:>
Description:
def collection_year(soup):
"""
Pub date of type collection will hold a year element for VOR articles
""" |
pub_date = first(raw_parser.pub_date(soup, pub_type="collection"))
if not pub_date:
pub_date = first(raw_parser.pub_date(soup, date_type="collection"))
if not pub_date:
return None
year = None
year_tag = raw_parser.year(pub_date)
if year_tag:
year = int(node_text(year_tag))
return year |
<SYSTEM_TASK:>
Find the article abstract and format it
<END_TASK>
<USER_TASK:>
Description:
def abstracts(soup):
"""
Find the article abstract and format it
""" |
abstracts = []
abstract_tags = raw_parser.abstract(soup)
for tag in abstract_tags:
abstract = {}
abstract["abstract_type"] = tag.get("abstract-type")
title_tag = raw_parser.title(tag)
if title_tag:
abstract["title"] = node_text(title_tag)
abstract["content"] = None
if raw_parser.paragraph(tag):
abstract["content"] = ""
abstract["full_content"] = ""
good_paragraphs = remove_doi_paragraph(raw_parser.paragraph(tag))
# Plain text content
glue = ""
for p_tag in good_paragraphs:
abstract["content"] += glue + node_text(p_tag)
glue = " "
# Content including markup tags
# When more than one paragraph, wrap each in a <p> tag
for p_tag in good_paragraphs:
abstract["full_content"] += '<p>' + node_contents_str(p_tag) + '</p>'
abstracts.append(abstract)
return abstracts |
<SYSTEM_TASK:>
Look for all object-id of pub-type-id = doi, these are the component DOI tags
<END_TASK>
<USER_TASK:>
Description:
def component_doi(soup):
"""
Look for all object-id of pub-type-id = doi, these are the component DOI tags
""" |
component_doi = []
object_id_tags = raw_parser.object_id(soup, pub_id_type = "doi")
# Get components too for later
component_list = components(soup)
position = 1
for tag in object_id_tags:
component_object = {}
component_object["doi"] = doi_uri_to_doi(tag.text)
component_object["position"] = position
# Try to find the type of component
for component in component_list:
if "doi" in component and component["doi"] == component_object["doi"]:
component_object["type"] = component["type"]
component_doi.append(component_object)
position = position + 1
return component_doi |
<SYSTEM_TASK:>
Used in media and graphics to extract data from their parent tags
<END_TASK>
<USER_TASK:>
Description:
def tag_details(tag, nodenames):
"""
Used in media and graphics to extract data from their parent tags
""" |
details = {}
details['type'] = tag.name
details['ordinal'] = tag_ordinal(tag)
# Ordinal value
if tag_details_sibling_ordinal(tag):
details['sibling_ordinal'] = tag_details_sibling_ordinal(tag)
# Asset name
if tag_details_asset(tag):
details['asset'] = tag_details_asset(tag)
object_id_tag = first(raw_parser.object_id(tag, pub_id_type= "doi"))
if object_id_tag:
details['component_doi'] = extract_component_doi(tag, nodenames)
return details |
<SYSTEM_TASK:>
Given a contrib tag, look for an email tag, and
<END_TASK>
<USER_TASK:>
Description:
def contrib_email(contrib_tag):
"""
Given a contrib tag, look for an email tag, and
only return the value if it is not inside an aff tag
""" |
email = []
for email_tag in extract_nodes(contrib_tag, "email"):
if email_tag.parent.name != "aff":
email.append(email_tag.text)
return email if len(email) > 0 else None |
<SYSTEM_TASK:>
Given a contrib tag, look for an phone tag
<END_TASK>
<USER_TASK:>
Description:
def contrib_phone(contrib_tag):
"""
Given a contrib tag, look for an phone tag
""" |
phone = None
if raw_parser.phone(contrib_tag):
phone = first(raw_parser.phone(contrib_tag)).text
return phone |
<SYSTEM_TASK:>
Given a contrib tag, look for an aff tag directly inside it
<END_TASK>
<USER_TASK:>
Description:
def contrib_inline_aff(contrib_tag):
"""
Given a contrib tag, look for an aff tag directly inside it
""" |
aff_tags = []
for child_tag in contrib_tag:
if child_tag and child_tag.name and child_tag.name == "aff":
aff_tags.append(child_tag)
return aff_tags |
<SYSTEM_TASK:>
Given a contrib tag, look for an xref tag of type ref_type directly inside the contrib tag
<END_TASK>
<USER_TASK:>
Description:
def contrib_xref(contrib_tag, ref_type):
"""
Given a contrib tag, look for an xref tag of type ref_type directly inside the contrib tag
""" |
aff_tags = []
for child_tag in contrib_tag:
if (child_tag and child_tag.name and child_tag.name == "xref"
and child_tag.get('ref-type') and child_tag.get('ref-type') == ref_type):
aff_tags.append(child_tag)
return aff_tags |
<SYSTEM_TASK:>
Non-byline authors for group author members
<END_TASK>
<USER_TASK:>
Description:
def authors_non_byline(soup, detail="full"):
"""Non-byline authors for group author members""" |
# Get a filtered list of contributors, in order to get their group-author-id
contrib_type = "author non-byline"
contributors_ = contributors(soup, detail)
non_byline_authors = [author for author in contributors_ if author.get('type', None) == contrib_type]
# Then renumber their position attribute
position = 1
for author in non_byline_authors:
author["position"] = position
position = position + 1
return non_byline_authors |