code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
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) | Show the current config. | 7.192903 | 6.653568 | 1.081059 |
return (event_type in ("modified", "created") and
filename.startswith(self.searchpath) and
os.path.isfile(filename)) | 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. | 4.91794 | 6.007727 | 0.818602 |
filename = os.path.relpath(src_path, self.searchpath)
if self.should_handle(event_type, src_path):
print("%s %s" % (event_type, filename))
if self.site.is_static(filename):
files = self.site.get_dependencies(filename)
self.site.copy_static... | 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. | 3.240191 | 3.41471 | 0.948892 |
@wraps(view)
def csrf_check(*args, **kwargs):
# an empty form is used to validate current csrf token and only that!
if not FlaskForm().validate():
raise Forbidden("CSRF validation failed.")
return view(*args, **kwargs)
return csrf_check | 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. | 8.278188 | 6.819128 | 1.213966 |
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")
user = User(
email=email,
password=password,
last_name=name,
... | def createuser(email, password, role=None, name=None, first_name=None) | Create new user. | 3.475986 | 3.461339 | 1.004232 |
if target.slug is None and target.name:
target.slug = target.auto_slug | def auto_slug_on_insert(mapper, connection, target) | Generate a slug from :prop:`Entity.auto_slug` for new entities, unless
slug is already set. | 4.934161 | 4.917699 | 1.003347 |
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) | Generate a slug from entity_type and id, unless slug is already set. | 5.121373 | 4.043238 | 1.266651 |
if instance not in session.new or not isinstance(instance, Entity):
return
if not current_app:
# working outside app_context. Raw object manipulation
return
_setup_default_permissions(instance) | def setup_default_permissions(session, instance) | Setup default permissions on newly created entities according to.
:attr:`Entity.__default_permissions__`. | 16.071651 | 14.894526 | 1.079031 |
from abilian.services import get_service
security = get_service("security")
for permission, roles in instance.__default_permissions__:
if permission == "create":
# use str for comparison instead of `abilian.services.security.CREATE`
# symbol to avoid imports that quickl... | def _setup_default_permissions(instance) | Separate method to conveniently call it from scripts for example. | 15.065213 | 13.677319 | 1.101474 |
for obj in session.dirty:
if not isinstance(obj, Entity):
continue
state = sa.inspect(obj)
history = state.attrs["updated_at"].history
if not any((history.added, history.deleted)):
obj.updated_at = datetime.utcnow() | 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. | 4.771907 | 5.080131 | 0.939328 |
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_classes if isclass(cls) and issubclass(cls, Entity)
] | def all_entity_classes() | Return the list of all concrete persistent classes that are subclasses
of Entity. | 6.607681 | 5.684454 | 1.162413 |
slug = self.name
if slug is not None:
slug = slugify(slug, separator=self.SLUG_SEPARATOR)
session = sa.orm.object_session(self)
if not session:
return None
query = session.query(Entity.slug).filter(
Entity._entity_t... | def auto_slug(self) | This property is used to auto-generate a slug from the name
attribute.
It can be customized by subclasses. | 3.633959 | 3.64165 | 0.997888 |
from abilian.services.indexing import indexable_role
from abilian.services.security import READ, Admin, Anonymous, Creator, Owner
from abilian.services import get_service
result = []
security = get_service("security")
# roles - required to match when user has a... | def _indexable_roles_and_users(self) | Return a string made for indexing roles having :any:`READ`
permission on this object. | 5.201988 | 4.836981 | 1.075462 |
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 for t in tags.entity_tags(self) if t.ns == default_ns] | def _indexable_tags(self) | Index tag ids for tags defined in this Entity's default tags
namespace. | 6.041813 | 4.899438 | 1.233164 |
locale = _get_locale()
territories = [
(code, name) for code, name in locale.territories.items() if len(code) == 2
] # skip 3-digit regions
if first is None and default_country_first:
first = default_country()
def sortkey(item):
if first is not None and item[0] == fir... | 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 | 3.516204 | 3.534011 | 0.994961 |
locale = _get_locale()
codes = current_app.config["BABEL_ACCEPT_LANGUAGES"]
return ((Locale.parse(code), locale.languages.get(code, code)) for code in codes) | 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. | 6.606188 | 5.490867 | 1.203123 |
utcnow = pytz.utc.localize(datetime.utcnow())
locale = _get_locale()
for tz in sorted(pytz.common_timezones):
tz = get_timezone(tz)
now = tz.normalize(utcnow.astimezone(tz))
label = "({}) {}".format(get_timezone_gmt(now, locale=locale), tz.zone)
yield (tz, label) | 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. | 3.507446 | 3.843106 | 0.912659 |
ctx = _request_ctx_stack.top
if ctx is None:
return None
translations = getattr(ctx, "babel_translations", None)
if translations is None:
babel_ext = ctx.app.extensions["babel"]
translations = None
trs = None
# reverse order: thus the application catalog is... | 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. | 5.524017 | 5.457464 | 1.012195 |
# 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
# Otherwise, try to guess the language from the user accept header the browser
# tran... | def localeselector() | Default locale selector used in abilian applications. | 4.380944 | 4.642935 | 0.943572 |
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:
locale_string = "_".join([locale.language, locale.territory])
localized_template_path = ".".join([ro... | def get_template_i18n(template_name, locale) | Build template list with preceding locale if found. | 2.360806 | 2.304385 | 1.024484 |
template_list = []
# Use locale if present in **context
if "locale" in context:
locale = Locale.parse(context["locale"])
else:
# Use get_locale() or default_locale
locale = flask_babel.get_locale()
if isinstance(template_name_or_list, str):
template_list = get_t... | def render_template_i18n(template_name_or_list, **context) | Try to build an ordered list of template to satisfy the current
locale. | 3.449039 | 3.419817 | 1.008545 |
module = importlib.import_module(module_name)
for path in (Path(p, translations_dir) for p in module.__path__):
if not (path.exists() and path.is_dir()):
continue
if not os.access(str(path), os.R_OK):
self.app.logger.warning(
... | 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. | 3.881775 | 3.965617 | 0.978858 |
response = self.make_response(*args, **kwargs) # type: Response
response.content_type = self.get_content_type(*args, **kwargs)
if attach:
filename = self.get_filename(*args, **kwargs)
if not filename:
filename = "file.bin"
headers = ... | def get(self, attach, *args, **kwargs) | :param attach: if True, return file as an attachment. | 2.674063 | 2.47315 | 1.081238 |
cursor = dbapi_connection.cursor()
try:
cursor.execute("SELECT 1")
except Exception:
# optional - dispose the whole pool
# instead of invalidating one at a time
# connection_proxy._pool.dispose()
# raise DisconnectionError - pool will try
# connecting ag... | 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. | 2.052257 | 2.191674 | 0.936388 |
m = sa.orm.class_mapper(model)
return list(
{p.key for p in m.iterate_properties if hasattr(p, "columns")}.difference(
filtered_columns
)
) | 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 | 4.292699 | 4.309873 | 0.996015 |
type_ = JSON
try:
if kwargs.pop("unique_sorted"):
type_ = JSONUniqueListType
except KeyError:
pass
return MutationList.as_mutable(type_(*args, **kwargs)) | 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. | 11.066635 | 8.234429 | 1.343947 |
if not isinstance(value, MutationDict):
if isinstance(value, dict):
return MutationDict(value)
# this call will raise ValueError
return Mutable.coerce(key, value)
else:
return value | def coerce(cls, key, value) | Convert plain dictionaries to MutationDict. | 5.783567 | 3.745662 | 1.544071 |
if not isinstance(value, MutationList):
if isinstance(value, list):
return MutationList(value)
# this call will raise ValueError
return Mutable.coerce(key, value)
else:
return value | def coerce(cls, key, value) | Convert list to MutationList. | 6.051545 | 3.868798 | 1.564193 |
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_path.open("wb") as out:
for chunk in iter(lambda: file_obj.read(CHUNK_SIZE), b""):
... | def add_file(self, user, file_obj, **metadata) | Add a new file.
:returns: file handle | 2.299932 | 2.451245 | 0.938271 |
user_dir = self.user_dir(user)
if not user_dir.exists():
return None
if not is_valid_handle(handle):
return None
file_path = user_dir / handle
if not file_path.exists() and not file_path.is_file():
return None
return file_p... | 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. | 2.54241 | 2.648414 | 0.959974 |
# FIXME: put lock in directory?
CLEAR_AFTER = self.config["DELETE_STALLED_AFTER"]
minimum_age = time.time() - CLEAR_AFTER
for user_dir in self.UPLOAD_DIR.iterdir():
if not user_dir.is_dir():
logger.error("Found non-directory in upload dir: %r", bytes... | def clear_stalled_files(self) | Scan upload directory and delete stalled files.
Stalled files are files uploaded more than
`DELETE_STALLED_AFTER` seconds ago. | 3.73948 | 3.310925 | 1.129436 |
if isinstance(cls_name, type):
cls_name = fqcn(cls_name)
return cls_name.rsplit(".", 1)[-1] | def friendly_fqcn(cls_name) | Friendly name of fully qualified class name.
:param cls_name: a string or a class | 3.356672 | 3.821815 | 0.878293 |
if not dt.tzinfo:
dt = pytz.utc.localize(dt)
return LOCALTZ.normalize(dt.astimezone(LOCALTZ)) | 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. | 3.007449 | 3.670627 | 0.819328 |
if not dt.tzinfo:
return pytz.utc.localize(dt)
return dt.astimezone(pytz.utc) | def utc_dt(dt) | Set UTC timezone on a datetime object.
A naive datetime is assumed to be in UTC TZ. | 2.398309 | 2.831657 | 0.846963 |
params = {}
for name in names:
value = request.form.get(name) or request.files.get(name)
if value is not None:
params[name] = value
return 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. | 2.558271 | 2.253118 | 1.135436 |
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", "ignore")
value = value.decode("ascii")
value = value.strip().lower()
value = re.sub(... | def slugify(value, separator="-") | Slugify an Unicode string, to make it URL friendly. | 2.768229 | 2.603792 | 1.063153 |
r = [int(ch) for ch in str(n)][::-1]
return (sum(r[0::2]) + sum(sum(divmod(d * 2, 10)) for d in r[1::2])) % 10 == 0 | 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 | 2.240235 | 2.170269 | 1.032238 |
def _validate_siret(form, field, siret=""):
if field is not None:
siret = (field.data or "").strip()
if len(siret) != 14:
msg = _("SIRET must have exactly 14 characters ({count})").format(
count=len(siret)
)
raise valida... | def siret_validator() | Validate a SIRET: check its length (14), its final code, and pass it
through the Luhn algorithm. | 4.484764 | 4.109047 | 1.091436 |
rel_attr_name, attr_name = attr_name.split(".", 1)
rel_attr = getattr(self.model, rel_attr_name, None)
rel_model = None
attr = None
if rel_attr is not None:
rel_model = rel_attr.property.mapper.class_
attr = getattr(rel_model, attr_name, None)
... | 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. | 2.266181 | 2.176103 | 1.041394 |
# type: (UUID) -> Path
_assert_uuid(uuid)
filename = str(uuid)
return Path(filename[0:2], filename[2:4], filename) | def rel_path(self, uuid) | Contruct relative path from repository top directory to the file
named after this uuid.
:param:uuid: :class:`UUID` instance | 5.564613 | 7.421134 | 0.749833 |
# type: (UUID) -> Path
top = self.app_state.path
rel_path = self.rel_path(uuid)
dest = top / rel_path
assert top in dest.parents
return dest | def abs_path(self, uuid) | Return absolute :class:`Path` object for given uuid.
:param:uuid: :class:`UUID` instance | 6.873917 | 8.108253 | 0.847768 |
# type: (UUID, Optional[Path]) -> Optional[Path]
path = self.abs_path(uuid)
if not path.exists():
return default
return path | def get(self, uuid, default=None) | 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 | 4.048894 | 5.761448 | 0.702756 |
# type: (UUID, Any, Optional[Text]) -> None
dest = self.abs_path(uuid)
if not dest.parent.exists():
dest.parent.mkdir(0o775, parents=True)
if hasattr(content, "read"):
content = content.read()
mode = "tw"
if not isinstance(content, str):... | def set(self, uuid, content, encoding="utf-8") | 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 | 2.993803 | 3.728024 | 0.803054 |
# type: (UUID) -> None
dest = self.abs_path(uuid)
if not dest.exists():
raise KeyError("No file can be found for this uuid", uuid)
dest.unlink() | def delete(self, uuid) | Delete file with given uuid.
:param:uuid: :class:`UUID` instance
:raises:KeyError if file does not exists | 6.805963 | 7.844516 | 0.867608 |
# type: (Session, RepositoryTransaction) -> None
if isinstance(session, sa.orm.scoped_session):
session = session()
s_id = id(session)
self.transactions[s_id] = (weakref.ref(session), transaction) | def set_transaction(self, session, transaction) | :param:session: :class:`sqlalchemy.orm.session.Session` instance
:param:transaction: :class:`RepositoryTransaction` instance | 5.050272 | 5.582598 | 0.904646 |
session = model_or_session
if not isinstance(session, (Session, sa.orm.scoped_session)):
if session is not None:
session = sa.orm.object_session(model_or_session)
if session is None:
session = db.session
if isinstance(session, sa... | 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 scoped
session will be used (db.session())
... | 2.492157 | 2.556029 | 0.975011 |
if self.__cleared:
return
if self._parent:
# nested transaction
self._commit_parent()
else:
self._commit_repository()
self._clear() | 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 | 11.444926 | 12.785854 | 0.895124 |
_assert_uuid(uuid)
try:
other.remove(uuid)
except KeyError:
pass
dest.add(uuid) | def _add_to(self, uuid, dest, other) | Add `item` to `dest` set, ensuring `item` is not present in `other`
set. | 4.741293 | 3.622172 | 1.308964 |
def setup_ns(cls):
setattr(cls, ENTITY_DEFAULT_NS_ATTR, ns)
return cls
return setup_ns | def ns(ns) | Class decorator that sets default tags namespace to use with its
instances. | 9.206605 | 5.63833 | 1.63286 |
ids = []
for t in tag_ids.split():
t = t.strip()
try:
t = int(t)
except ValueError:
pass
else:
ids.append(t)
if not ids:
return []
return Tag.query.filter(Tag.id.in_(ids... | 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. | 2.369267 | 2.805881 | 0.844393 |
if ns is None:
ns = self.entity_default_ns(entity)
field = TagsField(label=_l("Tags"), ns=ns)
cls = type("EntityNSTagsForm", (_TagsForm,), {"tags": field})
return cls | def entity_tags_form(self, entity, ns=None) | Construct a form class with a field for tags in namespace `ns`. | 6.523852 | 4.792291 | 1.361322 |
query = Tag.query.filter(Tag.ns == ns)
if label is not None:
return query.filter(Tag.label == label).first()
return query.all() | 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. | 3.010783 | 2.787262 | 1.080194 |
return {
"url": url_for("entity_tags.edit", object_id=obj.id),
"form": self.entity_tags_form(obj)(obj=obj, ns=ns),
"buttons": [EDIT_BUTTON],
} | def get_form_context(self, obj, ns=None) | Return a dict: form instance, action button, submit url...
Used by macro m_tags_form(entity) | 5.52198 | 4.399075 | 1.255259 |
reindexer = Reindexer(clear, progressive, batch_size)
reindexer.reindex_all() | 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 process before writing to the
index. Unused in sin... | 4.444469 | 5.14981 | 0.863036 |
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:
logger.error("Error building URL for search result", exc_info=True)
ret... | def url_for_hit(hit, default="#") | Helper for building URLs from results. | 3.859975 | 3.603289 | 1.071237 |
index_name = index
index = service.app_state.indexes[index_name]
adapted = service.adapted
session = safe_session()
updated = set()
writer = AsyncWriter(index)
try:
for op, cls_name, pk, data in items:
if pk is None:
continue
# always de... | def index_update(index, items) | :param:index: index name
:param:items: list of (operation, full class name, primary key, data) tuples. | 8.649199 | 8.060377 | 1.073051 |
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()
if not index_path.exists():
... | def init_indexes(self) | Create indexes for schemas. | 3.768485 | 3.46953 | 1.086166 |
logger.info("Resetting indexes")
state = self.app_state
for _name, idx in state.indexes.items():
writer = AsyncWriter(idx)
writer.commit(merge=True, optimize=True, mergetype=CLEAR)
state.indexes.clear()
state.indexed_classes.clear()
stat... | 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. | 8.708881 | 7.28078 | 1.196147 |
try:
idx = self.index()
except KeyError:
# index does not exists: service never started, may happens during
# tests
return []
with idx.reader() as r:
indexed = sorted(set(r.field_terms("object_type")))
app_indexed = se... | def searchable_object_types(self) | List of (object_types, friendly name) present in the index. | 10.045898 | 8.740714 | 1.149322 |
index = self.app_state.indexes[index]
if not fields:
fields = self.default_search_fields
valid_fields = {
f
for f in index.schema.names(check_names=fields)
if prefix or not f.endswith("_prefix")
}
for invalid in set(field... | 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 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... | 3.655087 | 3.66153 | 0.99824 |
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(cls)
self.adapted[cls_fqcn] = Adapter(cls, self.schemas["default"])
... | def register_class(self, cls, app_state=None) | Register a model class. | 4.841157 | 4.649704 | 1.041175 |
if (
not self.running
or session.transaction.nested # inside a sub-transaction:
# not yet written in DB
or session is not db.session()
):
# note: we have not tested too far if session is enclosed in a transaction
# at conn... | 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 impose a penalty on the initial commit
... | 9.345837 | 9.674774 | 0.966 |
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:
document = self.get_document(obj)
if document is None:
... | def index_objects(self, objects, index="default") | Bulk index a list of objects. | 4.487429 | 4.387019 | 1.022888 |
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_scripts.sub("", value)
url = value
if not url.startswith("http://") and not url.startsw... | def linkify_url(value) | Tranform an URL pulled from the database to a safe HTML fragment. | 2.726121 | 2.658973 | 1.025253 |
if user is None:
user = current_user
return {pref.key: pref.value for pref in user.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. | 3.835039 | 3.753353 | 1.021764 |
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
else:
d[k] = UserPreference(user=user, key=k, value=v)
db.ses... | def set_preferences(self, user=None, **kwargs) | Set preferences from keyword arguments. | 2.176692 | 2.093304 | 1.039836 |
manager = getattr(obj, _MANAGER_ATTR, None)
if manager is None:
manager = AttachmentsManager()
setattr(obj.__class__, _MANAGER_ATTR, manager)
return manager | def manager(self, obj) | Returns the :class:`AttachmentsManager` instance for this object. | 4.180858 | 2.989841 | 1.398355 |
return {
"url": url_for("attachments.create", entity_id=obj.id),
"form": self.Form(),
"buttons": [UPLOAD_BUTTON],
} | def get_form_context(self, obj) | Return a dict: form instance, action button, submit url...
Used by macro m_attachment_form(entity) | 8.25265 | 5.966418 | 1.383183 |
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(0)
login_user(user, force=True)
return
state = self.app_state
user = unwrap(cu... | def do_access_control(self) | `before_request` handler to check if user should be redirected to
login page. | 3.252497 | 3.28388 | 0.990444 |
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, tbl.c.id])
.select_from(tbl.join(entity_tag_tbl, entity_tag_tbl.c.ent... | def get_entities_for_reindex(tags) | Collect entities for theses tags. | 3.097212 | 3.026365 | 1.02341 |
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) | :param entities: as returned by :func:`get_entities_for_reindex` | 5.399114 | 5.500926 | 0.981492 |
if not clamd:
return None
res = self._scan(file_or_stream)
if isinstance(file_or_stream, Blob):
file_or_stream.meta["antivirus"] = res
return res | 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.meta['antivirus']. | 6.425872 | 3.896256 | 1.649243 |
'''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:
process = subprocess.Popen(*args... | def check_output(*args, **kwargs) | Compatibility wrapper for Python 2.6 missin g subprocess.check_output | 2.55602 | 1.942325 | 1.315959 |
self.object_id = kwargs.pop(self.pk, None)
if self.object_id is not None:
self.obj = self.Model.query.get(self.object_id)
actions.context["object"] = self.obj
return args, kwargs | def init_object(self, args, kwargs) | This method is reponsible for setting :attr:`obj`.
It is called during :meth:`prepare_args`. | 4.385509 | 4.70299 | 0.932494 |
args, kwargs = super().prepare_args(args, kwargs)
form_kwargs = self.get_form_kwargs()
self.form = self.Form(**form_kwargs)
return args, kwargs | def prepare_args(self, args, kwargs) | :attr:`form` is initialized here. See also :meth:`View.prepare_args`. | 3.365036 | 2.722205 | 1.236143 |
session = db.session()
with session.no_autoflush:
self.before_populate_obj()
self.form.populate_obj(self.obj)
session.add(self.obj)
self.after_populate_obj()
try:
session.flush()
self.send_activity()
s... | def form_valid(self, redirect_to=None) | Save object.
Called when form is validated.
:param redirect_to: real url (created with url_for) to redirect to,
instead of the view by default. | 2.871545 | 2.893163 | 0.992528 |
return {"id": obj.id, "text": self.get_label(obj), "name": obj.name} | def get_item(self, obj) | Return a result item.
:param obj: Instance object
:returns: a dictionnary with at least `id` and `text` values | 5.286159 | 6.172623 | 0.856388 |
'''Parse requirements file'''
with io.open(os.path.join('requirements', '{0}.pip'.format(name))) as f:
return f.readlines() | def pip(name) | Parse requirements file | 4.742959 | 4.731888 | 1.00234 |
file_list = []
with make_temp_file(blob) as in_fn, make_temp_file() as out_fn:
try:
subprocess.check_call(["pdftoppm", "-jpeg", in_fn, out_fn])
file_list = sorted(glob.glob(f"{out_fn}-*.jpg"))
converted_images = []
for... | def convert(self, blob, size=500) | Size is the maximum horizontal size. | 2.663442 | 2.616805 | 1.017822 |
timeout = self.run_timeout
with make_temp_file(blob) as in_fn, make_temp_file(
prefix="tmp-unoconv-", suffix=".pdf"
) as out_fn:
args = ["-f", "pdf", "-o", out_fn, in_fn]
# Hack for my Mac, FIXME later
if Path("/Applications/LibreOffice.a... | def convert(self, blob, **kw) | Convert using unoconv converter. | 3.268825 | 3.087799 | 1.058626 |
timeout = self.run_timeout
with make_temp_file(blob) as in_fn:
cmd = [self.soffice, "--headless", "--convert-to", "pdf", in_fn]
# # TODO: fix this if needed, or remove if not needed
# if os.path.exists(
# "/Applications/LibreOffice.app/C... | def convert(self, blob, **kw) | Convert using soffice converter. | 2.844652 | 2.740242 | 1.038102 |
@evalcontextfilter
@wraps(filter_func)
def _autoescape(eval_ctx, *args, **kwargs):
result = filter_func(*args, **kwargs)
if eval_ctx.autoescape:
result = Markup(result)
return result
return _autoescape | def autoescape(filter_func) | Decorator to autoescape result from filters. | 2.67584 | 2.4522 | 1.0912 |
result = "\n\n".join(
"<p>{}</p>".format(p.strip().replace("\n", Markup("<br />\n")))
for p in _PARAGRAPH_RE.split(escape(value))
)
return result | def paragraphs(value) | Blank lines delimitates paragraphs. | 4.60912 | 4.398161 | 1.047965 |
if size < above:
return str(size)
return "{:d}+".format(size - size % mod) | def roughsize(size, above=20, mod=10) | 6 -> '6' 15 -> '15' 134 -> '130+'. | 6.170877 | 4.744407 | 1.300663 |
try:
dt = dateutil.parser.parse(s)
except ValueError:
return None
return utc_dt(dt) | def datetimeparse(s) | Parse a string date time to a datetime object.
Suitable for dates serialized with .isoformat()
:return: None, or an aware datetime instance, tz=UTC. | 3.932057 | 4.497852 | 0.874208 |
# Fail silently for now XXX
if not dt:
return ""
if not now:
now = datetime.datetime.utcnow()
locale = babel.get_locale()
dt = utc_dt(dt)
now = utc_dt(now)
delta = dt - now
if date_threshold is not None:
dy, dw, dd = dt_cal = dt.isocalendar()
ny, n... | def age(dt, now=None, add_direction=True, date_threshold=None) | :param dt: :class:`datetime<datetime.datetime>` instance to format
:param now: :class:`datetime<datetime.datetime>` instance to compare to `dt`
:param add_direction: if `True`, will add "in" or "ago" (example for `en`
locale) to time difference `dt - now`, i.e "in 9 min." or " 9min. ago"
:param da... | 4.37247 | 4.361667 | 1.002477 |
if not isinstance(pattern, DateTimePattern):
pattern = parse_pattern(pattern)
map_fmt = {
# days
"d": "dd",
"dd": "dd",
"EEE": "D",
"EEEE": "DD",
"EEEEE": "D", # narrow name => short name
# months
"M": "mm",
"MM": "mm",
... | def babel2datepicker(pattern) | Convert date format from babel (http://babel.pocoo.org/docs/dates/#date-
fields)) to a format understood by bootstrap-datepicker. | 2.544573 | 2.580876 | 0.985934 |
self.logger.debug("Start service")
self._toggle_running(True, ignore_state) | def start(self, ignore_state=False) | Starts the service. | 9.387239 | 6.60818 | 1.420548 |
self.logger.debug("Stop service")
self._toggle_running(False, ignore_state) | def stop(self, ignore_state=False) | Stops the service. | 8.093668 | 6.710008 | 1.206208 |
try:
return current_app.extensions[self.name]
except KeyError:
raise ServiceNotRegistered(self.name) | def app_state(self) | Current service state in current application.
:raise:RuntimeError if working outside application context. | 6.174481 | 6.707466 | 0.920539 |
@wraps(meth)
def check_running(self, *args, **kwargs):
if not self.running:
return
return meth(self, *args, **kwargs)
return check_running | def if_running(meth) | Decorator for service methods that must be ran only if service is in
running state. | 2.321137 | 2.379939 | 0.975293 |
'''Clean the workspace'''
if self.config.clean:
logger.info('Cleaning')
self.execute(self.config.clean) | def clean(self) | Clean the workspace | 7.378057 | 7.464353 | 0.988439 |
'''Publish the current release to PyPI'''
if self.config.publish:
logger.info('Publish')
self.execute(self.config.publish) | def publish(self) | Publish the current release to PyPI | 7.931015 | 6.47158 | 1.225514 |
'''Display an header'''
print(' '.join((blue('>>'), cyan(text))))
sys.stdout.flush() | def header(text) | Display an header | 10.998755 | 12.087805 | 0.909905 |
'''Display informations'''
text = text.format(*args, **kwargs)
print(' '.join((purple('>>>'), text)))
sys.stdout.flush() | def info(text, *args, **kwargs) | Display informations | 8.415143 | 7.802795 | 1.078478 |
'''Display a success message'''
print(' '.join((green('✔'), white(text))))
sys.stdout.flush() | def success(text) | Display a success message | 7.793528 | 9.696047 | 0.803784 |
'''Display an error message'''
print(red('✘ {0}'.format(text)))
sys.stdout.flush() | def error(text) | Display an error message | 7.082975 | 8.784304 | 0.806322 |
'''Cleanup all build artifacts'''
header(clean.__doc__)
with ctx.cd(ROOT):
for pattern in CLEAN_PATTERNS:
info(pattern)
ctx.run('rm -rf {0}'.format(' '.join(CLEAN_PATTERNS))) | def clean(ctx) | Cleanup all build artifacts | 6.584699 | 6.083077 | 1.082462 |
'''Install or update development dependencies'''
header(deps.__doc__)
with ctx.cd(ROOT):
ctx.run('pip install -r requirements/develop.pip -r requirements/doc.pip', pty=True) | def deps(ctx) | Install or update development dependencies | 9.497567 | 7.08818 | 1.339916 |
'''Run a quality report'''
header(qa.__doc__)
with ctx.cd(ROOT):
info('Python Static Analysis')
flake8_results = ctx.run('flake8 bumpr', pty=True, warn=True)
if flake8_results.failed:
error('There is some lints to fix')
else:
success('No lint to fix')
... | def qa(ctx) | Run a quality report | 4.485185 | 4.374477 | 1.025308 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.