repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
abilian/abilian-core | abilian/services/security/service.py | SecurityService.ungrant_role | def ungrant_role(self, principal, role, object=None):
"""Ungrant `role` to `user` (either globally, if `object` is None, or
on the specific `object`)."""
assert principal
principal = unwrap(principal)
session = object_session(object) if object is not None else db.session
... | python | def ungrant_role(self, principal, role, object=None):
"""Ungrant `role` to `user` (either globally, if `object` is None, or
on the specific `object`)."""
assert principal
principal = unwrap(principal)
session = object_session(object) if object is not None else db.session
... | [
"def",
"ungrant_role",
"(",
"self",
",",
"principal",
",",
"role",
",",
"object",
"=",
"None",
")",
":",
"assert",
"principal",
"principal",
"=",
"unwrap",
"(",
"principal",
")",
"session",
"=",
"object_session",
"(",
"object",
")",
"if",
"object",
"is",
... | Ungrant `role` to `user` (either globally, if `object` is None, or
on the specific `object`). | [
"Ungrant",
"role",
"to",
"user",
"(",
"either",
"globally",
"if",
"object",
"is",
"None",
"or",
"on",
"the",
"specific",
"object",
")",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/security/service.py#L534-L576 |
abilian/abilian-core | abilian/services/security/service.py | SecurityService.has_permission | def has_permission(self, user, permission, obj=None, inherit=False, roles=None):
"""
:param obj: target object to check permissions.
:param inherit: check with permission inheritance. By default, check only
local roles.
:param roles: additional valid role or itera... | python | def has_permission(self, user, permission, obj=None, inherit=False, roles=None):
"""
:param obj: target object to check permissions.
:param inherit: check with permission inheritance. By default, check only
local roles.
:param roles: additional valid role or itera... | [
"def",
"has_permission",
"(",
"self",
",",
"user",
",",
"permission",
",",
"obj",
"=",
"None",
",",
"inherit",
"=",
"False",
",",
"roles",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"permission",
",",
"Permission",
")",
":",
"assert",
"perm... | :param obj: target object to check permissions.
:param inherit: check with permission inheritance. By default, check only
local roles.
:param roles: additional valid role or iterable of roles having
`permission`. | [
":",
"param",
"obj",
":",
"target",
"object",
"to",
"check",
"permissions",
".",
":",
"param",
"inherit",
":",
"check",
"with",
"permission",
"inheritance",
".",
"By",
"default",
"check",
"only",
"local",
"roles",
".",
":",
"param",
"roles",
":",
"addition... | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/security/service.py#L604-L676 |
abilian/abilian-core | abilian/services/security/service.py | SecurityService.query_entity_with_permission | def query_entity_with_permission(self, permission, user=None, Model=Entity):
"""Filter a query on an :class:`Entity` or on of its subclasses.
Usage::
read_q = security.query_entity_with_permission(READ, Model=MyModel)
MyModel.query.filter(read_q)
It should always be pl... | python | def query_entity_with_permission(self, permission, user=None, Model=Entity):
"""Filter a query on an :class:`Entity` or on of its subclasses.
Usage::
read_q = security.query_entity_with_permission(READ, Model=MyModel)
MyModel.query.filter(read_q)
It should always be pl... | [
"def",
"query_entity_with_permission",
"(",
"self",
",",
"permission",
",",
"user",
"=",
"None",
",",
"Model",
"=",
"Entity",
")",
":",
"assert",
"isinstance",
"(",
"permission",
",",
"Permission",
")",
"assert",
"issubclass",
"(",
"Model",
",",
"Entity",
")... | Filter a query on an :class:`Entity` or on of its subclasses.
Usage::
read_q = security.query_entity_with_permission(READ, Model=MyModel)
MyModel.query.filter(read_q)
It should always be placed before any `.join()` happens in the query; else
sqlalchemy might join to th... | [
"Filter",
"a",
"query",
"on",
"an",
":",
"class",
":",
"Entity",
"or",
"on",
"of",
"its",
"subclasses",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/security/service.py#L678-L761 |
abilian/abilian-core | abilian/services/security/service.py | SecurityService.get_permissions_assignments | def get_permissions_assignments(self, obj=None, permission=None):
"""
:param permission: return only roles having this permission
:returns: an dict where keys are `permissions` and values `roles` iterable.
"""
session = None
if obj is not None:
assert isinsta... | python | def get_permissions_assignments(self, obj=None, permission=None):
"""
:param permission: return only roles having this permission
:returns: an dict where keys are `permissions` and values `roles` iterable.
"""
session = None
if obj is not None:
assert isinsta... | [
"def",
"get_permissions_assignments",
"(",
"self",
",",
"obj",
"=",
"None",
",",
"permission",
"=",
"None",
")",
":",
"session",
"=",
"None",
"if",
"obj",
"is",
"not",
"None",
":",
"assert",
"isinstance",
"(",
"obj",
",",
"Entity",
")",
"session",
"=",
... | :param permission: return only roles having this permission
:returns: an dict where keys are `permissions` and values `roles` iterable. | [
":",
"param",
"permission",
":",
"return",
"only",
"roles",
"having",
"this",
"permission"
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/security/service.py#L763-L791 |
abilian/abilian-core | abilian/web/assets/mixin.py | AssetManagerMixin.register_asset | def register_asset(self, type_, *assets):
"""Register webassets bundle to be served on all pages.
:param type_: `"css"`, `"js-top"` or `"js""`.
:param assets:
a path to file, a :ref:`webassets.Bundle <webassets:bundles>`
instance or a callable that returns a
... | python | def register_asset(self, type_, *assets):
"""Register webassets bundle to be served on all pages.
:param type_: `"css"`, `"js-top"` or `"js""`.
:param assets:
a path to file, a :ref:`webassets.Bundle <webassets:bundles>`
instance or a callable that returns a
... | [
"def",
"register_asset",
"(",
"self",
",",
"type_",
",",
"*",
"assets",
")",
":",
"supported",
"=",
"list",
"(",
"self",
".",
"_assets_bundles",
".",
"keys",
"(",
")",
")",
"if",
"type_",
"not",
"in",
"supported",
":",
"msg",
"=",
"\"Invalid type: {}. Va... | Register webassets bundle to be served on all pages.
:param type_: `"css"`, `"js-top"` or `"js""`.
:param assets:
a path to file, a :ref:`webassets.Bundle <webassets:bundles>`
instance or a callable that returns a
:ref:`webassets.Bundle <webassets:bundles>` instance... | [
"Register",
"webassets",
"bundle",
"to",
"be",
"served",
"on",
"all",
"pages",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/assets/mixin.py#L115-L138 |
abilian/abilian-core | abilian/web/assets/mixin.py | AssetManagerMixin.register_i18n_js | def register_i18n_js(self, *paths):
"""Register templates path translations files, like
`select2/select2_locale_{lang}.js`.
Only existing files are registered.
"""
languages = self.config["BABEL_ACCEPT_LANGUAGES"]
assets = self.extensions["webassets"]
for path i... | python | def register_i18n_js(self, *paths):
"""Register templates path translations files, like
`select2/select2_locale_{lang}.js`.
Only existing files are registered.
"""
languages = self.config["BABEL_ACCEPT_LANGUAGES"]
assets = self.extensions["webassets"]
for path i... | [
"def",
"register_i18n_js",
"(",
"self",
",",
"*",
"paths",
")",
":",
"languages",
"=",
"self",
".",
"config",
"[",
"\"BABEL_ACCEPT_LANGUAGES\"",
"]",
"assets",
"=",
"self",
".",
"extensions",
"[",
"\"webassets\"",
"]",
"for",
"path",
"in",
"paths",
":",
"f... | Register templates path translations files, like
`select2/select2_locale_{lang}.js`.
Only existing files are registered. | [
"Register",
"templates",
"path",
"translations",
"files",
"like",
"select2",
"/",
"select2_locale_",
"{",
"lang",
"}",
".",
"js",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/assets/mixin.py#L140-L158 |
abilian/abilian-core | abilian/web/assets/mixin.py | AssetManagerMixin.register_base_assets | def register_base_assets(self):
"""Register assets needed by Abilian.
This is done in a separate method in order to allow applications
to redefine it at will.
"""
from abilian.web import assets as bundles
self.register_asset("css", bundles.LESS)
self.register_as... | python | def register_base_assets(self):
"""Register assets needed by Abilian.
This is done in a separate method in order to allow applications
to redefine it at will.
"""
from abilian.web import assets as bundles
self.register_asset("css", bundles.LESS)
self.register_as... | [
"def",
"register_base_assets",
"(",
"self",
")",
":",
"from",
"abilian",
".",
"web",
"import",
"assets",
"as",
"bundles",
"self",
".",
"register_asset",
"(",
"\"css\"",
",",
"bundles",
".",
"LESS",
")",
"self",
".",
"register_asset",
"(",
"\"js-top\"",
",",
... | Register assets needed by Abilian.
This is done in a separate method in order to allow applications
to redefine it at will. | [
"Register",
"assets",
"needed",
"by",
"Abilian",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/assets/mixin.py#L160-L171 |
abilian/abilian-core | abilian/web/views/images.py | user_photo_url | def user_photo_url(user, size):
"""Return url to use for this user."""
endpoint, kwargs = user_url_args(user, size)
return url_for(endpoint, **kwargs) | python | def user_photo_url(user, size):
"""Return url to use for this user."""
endpoint, kwargs = user_url_args(user, size)
return url_for(endpoint, **kwargs) | [
"def",
"user_photo_url",
"(",
"user",
",",
"size",
")",
":",
"endpoint",
",",
"kwargs",
"=",
"user_url_args",
"(",
"user",
",",
"size",
")",
"return",
"url_for",
"(",
"endpoint",
",",
"*",
"*",
"kwargs",
")"
] | Return url to use for this user. | [
"Return",
"url",
"to",
"use",
"for",
"this",
"user",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/views/images.py#L224-L227 |
abilian/abilian-core | abilian/web/views/images.py | BaseImageView.make_response | def make_response(self, image, size, mode, filename=None, *args, **kwargs):
"""
:param image: image as bytes
:param size: requested maximum width/height size
:param mode: one of 'scale', 'fit' or 'crop'
:param filename: filename
"""
try:
fmt = get_form... | python | def make_response(self, image, size, mode, filename=None, *args, **kwargs):
"""
:param image: image as bytes
:param size: requested maximum width/height size
:param mode: one of 'scale', 'fit' or 'crop'
:param filename: filename
"""
try:
fmt = get_form... | [
"def",
"make_response",
"(",
"self",
",",
"image",
",",
"size",
",",
"mode",
",",
"filename",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"fmt",
"=",
"get_format",
"(",
"image",
")",
"except",
"IOError",
":",
"# no... | :param image: image as bytes
:param size: requested maximum width/height size
:param mode: one of 'scale', 'fit' or 'crop'
:param filename: filename | [
":",
"param",
"image",
":",
"image",
"as",
"bytes",
":",
"param",
"size",
":",
"requested",
"maximum",
"width",
"/",
"height",
"size",
":",
"param",
"mode",
":",
"one",
"of",
"scale",
"fit",
"or",
"crop",
":",
"param",
"filename",
":",
"filename"
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/views/images.py#L60-L89 |
abilian/abilian-core | abilian/web/admin/panels/dashboard.py | newlogins | def newlogins(sessions):
"""Brand new logins each day, and total of users each day.
:return: data, total
2 lists of dictionaries of the following format [{'x':epoch, 'y': value},]
"""
if not sessions:
return [], []
users = {}
dates = {}
for session in sessions:
user =... | python | def newlogins(sessions):
"""Brand new logins each day, and total of users each day.
:return: data, total
2 lists of dictionaries of the following format [{'x':epoch, 'y': value},]
"""
if not sessions:
return [], []
users = {}
dates = {}
for session in sessions:
user =... | [
"def",
"newlogins",
"(",
"sessions",
")",
":",
"if",
"not",
"sessions",
":",
"return",
"[",
"]",
",",
"[",
"]",
"users",
"=",
"{",
"}",
"dates",
"=",
"{",
"}",
"for",
"session",
"in",
"sessions",
":",
"user",
"=",
"session",
".",
"user",
"# time va... | Brand new logins each day, and total of users each day.
:return: data, total
2 lists of dictionaries of the following format [{'x':epoch, 'y': value},] | [
"Brand",
"new",
"logins",
"each",
"day",
"and",
"total",
"of",
"users",
"each",
"day",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/admin/panels/dashboard.py#L111-L145 |
abilian/abilian-core | abilian/web/admin/panels/dashboard.py | uniquelogins | def uniquelogins(sessions):
"""Unique logins per days/weeks/months.
:return: daily, weekly, monthly
3 lists of dictionaries of the following format [{'x':epoch, 'y': value},]
"""
# sessions = LoginSession.query.order_by(LoginSession.started_at.asc()).all()
if not sessions:
return [], []... | python | def uniquelogins(sessions):
"""Unique logins per days/weeks/months.
:return: daily, weekly, monthly
3 lists of dictionaries of the following format [{'x':epoch, 'y': value},]
"""
# sessions = LoginSession.query.order_by(LoginSession.started_at.asc()).all()
if not sessions:
return [], []... | [
"def",
"uniquelogins",
"(",
"sessions",
")",
":",
"# sessions = LoginSession.query.order_by(LoginSession.started_at.asc()).all()",
"if",
"not",
"sessions",
":",
"return",
"[",
"]",
",",
"[",
"]",
",",
"[",
"]",
"dates",
"=",
"{",
"}",
"for",
"session",
"in",
"se... | Unique logins per days/weeks/months.
:return: daily, weekly, monthly
3 lists of dictionaries of the following format [{'x':epoch, 'y': value},] | [
"Unique",
"logins",
"per",
"days",
"/",
"weeks",
"/",
"months",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/admin/panels/dashboard.py#L148-L207 |
abilian/abilian-core | abilian/web/blueprints.py | allow_access_for_roles | def allow_access_for_roles(roles):
"""Access control helper to check user's roles against a list of valid
roles."""
if isinstance(roles, Role):
roles = (roles,)
valid_roles = frozenset(roles)
if Anonymous in valid_roles:
return allow_anonymous
def check_role(user, roles, **kwar... | python | def allow_access_for_roles(roles):
"""Access control helper to check user's roles against a list of valid
roles."""
if isinstance(roles, Role):
roles = (roles,)
valid_roles = frozenset(roles)
if Anonymous in valid_roles:
return allow_anonymous
def check_role(user, roles, **kwar... | [
"def",
"allow_access_for_roles",
"(",
"roles",
")",
":",
"if",
"isinstance",
"(",
"roles",
",",
"Role",
")",
":",
"roles",
"=",
"(",
"roles",
",",
")",
"valid_roles",
"=",
"frozenset",
"(",
"roles",
")",
"if",
"Anonymous",
"in",
"valid_roles",
":",
"retu... | Access control helper to check user's roles against a list of valid
roles. | [
"Access",
"control",
"helper",
"to",
"check",
"user",
"s",
"roles",
"against",
"a",
"list",
"of",
"valid",
"roles",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/blueprints.py#L12-L28 |
abilian/abilian-core | abilian/web/forms/fields.py | FileField.populate_obj | def populate_obj(self, obj, name):
"""Store file."""
from abilian.core.models.blob import Blob
delete_value = self.allow_delete and self.delete_files_index
if not self.has_file() and not delete_value:
# nothing uploaded, and nothing to delete
return
sta... | python | def populate_obj(self, obj, name):
"""Store file."""
from abilian.core.models.blob import Blob
delete_value = self.allow_delete and self.delete_files_index
if not self.has_file() and not delete_value:
# nothing uploaded, and nothing to delete
return
sta... | [
"def",
"populate_obj",
"(",
"self",
",",
"obj",
",",
"name",
")",
":",
"from",
"abilian",
".",
"core",
".",
"models",
".",
"blob",
"import",
"Blob",
"delete_value",
"=",
"self",
".",
"allow_delete",
"and",
"self",
".",
"delete_files_index",
"if",
"not",
... | Store file. | [
"Store",
"file",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/forms/fields.py#L243-L281 |
abilian/abilian-core | abilian/web/forms/fields.py | QuerySelect2Field._get_pk_from_identity | def _get_pk_from_identity(obj):
"""Copied / pasted, and fixed, from WTForms_sqlalchemy due to issue w/
SQLAlchemy >= 1.2."""
from sqlalchemy.orm.util import identity_key
cls, key = identity_key(instance=obj)[0:2]
return ":".join(text_type(x) for x in key) | python | def _get_pk_from_identity(obj):
"""Copied / pasted, and fixed, from WTForms_sqlalchemy due to issue w/
SQLAlchemy >= 1.2."""
from sqlalchemy.orm.util import identity_key
cls, key = identity_key(instance=obj)[0:2]
return ":".join(text_type(x) for x in key) | [
"def",
"_get_pk_from_identity",
"(",
"obj",
")",
":",
"from",
"sqlalchemy",
".",
"orm",
".",
"util",
"import",
"identity_key",
"cls",
",",
"key",
"=",
"identity_key",
"(",
"instance",
"=",
"obj",
")",
"[",
"0",
":",
"2",
"]",
"return",
"\":\"",
".",
"j... | Copied / pasted, and fixed, from WTForms_sqlalchemy due to issue w/
SQLAlchemy >= 1.2. | [
"Copied",
"/",
"pasted",
"and",
"fixed",
"from",
"WTForms_sqlalchemy",
"due",
"to",
"issue",
"w",
"/",
"SQLAlchemy",
">",
"=",
"1",
".",
"2",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/forms/fields.py#L523-L529 |
abilian/abilian-core | abilian/services/settings/service.py | SettingsService.keys | def keys(self, prefix=None):
"""List all keys, with optional prefix filtering."""
query = Setting.query
if prefix:
query = query.filter(Setting.key.startswith(prefix))
# don't use iteritems: 'value' require little processing whereas we only
# want 'key'
retur... | python | def keys(self, prefix=None):
"""List all keys, with optional prefix filtering."""
query = Setting.query
if prefix:
query = query.filter(Setting.key.startswith(prefix))
# don't use iteritems: 'value' require little processing whereas we only
# want 'key'
retur... | [
"def",
"keys",
"(",
"self",
",",
"prefix",
"=",
"None",
")",
":",
"query",
"=",
"Setting",
".",
"query",
"if",
"prefix",
":",
"query",
"=",
"query",
".",
"filter",
"(",
"Setting",
".",
"key",
".",
"startswith",
"(",
"prefix",
")",
")",
"# don't use i... | List all keys, with optional prefix filtering. | [
"List",
"all",
"keys",
"with",
"optional",
"prefix",
"filtering",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/settings/service.py#L18-L26 |
abilian/abilian-core | abilian/services/settings/service.py | SettingsService.iteritems | def iteritems(self, prefix=None):
"""Like dict.iteritems."""
query = Setting.query
if prefix:
query = query.filter(Setting.key.startswith(prefix))
for s in query.yield_per(1000):
yield (s.key, s.value) | python | def iteritems(self, prefix=None):
"""Like dict.iteritems."""
query = Setting.query
if prefix:
query = query.filter(Setting.key.startswith(prefix))
for s in query.yield_per(1000):
yield (s.key, s.value) | [
"def",
"iteritems",
"(",
"self",
",",
"prefix",
"=",
"None",
")",
":",
"query",
"=",
"Setting",
".",
"query",
"if",
"prefix",
":",
"query",
"=",
"query",
".",
"filter",
"(",
"Setting",
".",
"key",
".",
"startswith",
"(",
"prefix",
")",
")",
"for",
... | Like dict.iteritems. | [
"Like",
"dict",
".",
"iteritems",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/settings/service.py#L28-L35 |
abilian/abilian-core | abilian/core/models/comment.py | register | def register(cls):
"""Register an :class:`Entity` as a commentable class.
Can be used as a class decorator:
.. code-block:: python
@comment.register
class MyContent(Entity):
...
"""
if not issubclass(cls, Entity):
raise ValueError("Class must be a subclass of abilian... | python | def register(cls):
"""Register an :class:`Entity` as a commentable class.
Can be used as a class decorator:
.. code-block:: python
@comment.register
class MyContent(Entity):
...
"""
if not issubclass(cls, Entity):
raise ValueError("Class must be a subclass of abilian... | [
"def",
"register",
"(",
"cls",
")",
":",
"if",
"not",
"issubclass",
"(",
"cls",
",",
"Entity",
")",
":",
"raise",
"ValueError",
"(",
"\"Class must be a subclass of abilian.core.entities.Entity\"",
")",
"Commentable",
".",
"register",
"(",
"cls",
")",
"return",
"... | Register an :class:`Entity` as a commentable class.
Can be used as a class decorator:
.. code-block:: python
@comment.register
class MyContent(Entity):
... | [
"Register",
"an",
":",
"class",
":",
"Entity",
"as",
"a",
"commentable",
"class",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/models/comment.py#L23-L38 |
abilian/abilian-core | abilian/core/models/comment.py | is_commentable | def is_commentable(obj_or_class):
"""
:param obj_or_class: a class or instance
"""
if isinstance(obj_or_class, type):
return issubclass(obj_or_class, Commentable)
if not isinstance(obj_or_class, Commentable):
return False
if obj_or_class.id is None:
return False
re... | python | def is_commentable(obj_or_class):
"""
:param obj_or_class: a class or instance
"""
if isinstance(obj_or_class, type):
return issubclass(obj_or_class, Commentable)
if not isinstance(obj_or_class, Commentable):
return False
if obj_or_class.id is None:
return False
re... | [
"def",
"is_commentable",
"(",
"obj_or_class",
")",
":",
"if",
"isinstance",
"(",
"obj_or_class",
",",
"type",
")",
":",
"return",
"issubclass",
"(",
"obj_or_class",
",",
"Commentable",
")",
"if",
"not",
"isinstance",
"(",
"obj_or_class",
",",
"Commentable",
")... | :param obj_or_class: a class or instance | [
":",
"param",
"obj_or_class",
":",
"a",
"class",
"or",
"instance"
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/models/comment.py#L41-L54 |
abilian/abilian-core | abilian/core/models/comment.py | for_entity | def for_entity(obj, check_commentable=False):
"""Return comments on an entity."""
if check_commentable and not is_commentable(obj):
return []
return getattr(obj, ATTRIBUTE) | python | def for_entity(obj, check_commentable=False):
"""Return comments on an entity."""
if check_commentable and not is_commentable(obj):
return []
return getattr(obj, ATTRIBUTE) | [
"def",
"for_entity",
"(",
"obj",
",",
"check_commentable",
"=",
"False",
")",
":",
"if",
"check_commentable",
"and",
"not",
"is_commentable",
"(",
"obj",
")",
":",
"return",
"[",
"]",
"return",
"getattr",
"(",
"obj",
",",
"ATTRIBUTE",
")"
] | Return comments on an entity. | [
"Return",
"comments",
"on",
"an",
"entity",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/models/comment.py#L57-L62 |
abilian/abilian-core | abilian/web/action.py | Action.available | def available(self, context):
"""Determine if this actions is available in this `context`.
:param context: a dict whose content is left to application needs; if
:attr:`.condition` is a callable it receives `context`
in parameter.
"""
if no... | python | def available(self, context):
"""Determine if this actions is available in this `context`.
:param context: a dict whose content is left to application needs; if
:attr:`.condition` is a callable it receives `context`
in parameter.
"""
if no... | [
"def",
"available",
"(",
"self",
",",
"context",
")",
":",
"if",
"not",
"self",
".",
"_enabled",
":",
"return",
"False",
"try",
":",
"return",
"self",
".",
"pre_condition",
"(",
"context",
")",
"and",
"self",
".",
"_check_condition",
"(",
"context",
")",... | Determine if this actions is available in this `context`.
:param context: a dict whose content is left to application needs; if
:attr:`.condition` is a callable it receives `context`
in parameter. | [
"Determine",
"if",
"this",
"actions",
"is",
"available",
"in",
"this",
"context",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/action.py#L398-L410 |
abilian/abilian-core | abilian/web/action.py | ActionRegistry.installed | def installed(self, app=None):
"""Return `True` if the registry has been installed in current
applications."""
if app is None:
app = current_app
return self.__EXTENSION_NAME in app.extensions | python | def installed(self, app=None):
"""Return `True` if the registry has been installed in current
applications."""
if app is None:
app = current_app
return self.__EXTENSION_NAME in app.extensions | [
"def",
"installed",
"(",
"self",
",",
"app",
"=",
"None",
")",
":",
"if",
"app",
"is",
"None",
":",
"app",
"=",
"current_app",
"return",
"self",
".",
"__EXTENSION_NAME",
"in",
"app",
".",
"extensions"
] | Return `True` if the registry has been installed in current
applications. | [
"Return",
"True",
"if",
"the",
"registry",
"has",
"been",
"installed",
"in",
"current",
"applications",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/action.py#L574-L579 |
abilian/abilian-core | abilian/web/action.py | ActionRegistry.register | def register(self, *actions):
"""Register `actions` in the current application. All `actions` must be
an instance of :class:`.Action` or one of its subclasses.
If `overwrite` is `True`, then it is allowed to overwrite an
existing action with same name and category; else `ValueError`
... | python | def register(self, *actions):
"""Register `actions` in the current application. All `actions` must be
an instance of :class:`.Action` or one of its subclasses.
If `overwrite` is `True`, then it is allowed to overwrite an
existing action with same name and category; else `ValueError`
... | [
"def",
"register",
"(",
"self",
",",
"*",
"actions",
")",
":",
"assert",
"self",
".",
"installed",
"(",
")",
",",
"\"Actions not enabled on this application\"",
"assert",
"all",
"(",
"isinstance",
"(",
"a",
",",
"Action",
")",
"for",
"a",
"in",
"actions",
... | Register `actions` in the current application. All `actions` must be
an instance of :class:`.Action` or one of its subclasses.
If `overwrite` is `True`, then it is allowed to overwrite an
existing action with same name and category; else `ValueError`
is raised. | [
"Register",
"actions",
"in",
"the",
"current",
"application",
".",
"All",
"actions",
"must",
"be",
"an",
"instance",
"of",
":",
"class",
":",
".",
"Action",
"or",
"one",
"of",
"its",
"subclasses",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/action.py#L581-L595 |
abilian/abilian-core | abilian/web/action.py | ActionRegistry.actions | def actions(self, context=None):
"""Return a mapping of category => actions list.
Actions are filtered according to :meth:`.Action.available`.
if `context` is None, then current action context is used
(:attr:`context`).
"""
assert self.installed(), "Actions not enabled ... | python | def actions(self, context=None):
"""Return a mapping of category => actions list.
Actions are filtered according to :meth:`.Action.available`.
if `context` is None, then current action context is used
(:attr:`context`).
"""
assert self.installed(), "Actions not enabled ... | [
"def",
"actions",
"(",
"self",
",",
"context",
"=",
"None",
")",
":",
"assert",
"self",
".",
"installed",
"(",
")",
",",
"\"Actions not enabled on this application\"",
"result",
"=",
"{",
"}",
"if",
"context",
"is",
"None",
":",
"context",
"=",
"self",
"."... | Return a mapping of category => actions list.
Actions are filtered according to :meth:`.Action.available`.
if `context` is None, then current action context is used
(:attr:`context`). | [
"Return",
"a",
"mapping",
"of",
"category",
"=",
">",
"actions",
"list",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/action.py#L597-L612 |
abilian/abilian-core | abilian/web/action.py | ActionRegistry.for_category | def for_category(self, category, context=None):
"""Returns actions list for this category in current application.
Actions are filtered according to :meth:`.Action.available`.
if `context` is None, then current action context is used
(:attr:`context`)
"""
assert self.ins... | python | def for_category(self, category, context=None):
"""Returns actions list for this category in current application.
Actions are filtered according to :meth:`.Action.available`.
if `context` is None, then current action context is used
(:attr:`context`)
"""
assert self.ins... | [
"def",
"for_category",
"(",
"self",
",",
"category",
",",
"context",
"=",
"None",
")",
":",
"assert",
"self",
".",
"installed",
"(",
")",
",",
"\"Actions not enabled on this application\"",
"actions",
"=",
"self",
".",
"_state",
"[",
"\"categories\"",
"]",
"."... | Returns actions list for this category in current application.
Actions are filtered according to :meth:`.Action.available`.
if `context` is None, then current action context is used
(:attr:`context`) | [
"Returns",
"actions",
"list",
"for",
"this",
"category",
"in",
"current",
"application",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/action.py#L614-L628 |
abilian/abilian-core | abilian/web/forms/util.py | babel2datetime | def babel2datetime(pattern):
"""Convert date format from babel (http://babel.pocoo.org/docs/dates/#date-
fields)) to a format understood by datetime.strptime."""
if not isinstance(pattern, DateTimePattern):
pattern = parse_pattern(pattern)
map_fmt = {
# days
"d": "%d",
"... | python | def babel2datetime(pattern):
"""Convert date format from babel (http://babel.pocoo.org/docs/dates/#date-
fields)) to a format understood by datetime.strptime."""
if not isinstance(pattern, DateTimePattern):
pattern = parse_pattern(pattern)
map_fmt = {
# days
"d": "%d",
"... | [
"def",
"babel2datetime",
"(",
"pattern",
")",
":",
"if",
"not",
"isinstance",
"(",
"pattern",
",",
"DateTimePattern",
")",
":",
"pattern",
"=",
"parse_pattern",
"(",
"pattern",
")",
"map_fmt",
"=",
"{",
"# days",
"\"d\"",
":",
"\"%d\"",
",",
"\"dd\"",
":",... | Convert date format from babel (http://babel.pocoo.org/docs/dates/#date-
fields)) to a format understood by datetime.strptime. | [
"Convert",
"date",
"format",
"from",
"babel",
"(",
"http",
":",
"//",
"babel",
".",
"pocoo",
".",
"org",
"/",
"docs",
"/",
"dates",
"/",
"#date",
"-",
"fields",
"))",
"to",
"a",
"format",
"understood",
"by",
"datetime",
".",
"strptime",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/forms/util.py#L6-L43 |
abilian/abilian-core | abilian/services/auth/models.py | LoginSessionQuery.get_active_for | def get_active_for(self, user, user_agent=_MARK, ip_address=_MARK):
"""Return last known session for given user.
:param user: user session
:type user: `abilian.core.models.subjects.User`
:param user_agent: *exact* user agent string to lookup, or `None` to have
user_agent extrac... | python | def get_active_for(self, user, user_agent=_MARK, ip_address=_MARK):
"""Return last known session for given user.
:param user: user session
:type user: `abilian.core.models.subjects.User`
:param user_agent: *exact* user agent string to lookup, or `None` to have
user_agent extrac... | [
"def",
"get_active_for",
"(",
"self",
",",
"user",
",",
"user_agent",
"=",
"_MARK",
",",
"ip_address",
"=",
"_MARK",
")",
":",
"conditions",
"=",
"[",
"LoginSession",
".",
"user",
"==",
"user",
"]",
"if",
"user_agent",
"is",
"not",
"_MARK",
":",
"if",
... | Return last known session for given user.
:param user: user session
:type user: `abilian.core.models.subjects.User`
:param user_agent: *exact* user agent string to lookup, or `None` to have
user_agent extracted from request object. If not provided at all, no
filtering on user_a... | [
"Return",
"last",
"known",
"session",
"for",
"given",
"user",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/auth/models.py#L18-L54 |
abilian/abilian-core | abilian/cli/config.py | show | def show(only_path=False):
"""Show the current config."""
logger.setLevel(logging.INFO)
infos = ["\n", f'Instance path: "{current_app.instance_path}"']
logger.info("\n ".join(infos))
if not only_path:
log_config(current_app.config) | python | def show(only_path=False):
"""Show the current config."""
logger.setLevel(logging.INFO)
infos = ["\n", f'Instance path: "{current_app.instance_path}"']
logger.info("\n ".join(infos))
if not only_path:
log_config(current_app.config) | [
"def",
"show",
"(",
"only_path",
"=",
"False",
")",
":",
"logger",
".",
"setLevel",
"(",
"logging",
".",
"INFO",
")",
"infos",
"=",
"[",
"\"\\n\"",
",",
"f'Instance path: \"{current_app.instance_path}\"'",
"]",
"logger",
".",
"info",
"(",
"\"\\n \"",
".",
"... | Show the current config. | [
"Show",
"the",
"current",
"config",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/cli/config.py#L16-L24 |
Ceasar/staticjinja | staticjinja/reloader.py | Reloader.should_handle | def should_handle(self, event_type, filename):
"""Check if an event should be handled.
An event should be handled if a file in the searchpath was modified.
:param event_type: a string, representing the type of event
:param filename: the path to the file that triggered the event.
... | python | def should_handle(self, event_type, filename):
"""Check if an event should be handled.
An event should be handled if a file in the searchpath was modified.
:param event_type: a string, representing the type of event
:param filename: the path to the file that triggered the event.
... | [
"def",
"should_handle",
"(",
"self",
",",
"event_type",
",",
"filename",
")",
":",
"return",
"(",
"event_type",
"in",
"(",
"\"modified\"",
",",
"\"created\"",
")",
"and",
"filename",
".",
"startswith",
"(",
"self",
".",
"searchpath",
")",
"and",
"os",
".",... | Check if an event should be handled.
An event should be handled if a file in the searchpath was modified.
:param event_type: a string, representing the type of event
:param filename: the path to the file that triggered the event. | [
"Check",
"if",
"an",
"event",
"should",
"be",
"handled",
"."
] | train | https://github.com/Ceasar/staticjinja/blob/57b8cac81da7fee3387510af4843e1bd1fd3ba28/staticjinja/reloader.py#L20-L31 |
Ceasar/staticjinja | staticjinja/reloader.py | Reloader.event_handler | def event_handler(self, event_type, src_path):
"""Re-render templates if they are modified.
:param event_type: a string, representing the type of event
:param src_path: the path to the file that triggered the event.
"""
filename = os.path.relpath(src_path, self.searchpath)
... | python | def event_handler(self, event_type, src_path):
"""Re-render templates if they are modified.
:param event_type: a string, representing the type of event
:param src_path: the path to the file that triggered the event.
"""
filename = os.path.relpath(src_path, self.searchpath)
... | [
"def",
"event_handler",
"(",
"self",
",",
"event_type",
",",
"src_path",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"src_path",
",",
"self",
".",
"searchpath",
")",
"if",
"self",
".",
"should_handle",
"(",
"event_type",
",",
"src_... | Re-render templates if they are modified.
:param event_type: a string, representing the type of event
:param src_path: the path to the file that triggered the event. | [
"Re",
"-",
"render",
"templates",
"if",
"they",
"are",
"modified",
"."
] | train | https://github.com/Ceasar/staticjinja/blob/57b8cac81da7fee3387510af4843e1bd1fd3ba28/staticjinja/reloader.py#L33-L49 |
abilian/abilian-core | abilian/web/csrf.py | protect | def protect(view):
"""Protects a view agains CSRF attacks by checking `csrf_token` value in
submitted values. Do nothing if `config.WTF_CSRF_ENABLED` is not set.
Raises `werkzeug.exceptions.Forbidden` if validation fails.
"""
@wraps(view)
def csrf_check(*args, **kwargs):
# an empty for... | python | def protect(view):
"""Protects a view agains CSRF attacks by checking `csrf_token` value in
submitted values. Do nothing if `config.WTF_CSRF_ENABLED` is not set.
Raises `werkzeug.exceptions.Forbidden` if validation fails.
"""
@wraps(view)
def csrf_check(*args, **kwargs):
# an empty for... | [
"def",
"protect",
"(",
"view",
")",
":",
"@",
"wraps",
"(",
"view",
")",
"def",
"csrf_check",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# an empty form is used to validate current csrf token and only that!",
"if",
"not",
"FlaskForm",
"(",
")",
".",... | Protects a view agains CSRF attacks by checking `csrf_token` value in
submitted values. Do nothing if `config.WTF_CSRF_ENABLED` is not set.
Raises `werkzeug.exceptions.Forbidden` if validation fails. | [
"Protects",
"a",
"view",
"agains",
"CSRF",
"attacks",
"by",
"checking",
"csrf_token",
"value",
"in",
"submitted",
"values",
".",
"Do",
"nothing",
"if",
"config",
".",
"WTF_CSRF_ENABLED",
"is",
"not",
"set",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/csrf.py#L60-L75 |
abilian/abilian-core | abilian/cli/base.py | createuser | def createuser(email, password, role=None, name=None, first_name=None):
"""Create new user."""
if User.query.filter(User.email == email).count() > 0:
print(f"A user with email '{email}' already exists, aborting.")
return
# if password is None:
# password = prompt_pass("Password")
... | python | def createuser(email, password, role=None, name=None, first_name=None):
"""Create new user."""
if User.query.filter(User.email == email).count() > 0:
print(f"A user with email '{email}' already exists, aborting.")
return
# if password is None:
# password = prompt_pass("Password")
... | [
"def",
"createuser",
"(",
"email",
",",
"password",
",",
"role",
"=",
"None",
",",
"name",
"=",
"None",
",",
"first_name",
"=",
"None",
")",
":",
"if",
"User",
".",
"query",
".",
"filter",
"(",
"User",
".",
"email",
"==",
"email",
")",
".",
"count"... | Create new user. | [
"Create",
"new",
"user",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/cli/base.py#L41-L66 |
abilian/abilian-core | abilian/core/entities.py | auto_slug_on_insert | def auto_slug_on_insert(mapper, connection, target):
"""Generate a slug from :prop:`Entity.auto_slug` for new entities, unless
slug is already set."""
if target.slug is None and target.name:
target.slug = target.auto_slug | python | def auto_slug_on_insert(mapper, connection, target):
"""Generate a slug from :prop:`Entity.auto_slug` for new entities, unless
slug is already set."""
if target.slug is None and target.name:
target.slug = target.auto_slug | [
"def",
"auto_slug_on_insert",
"(",
"mapper",
",",
"connection",
",",
"target",
")",
":",
"if",
"target",
".",
"slug",
"is",
"None",
"and",
"target",
".",
"name",
":",
"target",
".",
"slug",
"=",
"target",
".",
"auto_slug"
] | Generate a slug from :prop:`Entity.auto_slug` for new entities, unless
slug is already set. | [
"Generate",
"a",
"slug",
"from",
":",
"prop",
":",
"Entity",
".",
"auto_slug",
"for",
"new",
"entities",
"unless",
"slug",
"is",
"already",
"set",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/entities.py#L72-L76 |
abilian/abilian-core | abilian/core/entities.py | auto_slug_after_insert | def auto_slug_after_insert(mapper, connection, target):
"""Generate a slug from entity_type and id, unless slug is already set."""
if target.slug is None:
target.slug = "{name}{sep}{id}".format(
name=target.entity_class.lower(), sep=target.SLUG_SEPARATOR, id=target.id
) | python | def auto_slug_after_insert(mapper, connection, target):
"""Generate a slug from entity_type and id, unless slug is already set."""
if target.slug is None:
target.slug = "{name}{sep}{id}".format(
name=target.entity_class.lower(), sep=target.SLUG_SEPARATOR, id=target.id
) | [
"def",
"auto_slug_after_insert",
"(",
"mapper",
",",
"connection",
",",
"target",
")",
":",
"if",
"target",
".",
"slug",
"is",
"None",
":",
"target",
".",
"slug",
"=",
"\"{name}{sep}{id}\"",
".",
"format",
"(",
"name",
"=",
"target",
".",
"entity_class",
"... | Generate a slug from entity_type and id, unless slug is already set. | [
"Generate",
"a",
"slug",
"from",
"entity_type",
"and",
"id",
"unless",
"slug",
"is",
"already",
"set",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/entities.py#L79-L84 |
abilian/abilian-core | abilian/core/entities.py | setup_default_permissions | def setup_default_permissions(session, instance):
"""Setup default permissions on newly created entities according to.
:attr:`Entity.__default_permissions__`.
"""
if instance not in session.new or not isinstance(instance, Entity):
return
if not current_app:
# working outside app_co... | python | def setup_default_permissions(session, instance):
"""Setup default permissions on newly created entities according to.
:attr:`Entity.__default_permissions__`.
"""
if instance not in session.new or not isinstance(instance, Entity):
return
if not current_app:
# working outside app_co... | [
"def",
"setup_default_permissions",
"(",
"session",
",",
"instance",
")",
":",
"if",
"instance",
"not",
"in",
"session",
".",
"new",
"or",
"not",
"isinstance",
"(",
"instance",
",",
"Entity",
")",
":",
"return",
"if",
"not",
"current_app",
":",
"# working ou... | Setup default permissions on newly created entities according to.
:attr:`Entity.__default_permissions__`. | [
"Setup",
"default",
"permissions",
"on",
"newly",
"created",
"entities",
"according",
"to",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/entities.py#L88-L100 |
abilian/abilian-core | abilian/core/entities.py | _setup_default_permissions | def _setup_default_permissions(instance):
"""Separate method to conveniently call it from scripts for example."""
from abilian.services import get_service
security = get_service("security")
for permission, roles in instance.__default_permissions__:
if permission == "create":
# use s... | python | def _setup_default_permissions(instance):
"""Separate method to conveniently call it from scripts for example."""
from abilian.services import get_service
security = get_service("security")
for permission, roles in instance.__default_permissions__:
if permission == "create":
# use s... | [
"def",
"_setup_default_permissions",
"(",
"instance",
")",
":",
"from",
"abilian",
".",
"services",
"import",
"get_service",
"security",
"=",
"get_service",
"(",
"\"security\"",
")",
"for",
"permission",
",",
"roles",
"in",
"instance",
".",
"__default_permissions__"... | Separate method to conveniently call it from scripts for example. | [
"Separate",
"method",
"to",
"conveniently",
"call",
"it",
"from",
"scripts",
"for",
"example",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/entities.py#L103-L116 |
abilian/abilian-core | abilian/core/entities.py | polymorphic_update_timestamp | def polymorphic_update_timestamp(session, flush_context, instances):
"""This listener ensures an update statement is emited for "entity" table
to update 'updated_at'.
With joined-table inheritance if the only modified attributes are
subclass's ones, then no update statement will be emitted.
"""
... | python | def polymorphic_update_timestamp(session, flush_context, instances):
"""This listener ensures an update statement is emited for "entity" table
to update 'updated_at'.
With joined-table inheritance if the only modified attributes are
subclass's ones, then no update statement will be emitted.
"""
... | [
"def",
"polymorphic_update_timestamp",
"(",
"session",
",",
"flush_context",
",",
"instances",
")",
":",
"for",
"obj",
"in",
"session",
".",
"dirty",
":",
"if",
"not",
"isinstance",
"(",
"obj",
",",
"Entity",
")",
":",
"continue",
"state",
"=",
"sa",
".",
... | This listener ensures an update statement is emited for "entity" table
to update 'updated_at'.
With joined-table inheritance if the only modified attributes are
subclass's ones, then no update statement will be emitted. | [
"This",
"listener",
"ensures",
"an",
"update",
"statement",
"is",
"emited",
"for",
"entity",
"table",
"to",
"update",
"updated_at",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/entities.py#L486-L499 |
abilian/abilian-core | abilian/core/entities.py | all_entity_classes | def all_entity_classes():
"""Return the list of all concrete persistent classes that are subclasses
of Entity."""
persistent_classes = Entity._decl_class_registry.values()
# with sqlalchemy 0.8 _decl_class_registry holds object that are not
# classes
return [
cls for cls in persistent_cl... | python | def all_entity_classes():
"""Return the list of all concrete persistent classes that are subclasses
of Entity."""
persistent_classes = Entity._decl_class_registry.values()
# with sqlalchemy 0.8 _decl_class_registry holds object that are not
# classes
return [
cls for cls in persistent_cl... | [
"def",
"all_entity_classes",
"(",
")",
":",
"persistent_classes",
"=",
"Entity",
".",
"_decl_class_registry",
".",
"values",
"(",
")",
"# with sqlalchemy 0.8 _decl_class_registry holds object that are not",
"# classes",
"return",
"[",
"cls",
"for",
"cls",
"in",
"persisten... | Return the list of all concrete persistent classes that are subclasses
of Entity. | [
"Return",
"the",
"list",
"of",
"all",
"concrete",
"persistent",
"classes",
"that",
"are",
"subclasses",
"of",
"Entity",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/entities.py#L503-L511 |
abilian/abilian-core | abilian/core/entities.py | Entity.auto_slug | def auto_slug(self):
"""This property is used to auto-generate a slug from the name
attribute.
It can be customized by subclasses.
"""
slug = self.name
if slug is not None:
slug = slugify(slug, separator=self.SLUG_SEPARATOR)
session = sa.orm.objec... | python | def auto_slug(self):
"""This property is used to auto-generate a slug from the name
attribute.
It can be customized by subclasses.
"""
slug = self.name
if slug is not None:
slug = slugify(slug, separator=self.SLUG_SEPARATOR)
session = sa.orm.objec... | [
"def",
"auto_slug",
"(",
"self",
")",
":",
"slug",
"=",
"self",
".",
"name",
"if",
"slug",
"is",
"not",
"None",
":",
"slug",
"=",
"slugify",
"(",
"slug",
",",
"separator",
"=",
"self",
".",
"SLUG_SEPARATOR",
")",
"session",
"=",
"sa",
".",
"orm",
"... | This property is used to auto-generate a slug from the name
attribute.
It can be customized by subclasses. | [
"This",
"property",
"is",
"used",
"to",
"auto",
"-",
"generate",
"a",
"slug",
"from",
"the",
"name",
"attribute",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/entities.py#L355-L382 |
abilian/abilian-core | abilian/core/entities.py | Entity._indexable_roles_and_users | def _indexable_roles_and_users(self):
"""Return a string made for indexing roles having :any:`READ`
permission on this object."""
from abilian.services.indexing import indexable_role
from abilian.services.security import READ, Admin, Anonymous, Creator, Owner
from abilian.service... | python | def _indexable_roles_and_users(self):
"""Return a string made for indexing roles having :any:`READ`
permission on this object."""
from abilian.services.indexing import indexable_role
from abilian.services.security import READ, Admin, Anonymous, Creator, Owner
from abilian.service... | [
"def",
"_indexable_roles_and_users",
"(",
"self",
")",
":",
"from",
"abilian",
".",
"services",
".",
"indexing",
"import",
"indexable_role",
"from",
"abilian",
".",
"services",
".",
"security",
"import",
"READ",
",",
"Admin",
",",
"Anonymous",
",",
"Creator",
... | Return a string made for indexing roles having :any:`READ`
permission on this object. | [
"Return",
"a",
"string",
"made",
"for",
"indexing",
"roles",
"having",
":",
"any",
":",
"READ",
"permission",
"on",
"this",
"object",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/entities.py#L385-L423 |
abilian/abilian-core | abilian/core/entities.py | Entity._indexable_tags | def _indexable_tags(self):
"""Index tag ids for tags defined in this Entity's default tags
namespace."""
tags = current_app.extensions.get("tags")
if not tags or not tags.supports_taggings(self):
return ""
default_ns = tags.entity_default_ns(self)
return [t f... | python | def _indexable_tags(self):
"""Index tag ids for tags defined in this Entity's default tags
namespace."""
tags = current_app.extensions.get("tags")
if not tags or not tags.supports_taggings(self):
return ""
default_ns = tags.entity_default_ns(self)
return [t f... | [
"def",
"_indexable_tags",
"(",
"self",
")",
":",
"tags",
"=",
"current_app",
".",
"extensions",
".",
"get",
"(",
"\"tags\"",
")",
"if",
"not",
"tags",
"or",
"not",
"tags",
".",
"supports_taggings",
"(",
"self",
")",
":",
"return",
"\"\"",
"default_ns",
"... | Index tag ids for tags defined in this Entity's default tags
namespace. | [
"Index",
"tag",
"ids",
"for",
"tags",
"defined",
"in",
"this",
"Entity",
"s",
"default",
"tags",
"namespace",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/entities.py#L426-L434 |
abilian/abilian-core | abilian/i18n.py | country_choices | def country_choices(first=None, default_country_first=True):
"""Return a list of (code, countries), alphabetically sorted on localized
country name.
:param first: Country code to be placed at the top
:param default_country_first:
:type default_country_first: bool
"""
locale = _get_locale()
... | python | def country_choices(first=None, default_country_first=True):
"""Return a list of (code, countries), alphabetically sorted on localized
country name.
:param first: Country code to be placed at the top
:param default_country_first:
:type default_country_first: bool
"""
locale = _get_locale()
... | [
"def",
"country_choices",
"(",
"first",
"=",
"None",
",",
"default_country_first",
"=",
"True",
")",
":",
"locale",
"=",
"_get_locale",
"(",
")",
"territories",
"=",
"[",
"(",
"code",
",",
"name",
")",
"for",
"code",
",",
"name",
"in",
"locale",
".",
"... | Return a list of (code, countries), alphabetically sorted on localized
country name.
:param first: Country code to be placed at the top
:param default_country_first:
:type default_country_first: bool | [
"Return",
"a",
"list",
"of",
"(",
"code",
"countries",
")",
"alphabetically",
"sorted",
"on",
"localized",
"country",
"name",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/i18n.py#L125-L147 |
abilian/abilian-core | abilian/i18n.py | supported_app_locales | def supported_app_locales():
"""Language codes and labels supported by current application.
:return: an iterable of `(:class:`babel.Locale`, label)`, label being the
locale language human name in current locale.
"""
locale = _get_locale()
codes = current_app.config["BABEL_ACCEPT_LANGUAGES"]
... | python | def supported_app_locales():
"""Language codes and labels supported by current application.
:return: an iterable of `(:class:`babel.Locale`, label)`, label being the
locale language human name in current locale.
"""
locale = _get_locale()
codes = current_app.config["BABEL_ACCEPT_LANGUAGES"]
... | [
"def",
"supported_app_locales",
"(",
")",
":",
"locale",
"=",
"_get_locale",
"(",
")",
"codes",
"=",
"current_app",
".",
"config",
"[",
"\"BABEL_ACCEPT_LANGUAGES\"",
"]",
"return",
"(",
"(",
"Locale",
".",
"parse",
"(",
"code",
")",
",",
"locale",
".",
"la... | Language codes and labels supported by current application.
:return: an iterable of `(:class:`babel.Locale`, label)`, label being the
locale language human name in current locale. | [
"Language",
"codes",
"and",
"labels",
"supported",
"by",
"current",
"application",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/i18n.py#L150-L158 |
abilian/abilian-core | abilian/i18n.py | timezones_choices | def timezones_choices():
"""Timezones values and their labels for current locale.
:return: an iterable of `(code, label)`, code being a timezone code and label
the timezone name in current locale.
"""
utcnow = pytz.utc.localize(datetime.utcnow())
locale = _get_locale()
for tz in sorted(pytz... | python | def timezones_choices():
"""Timezones values and their labels for current locale.
:return: an iterable of `(code, label)`, code being a timezone code and label
the timezone name in current locale.
"""
utcnow = pytz.utc.localize(datetime.utcnow())
locale = _get_locale()
for tz in sorted(pytz... | [
"def",
"timezones_choices",
"(",
")",
":",
"utcnow",
"=",
"pytz",
".",
"utc",
".",
"localize",
"(",
"datetime",
".",
"utcnow",
"(",
")",
")",
"locale",
"=",
"_get_locale",
"(",
")",
"for",
"tz",
"in",
"sorted",
"(",
"pytz",
".",
"common_timezones",
")"... | Timezones values and their labels for current locale.
:return: an iterable of `(code, label)`, code being a timezone code and label
the timezone name in current locale. | [
"Timezones",
"values",
"and",
"their",
"labels",
"for",
"current",
"locale",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/i18n.py#L161-L173 |
abilian/abilian-core | abilian/i18n.py | _get_translations_multi_paths | def _get_translations_multi_paths():
"""Return the correct gettext translations that should be used for this
request.
This will never fail and return a dummy translation object if used
outside of the request or if a translation cannot be found.
"""
ctx = _request_ctx_stack.top
if ctx is Non... | python | def _get_translations_multi_paths():
"""Return the correct gettext translations that should be used for this
request.
This will never fail and return a dummy translation object if used
outside of the request or if a translation cannot be found.
"""
ctx = _request_ctx_stack.top
if ctx is Non... | [
"def",
"_get_translations_multi_paths",
"(",
")",
":",
"ctx",
"=",
"_request_ctx_stack",
".",
"top",
"if",
"ctx",
"is",
"None",
":",
"return",
"None",
"translations",
"=",
"getattr",
"(",
"ctx",
",",
"\"babel_translations\"",
",",
"None",
")",
"if",
"translati... | Return the correct gettext translations that should be used for this
request.
This will never fail and return a dummy translation object if used
outside of the request or if a translation cannot be found. | [
"Return",
"the",
"correct",
"gettext",
"translations",
"that",
"should",
"be",
"used",
"for",
"this",
"request",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/i18n.py#L250-L292 |
abilian/abilian-core | abilian/i18n.py | localeselector | def localeselector():
"""Default locale selector used in abilian applications."""
# if a user is logged in, use the locale from the user settings
user = getattr(g, "user", None)
if user is not None:
locale = getattr(user, "locale", None)
if locale:
return locale
# Otherw... | python | def localeselector():
"""Default locale selector used in abilian applications."""
# if a user is logged in, use the locale from the user settings
user = getattr(g, "user", None)
if user is not None:
locale = getattr(user, "locale", None)
if locale:
return locale
# Otherw... | [
"def",
"localeselector",
"(",
")",
":",
"# if a user is logged in, use the locale from the user settings",
"user",
"=",
"getattr",
"(",
"g",
",",
"\"user\"",
",",
"None",
")",
"if",
"user",
"is",
"not",
"None",
":",
"locale",
"=",
"getattr",
"(",
"user",
",",
... | Default locale selector used in abilian applications. | [
"Default",
"locale",
"selector",
"used",
"in",
"abilian",
"applications",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/i18n.py#L302-L315 |
abilian/abilian-core | abilian/i18n.py | get_template_i18n | def get_template_i18n(template_name, locale):
"""Build template list with preceding locale if found."""
if locale is None:
return [template_name]
template_list = []
parts = template_name.rsplit(".", 1)
root = parts[0]
suffix = parts[1]
if locale.territory is not None:
local... | python | def get_template_i18n(template_name, locale):
"""Build template list with preceding locale if found."""
if locale is None:
return [template_name]
template_list = []
parts = template_name.rsplit(".", 1)
root = parts[0]
suffix = parts[1]
if locale.territory is not None:
local... | [
"def",
"get_template_i18n",
"(",
"template_name",
",",
"locale",
")",
":",
"if",
"locale",
"is",
"None",
":",
"return",
"[",
"template_name",
"]",
"template_list",
"=",
"[",
"]",
"parts",
"=",
"template_name",
".",
"rsplit",
"(",
"\".\"",
",",
"1",
")",
... | Build template list with preceding locale if found. | [
"Build",
"template",
"list",
"with",
"preceding",
"locale",
"if",
"found",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/i18n.py#L323-L343 |
abilian/abilian-core | abilian/i18n.py | render_template_i18n | def render_template_i18n(template_name_or_list, **context):
"""Try to build an ordered list of template to satisfy the current
locale."""
template_list = []
# Use locale if present in **context
if "locale" in context:
locale = Locale.parse(context["locale"])
else:
# Use get_local... | python | def render_template_i18n(template_name_or_list, **context):
"""Try to build an ordered list of template to satisfy the current
locale."""
template_list = []
# Use locale if present in **context
if "locale" in context:
locale = Locale.parse(context["locale"])
else:
# Use get_local... | [
"def",
"render_template_i18n",
"(",
"template_name_or_list",
",",
"*",
"*",
"context",
")",
":",
"template_list",
"=",
"[",
"]",
"# Use locale if present in **context",
"if",
"\"locale\"",
"in",
"context",
":",
"locale",
"=",
"Locale",
".",
"parse",
"(",
"context"... | Try to build an ordered list of template to satisfy the current
locale. | [
"Try",
"to",
"build",
"an",
"ordered",
"list",
"of",
"template",
"to",
"satisfy",
"the",
"current",
"locale",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/i18n.py#L364-L383 |
abilian/abilian-core | abilian/i18n.py | Babel.add_translations | def add_translations(
self, module_name, translations_dir="translations", domain="messages"
):
"""Add translations from external module.
For example::
babel.add_translations('abilian.core')
Will add translations files from `abilian.core` module.
"""
mod... | python | def add_translations(
self, module_name, translations_dir="translations", domain="messages"
):
"""Add translations from external module.
For example::
babel.add_translations('abilian.core')
Will add translations files from `abilian.core` module.
"""
mod... | [
"def",
"add_translations",
"(",
"self",
",",
"module_name",
",",
"translations_dir",
"=",
"\"translations\"",
",",
"domain",
"=",
"\"messages\"",
")",
":",
"module",
"=",
"importlib",
".",
"import_module",
"(",
"module_name",
")",
"for",
"path",
"in",
"(",
"Pa... | Add translations from external module.
For example::
babel.add_translations('abilian.core')
Will add translations files from `abilian.core` module. | [
"Add",
"translations",
"from",
"external",
"module",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/i18n.py#L190-L213 |
abilian/abilian-core | abilian/web/views/files.py | BaseFileDownload.get | def get(self, attach, *args, **kwargs):
"""
:param attach: if True, return file as an attachment.
"""
response = self.make_response(*args, **kwargs) # type: Response
response.content_type = self.get_content_type(*args, **kwargs)
if attach:
filename = self.ge... | python | def get(self, attach, *args, **kwargs):
"""
:param attach: if True, return file as an attachment.
"""
response = self.make_response(*args, **kwargs) # type: Response
response.content_type = self.get_content_type(*args, **kwargs)
if attach:
filename = self.ge... | [
"def",
"get",
"(",
"self",
",",
"attach",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"=",
"self",
".",
"make_response",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"# type: Response",
"response",
".",
"content_type",
"=",
"s... | :param attach: if True, return file as an attachment. | [
":",
"param",
"attach",
":",
"if",
"True",
"return",
"file",
"as",
"an",
"attachment",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/views/files.py#L79-L94 |
abilian/abilian-core | abilian/core/sqlalchemy.py | ping_connection | def ping_connection(dbapi_connection, connection_record, connection_proxy):
"""Ensure connections are valid.
From: `http://docs.sqlalchemy.org/en/rel_0_8/core/pooling.html`
In case db has been restarted pool may return invalid connections.
"""
cursor = dbapi_connection.cursor()
try:
cu... | python | def ping_connection(dbapi_connection, connection_record, connection_proxy):
"""Ensure connections are valid.
From: `http://docs.sqlalchemy.org/en/rel_0_8/core/pooling.html`
In case db has been restarted pool may return invalid connections.
"""
cursor = dbapi_connection.cursor()
try:
cu... | [
"def",
"ping_connection",
"(",
"dbapi_connection",
",",
"connection_record",
",",
"connection_proxy",
")",
":",
"cursor",
"=",
"dbapi_connection",
".",
"cursor",
"(",
")",
"try",
":",
"cursor",
".",
"execute",
"(",
"\"SELECT 1\"",
")",
"except",
"Exception",
":"... | Ensure connections are valid.
From: `http://docs.sqlalchemy.org/en/rel_0_8/core/pooling.html`
In case db has been restarted pool may return invalid connections. | [
"Ensure",
"connections",
"are",
"valid",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/sqlalchemy.py#L27-L45 |
abilian/abilian-core | abilian/core/sqlalchemy.py | filter_cols | def filter_cols(model, *filtered_columns):
"""Return columnsnames for a model except named ones.
Useful for defer() for example to retain only columns of interest
"""
m = sa.orm.class_mapper(model)
return list(
{p.key for p in m.iterate_properties if hasattr(p, "columns")}.difference(
... | python | def filter_cols(model, *filtered_columns):
"""Return columnsnames for a model except named ones.
Useful for defer() for example to retain only columns of interest
"""
m = sa.orm.class_mapper(model)
return list(
{p.key for p in m.iterate_properties if hasattr(p, "columns")}.difference(
... | [
"def",
"filter_cols",
"(",
"model",
",",
"*",
"filtered_columns",
")",
":",
"m",
"=",
"sa",
".",
"orm",
".",
"class_mapper",
"(",
"model",
")",
"return",
"list",
"(",
"{",
"p",
".",
"key",
"for",
"p",
"in",
"m",
".",
"iterate_properties",
"if",
"hasa... | Return columnsnames for a model except named ones.
Useful for defer() for example to retain only columns of interest | [
"Return",
"columnsnames",
"for",
"a",
"model",
"except",
"named",
"ones",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/sqlalchemy.py#L114-L124 |
abilian/abilian-core | abilian/core/sqlalchemy.py | JSONList | def JSONList(*args, **kwargs):
"""Stores a list as JSON on database, with mutability support.
If kwargs has a param `unique_sorted` (which evaluated to True),
list values are made unique and sorted.
"""
type_ = JSON
try:
if kwargs.pop("unique_sorted"):
type_ = JSONUniqueList... | python | def JSONList(*args, **kwargs):
"""Stores a list as JSON on database, with mutability support.
If kwargs has a param `unique_sorted` (which evaluated to True),
list values are made unique and sorted.
"""
type_ = JSON
try:
if kwargs.pop("unique_sorted"):
type_ = JSONUniqueList... | [
"def",
"JSONList",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"type_",
"=",
"JSON",
"try",
":",
"if",
"kwargs",
".",
"pop",
"(",
"\"unique_sorted\"",
")",
":",
"type_",
"=",
"JSONUniqueListType",
"except",
"KeyError",
":",
"pass",
"return",
"... | Stores a list as JSON on database, with mutability support.
If kwargs has a param `unique_sorted` (which evaluated to True),
list values are made unique and sorted. | [
"Stores",
"a",
"list",
"as",
"JSON",
"on",
"database",
"with",
"mutability",
"support",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/sqlalchemy.py#L302-L315 |
abilian/abilian-core | abilian/core/sqlalchemy.py | MutationDict.coerce | def coerce(cls, key, value):
"""Convert plain dictionaries to MutationDict."""
if not isinstance(value, MutationDict):
if isinstance(value, dict):
return MutationDict(value)
# this call will raise ValueError
return Mutable.coerce(key, value)
e... | python | def coerce(cls, key, value):
"""Convert plain dictionaries to MutationDict."""
if not isinstance(value, MutationDict):
if isinstance(value, dict):
return MutationDict(value)
# this call will raise ValueError
return Mutable.coerce(key, value)
e... | [
"def",
"coerce",
"(",
"cls",
",",
"key",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"MutationDict",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"return",
"MutationDict",
"(",
"value",
")",
"# this call ... | Convert plain dictionaries to MutationDict. | [
"Convert",
"plain",
"dictionaries",
"to",
"MutationDict",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/sqlalchemy.py#L131-L140 |
abilian/abilian-core | abilian/core/sqlalchemy.py | MutationList.coerce | def coerce(cls, key, value):
"""Convert list to MutationList."""
if not isinstance(value, MutationList):
if isinstance(value, list):
return MutationList(value)
# this call will raise ValueError
return Mutable.coerce(key, value)
else:
... | python | def coerce(cls, key, value):
"""Convert list to MutationList."""
if not isinstance(value, MutationList):
if isinstance(value, list):
return MutationList(value)
# this call will raise ValueError
return Mutable.coerce(key, value)
else:
... | [
"def",
"coerce",
"(",
"cls",
",",
"key",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"MutationList",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"return",
"MutationList",
"(",
"value",
")",
"# this call ... | Convert list to MutationList. | [
"Convert",
"list",
"to",
"MutationList",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/sqlalchemy.py#L187-L196 |
abilian/abilian-core | abilian/web/uploads/extension.py | FileUploadsExtension.add_file | def add_file(self, user, file_obj, **metadata):
"""Add a new file.
:returns: file handle
"""
user_dir = self.user_dir(user)
if not user_dir.exists():
user_dir.mkdir(mode=0o775)
handle = str(uuid1())
file_path = user_dir / handle
with file_pa... | python | def add_file(self, user, file_obj, **metadata):
"""Add a new file.
:returns: file handle
"""
user_dir = self.user_dir(user)
if not user_dir.exists():
user_dir.mkdir(mode=0o775)
handle = str(uuid1())
file_path = user_dir / handle
with file_pa... | [
"def",
"add_file",
"(",
"self",
",",
"user",
",",
"file_obj",
",",
"*",
"*",
"metadata",
")",
":",
"user_dir",
"=",
"self",
".",
"user_dir",
"(",
"user",
")",
"if",
"not",
"user_dir",
".",
"exists",
"(",
")",
":",
"user_dir",
".",
"mkdir",
"(",
"mo... | Add a new file.
:returns: file handle | [
"Add",
"a",
"new",
"file",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/uploads/extension.py#L86-L108 |
abilian/abilian-core | abilian/web/uploads/extension.py | FileUploadsExtension.get_file | def get_file(self, user, handle):
"""Retrieve a file for a user.
:returns: a :class:`pathlib.Path` instance to this file,
or None if no file can be found for this handle.
"""
user_dir = self.user_dir(user)
if not user_dir.exists():
return None
if... | python | def get_file(self, user, handle):
"""Retrieve a file for a user.
:returns: a :class:`pathlib.Path` instance to this file,
or None if no file can be found for this handle.
"""
user_dir = self.user_dir(user)
if not user_dir.exists():
return None
if... | [
"def",
"get_file",
"(",
"self",
",",
"user",
",",
"handle",
")",
":",
"user_dir",
"=",
"self",
".",
"user_dir",
"(",
"user",
")",
"if",
"not",
"user_dir",
".",
"exists",
"(",
")",
":",
"return",
"None",
"if",
"not",
"is_valid_handle",
"(",
"handle",
... | Retrieve a file for a user.
:returns: a :class:`pathlib.Path` instance to this file,
or None if no file can be found for this handle. | [
"Retrieve",
"a",
"file",
"for",
"a",
"user",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/uploads/extension.py#L110-L128 |
abilian/abilian-core | abilian/web/uploads/extension.py | FileUploadsExtension.clear_stalled_files | def clear_stalled_files(self):
"""Scan upload directory and delete stalled files.
Stalled files are files uploaded more than
`DELETE_STALLED_AFTER` seconds ago.
"""
# FIXME: put lock in directory?
CLEAR_AFTER = self.config["DELETE_STALLED_AFTER"]
minimum_age = ti... | python | def clear_stalled_files(self):
"""Scan upload directory and delete stalled files.
Stalled files are files uploaded more than
`DELETE_STALLED_AFTER` seconds ago.
"""
# FIXME: put lock in directory?
CLEAR_AFTER = self.config["DELETE_STALLED_AFTER"]
minimum_age = ti... | [
"def",
"clear_stalled_files",
"(",
"self",
")",
":",
"# FIXME: put lock in directory?",
"CLEAR_AFTER",
"=",
"self",
".",
"config",
"[",
"\"DELETE_STALLED_AFTER\"",
"]",
"minimum_age",
"=",
"time",
".",
"time",
"(",
")",
"-",
"CLEAR_AFTER",
"for",
"user_dir",
"in",... | Scan upload directory and delete stalled files.
Stalled files are files uploaded more than
`DELETE_STALLED_AFTER` seconds ago. | [
"Scan",
"upload",
"directory",
"and",
"delete",
"stalled",
"files",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/uploads/extension.py#L164-L187 |
abilian/abilian-core | abilian/core/util.py | friendly_fqcn | def friendly_fqcn(cls_name):
"""Friendly name of fully qualified class name.
:param cls_name: a string or a class
"""
if isinstance(cls_name, type):
cls_name = fqcn(cls_name)
return cls_name.rsplit(".", 1)[-1] | python | def friendly_fqcn(cls_name):
"""Friendly name of fully qualified class name.
:param cls_name: a string or a class
"""
if isinstance(cls_name, type):
cls_name = fqcn(cls_name)
return cls_name.rsplit(".", 1)[-1] | [
"def",
"friendly_fqcn",
"(",
"cls_name",
")",
":",
"if",
"isinstance",
"(",
"cls_name",
",",
"type",
")",
":",
"cls_name",
"=",
"fqcn",
"(",
"cls_name",
")",
"return",
"cls_name",
".",
"rsplit",
"(",
"\".\"",
",",
"1",
")",
"[",
"-",
"1",
"]"
] | Friendly name of fully qualified class name.
:param cls_name: a string or a class | [
"Friendly",
"name",
"of",
"fully",
"qualified",
"class",
"name",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/util.py#L37-L45 |
abilian/abilian-core | abilian/core/util.py | local_dt | def local_dt(dt):
"""Return an aware datetime in system timezone, from a naive or aware
datetime.
Naive datetime are assumed to be in UTC TZ.
"""
if not dt.tzinfo:
dt = pytz.utc.localize(dt)
return LOCALTZ.normalize(dt.astimezone(LOCALTZ)) | python | def local_dt(dt):
"""Return an aware datetime in system timezone, from a naive or aware
datetime.
Naive datetime are assumed to be in UTC TZ.
"""
if not dt.tzinfo:
dt = pytz.utc.localize(dt)
return LOCALTZ.normalize(dt.astimezone(LOCALTZ)) | [
"def",
"local_dt",
"(",
"dt",
")",
":",
"if",
"not",
"dt",
".",
"tzinfo",
":",
"dt",
"=",
"pytz",
".",
"utc",
".",
"localize",
"(",
"dt",
")",
"return",
"LOCALTZ",
".",
"normalize",
"(",
"dt",
".",
"astimezone",
"(",
"LOCALTZ",
")",
")"
] | Return an aware datetime in system timezone, from a naive or aware
datetime.
Naive datetime are assumed to be in UTC TZ. | [
"Return",
"an",
"aware",
"datetime",
"in",
"system",
"timezone",
"from",
"a",
"naive",
"or",
"aware",
"datetime",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/util.py#L53-L61 |
abilian/abilian-core | abilian/core/util.py | utc_dt | def utc_dt(dt):
"""Set UTC timezone on a datetime object.
A naive datetime is assumed to be in UTC TZ.
"""
if not dt.tzinfo:
return pytz.utc.localize(dt)
return dt.astimezone(pytz.utc) | python | def utc_dt(dt):
"""Set UTC timezone on a datetime object.
A naive datetime is assumed to be in UTC TZ.
"""
if not dt.tzinfo:
return pytz.utc.localize(dt)
return dt.astimezone(pytz.utc) | [
"def",
"utc_dt",
"(",
"dt",
")",
":",
"if",
"not",
"dt",
".",
"tzinfo",
":",
"return",
"pytz",
".",
"utc",
".",
"localize",
"(",
"dt",
")",
"return",
"dt",
".",
"astimezone",
"(",
"pytz",
".",
"utc",
")"
] | Set UTC timezone on a datetime object.
A naive datetime is assumed to be in UTC TZ. | [
"Set",
"UTC",
"timezone",
"on",
"a",
"datetime",
"object",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/util.py#L64-L71 |
abilian/abilian-core | abilian/core/util.py | get_params | def get_params(names):
"""Return a dictionary with params from request.
TODO: I think we don't use it anymore and it should be removed
before someone gets hurt.
"""
params = {}
for name in names:
value = request.form.get(name) or request.files.get(name)
if value is not None:
... | python | def get_params(names):
"""Return a dictionary with params from request.
TODO: I think we don't use it anymore and it should be removed
before someone gets hurt.
"""
params = {}
for name in names:
value = request.form.get(name) or request.files.get(name)
if value is not None:
... | [
"def",
"get_params",
"(",
"names",
")",
":",
"params",
"=",
"{",
"}",
"for",
"name",
"in",
"names",
":",
"value",
"=",
"request",
".",
"form",
".",
"get",
"(",
"name",
")",
"or",
"request",
".",
"files",
".",
"get",
"(",
"name",
")",
"if",
"value... | Return a dictionary with params from request.
TODO: I think we don't use it anymore and it should be removed
before someone gets hurt. | [
"Return",
"a",
"dictionary",
"with",
"params",
"from",
"request",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/util.py#L74-L85 |
abilian/abilian-core | abilian/core/util.py | slugify | def slugify(value, separator="-"):
"""Slugify an Unicode string, to make it URL friendly."""
if not isinstance(value, str):
raise ValueError("value must be a Unicode string")
value = _NOT_WORD_RE.sub(" ", value)
value = unicodedata.normalize("NFKD", value)
value = value.encode("ascii", "igno... | python | def slugify(value, separator="-"):
"""Slugify an Unicode string, to make it URL friendly."""
if not isinstance(value, str):
raise ValueError("value must be a Unicode string")
value = _NOT_WORD_RE.sub(" ", value)
value = unicodedata.normalize("NFKD", value)
value = value.encode("ascii", "igno... | [
"def",
"slugify",
"(",
"value",
",",
"separator",
"=",
"\"-\"",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"raise",
"ValueError",
"(",
"\"value must be a Unicode string\"",
")",
"value",
"=",
"_NOT_WORD_RE",
".",
"sub",
"(",
"... | Slugify an Unicode string, to make it URL friendly. | [
"Slugify",
"an",
"Unicode",
"string",
"to",
"make",
"it",
"URL",
"friendly",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/util.py#L178-L188 |
abilian/abilian-core | abilian/web/forms/validators.py | luhn | def luhn(n):
"""Validate that a string made of numeric characters verify Luhn test. Used
by siret validator.
from
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers#Python
https://en.wikipedia.org/wiki/Luhn_algorithm
"""
r = [int(ch) for ch in str(n)][::-1]
return (sum(r[0::2]... | python | def luhn(n):
"""Validate that a string made of numeric characters verify Luhn test. Used
by siret validator.
from
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers#Python
https://en.wikipedia.org/wiki/Luhn_algorithm
"""
r = [int(ch) for ch in str(n)][::-1]
return (sum(r[0::2]... | [
"def",
"luhn",
"(",
"n",
")",
":",
"r",
"=",
"[",
"int",
"(",
"ch",
")",
"for",
"ch",
"in",
"str",
"(",
"n",
")",
"]",
"[",
":",
":",
"-",
"1",
"]",
"return",
"(",
"sum",
"(",
"r",
"[",
"0",
":",
":",
"2",
"]",
")",
"+",
"sum",
"(",
... | Validate that a string made of numeric characters verify Luhn test. Used
by siret validator.
from
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers#Python
https://en.wikipedia.org/wiki/Luhn_algorithm | [
"Validate",
"that",
"a",
"string",
"made",
"of",
"numeric",
"characters",
"verify",
"Luhn",
"test",
".",
"Used",
"by",
"siret",
"validator",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/forms/validators.py#L218-L227 |
abilian/abilian-core | abilian/web/forms/validators.py | siret_validator | def siret_validator():
"""Validate a SIRET: check its length (14), its final code, and pass it
through the Luhn algorithm."""
def _validate_siret(form, field, siret=""):
"""SIRET validator.
A WTForm validator wants a form and a field as parameters. We
also want to give directly a s... | python | def siret_validator():
"""Validate a SIRET: check its length (14), its final code, and pass it
through the Luhn algorithm."""
def _validate_siret(form, field, siret=""):
"""SIRET validator.
A WTForm validator wants a form and a field as parameters. We
also want to give directly a s... | [
"def",
"siret_validator",
"(",
")",
":",
"def",
"_validate_siret",
"(",
"form",
",",
"field",
",",
"siret",
"=",
"\"\"",
")",
":",
"\"\"\"SIRET validator.\n\n A WTForm validator wants a form and a field as parameters. We\n also want to give directly a siret, for a scr... | Validate a SIRET: check its length (14), its final code, and pass it
through the Luhn algorithm. | [
"Validate",
"a",
"SIRET",
":",
"check",
"its",
"length",
"(",
"14",
")",
"its",
"final",
"code",
"and",
"pass",
"it",
"through",
"the",
"Luhn",
"algorithm",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/forms/validators.py#L239-L271 |
abilian/abilian-core | abilian/web/search/criterion.py | TextSearchCriterion.get_rel_attr | def get_rel_attr(self, attr_name, model):
"""For a related attribute specification, returns (related model,
attribute).
Returns (None, None) if model is not found, or (model, None) if
attribute is not found.
"""
rel_attr_name, attr_name = attr_name.split(".", 1)
... | python | def get_rel_attr(self, attr_name, model):
"""For a related attribute specification, returns (related model,
attribute).
Returns (None, None) if model is not found, or (model, None) if
attribute is not found.
"""
rel_attr_name, attr_name = attr_name.split(".", 1)
... | [
"def",
"get_rel_attr",
"(",
"self",
",",
"attr_name",
",",
"model",
")",
":",
"rel_attr_name",
",",
"attr_name",
"=",
"attr_name",
".",
"split",
"(",
"\".\"",
",",
"1",
")",
"rel_attr",
"=",
"getattr",
"(",
"self",
".",
"model",
",",
"rel_attr_name",
","... | For a related attribute specification, returns (related model,
attribute).
Returns (None, None) if model is not found, or (model, None) if
attribute is not found. | [
"For",
"a",
"related",
"attribute",
"specification",
"returns",
"(",
"related",
"model",
"attribute",
")",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/search/criterion.py#L171-L187 |
abilian/abilian-core | abilian/services/repository/service.py | RepositoryService.rel_path | def rel_path(self, uuid):
# type: (UUID) -> Path
"""Contruct relative path from repository top directory to the file
named after this uuid.
:param:uuid: :class:`UUID` instance
"""
_assert_uuid(uuid)
filename = str(uuid)
return Path(filename[0:2], filename... | python | def rel_path(self, uuid):
# type: (UUID) -> Path
"""Contruct relative path from repository top directory to the file
named after this uuid.
:param:uuid: :class:`UUID` instance
"""
_assert_uuid(uuid)
filename = str(uuid)
return Path(filename[0:2], filename... | [
"def",
"rel_path",
"(",
"self",
",",
"uuid",
")",
":",
"# type: (UUID) -> Path",
"_assert_uuid",
"(",
"uuid",
")",
"filename",
"=",
"str",
"(",
"uuid",
")",
"return",
"Path",
"(",
"filename",
"[",
"0",
":",
"2",
"]",
",",
"filename",
"[",
"2",
":",
"... | Contruct relative path from repository top directory to the file
named after this uuid.
:param:uuid: :class:`UUID` instance | [
"Contruct",
"relative",
"path",
"from",
"repository",
"top",
"directory",
"to",
"the",
"file",
"named",
"after",
"this",
"uuid",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/repository/service.py#L48-L57 |
abilian/abilian-core | abilian/services/repository/service.py | RepositoryService.abs_path | def abs_path(self, uuid):
# type: (UUID) -> Path
"""Return absolute :class:`Path` object for given uuid.
:param:uuid: :class:`UUID` instance
"""
top = self.app_state.path
rel_path = self.rel_path(uuid)
dest = top / rel_path
assert top in dest.parents
... | python | def abs_path(self, uuid):
# type: (UUID) -> Path
"""Return absolute :class:`Path` object for given uuid.
:param:uuid: :class:`UUID` instance
"""
top = self.app_state.path
rel_path = self.rel_path(uuid)
dest = top / rel_path
assert top in dest.parents
... | [
"def",
"abs_path",
"(",
"self",
",",
"uuid",
")",
":",
"# type: (UUID) -> Path",
"top",
"=",
"self",
".",
"app_state",
".",
"path",
"rel_path",
"=",
"self",
".",
"rel_path",
"(",
"uuid",
")",
"dest",
"=",
"top",
"/",
"rel_path",
"assert",
"top",
"in",
... | Return absolute :class:`Path` object for given uuid.
:param:uuid: :class:`UUID` instance | [
"Return",
"absolute",
":",
"class",
":",
"Path",
"object",
"for",
"given",
"uuid",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/repository/service.py#L59-L69 |
abilian/abilian-core | abilian/services/repository/service.py | RepositoryService.get | def get(self, uuid, default=None):
# type: (UUID, Optional[Path]) -> Optional[Path]
"""Return absolute :class:`Path` object for given uuid, if this uuid
exists in repository, or `default` if it doesn't.
:param:uuid: :class:`UUID` instance
"""
path = self.abs_path(uuid)
... | python | def get(self, uuid, default=None):
# type: (UUID, Optional[Path]) -> Optional[Path]
"""Return absolute :class:`Path` object for given uuid, if this uuid
exists in repository, or `default` if it doesn't.
:param:uuid: :class:`UUID` instance
"""
path = self.abs_path(uuid)
... | [
"def",
"get",
"(",
"self",
",",
"uuid",
",",
"default",
"=",
"None",
")",
":",
"# type: (UUID, Optional[Path]) -> Optional[Path]",
"path",
"=",
"self",
".",
"abs_path",
"(",
"uuid",
")",
"if",
"not",
"path",
".",
"exists",
"(",
")",
":",
"return",
"default... | Return absolute :class:`Path` object for given uuid, if this uuid
exists in repository, or `default` if it doesn't.
:param:uuid: :class:`UUID` instance | [
"Return",
"absolute",
":",
"class",
":",
"Path",
"object",
"for",
"given",
"uuid",
"if",
"this",
"uuid",
"exists",
"in",
"repository",
"or",
"default",
"if",
"it",
"doesn",
"t",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/repository/service.py#L71-L81 |
abilian/abilian-core | abilian/services/repository/service.py | RepositoryService.set | def set(self, uuid, content, encoding="utf-8"):
# type: (UUID, Any, Optional[Text]) -> None
"""Store binary content with uuid as key.
:param:uuid: :class:`UUID` instance
:param:content: string, bytes, or any object with a `read()` method
:param:encoding: encoding to use when con... | python | def set(self, uuid, content, encoding="utf-8"):
# type: (UUID, Any, Optional[Text]) -> None
"""Store binary content with uuid as key.
:param:uuid: :class:`UUID` instance
:param:content: string, bytes, or any object with a `read()` method
:param:encoding: encoding to use when con... | [
"def",
"set",
"(",
"self",
",",
"uuid",
",",
"content",
",",
"encoding",
"=",
"\"utf-8\"",
")",
":",
"# type: (UUID, Any, Optional[Text]) -> None",
"dest",
"=",
"self",
".",
"abs_path",
"(",
"uuid",
")",
"if",
"not",
"dest",
".",
"parent",
".",
"exists",
"... | Store binary content with uuid as key.
:param:uuid: :class:`UUID` instance
:param:content: string, bytes, or any object with a `read()` method
:param:encoding: encoding to use when content is Unicode | [
"Store",
"binary",
"content",
"with",
"uuid",
"as",
"key",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/repository/service.py#L83-L104 |
abilian/abilian-core | abilian/services/repository/service.py | RepositoryService.delete | def delete(self, uuid):
# type: (UUID) -> None
"""Delete file with given uuid.
:param:uuid: :class:`UUID` instance
:raises:KeyError if file does not exists
"""
dest = self.abs_path(uuid)
if not dest.exists():
raise KeyError("No file can be found for t... | python | def delete(self, uuid):
# type: (UUID) -> None
"""Delete file with given uuid.
:param:uuid: :class:`UUID` instance
:raises:KeyError if file does not exists
"""
dest = self.abs_path(uuid)
if not dest.exists():
raise KeyError("No file can be found for t... | [
"def",
"delete",
"(",
"self",
",",
"uuid",
")",
":",
"# type: (UUID) -> None",
"dest",
"=",
"self",
".",
"abs_path",
"(",
"uuid",
")",
"if",
"not",
"dest",
".",
"exists",
"(",
")",
":",
"raise",
"KeyError",
"(",
"\"No file can be found for this uuid\"",
",",... | Delete file with given uuid.
:param:uuid: :class:`UUID` instance
:raises:KeyError if file does not exists | [
"Delete",
"file",
"with",
"given",
"uuid",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/repository/service.py#L106-L117 |
abilian/abilian-core | abilian/services/repository/service.py | SessionRepositoryState.set_transaction | def set_transaction(self, session, transaction):
# type: (Session, RepositoryTransaction) -> None
"""
:param:session: :class:`sqlalchemy.orm.session.Session` instance
:param:transaction: :class:`RepositoryTransaction` instance
"""
if isinstance(session, sa.orm.scoped_sess... | python | def set_transaction(self, session, transaction):
# type: (Session, RepositoryTransaction) -> None
"""
:param:session: :class:`sqlalchemy.orm.session.Session` instance
:param:transaction: :class:`RepositoryTransaction` instance
"""
if isinstance(session, sa.orm.scoped_sess... | [
"def",
"set_transaction",
"(",
"self",
",",
"session",
",",
"transaction",
")",
":",
"# type: (Session, RepositoryTransaction) -> None",
"if",
"isinstance",
"(",
"session",
",",
"sa",
".",
"orm",
".",
"scoped_session",
")",
":",
"session",
"=",
"session",
"(",
"... | :param:session: :class:`sqlalchemy.orm.session.Session` instance
:param:transaction: :class:`RepositoryTransaction` instance | [
":",
"param",
":",
"session",
":",
":",
"class",
":",
"sqlalchemy",
".",
"orm",
".",
"session",
".",
"Session",
"instance",
":",
"param",
":",
"transaction",
":",
":",
"class",
":",
"RepositoryTransaction",
"instance"
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/repository/service.py#L176-L186 |
abilian/abilian-core | abilian/services/repository/service.py | SessionRepositoryService._session_for | def _session_for(self, model_or_session):
"""Return session instance for object parameter.
If parameter is a session instance, it is return as is.
If parameter is a registered model instance, its session will be used.
If parameter is a detached model instance, or None, application scop... | python | def _session_for(self, model_or_session):
"""Return session instance for object parameter.
If parameter is a session instance, it is return as is.
If parameter is a registered model instance, its session will be used.
If parameter is a detached model instance, or None, application scop... | [
"def",
"_session_for",
"(",
"self",
",",
"model_or_session",
")",
":",
"session",
"=",
"model_or_session",
"if",
"not",
"isinstance",
"(",
"session",
",",
"(",
"Session",
",",
"sa",
".",
"orm",
".",
"scoped_session",
")",
")",
":",
"if",
"session",
"is",
... | Return session instance for object parameter.
If parameter is a session instance, it is return as is.
If parameter is a registered model instance, its session will be used.
If parameter is a detached model instance, or None, application scoped
session will be used (db.session())
... | [
"Return",
"session",
"instance",
"for",
"object",
"parameter",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/repository/service.py#L289-L312 |
abilian/abilian-core | abilian/services/repository/service.py | RepositoryTransaction.commit | def commit(self, session=None):
"""Merge modified objects into parent transaction.
Once commited a transaction object is not usable anymore
:param:session: current sqlalchemy Session
"""
if self.__cleared:
return
if self._parent:
# nested transa... | python | def commit(self, session=None):
"""Merge modified objects into parent transaction.
Once commited a transaction object is not usable anymore
:param:session: current sqlalchemy Session
"""
if self.__cleared:
return
if self._parent:
# nested transa... | [
"def",
"commit",
"(",
"self",
",",
"session",
"=",
"None",
")",
":",
"if",
"self",
".",
"__cleared",
":",
"return",
"if",
"self",
".",
"_parent",
":",
"# nested transaction",
"self",
".",
"_commit_parent",
"(",
")",
"else",
":",
"self",
".",
"_commit_rep... | Merge modified objects into parent transaction.
Once commited a transaction object is not usable anymore
:param:session: current sqlalchemy Session | [
"Merge",
"modified",
"objects",
"into",
"parent",
"transaction",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/repository/service.py#L407-L422 |
abilian/abilian-core | abilian/services/repository/service.py | RepositoryTransaction._add_to | def _add_to(self, uuid, dest, other):
"""Add `item` to `dest` set, ensuring `item` is not present in `other`
set."""
_assert_uuid(uuid)
try:
other.remove(uuid)
except KeyError:
pass
dest.add(uuid) | python | def _add_to(self, uuid, dest, other):
"""Add `item` to `dest` set, ensuring `item` is not present in `other`
set."""
_assert_uuid(uuid)
try:
other.remove(uuid)
except KeyError:
pass
dest.add(uuid) | [
"def",
"_add_to",
"(",
"self",
",",
"uuid",
",",
"dest",
",",
"other",
")",
":",
"_assert_uuid",
"(",
"uuid",
")",
"try",
":",
"other",
".",
"remove",
"(",
"uuid",
")",
"except",
"KeyError",
":",
"pass",
"dest",
".",
"add",
"(",
"uuid",
")"
] | Add `item` to `dest` set, ensuring `item` is not present in `other`
set. | [
"Add",
"item",
"to",
"dest",
"set",
"ensuring",
"item",
"is",
"not",
"present",
"in",
"other",
"set",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/repository/service.py#L453-L461 |
abilian/abilian-core | abilian/web/tags/extension.py | ns | def ns(ns):
"""Class decorator that sets default tags namespace to use with its
instances."""
def setup_ns(cls):
setattr(cls, ENTITY_DEFAULT_NS_ATTR, ns)
return cls
return setup_ns | python | def ns(ns):
"""Class decorator that sets default tags namespace to use with its
instances."""
def setup_ns(cls):
setattr(cls, ENTITY_DEFAULT_NS_ATTR, ns)
return cls
return setup_ns | [
"def",
"ns",
"(",
"ns",
")",
":",
"def",
"setup_ns",
"(",
"cls",
")",
":",
"setattr",
"(",
"cls",
",",
"ENTITY_DEFAULT_NS_ATTR",
",",
"ns",
")",
"return",
"cls",
"return",
"setup_ns"
] | Class decorator that sets default tags namespace to use with its
instances. | [
"Class",
"decorator",
"that",
"sets",
"default",
"tags",
"namespace",
"to",
"use",
"with",
"its",
"instances",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/tags/extension.py#L19-L27 |
abilian/abilian-core | abilian/web/tags/extension.py | TagsExtension.tags_from_hit | def tags_from_hit(self, tag_ids):
"""
:param tag_ids: indexed ids of tags in hit result.
Do not pass hit instances.
:returns: an iterable of :class:`Tag` instances.
"""
ids = []
for t in tag_ids.split():
t = t.strip()
try:
... | python | def tags_from_hit(self, tag_ids):
"""
:param tag_ids: indexed ids of tags in hit result.
Do not pass hit instances.
:returns: an iterable of :class:`Tag` instances.
"""
ids = []
for t in tag_ids.split():
t = t.strip()
try:
... | [
"def",
"tags_from_hit",
"(",
"self",
",",
"tag_ids",
")",
":",
"ids",
"=",
"[",
"]",
"for",
"t",
"in",
"tag_ids",
".",
"split",
"(",
")",
":",
"t",
"=",
"t",
".",
"strip",
"(",
")",
"try",
":",
"t",
"=",
"int",
"(",
"t",
")",
"except",
"Value... | :param tag_ids: indexed ids of tags in hit result.
Do not pass hit instances.
:returns: an iterable of :class:`Tag` instances. | [
":",
"param",
"tag_ids",
":",
"indexed",
"ids",
"of",
"tags",
"in",
"hit",
"result",
".",
"Do",
"not",
"pass",
"hit",
"instances",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/tags/extension.py#L65-L85 |
abilian/abilian-core | abilian/web/tags/extension.py | TagsExtension.entity_tags_form | def entity_tags_form(self, entity, ns=None):
"""Construct a form class with a field for tags in namespace `ns`."""
if ns is None:
ns = self.entity_default_ns(entity)
field = TagsField(label=_l("Tags"), ns=ns)
cls = type("EntityNSTagsForm", (_TagsForm,), {"tags": field})
... | python | def entity_tags_form(self, entity, ns=None):
"""Construct a form class with a field for tags in namespace `ns`."""
if ns is None:
ns = self.entity_default_ns(entity)
field = TagsField(label=_l("Tags"), ns=ns)
cls = type("EntityNSTagsForm", (_TagsForm,), {"tags": field})
... | [
"def",
"entity_tags_form",
"(",
"self",
",",
"entity",
",",
"ns",
"=",
"None",
")",
":",
"if",
"ns",
"is",
"None",
":",
"ns",
"=",
"self",
".",
"entity_default_ns",
"(",
"entity",
")",
"field",
"=",
"TagsField",
"(",
"label",
"=",
"_l",
"(",
"\"Tags\... | Construct a form class with a field for tags in namespace `ns`. | [
"Construct",
"a",
"form",
"class",
"with",
"a",
"field",
"for",
"tags",
"in",
"namespace",
"ns",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/tags/extension.py#L90-L97 |
abilian/abilian-core | abilian/web/tags/extension.py | TagsExtension.get | def get(self, ns, label=None):
"""Return :class:`tags instances<~Tag>` for the namespace `ns`, ordered
by label.
If `label` is not None the only one instance may be returned, or
`None` if no tags exists for this label.
"""
query = Tag.query.filter(Tag.ns == ns)
... | python | def get(self, ns, label=None):
"""Return :class:`tags instances<~Tag>` for the namespace `ns`, ordered
by label.
If `label` is not None the only one instance may be returned, or
`None` if no tags exists for this label.
"""
query = Tag.query.filter(Tag.ns == ns)
... | [
"def",
"get",
"(",
"self",
",",
"ns",
",",
"label",
"=",
"None",
")",
":",
"query",
"=",
"Tag",
".",
"query",
".",
"filter",
"(",
"Tag",
".",
"ns",
"==",
"ns",
")",
"if",
"label",
"is",
"not",
"None",
":",
"return",
"query",
".",
"filter",
"(",... | Return :class:`tags instances<~Tag>` for the namespace `ns`, ordered
by label.
If `label` is not None the only one instance may be returned, or
`None` if no tags exists for this label. | [
"Return",
":",
"class",
":",
"tags",
"instances<~Tag",
">",
"for",
"the",
"namespace",
"ns",
"ordered",
"by",
"label",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/tags/extension.py#L99-L111 |
abilian/abilian-core | abilian/web/tags/extension.py | TagsExtension.get_form_context | def get_form_context(self, obj, ns=None):
"""Return a dict: form instance, action button, submit url...
Used by macro m_tags_form(entity)
"""
return {
"url": url_for("entity_tags.edit", object_id=obj.id),
"form": self.entity_tags_form(obj)(obj=obj, ns=ns),
... | python | def get_form_context(self, obj, ns=None):
"""Return a dict: form instance, action button, submit url...
Used by macro m_tags_form(entity)
"""
return {
"url": url_for("entity_tags.edit", object_id=obj.id),
"form": self.entity_tags_form(obj)(obj=obj, ns=ns),
... | [
"def",
"get_form_context",
"(",
"self",
",",
"obj",
",",
"ns",
"=",
"None",
")",
":",
"return",
"{",
"\"url\"",
":",
"url_for",
"(",
"\"entity_tags.edit\"",
",",
"object_id",
"=",
"obj",
".",
"id",
")",
",",
"\"form\"",
":",
"self",
".",
"entity_tags_for... | Return a dict: form instance, action button, submit url...
Used by macro m_tags_form(entity) | [
"Return",
"a",
"dict",
":",
"form",
"instance",
"action",
"button",
"submit",
"url",
"..."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/tags/extension.py#L136-L145 |
abilian/abilian-core | abilian/cli/indexing.py | reindex | def reindex(clear: bool, progressive: bool, batch_size: int):
"""Reindex all content; optionally clear index before.
All is done in asingle transaction by default.
:param clear: clear index content.
:param progressive: don't run in a single transaction.
:param batch_size: number of documents to pr... | python | def reindex(clear: bool, progressive: bool, batch_size: int):
"""Reindex all content; optionally clear index before.
All is done in asingle transaction by default.
:param clear: clear index content.
:param progressive: don't run in a single transaction.
:param batch_size: number of documents to pr... | [
"def",
"reindex",
"(",
"clear",
":",
"bool",
",",
"progressive",
":",
"bool",
",",
"batch_size",
":",
"int",
")",
":",
"reindexer",
"=",
"Reindexer",
"(",
"clear",
",",
"progressive",
",",
"batch_size",
")",
"reindexer",
".",
"reindex_all",
"(",
")"
] | Reindex all content; optionally clear index before.
All is done in asingle transaction by default.
:param clear: clear index content.
:param progressive: don't run in a single transaction.
:param batch_size: number of documents to process before writing to the
index. Unused in sin... | [
"Reindex",
"all",
"content",
";",
"optionally",
"clear",
"index",
"before",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/cli/indexing.py#L30-L42 |
abilian/abilian-core | abilian/services/indexing/service.py | url_for_hit | def url_for_hit(hit, default="#"):
"""Helper for building URLs from results."""
try:
object_type = hit["object_type"]
object_id = int(hit["id"])
return current_app.default_view.url_for(hit, object_type, object_id)
except KeyError:
return default
except Exception:
... | python | def url_for_hit(hit, default="#"):
"""Helper for building URLs from results."""
try:
object_type = hit["object_type"]
object_id = int(hit["id"])
return current_app.default_view.url_for(hit, object_type, object_id)
except KeyError:
return default
except Exception:
... | [
"def",
"url_for_hit",
"(",
"hit",
",",
"default",
"=",
"\"#\"",
")",
":",
"try",
":",
"object_type",
"=",
"hit",
"[",
"\"object_type\"",
"]",
"object_id",
"=",
"int",
"(",
"hit",
"[",
"\"id\"",
"]",
")",
"return",
"current_app",
".",
"default_view",
".",... | Helper for building URLs from results. | [
"Helper",
"for",
"building",
"URLs",
"from",
"results",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/indexing/service.py#L49-L59 |
abilian/abilian-core | abilian/services/indexing/service.py | index_update | def index_update(index, items):
"""
:param:index: index name
:param:items: list of (operation, full class name, primary key, data) tuples.
"""
index_name = index
index = service.app_state.indexes[index_name]
adapted = service.adapted
session = safe_session()
updated = set()
writ... | python | def index_update(index, items):
"""
:param:index: index name
:param:items: list of (operation, full class name, primary key, data) tuples.
"""
index_name = index
index = service.app_state.indexes[index_name]
adapted = service.adapted
session = safe_session()
updated = set()
writ... | [
"def",
"index_update",
"(",
"index",
",",
"items",
")",
":",
"index_name",
"=",
"index",
"index",
"=",
"service",
".",
"app_state",
".",
"indexes",
"[",
"index_name",
"]",
"adapted",
"=",
"service",
".",
"adapted",
"session",
"=",
"safe_session",
"(",
")",... | :param:index: index name
:param:items: list of (operation, full class name, primary key, data) tuples. | [
":",
"param",
":",
"index",
":",
"index",
"name",
":",
"param",
":",
"items",
":",
"list",
"of",
"(",
"operation",
"full",
"class",
"name",
"primary",
"key",
"data",
")",
"tuples",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/indexing/service.py#L499-L562 |
abilian/abilian-core | abilian/services/indexing/service.py | WhooshIndexService.init_indexes | def init_indexes(self):
"""Create indexes for schemas."""
state = self.app_state
for name, schema in self.schemas.items():
if current_app.testing:
storage = TestingStorage()
else:
index_path = (Path(state.whoosh_base) / name).absolute()
... | python | def init_indexes(self):
"""Create indexes for schemas."""
state = self.app_state
for name, schema in self.schemas.items():
if current_app.testing:
storage = TestingStorage()
else:
index_path = (Path(state.whoosh_base) / name).absolute()
... | [
"def",
"init_indexes",
"(",
"self",
")",
":",
"state",
"=",
"self",
".",
"app_state",
"for",
"name",
",",
"schema",
"in",
"self",
".",
"schemas",
".",
"items",
"(",
")",
":",
"if",
"current_app",
".",
"testing",
":",
"storage",
"=",
"TestingStorage",
"... | Create indexes for schemas. | [
"Create",
"indexes",
"for",
"schemas",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/indexing/service.py#L161-L179 |
abilian/abilian-core | abilian/services/indexing/service.py | WhooshIndexService.clear | def clear(self):
"""Remove all content from indexes, and unregister all classes.
After clear() the service is stopped. It must be started again
to create new indexes and register classes.
"""
logger.info("Resetting indexes")
state = self.app_state
for _name, idx... | python | def clear(self):
"""Remove all content from indexes, and unregister all classes.
After clear() the service is stopped. It must be started again
to create new indexes and register classes.
"""
logger.info("Resetting indexes")
state = self.app_state
for _name, idx... | [
"def",
"clear",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"\"Resetting indexes\"",
")",
"state",
"=",
"self",
".",
"app_state",
"for",
"_name",
",",
"idx",
"in",
"state",
".",
"indexes",
".",
"items",
"(",
")",
":",
"writer",
"=",
"AsyncWriter... | Remove all content from indexes, and unregister all classes.
After clear() the service is stopped. It must be started again
to create new indexes and register classes. | [
"Remove",
"all",
"content",
"from",
"indexes",
"and",
"unregister",
"all",
"classes",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/indexing/service.py#L181-L200 |
abilian/abilian-core | abilian/services/indexing/service.py | WhooshIndexService.searchable_object_types | def searchable_object_types(self):
"""List of (object_types, friendly name) present in the index."""
try:
idx = self.index()
except KeyError:
# index does not exists: service never started, may happens during
# tests
return []
with idx.rea... | python | def searchable_object_types(self):
"""List of (object_types, friendly name) present in the index."""
try:
idx = self.index()
except KeyError:
# index does not exists: service never started, may happens during
# tests
return []
with idx.rea... | [
"def",
"searchable_object_types",
"(",
"self",
")",
":",
"try",
":",
"idx",
"=",
"self",
".",
"index",
"(",
")",
"except",
"KeyError",
":",
"# index does not exists: service never started, may happens during",
"# tests",
"return",
"[",
"]",
"with",
"idx",
".",
"re... | List of (object_types, friendly name) present in the index. | [
"List",
"of",
"(",
"object_types",
"friendly",
"name",
")",
"present",
"in",
"the",
"index",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/indexing/service.py#L216-L229 |
abilian/abilian-core | abilian/services/indexing/service.py | WhooshIndexService.search | def search(
self,
q,
index="default",
fields=None,
Models=(),
object_types=(),
prefix=True,
facet_by_type=None,
**search_args,
):
"""Interface to search indexes.
:param q: unparsed search string.
:param index: name of i... | python | def search(
self,
q,
index="default",
fields=None,
Models=(),
object_types=(),
prefix=True,
facet_by_type=None,
**search_args,
):
"""Interface to search indexes.
:param q: unparsed search string.
:param index: name of i... | [
"def",
"search",
"(",
"self",
",",
"q",
",",
"index",
"=",
"\"default\"",
",",
"fields",
"=",
"None",
",",
"Models",
"=",
"(",
")",
",",
"object_types",
"=",
"(",
")",
",",
"prefix",
"=",
"True",
",",
"facet_by_type",
"=",
"None",
",",
"*",
"*",
... | Interface to search indexes.
:param q: unparsed search string.
:param index: name of index to use for search.
:param fields: optionnal mapping of field names -> boost factor?
:param Models: list of Model classes to limit search on.
:param object_types: same as `Models`, but dire... | [
"Interface",
"to",
"search",
"indexes",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/indexing/service.py#L231-L348 |
abilian/abilian-core | abilian/services/indexing/service.py | WhooshIndexService.register_class | def register_class(self, cls, app_state=None):
"""Register a model class."""
state = app_state if app_state is not None else self.app_state
for Adapter in self.adapters_cls:
if Adapter.can_adapt(cls):
break
else:
return
cls_fqcn = fqcn(cl... | python | def register_class(self, cls, app_state=None):
"""Register a model class."""
state = app_state if app_state is not None else self.app_state
for Adapter in self.adapters_cls:
if Adapter.can_adapt(cls):
break
else:
return
cls_fqcn = fqcn(cl... | [
"def",
"register_class",
"(",
"self",
",",
"cls",
",",
"app_state",
"=",
"None",
")",
":",
"state",
"=",
"app_state",
"if",
"app_state",
"is",
"not",
"None",
"else",
"self",
".",
"app_state",
"for",
"Adapter",
"in",
"self",
".",
"adapters_cls",
":",
"if"... | Register a model class. | [
"Register",
"a",
"model",
"class",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/indexing/service.py#L364-L377 |
abilian/abilian-core | abilian/services/indexing/service.py | WhooshIndexService.after_commit | def after_commit(self, session):
"""Any db updates go through here.
We check if any of these models have ``__searchable__`` fields,
indicating they need to be indexed. With these we update the
whoosh index for the model. If no index exists, it will be
created here; this could im... | python | def after_commit(self, session):
"""Any db updates go through here.
We check if any of these models have ``__searchable__`` fields,
indicating they need to be indexed. With these we update the
whoosh index for the model. If no index exists, it will be
created here; this could im... | [
"def",
"after_commit",
"(",
"self",
",",
"session",
")",
":",
"if",
"(",
"not",
"self",
".",
"running",
"or",
"session",
".",
"transaction",
".",
"nested",
"# inside a sub-transaction:",
"# not yet written in DB",
"or",
"session",
"is",
"not",
"db",
".",
"sess... | Any db updates go through here.
We check if any of these models have ``__searchable__`` fields,
indicating they need to be indexed. With these we update the
whoosh index for the model. If no index exists, it will be
created here; this could impose a penalty on the initial commit
... | [
"Any",
"db",
"updates",
"go",
"through",
"here",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/indexing/service.py#L399-L434 |
abilian/abilian-core | abilian/services/indexing/service.py | WhooshIndexService.index_objects | def index_objects(self, objects, index="default"):
"""Bulk index a list of objects."""
if not objects:
return
index_name = index
index = self.app_state.indexes[index_name]
indexed = set()
with index.writer() as writer:
for obj in objects:
... | python | def index_objects(self, objects, index="default"):
"""Bulk index a list of objects."""
if not objects:
return
index_name = index
index = self.app_state.indexes[index_name]
indexed = set()
with index.writer() as writer:
for obj in objects:
... | [
"def",
"index_objects",
"(",
"self",
",",
"objects",
",",
"index",
"=",
"\"default\"",
")",
":",
"if",
"not",
"objects",
":",
"return",
"index_name",
"=",
"index",
"index",
"=",
"self",
".",
"app_state",
".",
"indexes",
"[",
"index_name",
"]",
"indexed",
... | Bulk index a list of objects. | [
"Bulk",
"index",
"a",
"list",
"of",
"objects",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/indexing/service.py#L464-L492 |
abilian/abilian-core | abilian/web/forms/widgets.py | linkify_url | def linkify_url(value):
"""Tranform an URL pulled from the database to a safe HTML fragment."""
value = value.strip()
rjs = r"[\s]*(&#x.{1,7})?".join(list("javascript:"))
rvb = r"[\s]*(&#x.{1,7})?".join(list("vbscript:"))
re_scripts = re.compile(f"({rjs})|({rvb})", re.IGNORECASE)
value = re_s... | python | def linkify_url(value):
"""Tranform an URL pulled from the database to a safe HTML fragment."""
value = value.strip()
rjs = r"[\s]*(&#x.{1,7})?".join(list("javascript:"))
rvb = r"[\s]*(&#x.{1,7})?".join(list("vbscript:"))
re_scripts = re.compile(f"({rjs})|({rvb})", re.IGNORECASE)
value = re_s... | [
"def",
"linkify_url",
"(",
"value",
")",
":",
"value",
"=",
"value",
".",
"strip",
"(",
")",
"rjs",
"=",
"r\"[\\s]*(&#x.{1,7})?\"",
".",
"join",
"(",
"list",
"(",
"\"javascript:\"",
")",
")",
"rvb",
"=",
"r\"[\\s]*(&#x.{1,7})?\"",
".",
"join",
"(",
"list",... | Tranform an URL pulled from the database to a safe HTML fragment. | [
"Tranform",
"an",
"URL",
"pulled",
"from",
"the",
"database",
"to",
"a",
"safe",
"HTML",
"fragment",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/forms/widgets.py#L81-L112 |
abilian/abilian-core | abilian/services/preferences/service.py | PreferenceService.get_preferences | def get_preferences(self, user=None):
"""Return a string->value dictionnary representing the given user
preferences.
If no user is provided, the current user is used instead.
"""
if user is None:
user = current_user
return {pref.key: pref.value for pref in us... | python | def get_preferences(self, user=None):
"""Return a string->value dictionnary representing the given user
preferences.
If no user is provided, the current user is used instead.
"""
if user is None:
user = current_user
return {pref.key: pref.value for pref in us... | [
"def",
"get_preferences",
"(",
"self",
",",
"user",
"=",
"None",
")",
":",
"if",
"user",
"is",
"None",
":",
"user",
"=",
"current_user",
"return",
"{",
"pref",
".",
"key",
":",
"pref",
".",
"value",
"for",
"pref",
"in",
"user",
".",
"preferences",
"}... | Return a string->value dictionnary representing the given user
preferences.
If no user is provided, the current user is used instead. | [
"Return",
"a",
"string",
"-",
">",
"value",
"dictionnary",
"representing",
"the",
"given",
"user",
"preferences",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/preferences/service.py#L63-L71 |
abilian/abilian-core | abilian/services/preferences/service.py | PreferenceService.set_preferences | def set_preferences(self, user=None, **kwargs):
"""Set preferences from keyword arguments."""
if user is None:
user = current_user
d = {pref.key: pref for pref in user.preferences}
for k, v in kwargs.items():
if k in d:
d[k].value = v
... | python | def set_preferences(self, user=None, **kwargs):
"""Set preferences from keyword arguments."""
if user is None:
user = current_user
d = {pref.key: pref for pref in user.preferences}
for k, v in kwargs.items():
if k in d:
d[k].value = v
... | [
"def",
"set_preferences",
"(",
"self",
",",
"user",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"user",
"is",
"None",
":",
"user",
"=",
"current_user",
"d",
"=",
"{",
"pref",
".",
"key",
":",
"pref",
"for",
"pref",
"in",
"user",
".",
"p... | Set preferences from keyword arguments. | [
"Set",
"preferences",
"from",
"keyword",
"arguments",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/preferences/service.py#L73-L84 |
abilian/abilian-core | abilian/web/attachments/extension.py | AttachmentExtension.manager | def manager(self, obj):
"""Returns the :class:`AttachmentsManager` instance for this object."""
manager = getattr(obj, _MANAGER_ATTR, None)
if manager is None:
manager = AttachmentsManager()
setattr(obj.__class__, _MANAGER_ATTR, manager)
return manager | python | def manager(self, obj):
"""Returns the :class:`AttachmentsManager` instance for this object."""
manager = getattr(obj, _MANAGER_ATTR, None)
if manager is None:
manager = AttachmentsManager()
setattr(obj.__class__, _MANAGER_ATTR, manager)
return manager | [
"def",
"manager",
"(",
"self",
",",
"obj",
")",
":",
"manager",
"=",
"getattr",
"(",
"obj",
",",
"_MANAGER_ATTR",
",",
"None",
")",
"if",
"manager",
"is",
"None",
":",
"manager",
"=",
"AttachmentsManager",
"(",
")",
"setattr",
"(",
"obj",
".",
"__class... | Returns the :class:`AttachmentsManager` instance for this object. | [
"Returns",
"the",
":",
"class",
":",
"AttachmentsManager",
"instance",
"for",
"this",
"object",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/attachments/extension.py#L28-L35 |
abilian/abilian-core | abilian/web/attachments/extension.py | AttachmentsManager.get_form_context | def get_form_context(self, obj):
"""Return a dict: form instance, action button, submit url...
Used by macro m_attachment_form(entity)
"""
return {
"url": url_for("attachments.create", entity_id=obj.id),
"form": self.Form(),
"buttons": [UPLOAD_BUTTON]... | python | def get_form_context(self, obj):
"""Return a dict: form instance, action button, submit url...
Used by macro m_attachment_form(entity)
"""
return {
"url": url_for("attachments.create", entity_id=obj.id),
"form": self.Form(),
"buttons": [UPLOAD_BUTTON]... | [
"def",
"get_form_context",
"(",
"self",
",",
"obj",
")",
":",
"return",
"{",
"\"url\"",
":",
"url_for",
"(",
"\"attachments.create\"",
",",
"entity_id",
"=",
"obj",
".",
"id",
")",
",",
"\"form\"",
":",
"self",
".",
"Form",
"(",
")",
",",
"\"buttons\"",
... | Return a dict: form instance, action button, submit url...
Used by macro m_attachment_form(entity) | [
"Return",
"a",
"dict",
":",
"form",
"instance",
"action",
"button",
"submit",
"url",
"..."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/attachments/extension.py#L109-L118 |
abilian/abilian-core | abilian/services/auth/service.py | AuthService.do_access_control | def do_access_control(self):
"""`before_request` handler to check if user should be redirected to
login page."""
from abilian.services import get_service
if current_app.testing and current_app.config.get("NO_LOGIN"):
# Special case for tests
user = User.query.get... | python | def do_access_control(self):
"""`before_request` handler to check if user should be redirected to
login page."""
from abilian.services import get_service
if current_app.testing and current_app.config.get("NO_LOGIN"):
# Special case for tests
user = User.query.get... | [
"def",
"do_access_control",
"(",
"self",
")",
":",
"from",
"abilian",
".",
"services",
"import",
"get_service",
"if",
"current_app",
".",
"testing",
"and",
"current_app",
".",
"config",
".",
"get",
"(",
"\"NO_LOGIN\"",
")",
":",
"# Special case for tests",
"user... | `before_request` handler to check if user should be redirected to
login page. | [
"before_request",
"handler",
"to",
"check",
"if",
"user",
"should",
"be",
"redirected",
"to",
"login",
"page",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/auth/service.py#L174-L219 |
abilian/abilian-core | abilian/web/tags/admin.py | get_entities_for_reindex | def get_entities_for_reindex(tags):
"""Collect entities for theses tags."""
if isinstance(tags, Tag):
tags = (tags,)
session = db.session()
indexing = get_service("indexing")
tbl = Entity.__table__
tag_ids = [t.id for t in tags]
query = (
sa.sql.select([tbl.c.entity_type, tb... | python | def get_entities_for_reindex(tags):
"""Collect entities for theses tags."""
if isinstance(tags, Tag):
tags = (tags,)
session = db.session()
indexing = get_service("indexing")
tbl = Entity.__table__
tag_ids = [t.id for t in tags]
query = (
sa.sql.select([tbl.c.entity_type, tb... | [
"def",
"get_entities_for_reindex",
"(",
"tags",
")",
":",
"if",
"isinstance",
"(",
"tags",
",",
"Tag",
")",
":",
"tags",
"=",
"(",
"tags",
",",
")",
"session",
"=",
"db",
".",
"session",
"(",
")",
"indexing",
"=",
"get_service",
"(",
"\"indexing\"",
")... | Collect entities for theses tags. | [
"Collect",
"entities",
"for",
"theses",
"tags",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/tags/admin.py#L29-L54 |
abilian/abilian-core | abilian/web/tags/admin.py | schedule_entities_reindex | def schedule_entities_reindex(entities):
"""
:param entities: as returned by :func:`get_entities_for_reindex`
"""
entities = [(e[0], e[1], e[2], dict(e[3])) for e in entities]
return index_update.apply_async(kwargs={"index": "default", "items": entities}) | python | def schedule_entities_reindex(entities):
"""
:param entities: as returned by :func:`get_entities_for_reindex`
"""
entities = [(e[0], e[1], e[2], dict(e[3])) for e in entities]
return index_update.apply_async(kwargs={"index": "default", "items": entities}) | [
"def",
"schedule_entities_reindex",
"(",
"entities",
")",
":",
"entities",
"=",
"[",
"(",
"e",
"[",
"0",
"]",
",",
"e",
"[",
"1",
"]",
",",
"e",
"[",
"2",
"]",
",",
"dict",
"(",
"e",
"[",
"3",
"]",
")",
")",
"for",
"e",
"in",
"entities",
"]",... | :param entities: as returned by :func:`get_entities_for_reindex` | [
":",
"param",
"entities",
":",
"as",
"returned",
"by",
":",
"func",
":",
"get_entities_for_reindex"
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/tags/admin.py#L57-L62 |
abilian/abilian-core | abilian/services/antivirus/service.py | AntiVirusService.scan | def scan(self, file_or_stream):
"""
:param file_or_stream: :class:`Blob` instance, filename or file object
:returns: True if file is 'clean', False if a virus is detected, None if
file could not be scanned.
If `file_or_stream` is a Blob, scan result is stored in
Blob.me... | python | def scan(self, file_or_stream):
"""
:param file_or_stream: :class:`Blob` instance, filename or file object
:returns: True if file is 'clean', False if a virus is detected, None if
file could not be scanned.
If `file_or_stream` is a Blob, scan result is stored in
Blob.me... | [
"def",
"scan",
"(",
"self",
",",
"file_or_stream",
")",
":",
"if",
"not",
"clamd",
":",
"return",
"None",
"res",
"=",
"self",
".",
"_scan",
"(",
"file_or_stream",
")",
"if",
"isinstance",
"(",
"file_or_stream",
",",
"Blob",
")",
":",
"file_or_stream",
".... | :param file_or_stream: :class:`Blob` instance, filename or file object
:returns: True if file is 'clean', False if a virus is detected, None if
file could not be scanned.
If `file_or_stream` is a Blob, scan result is stored in
Blob.meta['antivirus']. | [
":",
"param",
"file_or_stream",
":",
":",
"class",
":",
"Blob",
"instance",
"filename",
"or",
"file",
"object"
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/antivirus/service.py#L64-L80 |
noirbizarre/bumpr | bumpr/helpers.py | check_output | def check_output(*args, **kwargs):
'''Compatibility wrapper for Python 2.6 missin g subprocess.check_output'''
if hasattr(subprocess, 'check_output'):
return subprocess.check_output(stderr=subprocess.STDOUT, universal_newlines=True,
*args, **kwargs)
else:
... | python | def check_output(*args, **kwargs):
'''Compatibility wrapper for Python 2.6 missin g subprocess.check_output'''
if hasattr(subprocess, 'check_output'):
return subprocess.check_output(stderr=subprocess.STDOUT, universal_newlines=True,
*args, **kwargs)
else:
... | [
"def",
"check_output",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"hasattr",
"(",
"subprocess",
",",
"'check_output'",
")",
":",
"return",
"subprocess",
".",
"check_output",
"(",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
",",
"universal_n... | Compatibility wrapper for Python 2.6 missin g subprocess.check_output | [
"Compatibility",
"wrapper",
"for",
"Python",
"2",
".",
"6",
"missin",
"g",
"subprocess",
".",
"check_output"
] | train | https://github.com/noirbizarre/bumpr/blob/221dbb3deaf1cae7922f6a477f3d29d6bf0c0035/bumpr/helpers.py#L13-L27 |
abilian/abilian-core | abilian/web/views/object.py | BaseObjectView.init_object | def init_object(self, args, kwargs):
"""This method is reponsible for setting :attr:`obj`.
It is called during :meth:`prepare_args`.
"""
self.object_id = kwargs.pop(self.pk, None)
if self.object_id is not None:
self.obj = self.Model.query.get(self.object_id)
... | python | def init_object(self, args, kwargs):
"""This method is reponsible for setting :attr:`obj`.
It is called during :meth:`prepare_args`.
"""
self.object_id = kwargs.pop(self.pk, None)
if self.object_id is not None:
self.obj = self.Model.query.get(self.object_id)
... | [
"def",
"init_object",
"(",
"self",
",",
"args",
",",
"kwargs",
")",
":",
"self",
".",
"object_id",
"=",
"kwargs",
".",
"pop",
"(",
"self",
".",
"pk",
",",
"None",
")",
"if",
"self",
".",
"object_id",
"is",
"not",
"None",
":",
"self",
".",
"obj",
... | This method is reponsible for setting :attr:`obj`.
It is called during :meth:`prepare_args`. | [
"This",
"method",
"is",
"reponsible",
"for",
"setting",
":",
"attr",
":",
"obj",
"."
] | train | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/views/object.py#L76-L86 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.