repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
opendatateam/udata | udata/core/discussions/actions.py | discussions_for | def discussions_for(user, only_open=True):
'''
Build a queryset to query discussions related to a given user's assets.
It includes discussions coming from the user's organizations
:param bool only_open: whether to include closed discussions or not.
'''
# Only fetch required fields for discussi... | python | def discussions_for(user, only_open=True):
'''
Build a queryset to query discussions related to a given user's assets.
It includes discussions coming from the user's organizations
:param bool only_open: whether to include closed discussions or not.
'''
# Only fetch required fields for discussi... | [
"def",
"discussions_for",
"(",
"user",
",",
"only_open",
"=",
"True",
")",
":",
"# Only fetch required fields for discussion filtering (id and slug)",
"# Greatly improve performances and memory usage",
"datasets",
"=",
"Dataset",
".",
"objects",
".",
"owned_by",
"(",
"user",
... | Build a queryset to query discussions related to a given user's assets.
It includes discussions coming from the user's organizations
:param bool only_open: whether to include closed discussions or not. | [
"Build",
"a",
"queryset",
"to",
"query",
"discussions",
"related",
"to",
"a",
"given",
"user",
"s",
"assets",
"."
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/discussions/actions.py#L9-L25 | train |
opendatateam/udata | udata/frontend/markdown.py | nofollow_callback | def nofollow_callback(attrs, new=False):
"""
Turn relative links into external ones and avoid `nofollow` for us,
otherwise add `nofollow`.
That callback is not splitted in order to parse the URL only once.
"""
parsed_url = urlparse(attrs[(None, 'href')])
if parsed_url.netloc in ('', current... | python | def nofollow_callback(attrs, new=False):
"""
Turn relative links into external ones and avoid `nofollow` for us,
otherwise add `nofollow`.
That callback is not splitted in order to parse the URL only once.
"""
parsed_url = urlparse(attrs[(None, 'href')])
if parsed_url.netloc in ('', current... | [
"def",
"nofollow_callback",
"(",
"attrs",
",",
"new",
"=",
"False",
")",
":",
"parsed_url",
"=",
"urlparse",
"(",
"attrs",
"[",
"(",
"None",
",",
"'href'",
")",
"]",
")",
"if",
"parsed_url",
".",
"netloc",
"in",
"(",
"''",
",",
"current_app",
".",
"c... | Turn relative links into external ones and avoid `nofollow` for us,
otherwise add `nofollow`.
That callback is not splitted in order to parse the URL only once. | [
"Turn",
"relative",
"links",
"into",
"external",
"ones",
"and",
"avoid",
"nofollow",
"for",
"us"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/frontend/markdown.py#L40-L59 | train |
opendatateam/udata | udata/frontend/markdown.py | bleach_clean | def bleach_clean(stream):
"""
Sanitize malicious attempts but keep the `EXCERPT_TOKEN`.
By default, only keeps `bleach.ALLOWED_TAGS`.
"""
return bleach.clean(
stream,
tags=current_app.config['MD_ALLOWED_TAGS'],
attributes=current_app.config['MD_ALLOWED_ATTRIBUTES'],
s... | python | def bleach_clean(stream):
"""
Sanitize malicious attempts but keep the `EXCERPT_TOKEN`.
By default, only keeps `bleach.ALLOWED_TAGS`.
"""
return bleach.clean(
stream,
tags=current_app.config['MD_ALLOWED_TAGS'],
attributes=current_app.config['MD_ALLOWED_ATTRIBUTES'],
s... | [
"def",
"bleach_clean",
"(",
"stream",
")",
":",
"return",
"bleach",
".",
"clean",
"(",
"stream",
",",
"tags",
"=",
"current_app",
".",
"config",
"[",
"'MD_ALLOWED_TAGS'",
"]",
",",
"attributes",
"=",
"current_app",
".",
"config",
"[",
"'MD_ALLOWED_ATTRIBUTES'"... | Sanitize malicious attempts but keep the `EXCERPT_TOKEN`.
By default, only keeps `bleach.ALLOWED_TAGS`. | [
"Sanitize",
"malicious",
"attempts",
"but",
"keep",
"the",
"EXCERPT_TOKEN",
".",
"By",
"default",
"only",
"keeps",
"bleach",
".",
"ALLOWED_TAGS",
"."
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/frontend/markdown.py#L94-L104 | train |
opendatateam/udata | udata/core/badges/commands.py | toggle | def toggle(path_or_id, badge_kind):
'''Toggle a `badge_kind` for a given `path_or_id`
The `path_or_id` is either an id, a slug or a file containing a list
of ids or slugs.
'''
if exists(path_or_id):
with open(path_or_id) as open_file:
for id_or_slug in open_file.readlines():
... | python | def toggle(path_or_id, badge_kind):
'''Toggle a `badge_kind` for a given `path_or_id`
The `path_or_id` is either an id, a slug or a file containing a list
of ids or slugs.
'''
if exists(path_or_id):
with open(path_or_id) as open_file:
for id_or_slug in open_file.readlines():
... | [
"def",
"toggle",
"(",
"path_or_id",
",",
"badge_kind",
")",
":",
"if",
"exists",
"(",
"path_or_id",
")",
":",
"with",
"open",
"(",
"path_or_id",
")",
"as",
"open_file",
":",
"for",
"id_or_slug",
"in",
"open_file",
".",
"readlines",
"(",
")",
":",
"toggle... | Toggle a `badge_kind` for a given `path_or_id`
The `path_or_id` is either an id, a slug or a file containing a list
of ids or slugs. | [
"Toggle",
"a",
"badge_kind",
"for",
"a",
"given",
"path_or_id"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/badges/commands.py#L35-L46 | train |
opendatateam/udata | udata/core/storages/views.py | upload | def upload(name):
'''Handle upload on POST if authorized.'''
storage = fs.by_name(name)
return jsonify(success=True, **handle_upload(storage)) | python | def upload(name):
'''Handle upload on POST if authorized.'''
storage = fs.by_name(name)
return jsonify(success=True, **handle_upload(storage)) | [
"def",
"upload",
"(",
"name",
")",
":",
"storage",
"=",
"fs",
".",
"by_name",
"(",
"name",
")",
"return",
"jsonify",
"(",
"success",
"=",
"True",
",",
"*",
"*",
"handle_upload",
"(",
"storage",
")",
")"
] | Handle upload on POST if authorized. | [
"Handle",
"upload",
"on",
"POST",
"if",
"authorized",
"."
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/storages/views.py#L22-L25 | train |
opendatateam/udata | udata/search/__init__.py | unindex_model_on_delete | def unindex_model_on_delete(sender, document, **kwargs):
'''Unindex Mongo document on post_delete'''
if current_app.config.get('AUTO_INDEX'):
unindex.delay(document) | python | def unindex_model_on_delete(sender, document, **kwargs):
'''Unindex Mongo document on post_delete'''
if current_app.config.get('AUTO_INDEX'):
unindex.delay(document) | [
"def",
"unindex_model_on_delete",
"(",
"sender",
",",
"document",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"current_app",
".",
"config",
".",
"get",
"(",
"'AUTO_INDEX'",
")",
":",
"unindex",
".",
"delay",
"(",
"document",
")"
] | Unindex Mongo document on post_delete | [
"Unindex",
"Mongo",
"document",
"on",
"post_delete"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/search/__init__.py#L167-L170 | train |
opendatateam/udata | udata/search/__init__.py | register | def register(adapter):
'''Register a search adapter'''
# register the class in the catalog
if adapter.model and adapter.model not in adapter_catalog:
adapter_catalog[adapter.model] = adapter
# Automatically (re|un)index objects on save/delete
post_save.connect(reindex_model_on_save, ... | python | def register(adapter):
'''Register a search adapter'''
# register the class in the catalog
if adapter.model and adapter.model not in adapter_catalog:
adapter_catalog[adapter.model] = adapter
# Automatically (re|un)index objects on save/delete
post_save.connect(reindex_model_on_save, ... | [
"def",
"register",
"(",
"adapter",
")",
":",
"# register the class in the catalog",
"if",
"adapter",
".",
"model",
"and",
"adapter",
".",
"model",
"not",
"in",
"adapter_catalog",
":",
"adapter_catalog",
"[",
"adapter",
".",
"model",
"]",
"=",
"adapter",
"# Autom... | Register a search adapter | [
"Register",
"a",
"search",
"adapter"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/search/__init__.py#L173-L181 | train |
opendatateam/udata | udata/forms/__init__.py | CommonFormMixin.process | def process(self, formdata=None, obj=None, data=None, **kwargs):
'''Wrap the process method to store the current object instance'''
self._obj = obj
super(CommonFormMixin, self).process(formdata, obj, data, **kwargs) | python | def process(self, formdata=None, obj=None, data=None, **kwargs):
'''Wrap the process method to store the current object instance'''
self._obj = obj
super(CommonFormMixin, self).process(formdata, obj, data, **kwargs) | [
"def",
"process",
"(",
"self",
",",
"formdata",
"=",
"None",
",",
"obj",
"=",
"None",
",",
"data",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_obj",
"=",
"obj",
"super",
"(",
"CommonFormMixin",
",",
"self",
")",
".",
"process",
... | Wrap the process method to store the current object instance | [
"Wrap",
"the",
"process",
"method",
"to",
"store",
"the",
"current",
"object",
"instance"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/forms/__init__.py#L19-L22 | train |
opendatateam/udata | udata/linkchecker/backends.py | get | def get(name):
'''Get a linkchecker given its name or fallback on default'''
linkcheckers = get_enabled(ENTRYPOINT, current_app)
linkcheckers.update(no_check=NoCheckLinkchecker) # no_check always enabled
selected_linkchecker = linkcheckers.get(name)
if not selected_linkchecker:
default_link... | python | def get(name):
'''Get a linkchecker given its name or fallback on default'''
linkcheckers = get_enabled(ENTRYPOINT, current_app)
linkcheckers.update(no_check=NoCheckLinkchecker) # no_check always enabled
selected_linkchecker = linkcheckers.get(name)
if not selected_linkchecker:
default_link... | [
"def",
"get",
"(",
"name",
")",
":",
"linkcheckers",
"=",
"get_enabled",
"(",
"ENTRYPOINT",
",",
"current_app",
")",
"linkcheckers",
".",
"update",
"(",
"no_check",
"=",
"NoCheckLinkchecker",
")",
"# no_check always enabled",
"selected_linkchecker",
"=",
"linkchecke... | Get a linkchecker given its name or fallback on default | [
"Get",
"a",
"linkchecker",
"given",
"its",
"name",
"or",
"fallback",
"on",
"default"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/linkchecker/backends.py#L28-L40 | train |
opendatateam/udata | udata/features/notifications/actions.py | get_notifications | def get_notifications(user):
'''List notification for a given user'''
notifications = []
for name, func in _providers.items():
notifications.extend([{
'type': name,
'created_on': dt,
'details': details
} for dt, details in func(user)])
return notific... | python | def get_notifications(user):
'''List notification for a given user'''
notifications = []
for name, func in _providers.items():
notifications.extend([{
'type': name,
'created_on': dt,
'details': details
} for dt, details in func(user)])
return notific... | [
"def",
"get_notifications",
"(",
"user",
")",
":",
"notifications",
"=",
"[",
"]",
"for",
"name",
",",
"func",
"in",
"_providers",
".",
"items",
"(",
")",
":",
"notifications",
".",
"extend",
"(",
"[",
"{",
"'type'",
":",
"name",
",",
"'created_on'",
"... | List notification for a given user | [
"List",
"notification",
"for",
"a",
"given",
"user"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/features/notifications/actions.py#L29-L40 | train |
opendatateam/udata | udata/core/tags/tasks.py | count_tags | def count_tags(self):
'''Count tag occurences by type and update the tag collection'''
for key, model in TAGGED.items():
collection = '{0}_tags'.format(key)
results = (model.objects(tags__exists=True)
.map_reduce(map_tags, reduce_tags, collection))
for result in r... | python | def count_tags(self):
'''Count tag occurences by type and update the tag collection'''
for key, model in TAGGED.items():
collection = '{0}_tags'.format(key)
results = (model.objects(tags__exists=True)
.map_reduce(map_tags, reduce_tags, collection))
for result in r... | [
"def",
"count_tags",
"(",
"self",
")",
":",
"for",
"key",
",",
"model",
"in",
"TAGGED",
".",
"items",
"(",
")",
":",
"collection",
"=",
"'{0}_tags'",
".",
"format",
"(",
"key",
")",
"results",
"=",
"(",
"model",
".",
"objects",
"(",
"tags__exists",
"... | Count tag occurences by type and update the tag collection | [
"Count",
"tag",
"occurences",
"by",
"type",
"and",
"update",
"the",
"tag",
"collection"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/tags/tasks.py#L38-L48 | train |
opendatateam/udata | udata/search/adapter.py | ModelSearchAdapter.from_model | def from_model(cls, document):
"""By default use the ``to_dict`` method
and exclude ``_id``, ``_cls`` and ``owner`` fields
"""
return cls(meta={'id': document.id}, **cls.serialize(document)) | python | def from_model(cls, document):
"""By default use the ``to_dict`` method
and exclude ``_id``, ``_cls`` and ``owner`` fields
"""
return cls(meta={'id': document.id}, **cls.serialize(document)) | [
"def",
"from_model",
"(",
"cls",
",",
"document",
")",
":",
"return",
"cls",
"(",
"meta",
"=",
"{",
"'id'",
":",
"document",
".",
"id",
"}",
",",
"*",
"*",
"cls",
".",
"serialize",
"(",
"document",
")",
")"
] | By default use the ``to_dict`` method
and exclude ``_id``, ``_cls`` and ``owner`` fields | [
"By",
"default",
"use",
"the",
"to_dict",
"method"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/search/adapter.py#L38-L43 | train |
opendatateam/udata | udata/search/adapter.py | ModelSearchAdapter.completer_tokenize | def completer_tokenize(cls, value, min_length=3):
'''Quick and dirty tokenizer for completion suggester'''
tokens = list(itertools.chain(*[
[m for m in n.split("'") if len(m) > min_length]
for n in value.split(' ')
]))
return list(set([value] + tokens + [' '.join(... | python | def completer_tokenize(cls, value, min_length=3):
'''Quick and dirty tokenizer for completion suggester'''
tokens = list(itertools.chain(*[
[m for m in n.split("'") if len(m) > min_length]
for n in value.split(' ')
]))
return list(set([value] + tokens + [' '.join(... | [
"def",
"completer_tokenize",
"(",
"cls",
",",
"value",
",",
"min_length",
"=",
"3",
")",
":",
"tokens",
"=",
"list",
"(",
"itertools",
".",
"chain",
"(",
"*",
"[",
"[",
"m",
"for",
"m",
"in",
"n",
".",
"split",
"(",
"\"'\"",
")",
"if",
"len",
"("... | Quick and dirty tokenizer for completion suggester | [
"Quick",
"and",
"dirty",
"tokenizer",
"for",
"completion",
"suggester"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/search/adapter.py#L54-L60 | train |
opendatateam/udata | udata/search/adapter.py | ModelSearchAdapter.facet_search | def facet_search(cls, *facets):
'''
Build a FacetSearch for a given list of facets
Elasticsearch DSL doesn't allow to list facets
once and for all and then later select them.
They are always all requested
As we don't use them every time and facet computation
can... | python | def facet_search(cls, *facets):
'''
Build a FacetSearch for a given list of facets
Elasticsearch DSL doesn't allow to list facets
once and for all and then later select them.
They are always all requested
As we don't use them every time and facet computation
can... | [
"def",
"facet_search",
"(",
"cls",
",",
"*",
"facets",
")",
":",
"f",
"=",
"dict",
"(",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"cls",
".",
"facets",
".",
"items",
"(",
")",
"if",
"k",
"in",
"facets",
")",
"class",
"TempSearch",
... | Build a FacetSearch for a given list of facets
Elasticsearch DSL doesn't allow to list facets
once and for all and then later select them.
They are always all requested
As we don't use them every time and facet computation
can take some time, we build the FacetedSearch
... | [
"Build",
"a",
"FacetSearch",
"for",
"a",
"given",
"list",
"of",
"facets"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/search/adapter.py#L63-L88 | train |
opendatateam/udata | udata/models/slug_fields.py | populate_slug | def populate_slug(instance, field):
'''
Populate a slug field if needed.
'''
value = getattr(instance, field.db_field)
try:
previous = instance.__class__.objects.get(id=instance.id)
except Exception:
previous = None
# Field value has changed
changed = field.db_field in ... | python | def populate_slug(instance, field):
'''
Populate a slug field if needed.
'''
value = getattr(instance, field.db_field)
try:
previous = instance.__class__.objects.get(id=instance.id)
except Exception:
previous = None
# Field value has changed
changed = field.db_field in ... | [
"def",
"populate_slug",
"(",
"instance",
",",
"field",
")",
":",
"value",
"=",
"getattr",
"(",
"instance",
",",
"field",
".",
"db_field",
")",
"try",
":",
"previous",
"=",
"instance",
".",
"__class__",
".",
"objects",
".",
"get",
"(",
"id",
"=",
"insta... | Populate a slug field if needed. | [
"Populate",
"a",
"slug",
"field",
"if",
"needed",
"."
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/models/slug_fields.py#L113-L193 | train |
opendatateam/udata | udata/models/slug_fields.py | SlugField.slugify | def slugify(self, value):
'''
Apply slugification according to specified field rules
'''
if value is None:
return
return slugify.slugify(value, max_length=self.max_length,
separator=self.separator,
to_lowe... | python | def slugify(self, value):
'''
Apply slugification according to specified field rules
'''
if value is None:
return
return slugify.slugify(value, max_length=self.max_length,
separator=self.separator,
to_lowe... | [
"def",
"slugify",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"return",
"slugify",
".",
"slugify",
"(",
"value",
",",
"max_length",
"=",
"self",
".",
"max_length",
",",
"separator",
"=",
"self",
".",
"separator",
",... | Apply slugification according to specified field rules | [
"Apply",
"slugification",
"according",
"to",
"specified",
"field",
"rules"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/models/slug_fields.py#L55-L64 | train |
opendatateam/udata | udata/models/slug_fields.py | SlugField.cleanup_on_delete | def cleanup_on_delete(self, sender, document, **kwargs):
'''
Clean up slug redirections on object deletion
'''
if not self.follow or sender is not self.owner_document:
return
slug = getattr(document, self.db_field)
namespace = self.owner_document.__name__
... | python | def cleanup_on_delete(self, sender, document, **kwargs):
'''
Clean up slug redirections on object deletion
'''
if not self.follow or sender is not self.owner_document:
return
slug = getattr(document, self.db_field)
namespace = self.owner_document.__name__
... | [
"def",
"cleanup_on_delete",
"(",
"self",
",",
"sender",
",",
"document",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"follow",
"or",
"sender",
"is",
"not",
"self",
".",
"owner_document",
":",
"return",
"slug",
"=",
"getattr",
"(",
"doc... | Clean up slug redirections on object deletion | [
"Clean",
"up",
"slug",
"redirections",
"on",
"object",
"deletion"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/models/slug_fields.py#L76-L84 | train |
opendatateam/udata | udata/core/badges/forms.py | badge_form | def badge_form(model):
'''A form factory for a given model badges'''
class BadgeForm(ModelForm):
model_class = Badge
kind = fields.RadioField(
_('Kind'), [validators.DataRequired()],
choices=model.__badges__.items(),
description=_('Kind of badge (certified, e... | python | def badge_form(model):
'''A form factory for a given model badges'''
class BadgeForm(ModelForm):
model_class = Badge
kind = fields.RadioField(
_('Kind'), [validators.DataRequired()],
choices=model.__badges__.items(),
description=_('Kind of badge (certified, e... | [
"def",
"badge_form",
"(",
"model",
")",
":",
"class",
"BadgeForm",
"(",
"ModelForm",
")",
":",
"model_class",
"=",
"Badge",
"kind",
"=",
"fields",
".",
"RadioField",
"(",
"_",
"(",
"'Kind'",
")",
",",
"[",
"validators",
".",
"DataRequired",
"(",
")",
"... | A form factory for a given model badges | [
"A",
"form",
"factory",
"for",
"a",
"given",
"model",
"badges"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/badges/forms.py#L11-L21 | train |
opendatateam/udata | udata/core/jobs/actions.py | delay | def delay(name, args, kwargs):
'''Run a job asynchronously'''
args = args or []
kwargs = dict(k.split() for k in kwargs) if kwargs else {}
if name not in celery.tasks:
log.error('Job %s not found', name)
job = celery.tasks[name]
log.info('Sending job %s', name)
async_result = job.del... | python | def delay(name, args, kwargs):
'''Run a job asynchronously'''
args = args or []
kwargs = dict(k.split() for k in kwargs) if kwargs else {}
if name not in celery.tasks:
log.error('Job %s not found', name)
job = celery.tasks[name]
log.info('Sending job %s', name)
async_result = job.del... | [
"def",
"delay",
"(",
"name",
",",
"args",
",",
"kwargs",
")",
":",
"args",
"=",
"args",
"or",
"[",
"]",
"kwargs",
"=",
"dict",
"(",
"k",
".",
"split",
"(",
")",
"for",
"k",
"in",
"kwargs",
")",
"if",
"kwargs",
"else",
"{",
"}",
"if",
"name",
... | Run a job asynchronously | [
"Run",
"a",
"job",
"asynchronously"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/jobs/actions.py#L22-L31 | train |
opendatateam/udata | udata/harvest/filters.py | is_url | def is_url(default_scheme='http', **kwargs):
"""Return a converter that converts a clean string to an URL."""
def converter(value):
if value is None:
return value
if '://' not in value and default_scheme:
value = '://'.join((default_scheme, value.strip()))
try:
... | python | def is_url(default_scheme='http', **kwargs):
"""Return a converter that converts a clean string to an URL."""
def converter(value):
if value is None:
return value
if '://' not in value and default_scheme:
value = '://'.join((default_scheme, value.strip()))
try:
... | [
"def",
"is_url",
"(",
"default_scheme",
"=",
"'http'",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"converter",
"(",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"value",
"if",
"'://'",
"not",
"in",
"value",
"and",
"default_scheme",
":"... | Return a converter that converts a clean string to an URL. | [
"Return",
"a",
"converter",
"that",
"converts",
"a",
"clean",
"string",
"to",
"an",
"URL",
"."
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/harvest/filters.py#L89-L100 | train |
opendatateam/udata | udata/harvest/filters.py | hash | def hash(value):
'''Detect an hash type'''
if not value:
return
elif len(value) == 32:
type = 'md5'
elif len(value) == 40:
type = 'sha1'
elif len(value) == 64:
type = 'sha256'
else:
return None
return {'type': type, 'value': value} | python | def hash(value):
'''Detect an hash type'''
if not value:
return
elif len(value) == 32:
type = 'md5'
elif len(value) == 40:
type = 'sha1'
elif len(value) == 64:
type = 'sha256'
else:
return None
return {'type': type, 'value': value} | [
"def",
"hash",
"(",
"value",
")",
":",
"if",
"not",
"value",
":",
"return",
"elif",
"len",
"(",
"value",
")",
"==",
"32",
":",
"type",
"=",
"'md5'",
"elif",
"len",
"(",
"value",
")",
"==",
"40",
":",
"type",
"=",
"'sha1'",
"elif",
"len",
"(",
"... | Detect an hash type | [
"Detect",
"an",
"hash",
"type"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/harvest/filters.py#L103-L115 | train |
opendatateam/udata | udata/search/commands.py | iter_adapters | def iter_adapters():
'''Iter over adapter in predictable way'''
adapters = adapter_catalog.values()
return sorted(adapters, key=lambda a: a.model.__name__) | python | def iter_adapters():
'''Iter over adapter in predictable way'''
adapters = adapter_catalog.values()
return sorted(adapters, key=lambda a: a.model.__name__) | [
"def",
"iter_adapters",
"(",
")",
":",
"adapters",
"=",
"adapter_catalog",
".",
"values",
"(",
")",
"return",
"sorted",
"(",
"adapters",
",",
"key",
"=",
"lambda",
"a",
":",
"a",
".",
"model",
".",
"__name__",
")"
] | Iter over adapter in predictable way | [
"Iter",
"over",
"adapter",
"in",
"predictable",
"way"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/search/commands.py#L38-L41 | train |
opendatateam/udata | udata/search/commands.py | iter_qs | def iter_qs(qs, adapter):
'''Safely iterate over a DB QuerySet yielding ES documents'''
for obj in qs.no_cache().no_dereference().timeout(False):
if adapter.is_indexable(obj):
try:
doc = adapter.from_model(obj).to_dict(include_meta=True)
yield doc
... | python | def iter_qs(qs, adapter):
'''Safely iterate over a DB QuerySet yielding ES documents'''
for obj in qs.no_cache().no_dereference().timeout(False):
if adapter.is_indexable(obj):
try:
doc = adapter.from_model(obj).to_dict(include_meta=True)
yield doc
... | [
"def",
"iter_qs",
"(",
"qs",
",",
"adapter",
")",
":",
"for",
"obj",
"in",
"qs",
".",
"no_cache",
"(",
")",
".",
"no_dereference",
"(",
")",
".",
"timeout",
"(",
"False",
")",
":",
"if",
"adapter",
".",
"is_indexable",
"(",
"obj",
")",
":",
"try",
... | Safely iterate over a DB QuerySet yielding ES documents | [
"Safely",
"iterate",
"over",
"a",
"DB",
"QuerySet",
"yielding",
"ES",
"documents"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/search/commands.py#L44-L54 | train |
opendatateam/udata | udata/search/commands.py | index_model | def index_model(index_name, adapter):
''' Indel all objects given a model'''
model = adapter.model
log.info('Indexing {0} objects'.format(model.__name__))
qs = model.objects
if hasattr(model.objects, 'visible'):
qs = qs.visible()
if adapter.exclude_fields:
qs = qs.exclude(*adapte... | python | def index_model(index_name, adapter):
''' Indel all objects given a model'''
model = adapter.model
log.info('Indexing {0} objects'.format(model.__name__))
qs = model.objects
if hasattr(model.objects, 'visible'):
qs = qs.visible()
if adapter.exclude_fields:
qs = qs.exclude(*adapte... | [
"def",
"index_model",
"(",
"index_name",
",",
"adapter",
")",
":",
"model",
"=",
"adapter",
".",
"model",
"log",
".",
"info",
"(",
"'Indexing {0} objects'",
".",
"format",
"(",
"model",
".",
"__name__",
")",
")",
"qs",
"=",
"model",
".",
"objects",
"if",... | Indel all objects given a model | [
"Indel",
"all",
"objects",
"given",
"a",
"model"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/search/commands.py#L64-L80 | train |
opendatateam/udata | udata/search/commands.py | enable_refresh | def enable_refresh(index_name):
'''
Enable refresh and force merge. To be used after indexing.
See: https://www.elastic.co/guide/en/elasticsearch/reference/master/indices-update-settings.html#bulk
''' # noqa
refresh_interval = current_app.config['ELASTICSEARCH_REFRESH_INTERVAL']
es.indices.put... | python | def enable_refresh(index_name):
'''
Enable refresh and force merge. To be used after indexing.
See: https://www.elastic.co/guide/en/elasticsearch/reference/master/indices-update-settings.html#bulk
''' # noqa
refresh_interval = current_app.config['ELASTICSEARCH_REFRESH_INTERVAL']
es.indices.put... | [
"def",
"enable_refresh",
"(",
"index_name",
")",
":",
"# noqa",
"refresh_interval",
"=",
"current_app",
".",
"config",
"[",
"'ELASTICSEARCH_REFRESH_INTERVAL'",
"]",
"es",
".",
"indices",
".",
"put_settings",
"(",
"index",
"=",
"index_name",
",",
"body",
"=",
"{"... | Enable refresh and force merge. To be used after indexing.
See: https://www.elastic.co/guide/en/elasticsearch/reference/master/indices-update-settings.html#bulk | [
"Enable",
"refresh",
"and",
"force",
"merge",
".",
"To",
"be",
"used",
"after",
"indexing",
"."
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/search/commands.py#L96-L106 | train |
opendatateam/udata | udata/search/commands.py | set_alias | def set_alias(index_name, delete=True):
'''
Properly end an indexation by creating an alias.
Previous alias is deleted if needed.
'''
log.info('Creating alias "{0}" on index "{1}"'.format(
es.index_name, index_name))
if es.indices.exists_alias(name=es.index_name):
alias = es.indi... | python | def set_alias(index_name, delete=True):
'''
Properly end an indexation by creating an alias.
Previous alias is deleted if needed.
'''
log.info('Creating alias "{0}" on index "{1}"'.format(
es.index_name, index_name))
if es.indices.exists_alias(name=es.index_name):
alias = es.indi... | [
"def",
"set_alias",
"(",
"index_name",
",",
"delete",
"=",
"True",
")",
":",
"log",
".",
"info",
"(",
"'Creating alias \"{0}\" on index \"{1}\"'",
".",
"format",
"(",
"es",
".",
"index_name",
",",
"index_name",
")",
")",
"if",
"es",
".",
"indices",
".",
"e... | Properly end an indexation by creating an alias.
Previous alias is deleted if needed. | [
"Properly",
"end",
"an",
"indexation",
"by",
"creating",
"an",
"alias",
".",
"Previous",
"alias",
"is",
"deleted",
"if",
"needed",
"."
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/search/commands.py#L109-L127 | train |
opendatateam/udata | udata/search/commands.py | handle_error | def handle_error(index_name, keep=False):
'''
Handle errors while indexing.
In case of error, properly log it, remove the index and exit.
If `keep` is `True`, index is not deleted.
'''
# Handle keyboard interrupt
signal.signal(signal.SIGINT, signal.default_int_handler)
signal.signal(sign... | python | def handle_error(index_name, keep=False):
'''
Handle errors while indexing.
In case of error, properly log it, remove the index and exit.
If `keep` is `True`, index is not deleted.
'''
# Handle keyboard interrupt
signal.signal(signal.SIGINT, signal.default_int_handler)
signal.signal(sign... | [
"def",
"handle_error",
"(",
"index_name",
",",
"keep",
"=",
"False",
")",
":",
"# Handle keyboard interrupt",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGINT",
",",
"signal",
".",
"default_int_handler",
")",
"signal",
".",
"signal",
"(",
"signal",
".",
... | Handle errors while indexing.
In case of error, properly log it, remove the index and exit.
If `keep` is `True`, index is not deleted. | [
"Handle",
"errors",
"while",
"indexing",
".",
"In",
"case",
"of",
"error",
"properly",
"log",
"it",
"remove",
"the",
"index",
"and",
"exit",
".",
"If",
"keep",
"is",
"True",
"index",
"is",
"not",
"deleted",
"."
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/search/commands.py#L131-L154 | train |
opendatateam/udata | udata/search/commands.py | index | def index(models=None, name=None, force=False, keep=False):
'''
Initialize or rebuild the search index
Models to reindex can optionally be specified as arguments.
If not, all models are reindexed.
'''
index_name = name or default_index_name()
doc_types_names = [m.__name__.lower() for m in ... | python | def index(models=None, name=None, force=False, keep=False):
'''
Initialize or rebuild the search index
Models to reindex can optionally be specified as arguments.
If not, all models are reindexed.
'''
index_name = name or default_index_name()
doc_types_names = [m.__name__.lower() for m in ... | [
"def",
"index",
"(",
"models",
"=",
"None",
",",
"name",
"=",
"None",
",",
"force",
"=",
"False",
",",
"keep",
"=",
"False",
")",
":",
"index_name",
"=",
"name",
"or",
"default_index_name",
"(",
")",
"doc_types_names",
"=",
"[",
"m",
".",
"__name__",
... | Initialize or rebuild the search index
Models to reindex can optionally be specified as arguments.
If not, all models are reindexed. | [
"Initialize",
"or",
"rebuild",
"the",
"search",
"index"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/search/commands.py#L162-L214 | train |
opendatateam/udata | udata/app.py | create_app | def create_app(config='udata.settings.Defaults', override=None,
init_logging=init_logging):
'''Factory for a minimal application'''
app = UDataApp(APP_NAME)
app.config.from_object(config)
settings = os.environ.get('UDATA_SETTINGS', join(os.getcwd(), 'udata.cfg'))
if exists(settings):... | python | def create_app(config='udata.settings.Defaults', override=None,
init_logging=init_logging):
'''Factory for a minimal application'''
app = UDataApp(APP_NAME)
app.config.from_object(config)
settings = os.environ.get('UDATA_SETTINGS', join(os.getcwd(), 'udata.cfg'))
if exists(settings):... | [
"def",
"create_app",
"(",
"config",
"=",
"'udata.settings.Defaults'",
",",
"override",
"=",
"None",
",",
"init_logging",
"=",
"init_logging",
")",
":",
"app",
"=",
"UDataApp",
"(",
"APP_NAME",
")",
"app",
".",
"config",
".",
"from_object",
"(",
"config",
")"... | Factory for a minimal application | [
"Factory",
"for",
"a",
"minimal",
"application"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/app.py#L155-L188 | train |
opendatateam/udata | udata/app.py | standalone | def standalone(app):
'''Factory for an all in one application'''
from udata import api, core, frontend
core.init_app(app)
frontend.init_app(app)
api.init_app(app)
register_features(app)
return app | python | def standalone(app):
'''Factory for an all in one application'''
from udata import api, core, frontend
core.init_app(app)
frontend.init_app(app)
api.init_app(app)
register_features(app)
return app | [
"def",
"standalone",
"(",
"app",
")",
":",
"from",
"udata",
"import",
"api",
",",
"core",
",",
"frontend",
"core",
".",
"init_app",
"(",
"app",
")",
"frontend",
".",
"init_app",
"(",
"app",
")",
"api",
".",
"init_app",
"(",
"app",
")",
"register_featur... | Factory for an all in one application | [
"Factory",
"for",
"an",
"all",
"in",
"one",
"application"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/app.py#L191-L201 | train |
opendatateam/udata | udata/commands/db.py | get_migration | def get_migration(plugin, filename):
'''Get an existing migration record if exists'''
db = get_db()
return db.migrations.find_one({'plugin': plugin, 'filename': filename}) | python | def get_migration(plugin, filename):
'''Get an existing migration record if exists'''
db = get_db()
return db.migrations.find_one({'plugin': plugin, 'filename': filename}) | [
"def",
"get_migration",
"(",
"plugin",
",",
"filename",
")",
":",
"db",
"=",
"get_db",
"(",
")",
"return",
"db",
".",
"migrations",
".",
"find_one",
"(",
"{",
"'plugin'",
":",
"plugin",
",",
"'filename'",
":",
"filename",
"}",
")"
] | Get an existing migration record if exists | [
"Get",
"an",
"existing",
"migration",
"record",
"if",
"exists"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/commands/db.py#L85-L88 | train |
opendatateam/udata | udata/commands/db.py | record_migration | def record_migration(plugin, filename, script, **kwargs):
'''Only record a migration without applying it'''
db = get_db()
db.eval(RECORD_WRAPPER, plugin, filename, script)
return True | python | def record_migration(plugin, filename, script, **kwargs):
'''Only record a migration without applying it'''
db = get_db()
db.eval(RECORD_WRAPPER, plugin, filename, script)
return True | [
"def",
"record_migration",
"(",
"plugin",
",",
"filename",
",",
"script",
",",
"*",
"*",
"kwargs",
")",
":",
"db",
"=",
"get_db",
"(",
")",
"db",
".",
"eval",
"(",
"RECORD_WRAPPER",
",",
"plugin",
",",
"filename",
",",
"script",
")",
"return",
"True"
] | Only record a migration without applying it | [
"Only",
"record",
"a",
"migration",
"without",
"applying",
"it"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/commands/db.py#L115-L119 | train |
opendatateam/udata | udata/commands/db.py | available_migrations | def available_migrations():
'''
List available migrations for udata and enabled plugins
Each row is tuple with following signature:
(plugin, package, filename)
'''
migrations = []
for filename in resource_listdir('udata', 'migrations'):
if filename.endswith('.js'):
... | python | def available_migrations():
'''
List available migrations for udata and enabled plugins
Each row is tuple with following signature:
(plugin, package, filename)
'''
migrations = []
for filename in resource_listdir('udata', 'migrations'):
if filename.endswith('.js'):
... | [
"def",
"available_migrations",
"(",
")",
":",
"migrations",
"=",
"[",
"]",
"for",
"filename",
"in",
"resource_listdir",
"(",
"'udata'",
",",
"'migrations'",
")",
":",
"if",
"filename",
".",
"endswith",
"(",
"'.js'",
")",
":",
"migrations",
".",
"append",
"... | List available migrations for udata and enabled plugins
Each row is tuple with following signature:
(plugin, package, filename) | [
"List",
"available",
"migrations",
"for",
"udata",
"and",
"enabled",
"plugins"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/commands/db.py#L122-L141 | train |
opendatateam/udata | udata/commands/db.py | log_status | def log_status(plugin, filename, status):
'''Properly display a migration status line'''
display = ':'.join((plugin, filename)) + ' '
log.info('%s [%s]', '{:.<70}'.format(display), status) | python | def log_status(plugin, filename, status):
'''Properly display a migration status line'''
display = ':'.join((plugin, filename)) + ' '
log.info('%s [%s]', '{:.<70}'.format(display), status) | [
"def",
"log_status",
"(",
"plugin",
",",
"filename",
",",
"status",
")",
":",
"display",
"=",
"':'",
".",
"join",
"(",
"(",
"plugin",
",",
"filename",
")",
")",
"+",
"' '",
"log",
".",
"info",
"(",
"'%s [%s]'",
",",
"'{:.<70}'",
".",
"format",
"(",
... | Properly display a migration status line | [
"Properly",
"display",
"a",
"migration",
"status",
"line"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/commands/db.py#L144-L147 | train |
opendatateam/udata | udata/commands/db.py | status | def status():
'''Display the database migrations status'''
for plugin, package, filename in available_migrations():
migration = get_migration(plugin, filename)
if migration:
status = green(migration['date'].strftime(DATE_FORMAT))
else:
status = yellow('Not applied... | python | def status():
'''Display the database migrations status'''
for plugin, package, filename in available_migrations():
migration = get_migration(plugin, filename)
if migration:
status = green(migration['date'].strftime(DATE_FORMAT))
else:
status = yellow('Not applied... | [
"def",
"status",
"(",
")",
":",
"for",
"plugin",
",",
"package",
",",
"filename",
"in",
"available_migrations",
"(",
")",
":",
"migration",
"=",
"get_migration",
"(",
"plugin",
",",
"filename",
")",
"if",
"migration",
":",
"status",
"=",
"green",
"(",
"m... | Display the database migrations status | [
"Display",
"the",
"database",
"migrations",
"status"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/commands/db.py#L151-L159 | train |
opendatateam/udata | udata/commands/db.py | migrate | def migrate(record, dry_run=False):
'''Perform database migrations'''
handler = record_migration if record else execute_migration
success = True
for plugin, package, filename in available_migrations():
migration = get_migration(plugin, filename)
if migration or not success:
l... | python | def migrate(record, dry_run=False):
'''Perform database migrations'''
handler = record_migration if record else execute_migration
success = True
for plugin, package, filename in available_migrations():
migration = get_migration(plugin, filename)
if migration or not success:
l... | [
"def",
"migrate",
"(",
"record",
",",
"dry_run",
"=",
"False",
")",
":",
"handler",
"=",
"record_migration",
"if",
"record",
"else",
"execute_migration",
"success",
"=",
"True",
"for",
"plugin",
",",
"package",
",",
"filename",
"in",
"available_migrations",
"(... | Perform database migrations | [
"Perform",
"database",
"migrations"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/commands/db.py#L167-L179 | train |
opendatateam/udata | udata/commands/db.py | unrecord | def unrecord(plugin_or_specs, filename):
'''
Remove a database migration record.
\b
A record can be expressed with the following syntaxes:
- plugin filename
- plugin fliename.js
- plugin:filename
- plugin:fliename.js
'''
plugin, filename = normalize_migration(plugin_or_specs... | python | def unrecord(plugin_or_specs, filename):
'''
Remove a database migration record.
\b
A record can be expressed with the following syntaxes:
- plugin filename
- plugin fliename.js
- plugin:filename
- plugin:fliename.js
'''
plugin, filename = normalize_migration(plugin_or_specs... | [
"def",
"unrecord",
"(",
"plugin_or_specs",
",",
"filename",
")",
":",
"plugin",
",",
"filename",
"=",
"normalize_migration",
"(",
"plugin_or_specs",
",",
"filename",
")",
"migration",
"=",
"get_migration",
"(",
"plugin",
",",
"filename",
")",
"if",
"migration",
... | Remove a database migration record.
\b
A record can be expressed with the following syntaxes:
- plugin filename
- plugin fliename.js
- plugin:filename
- plugin:fliename.js | [
"Remove",
"a",
"database",
"migration",
"record",
"."
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/commands/db.py#L185-L203 | train |
opendatateam/udata | udata/uris.py | validate | def validate(url, schemes=None, tlds=None, private=None, local=None,
credentials=None):
'''
Validate and normalize an URL
:param str url: The URL to validate and normalize
:return str: The normalized URL
:raises ValidationError: when URL does not validate
'''
url = url.strip()
... | python | def validate(url, schemes=None, tlds=None, private=None, local=None,
credentials=None):
'''
Validate and normalize an URL
:param str url: The URL to validate and normalize
:return str: The normalized URL
:raises ValidationError: when URL does not validate
'''
url = url.strip()
... | [
"def",
"validate",
"(",
"url",
",",
"schemes",
"=",
"None",
",",
"tlds",
"=",
"None",
",",
"private",
"=",
"None",
",",
"local",
"=",
"None",
",",
"credentials",
"=",
"None",
")",
":",
"url",
"=",
"url",
".",
"strip",
"(",
")",
"private",
"=",
"c... | Validate and normalize an URL
:param str url: The URL to validate and normalize
:return str: The normalized URL
:raises ValidationError: when URL does not validate | [
"Validate",
"and",
"normalize",
"an",
"URL"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/uris.py#L69-L119 | train |
opendatateam/udata | udata/core/dataset/models.py | get_json_ld_extra | def get_json_ld_extra(key, value):
'''Serialize an extras key, value pair into JSON-LD'''
value = value.serialize() if hasattr(value, 'serialize') else value
return {
'@type': 'http://schema.org/PropertyValue',
'name': key,
'value': value,
} | python | def get_json_ld_extra(key, value):
'''Serialize an extras key, value pair into JSON-LD'''
value = value.serialize() if hasattr(value, 'serialize') else value
return {
'@type': 'http://schema.org/PropertyValue',
'name': key,
'value': value,
} | [
"def",
"get_json_ld_extra",
"(",
"key",
",",
"value",
")",
":",
"value",
"=",
"value",
".",
"serialize",
"(",
")",
"if",
"hasattr",
"(",
"value",
",",
"'serialize'",
")",
"else",
"value",
"return",
"{",
"'@type'",
":",
"'http://schema.org/PropertyValue'",
",... | Serialize an extras key, value pair into JSON-LD | [
"Serialize",
"an",
"extras",
"key",
"value",
"pair",
"into",
"JSON",
"-",
"LD"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/dataset/models.py#L105-L112 | train |
opendatateam/udata | udata/core/dataset/models.py | get_resource | def get_resource(id):
'''Fetch a resource given its UUID'''
dataset = Dataset.objects(resources__id=id).first()
if dataset:
return get_by(dataset.resources, 'id', id)
else:
return CommunityResource.objects(id=id).first() | python | def get_resource(id):
'''Fetch a resource given its UUID'''
dataset = Dataset.objects(resources__id=id).first()
if dataset:
return get_by(dataset.resources, 'id', id)
else:
return CommunityResource.objects(id=id).first() | [
"def",
"get_resource",
"(",
"id",
")",
":",
"dataset",
"=",
"Dataset",
".",
"objects",
"(",
"resources__id",
"=",
"id",
")",
".",
"first",
"(",
")",
"if",
"dataset",
":",
"return",
"get_by",
"(",
"dataset",
".",
"resources",
",",
"'id'",
",",
"id",
"... | Fetch a resource given its UUID | [
"Fetch",
"a",
"resource",
"given",
"its",
"UUID"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/dataset/models.py#L692-L698 | train |
opendatateam/udata | udata/core/dataset/models.py | License.guess | def guess(cls, *strings, **kwargs):
'''
Try to guess a license from a list of strings.
Accept a `default` keyword argument which will be
the default fallback license.
'''
license = None
for string in strings:
license = cls.guess_one(string)
... | python | def guess(cls, *strings, **kwargs):
'''
Try to guess a license from a list of strings.
Accept a `default` keyword argument which will be
the default fallback license.
'''
license = None
for string in strings:
license = cls.guess_one(string)
... | [
"def",
"guess",
"(",
"cls",
",",
"*",
"strings",
",",
"*",
"*",
"kwargs",
")",
":",
"license",
"=",
"None",
"for",
"string",
"in",
"strings",
":",
"license",
"=",
"cls",
".",
"guess_one",
"(",
"string",
")",
"if",
"license",
":",
"break",
"return",
... | Try to guess a license from a list of strings.
Accept a `default` keyword argument which will be
the default fallback license. | [
"Try",
"to",
"guess",
"a",
"license",
"from",
"a",
"list",
"of",
"strings",
"."
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/dataset/models.py#L134-L146 | train |
opendatateam/udata | udata/core/dataset/models.py | License.guess_one | def guess_one(cls, text):
'''
Try to guess license from a string.
Try to exact match on identifier then slugified title
and fallback on edit distance ranking (after slugification)
'''
if not text:
return
qs = cls.objects
text = text.strip().lo... | python | def guess_one(cls, text):
'''
Try to guess license from a string.
Try to exact match on identifier then slugified title
and fallback on edit distance ranking (after slugification)
'''
if not text:
return
qs = cls.objects
text = text.strip().lo... | [
"def",
"guess_one",
"(",
"cls",
",",
"text",
")",
":",
"if",
"not",
"text",
":",
"return",
"qs",
"=",
"cls",
".",
"objects",
"text",
"=",
"text",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
"# Stored identifiers are lower case",
"slug",
"=",
"cls",... | Try to guess license from a string.
Try to exact match on identifier then slugified title
and fallback on edit distance ranking (after slugification) | [
"Try",
"to",
"guess",
"license",
"from",
"a",
"string",
"."
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/dataset/models.py#L149-L185 | train |
opendatateam/udata | udata/core/dataset/models.py | ResourceMixin.need_check | def need_check(self):
'''Does the resource needs to be checked against its linkchecker?
We check unavailable resources often, unless they go over the
threshold. Available resources are checked less and less frequently
based on their historical availability.
'''
min_cache... | python | def need_check(self):
'''Does the resource needs to be checked against its linkchecker?
We check unavailable resources often, unless they go over the
threshold. Available resources are checked less and less frequently
based on their historical availability.
'''
min_cache... | [
"def",
"need_check",
"(",
"self",
")",
":",
"min_cache_duration",
",",
"max_cache_duration",
",",
"ko_threshold",
"=",
"[",
"current_app",
".",
"config",
".",
"get",
"(",
"k",
")",
"for",
"k",
"in",
"(",
"'LINKCHECKING_MIN_CACHE_DURATION'",
",",
"'LINKCHECKING_M... | Does the resource needs to be checked against its linkchecker?
We check unavailable resources often, unless they go over the
threshold. Available resources are checked less and less frequently
based on their historical availability. | [
"Does",
"the",
"resource",
"needs",
"to",
"be",
"checked",
"against",
"its",
"linkchecker?"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/dataset/models.py#L258-L291 | train |
opendatateam/udata | udata/core/dataset/models.py | Dataset.check_availability | def check_availability(self):
"""Check if resources from that dataset are available.
Return a list of (boolean or 'unknown')
"""
# Only check remote resources.
remote_resources = [resource
for resource in self.resources
if ... | python | def check_availability(self):
"""Check if resources from that dataset are available.
Return a list of (boolean or 'unknown')
"""
# Only check remote resources.
remote_resources = [resource
for resource in self.resources
if ... | [
"def",
"check_availability",
"(",
"self",
")",
":",
"# Only check remote resources.",
"remote_resources",
"=",
"[",
"resource",
"for",
"resource",
"in",
"self",
".",
"resources",
"if",
"resource",
".",
"filetype",
"==",
"'remote'",
"]",
"if",
"not",
"remote_resour... | Check if resources from that dataset are available.
Return a list of (boolean or 'unknown') | [
"Check",
"if",
"resources",
"from",
"that",
"dataset",
"are",
"available",
"."
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/dataset/models.py#L471-L482 | train |
opendatateam/udata | udata/core/dataset/models.py | Dataset.next_update | def next_update(self):
"""Compute the next expected update date,
given the frequency and last_update.
Return None if the frequency is not handled.
"""
delta = None
if self.frequency == 'daily':
delta = timedelta(days=1)
elif self.frequency == 'weekly'... | python | def next_update(self):
"""Compute the next expected update date,
given the frequency and last_update.
Return None if the frequency is not handled.
"""
delta = None
if self.frequency == 'daily':
delta = timedelta(days=1)
elif self.frequency == 'weekly'... | [
"def",
"next_update",
"(",
"self",
")",
":",
"delta",
"=",
"None",
"if",
"self",
".",
"frequency",
"==",
"'daily'",
":",
"delta",
"=",
"timedelta",
"(",
"days",
"=",
"1",
")",
"elif",
"self",
".",
"frequency",
"==",
"'weekly'",
":",
"delta",
"=",
"ti... | Compute the next expected update date,
given the frequency and last_update.
Return None if the frequency is not handled. | [
"Compute",
"the",
"next",
"expected",
"update",
"date"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/dataset/models.py#L492-L524 | train |
opendatateam/udata | udata/core/dataset/models.py | Dataset.quality | def quality(self):
"""Return a dict filled with metrics related to the inner
quality of the dataset:
* number of tags
* description length
* and so on
"""
from udata.models import Discussion # noqa: Prevent circular imports
result = {}
... | python | def quality(self):
"""Return a dict filled with metrics related to the inner
quality of the dataset:
* number of tags
* description length
* and so on
"""
from udata.models import Discussion # noqa: Prevent circular imports
result = {}
... | [
"def",
"quality",
"(",
"self",
")",
":",
"from",
"udata",
".",
"models",
"import",
"Discussion",
"# noqa: Prevent circular imports",
"result",
"=",
"{",
"}",
"if",
"not",
"self",
".",
"id",
":",
"# Quality is only relevant on saved Datasets",
"return",
"result",
"... | Return a dict filled with metrics related to the inner
quality of the dataset:
* number of tags
* description length
* and so on | [
"Return",
"a",
"dict",
"filled",
"with",
"metrics",
"related",
"to",
"the",
"inner"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/dataset/models.py#L527-L561 | train |
opendatateam/udata | udata/core/dataset/models.py | Dataset.compute_quality_score | def compute_quality_score(self, quality):
"""Compute the score related to the quality of that dataset."""
score = 0
UNIT = 2
if 'frequency' in quality:
# TODO: should be related to frequency.
if quality['update_in'] < 0:
score += UNIT
e... | python | def compute_quality_score(self, quality):
"""Compute the score related to the quality of that dataset."""
score = 0
UNIT = 2
if 'frequency' in quality:
# TODO: should be related to frequency.
if quality['update_in'] < 0:
score += UNIT
e... | [
"def",
"compute_quality_score",
"(",
"self",
",",
"quality",
")",
":",
"score",
"=",
"0",
"UNIT",
"=",
"2",
"if",
"'frequency'",
"in",
"quality",
":",
"# TODO: should be related to frequency.",
"if",
"quality",
"[",
"'update_in'",
"]",
"<",
"0",
":",
"score",
... | Compute the score related to the quality of that dataset. | [
"Compute",
"the",
"score",
"related",
"to",
"the",
"quality",
"of",
"that",
"dataset",
"."
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/dataset/models.py#L563-L595 | train |
opendatateam/udata | udata/core/dataset/models.py | Dataset.add_resource | def add_resource(self, resource):
'''Perform an atomic prepend for a new resource'''
resource.validate()
self.update(__raw__={
'$push': {
'resources': {
'$each': [resource.to_mongo()],
'$position': 0
}
... | python | def add_resource(self, resource):
'''Perform an atomic prepend for a new resource'''
resource.validate()
self.update(__raw__={
'$push': {
'resources': {
'$each': [resource.to_mongo()],
'$position': 0
}
... | [
"def",
"add_resource",
"(",
"self",
",",
"resource",
")",
":",
"resource",
".",
"validate",
"(",
")",
"self",
".",
"update",
"(",
"__raw__",
"=",
"{",
"'$push'",
":",
"{",
"'resources'",
":",
"{",
"'$each'",
":",
"[",
"resource",
".",
"to_mongo",
"(",
... | Perform an atomic prepend for a new resource | [
"Perform",
"an",
"atomic",
"prepend",
"for",
"a",
"new",
"resource"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/dataset/models.py#L602-L615 | train |
opendatateam/udata | udata/core/dataset/models.py | Dataset.update_resource | def update_resource(self, resource):
'''Perform an atomic update for an existing resource'''
index = self.resources.index(resource)
data = {
'resources__{index}'.format(index=index): resource
}
self.update(**data)
self.reload()
post_save.send(self.__cl... | python | def update_resource(self, resource):
'''Perform an atomic update for an existing resource'''
index = self.resources.index(resource)
data = {
'resources__{index}'.format(index=index): resource
}
self.update(**data)
self.reload()
post_save.send(self.__cl... | [
"def",
"update_resource",
"(",
"self",
",",
"resource",
")",
":",
"index",
"=",
"self",
".",
"resources",
".",
"index",
"(",
"resource",
")",
"data",
"=",
"{",
"'resources__{index}'",
".",
"format",
"(",
"index",
"=",
"index",
")",
":",
"resource",
"}",
... | Perform an atomic update for an existing resource | [
"Perform",
"an",
"atomic",
"update",
"for",
"an",
"existing",
"resource"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/dataset/models.py#L617-L625 | train |
opendatateam/udata | udata/search/result.py | SearchResult.get_aggregation | def get_aggregation(self, name):
'''
Fetch an aggregation result given its name
As there is no way at this point know the aggregation type
(ie. bucket, pipeline or metric)
we guess it from the response attributes.
Only bucket and metric types are handled
'''
... | python | def get_aggregation(self, name):
'''
Fetch an aggregation result given its name
As there is no way at this point know the aggregation type
(ie. bucket, pipeline or metric)
we guess it from the response attributes.
Only bucket and metric types are handled
'''
... | [
"def",
"get_aggregation",
"(",
"self",
",",
"name",
")",
":",
"agg",
"=",
"self",
".",
"aggregations",
"[",
"name",
"]",
"if",
"'buckets'",
"in",
"agg",
":",
"return",
"agg",
"[",
"'buckets'",
"]",
"else",
":",
"return",
"agg"
] | Fetch an aggregation result given its name
As there is no way at this point know the aggregation type
(ie. bucket, pipeline or metric)
we guess it from the response attributes.
Only bucket and metric types are handled | [
"Fetch",
"an",
"aggregation",
"result",
"given",
"its",
"name"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/search/result.py#L98-L111 | train |
opendatateam/udata | udata/i18n.py | language | def language(lang_code):
'''Force a given language'''
ctx = None
if not request:
ctx = current_app.test_request_context()
ctx.push()
backup = g.get('lang_code')
g.lang_code = lang_code
refresh()
yield
g.lang_code = backup
if ctx:
ctx.pop()
refresh() | python | def language(lang_code):
'''Force a given language'''
ctx = None
if not request:
ctx = current_app.test_request_context()
ctx.push()
backup = g.get('lang_code')
g.lang_code = lang_code
refresh()
yield
g.lang_code = backup
if ctx:
ctx.pop()
refresh() | [
"def",
"language",
"(",
"lang_code",
")",
":",
"ctx",
"=",
"None",
"if",
"not",
"request",
":",
"ctx",
"=",
"current_app",
".",
"test_request_context",
"(",
")",
"ctx",
".",
"push",
"(",
")",
"backup",
"=",
"g",
".",
"get",
"(",
"'lang_code'",
")",
"... | Force a given language | [
"Force",
"a",
"given",
"language"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/i18n.py#L145-L158 | train |
opendatateam/udata | udata/i18n.py | redirect_to_lang | def redirect_to_lang(*args, **kwargs):
'''Redirect non lang-prefixed urls to default language.'''
endpoint = request.endpoint.replace('_redirect', '')
kwargs = multi_to_dict(request.args)
kwargs.update(request.view_args)
kwargs['lang_code'] = default_lang
return redirect(url_for(endpoint, **kwar... | python | def redirect_to_lang(*args, **kwargs):
'''Redirect non lang-prefixed urls to default language.'''
endpoint = request.endpoint.replace('_redirect', '')
kwargs = multi_to_dict(request.args)
kwargs.update(request.view_args)
kwargs['lang_code'] = default_lang
return redirect(url_for(endpoint, **kwar... | [
"def",
"redirect_to_lang",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"endpoint",
"=",
"request",
".",
"endpoint",
".",
"replace",
"(",
"'_redirect'",
",",
"''",
")",
"kwargs",
"=",
"multi_to_dict",
"(",
"request",
".",
"args",
")",
"kwargs",
... | Redirect non lang-prefixed urls to default language. | [
"Redirect",
"non",
"lang",
"-",
"prefixed",
"urls",
"to",
"default",
"language",
"."
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/i18n.py#L203-L209 | train |
opendatateam/udata | udata/i18n.py | redirect_to_unlocalized | def redirect_to_unlocalized(*args, **kwargs):
'''Redirect lang-prefixed urls to no prefixed URL.'''
endpoint = request.endpoint.replace('_redirect', '')
kwargs = multi_to_dict(request.args)
kwargs.update(request.view_args)
kwargs.pop('lang_code', None)
return redirect(url_for(endpoint, **kwargs)... | python | def redirect_to_unlocalized(*args, **kwargs):
'''Redirect lang-prefixed urls to no prefixed URL.'''
endpoint = request.endpoint.replace('_redirect', '')
kwargs = multi_to_dict(request.args)
kwargs.update(request.view_args)
kwargs.pop('lang_code', None)
return redirect(url_for(endpoint, **kwargs)... | [
"def",
"redirect_to_unlocalized",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"endpoint",
"=",
"request",
".",
"endpoint",
".",
"replace",
"(",
"'_redirect'",
",",
"''",
")",
"kwargs",
"=",
"multi_to_dict",
"(",
"request",
".",
"args",
")",
"kwa... | Redirect lang-prefixed urls to no prefixed URL. | [
"Redirect",
"lang",
"-",
"prefixed",
"urls",
"to",
"no",
"prefixed",
"URL",
"."
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/i18n.py#L212-L218 | train |
opendatateam/udata | udata/i18n.py | PluggableDomain.get_translations | def get_translations(self):
"""Returns 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 = stack.top
if ctx... | python | def get_translations(self):
"""Returns 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 = stack.top
if ctx... | [
"def",
"get_translations",
"(",
"self",
")",
":",
"ctx",
"=",
"stack",
".",
"top",
"if",
"ctx",
"is",
"None",
":",
"return",
"NullTranslations",
"(",
")",
"locale",
"=",
"get_locale",
"(",
")",
"cache",
"=",
"self",
".",
"get_translations_cache",
"(",
"c... | Returns 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. | [
"Returns",
"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",
"... | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/i18n.py#L37-L96 | train |
opendatateam/udata | udata/core/discussions/models.py | Discussion.person_involved | def person_involved(self, person):
"""Return True if the given person has been involved in the
discussion, False otherwise.
"""
return any(message.posted_by == person for message in self.discussion) | python | def person_involved(self, person):
"""Return True if the given person has been involved in the
discussion, False otherwise.
"""
return any(message.posted_by == person for message in self.discussion) | [
"def",
"person_involved",
"(",
"self",
",",
"person",
")",
":",
"return",
"any",
"(",
"message",
".",
"posted_by",
"==",
"person",
"for",
"message",
"in",
"self",
".",
"discussion",
")"
] | Return True if the given person has been involved in the
discussion, False otherwise. | [
"Return",
"True",
"if",
"the",
"given",
"person",
"has",
"been",
"involved",
"in",
"the"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/discussions/models.py#L37-L42 | train |
opendatateam/udata | udata/linkchecker/checker.py | is_ignored | def is_ignored(resource):
'''Check of the resource's URL is part of LINKCHECKING_IGNORE_DOMAINS'''
ignored_domains = current_app.config['LINKCHECKING_IGNORE_DOMAINS']
url = resource.url
if url:
parsed_url = urlparse(url)
return parsed_url.netloc in ignored_domains
return True | python | def is_ignored(resource):
'''Check of the resource's URL is part of LINKCHECKING_IGNORE_DOMAINS'''
ignored_domains = current_app.config['LINKCHECKING_IGNORE_DOMAINS']
url = resource.url
if url:
parsed_url = urlparse(url)
return parsed_url.netloc in ignored_domains
return True | [
"def",
"is_ignored",
"(",
"resource",
")",
":",
"ignored_domains",
"=",
"current_app",
".",
"config",
"[",
"'LINKCHECKING_IGNORE_DOMAINS'",
"]",
"url",
"=",
"resource",
".",
"url",
"if",
"url",
":",
"parsed_url",
"=",
"urlparse",
"(",
"url",
")",
"return",
"... | Check of the resource's URL is part of LINKCHECKING_IGNORE_DOMAINS | [
"Check",
"of",
"the",
"resource",
"s",
"URL",
"is",
"part",
"of",
"LINKCHECKING_IGNORE_DOMAINS"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/linkchecker/checker.py#L25-L32 | train |
opendatateam/udata | udata/linkchecker/checker.py | check_resource | def check_resource(resource):
'''
Check a resource availability against a linkchecker backend
The linkchecker used can be configured on a resource basis by setting
the `resource.extras['check:checker']` attribute with a key that points
to a valid `udata.linkcheckers` entrypoint. If not set, it will... | python | def check_resource(resource):
'''
Check a resource availability against a linkchecker backend
The linkchecker used can be configured on a resource basis by setting
the `resource.extras['check:checker']` attribute with a key that points
to a valid `udata.linkcheckers` entrypoint. If not set, it will... | [
"def",
"check_resource",
"(",
"resource",
")",
":",
"linkchecker_type",
"=",
"resource",
".",
"extras",
".",
"get",
"(",
"'check:checker'",
")",
"LinkChecker",
"=",
"get_linkchecker",
"(",
"linkchecker_type",
")",
"if",
"not",
"LinkChecker",
":",
"return",
"{",
... | Check a resource availability against a linkchecker backend
The linkchecker used can be configured on a resource basis by setting
the `resource.extras['check:checker']` attribute with a key that points
to a valid `udata.linkcheckers` entrypoint. If not set, it will
fallback on the default linkchecker d... | [
"Check",
"a",
"resource",
"availability",
"against",
"a",
"linkchecker",
"backend"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/linkchecker/checker.py#L40-L74 | train |
opendatateam/udata | udata/models/owned.py | owned_pre_save | def owned_pre_save(sender, document, **kwargs):
'''
Owned mongoengine.pre_save signal handler
Need to fetch original owner before the new one erase it.
'''
if not isinstance(document, Owned):
return
changed_fields = getattr(document, '_changed_fields', [])
if 'organization' in change... | python | def owned_pre_save(sender, document, **kwargs):
'''
Owned mongoengine.pre_save signal handler
Need to fetch original owner before the new one erase it.
'''
if not isinstance(document, Owned):
return
changed_fields = getattr(document, '_changed_fields', [])
if 'organization' in change... | [
"def",
"owned_pre_save",
"(",
"sender",
",",
"document",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"document",
",",
"Owned",
")",
":",
"return",
"changed_fields",
"=",
"getattr",
"(",
"document",
",",
"'_changed_fields'",
",",
"[",... | Owned mongoengine.pre_save signal handler
Need to fetch original owner before the new one erase it. | [
"Owned",
"mongoengine",
".",
"pre_save",
"signal",
"handler",
"Need",
"to",
"fetch",
"original",
"owner",
"before",
"the",
"new",
"one",
"erase",
"it",
"."
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/models/owned.py#L41-L68 | train |
opendatateam/udata | udata/models/owned.py | owned_post_save | def owned_post_save(sender, document, **kwargs):
'''
Owned mongoengine.post_save signal handler
Dispatch the `Owned.on_owner_change` signal
once the document has been saved including the previous owner.
The signal handler should have the following signature:
``def handler(document, previous)``
... | python | def owned_post_save(sender, document, **kwargs):
'''
Owned mongoengine.post_save signal handler
Dispatch the `Owned.on_owner_change` signal
once the document has been saved including the previous owner.
The signal handler should have the following signature:
``def handler(document, previous)``
... | [
"def",
"owned_post_save",
"(",
"sender",
",",
"document",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"document",
",",
"Owned",
")",
"and",
"hasattr",
"(",
"document",
",",
"'_previous_owner'",
")",
":",
"Owned",
".",
"on_owner_change",
"."... | Owned mongoengine.post_save signal handler
Dispatch the `Owned.on_owner_change` signal
once the document has been saved including the previous owner.
The signal handler should have the following signature:
``def handler(document, previous)`` | [
"Owned",
"mongoengine",
".",
"post_save",
"signal",
"handler",
"Dispatch",
"the",
"Owned",
".",
"on_owner_change",
"signal",
"once",
"the",
"document",
"has",
"been",
"saved",
"including",
"the",
"previous",
"owner",
"."
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/models/owned.py#L71-L81 | train |
opendatateam/udata | udata/core/dataset/preview.py | get_enabled_plugins | def get_enabled_plugins():
'''
Returns enabled preview plugins.
Plugins are sorted, defaults come last
'''
plugins = entrypoints.get_enabled('udata.preview', current_app).values()
valid = [p for p in plugins if issubclass(p, PreviewPlugin)]
for plugin in plugins:
if plugin not in va... | python | def get_enabled_plugins():
'''
Returns enabled preview plugins.
Plugins are sorted, defaults come last
'''
plugins = entrypoints.get_enabled('udata.preview', current_app).values()
valid = [p for p in plugins if issubclass(p, PreviewPlugin)]
for plugin in plugins:
if plugin not in va... | [
"def",
"get_enabled_plugins",
"(",
")",
":",
"plugins",
"=",
"entrypoints",
".",
"get_enabled",
"(",
"'udata.preview'",
",",
"current_app",
")",
".",
"values",
"(",
")",
"valid",
"=",
"[",
"p",
"for",
"p",
"in",
"plugins",
"if",
"issubclass",
"(",
"p",
"... | Returns enabled preview plugins.
Plugins are sorted, defaults come last | [
"Returns",
"enabled",
"preview",
"plugins",
"."
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/dataset/preview.py#L64-L77 | train |
opendatateam/udata | udata/core/dataset/preview.py | get_preview_url | def get_preview_url(resource):
'''
Returns the most pertinent preview URL associated to the resource, if any.
:param ResourceMixin resource: the (community) resource to preview
:return: a preview url to be displayed into an iframe or a new window
:rtype: HttpResponse
'''
candidates = (p.pre... | python | def get_preview_url(resource):
'''
Returns the most pertinent preview URL associated to the resource, if any.
:param ResourceMixin resource: the (community) resource to preview
:return: a preview url to be displayed into an iframe or a new window
:rtype: HttpResponse
'''
candidates = (p.pre... | [
"def",
"get_preview_url",
"(",
"resource",
")",
":",
"candidates",
"=",
"(",
"p",
".",
"preview_url",
"(",
"resource",
")",
"for",
"p",
"in",
"get_enabled_plugins",
"(",
")",
"if",
"p",
".",
"can_preview",
"(",
"resource",
")",
")",
"return",
"next",
"("... | Returns the most pertinent preview URL associated to the resource, if any.
:param ResourceMixin resource: the (community) resource to preview
:return: a preview url to be displayed into an iframe or a new window
:rtype: HttpResponse | [
"Returns",
"the",
"most",
"pertinent",
"preview",
"URL",
"associated",
"to",
"the",
"resource",
"if",
"any",
"."
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/dataset/preview.py#L80-L91 | train |
opendatateam/udata | udata/utils.py | get_by | def get_by(lst, field, value):
'''Find an object in a list given a field value'''
for row in lst:
if ((isinstance(row, dict) and row.get(field) == value) or
(getattr(row, field, None) == value)):
return row | python | def get_by(lst, field, value):
'''Find an object in a list given a field value'''
for row in lst:
if ((isinstance(row, dict) and row.get(field) == value) or
(getattr(row, field, None) == value)):
return row | [
"def",
"get_by",
"(",
"lst",
",",
"field",
",",
"value",
")",
":",
"for",
"row",
"in",
"lst",
":",
"if",
"(",
"(",
"isinstance",
"(",
"row",
",",
"dict",
")",
"and",
"row",
".",
"get",
"(",
"field",
")",
"==",
"value",
")",
"or",
"(",
"getattr"... | Find an object in a list given a field value | [
"Find",
"an",
"object",
"in",
"a",
"list",
"given",
"a",
"field",
"value"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/utils.py#L22-L27 | train |
opendatateam/udata | udata/utils.py | multi_to_dict | def multi_to_dict(multi):
'''Transform a Werkzeug multidictionnary into a flat dictionnary'''
return dict(
(key, value[0] if len(value) == 1 else value)
for key, value in multi.to_dict(False).items()
) | python | def multi_to_dict(multi):
'''Transform a Werkzeug multidictionnary into a flat dictionnary'''
return dict(
(key, value[0] if len(value) == 1 else value)
for key, value in multi.to_dict(False).items()
) | [
"def",
"multi_to_dict",
"(",
"multi",
")",
":",
"return",
"dict",
"(",
"(",
"key",
",",
"value",
"[",
"0",
"]",
"if",
"len",
"(",
"value",
")",
"==",
"1",
"else",
"value",
")",
"for",
"key",
",",
"value",
"in",
"multi",
".",
"to_dict",
"(",
"Fals... | Transform a Werkzeug multidictionnary into a flat dictionnary | [
"Transform",
"a",
"Werkzeug",
"multidictionnary",
"into",
"a",
"flat",
"dictionnary"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/utils.py#L30-L35 | train |
opendatateam/udata | udata/utils.py | daterange_start | def daterange_start(value):
'''Parse a date range start boundary'''
if not value:
return None
elif isinstance(value, datetime):
return value.date()
elif isinstance(value, date):
return value
result = parse_dt(value).date()
dashes = value.count('-')
if dashes >= 2:
... | python | def daterange_start(value):
'''Parse a date range start boundary'''
if not value:
return None
elif isinstance(value, datetime):
return value.date()
elif isinstance(value, date):
return value
result = parse_dt(value).date()
dashes = value.count('-')
if dashes >= 2:
... | [
"def",
"daterange_start",
"(",
"value",
")",
":",
"if",
"not",
"value",
":",
"return",
"None",
"elif",
"isinstance",
"(",
"value",
",",
"datetime",
")",
":",
"return",
"value",
".",
"date",
"(",
")",
"elif",
"isinstance",
"(",
"value",
",",
"date",
")"... | Parse a date range start boundary | [
"Parse",
"a",
"date",
"range",
"start",
"boundary"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/utils.py#L100-L119 | train |
opendatateam/udata | udata/utils.py | daterange_end | def daterange_end(value):
'''Parse a date range end boundary'''
if not value:
return None
elif isinstance(value, datetime):
return value.date()
elif isinstance(value, date):
return value
result = parse_dt(value).date()
dashes = value.count('-')
if dashes >= 2:
... | python | def daterange_end(value):
'''Parse a date range end boundary'''
if not value:
return None
elif isinstance(value, datetime):
return value.date()
elif isinstance(value, date):
return value
result = parse_dt(value).date()
dashes = value.count('-')
if dashes >= 2:
... | [
"def",
"daterange_end",
"(",
"value",
")",
":",
"if",
"not",
"value",
":",
"return",
"None",
"elif",
"isinstance",
"(",
"value",
",",
"datetime",
")",
":",
"return",
"value",
".",
"date",
"(",
")",
"elif",
"isinstance",
"(",
"value",
",",
"date",
")",
... | Parse a date range end boundary | [
"Parse",
"a",
"date",
"range",
"end",
"boundary"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/utils.py#L122-L142 | train |
opendatateam/udata | udata/utils.py | to_iso | def to_iso(dt):
'''
Format a date or datetime into an ISO-8601 string
Support dates before 1900.
'''
if isinstance(dt, datetime):
return to_iso_datetime(dt)
elif isinstance(dt, date):
return to_iso_date(dt) | python | def to_iso(dt):
'''
Format a date or datetime into an ISO-8601 string
Support dates before 1900.
'''
if isinstance(dt, datetime):
return to_iso_datetime(dt)
elif isinstance(dt, date):
return to_iso_date(dt) | [
"def",
"to_iso",
"(",
"dt",
")",
":",
"if",
"isinstance",
"(",
"dt",
",",
"datetime",
")",
":",
"return",
"to_iso_datetime",
"(",
"dt",
")",
"elif",
"isinstance",
"(",
"dt",
",",
"date",
")",
":",
"return",
"to_iso_date",
"(",
"dt",
")"
] | Format a date or datetime into an ISO-8601 string
Support dates before 1900. | [
"Format",
"a",
"date",
"or",
"datetime",
"into",
"an",
"ISO",
"-",
"8601",
"string"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/utils.py#L145-L154 | train |
opendatateam/udata | udata/utils.py | to_iso_datetime | def to_iso_datetime(dt):
'''
Format a date or datetime into an ISO-8601 datetime string.
Time is set to 00:00:00 for dates.
Support dates before 1900.
'''
if dt:
date_str = to_iso_date(dt)
time_str = '{dt.hour:02d}:{dt.minute:02d}:{dt.second:02d}'.format(
dt=dt) if ... | python | def to_iso_datetime(dt):
'''
Format a date or datetime into an ISO-8601 datetime string.
Time is set to 00:00:00 for dates.
Support dates before 1900.
'''
if dt:
date_str = to_iso_date(dt)
time_str = '{dt.hour:02d}:{dt.minute:02d}:{dt.second:02d}'.format(
dt=dt) if ... | [
"def",
"to_iso_datetime",
"(",
"dt",
")",
":",
"if",
"dt",
":",
"date_str",
"=",
"to_iso_date",
"(",
"dt",
")",
"time_str",
"=",
"'{dt.hour:02d}:{dt.minute:02d}:{dt.second:02d}'",
".",
"format",
"(",
"dt",
"=",
"dt",
")",
"if",
"isinstance",
"(",
"dt",
",",
... | Format a date or datetime into an ISO-8601 datetime string.
Time is set to 00:00:00 for dates.
Support dates before 1900. | [
"Format",
"a",
"date",
"or",
"datetime",
"into",
"an",
"ISO",
"-",
"8601",
"datetime",
"string",
"."
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/utils.py#L167-L179 | train |
opendatateam/udata | udata/utils.py | recursive_get | def recursive_get(obj, key):
'''
Get an attribute or a key recursively.
:param obj: The object to fetch attribute or key on
:type obj: object|dict
:param key: Either a string in dotted-notation ar an array of string
:type key: string|list|tuple
'''
if not obj or not key:
return
... | python | def recursive_get(obj, key):
'''
Get an attribute or a key recursively.
:param obj: The object to fetch attribute or key on
:type obj: object|dict
:param key: Either a string in dotted-notation ar an array of string
:type key: string|list|tuple
'''
if not obj or not key:
return
... | [
"def",
"recursive_get",
"(",
"obj",
",",
"key",
")",
":",
"if",
"not",
"obj",
"or",
"not",
"key",
":",
"return",
"parts",
"=",
"key",
".",
"split",
"(",
"'.'",
")",
"if",
"isinstance",
"(",
"key",
",",
"basestring",
")",
"else",
"key",
"key",
"=",
... | Get an attribute or a key recursively.
:param obj: The object to fetch attribute or key on
:type obj: object|dict
:param key: Either a string in dotted-notation ar an array of string
:type key: string|list|tuple | [
"Get",
"an",
"attribute",
"or",
"a",
"key",
"recursively",
"."
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/utils.py#L218-L235 | train |
opendatateam/udata | udata/utils.py | unique_string | def unique_string(length=UUID_LENGTH):
'''Generate a unique string'''
# We need a string at least as long as length
string = str(uuid4()) * int(math.ceil(length / float(UUID_LENGTH)))
return string[:length] if length else string | python | def unique_string(length=UUID_LENGTH):
'''Generate a unique string'''
# We need a string at least as long as length
string = str(uuid4()) * int(math.ceil(length / float(UUID_LENGTH)))
return string[:length] if length else string | [
"def",
"unique_string",
"(",
"length",
"=",
"UUID_LENGTH",
")",
":",
"# We need a string at least as long as length",
"string",
"=",
"str",
"(",
"uuid4",
"(",
")",
")",
"*",
"int",
"(",
"math",
".",
"ceil",
"(",
"length",
"/",
"float",
"(",
"UUID_LENGTH",
")... | Generate a unique string | [
"Generate",
"a",
"unique",
"string"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/utils.py#L238-L242 | train |
opendatateam/udata | udata/utils.py | safe_unicode | def safe_unicode(string):
'''Safely transform any object into utf8 encoded bytes'''
if not isinstance(string, basestring):
string = unicode(string)
if isinstance(string, unicode):
string = string.encode('utf8')
return string | python | def safe_unicode(string):
'''Safely transform any object into utf8 encoded bytes'''
if not isinstance(string, basestring):
string = unicode(string)
if isinstance(string, unicode):
string = string.encode('utf8')
return string | [
"def",
"safe_unicode",
"(",
"string",
")",
":",
"if",
"not",
"isinstance",
"(",
"string",
",",
"basestring",
")",
":",
"string",
"=",
"unicode",
"(",
"string",
")",
"if",
"isinstance",
"(",
"string",
",",
"unicode",
")",
":",
"string",
"=",
"string",
"... | Safely transform any object into utf8 encoded bytes | [
"Safely",
"transform",
"any",
"object",
"into",
"utf8",
"encoded",
"bytes"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/utils.py#L277-L283 | train |
opendatateam/udata | udata/features/territories/views.py | redirect_territory | def redirect_territory(level, code):
"""
Implicit redirect given the INSEE code.
Optimistically redirect to the latest valid/known INSEE code.
"""
territory = GeoZone.objects.valid_at(datetime.now()).filter(
code=code, level='fr:{level}'.format(level=level)).first()
return redirect(url_... | python | def redirect_territory(level, code):
"""
Implicit redirect given the INSEE code.
Optimistically redirect to the latest valid/known INSEE code.
"""
territory = GeoZone.objects.valid_at(datetime.now()).filter(
code=code, level='fr:{level}'.format(level=level)).first()
return redirect(url_... | [
"def",
"redirect_territory",
"(",
"level",
",",
"code",
")",
":",
"territory",
"=",
"GeoZone",
".",
"objects",
".",
"valid_at",
"(",
"datetime",
".",
"now",
"(",
")",
")",
".",
"filter",
"(",
"code",
"=",
"code",
",",
"level",
"=",
"'fr:{level}'",
".",... | Implicit redirect given the INSEE code.
Optimistically redirect to the latest valid/known INSEE code. | [
"Implicit",
"redirect",
"given",
"the",
"INSEE",
"code",
"."
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/features/territories/views.py#L86-L94 | train |
opendatateam/udata | udata/core/jobs/commands.py | scheduled | def scheduled():
'''
List scheduled jobs.
'''
for job in sorted(schedulables(), key=lambda s: s.name):
for task in PeriodicTask.objects(task=job.name):
label = job_label(task.task, task.args, task.kwargs)
echo(SCHEDULE_LINE.format(
name=white(task.name.enc... | python | def scheduled():
'''
List scheduled jobs.
'''
for job in sorted(schedulables(), key=lambda s: s.name):
for task in PeriodicTask.objects(task=job.name):
label = job_label(task.task, task.args, task.kwargs)
echo(SCHEDULE_LINE.format(
name=white(task.name.enc... | [
"def",
"scheduled",
"(",
")",
":",
"for",
"job",
"in",
"sorted",
"(",
"schedulables",
"(",
")",
",",
"key",
"=",
"lambda",
"s",
":",
"s",
".",
"name",
")",
":",
"for",
"task",
"in",
"PeriodicTask",
".",
"objects",
"(",
"task",
"=",
"job",
".",
"n... | List scheduled jobs. | [
"List",
"scheduled",
"jobs",
"."
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/jobs/commands.py#L140-L151 | train |
opendatateam/udata | udata/commands/purge.py | purge | def purge(datasets, reuses, organizations):
'''
Permanently remove data flagged as deleted.
If no model flag is given, all models are purged.
'''
purge_all = not any((datasets, reuses, organizations))
if purge_all or datasets:
log.info('Purging datasets')
purge_datasets()
... | python | def purge(datasets, reuses, organizations):
'''
Permanently remove data flagged as deleted.
If no model flag is given, all models are purged.
'''
purge_all = not any((datasets, reuses, organizations))
if purge_all or datasets:
log.info('Purging datasets')
purge_datasets()
... | [
"def",
"purge",
"(",
"datasets",
",",
"reuses",
",",
"organizations",
")",
":",
"purge_all",
"=",
"not",
"any",
"(",
"(",
"datasets",
",",
"reuses",
",",
"organizations",
")",
")",
"if",
"purge_all",
"or",
"datasets",
":",
"log",
".",
"info",
"(",
"'Pu... | Permanently remove data flagged as deleted.
If no model flag is given, all models are purged. | [
"Permanently",
"remove",
"data",
"flagged",
"as",
"deleted",
"."
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/commands/purge.py#L21-L41 | train |
opendatateam/udata | udata/search/query.py | SearchQuery.clean_parameters | def clean_parameters(self, params):
'''Only keep known parameters'''
return {k: v for k, v in params.items() if k in self.adapter.facets} | python | def clean_parameters(self, params):
'''Only keep known parameters'''
return {k: v for k, v in params.items() if k in self.adapter.facets} | [
"def",
"clean_parameters",
"(",
"self",
",",
"params",
")",
":",
"return",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"params",
".",
"items",
"(",
")",
"if",
"k",
"in",
"self",
".",
"adapter",
".",
"facets",
"}"
] | Only keep known parameters | [
"Only",
"keep",
"known",
"parameters"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/search/query.py#L40-L42 | train |
opendatateam/udata | udata/search/query.py | SearchQuery.extract_sort | def extract_sort(self, params):
'''Extract and build sort query from parameters'''
sorts = params.pop('sort', [])
sorts = [sorts] if isinstance(sorts, basestring) else sorts
sorts = [(s[1:], 'desc')
if s.startswith('-') else (s, 'asc')
for s in sorts]
... | python | def extract_sort(self, params):
'''Extract and build sort query from parameters'''
sorts = params.pop('sort', [])
sorts = [sorts] if isinstance(sorts, basestring) else sorts
sorts = [(s[1:], 'desc')
if s.startswith('-') else (s, 'asc')
for s in sorts]
... | [
"def",
"extract_sort",
"(",
"self",
",",
"params",
")",
":",
"sorts",
"=",
"params",
".",
"pop",
"(",
"'sort'",
",",
"[",
"]",
")",
"sorts",
"=",
"[",
"sorts",
"]",
"if",
"isinstance",
"(",
"sorts",
",",
"basestring",
")",
"else",
"sorts",
"sorts",
... | Extract and build sort query from parameters | [
"Extract",
"and",
"build",
"sort",
"query",
"from",
"parameters"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/search/query.py#L44-L54 | train |
opendatateam/udata | udata/search/query.py | SearchQuery.extract_pagination | def extract_pagination(self, params):
'''Extract and build pagination from parameters'''
try:
params_page = int(params.pop('page', 1) or 1)
self.page = max(params_page, 1)
except:
# Failsafe, if page cannot be parsed, we falback on first page
self.... | python | def extract_pagination(self, params):
'''Extract and build pagination from parameters'''
try:
params_page = int(params.pop('page', 1) or 1)
self.page = max(params_page, 1)
except:
# Failsafe, if page cannot be parsed, we falback on first page
self.... | [
"def",
"extract_pagination",
"(",
"self",
",",
"params",
")",
":",
"try",
":",
"params_page",
"=",
"int",
"(",
"params",
".",
"pop",
"(",
"'page'",
",",
"1",
")",
"or",
"1",
")",
"self",
".",
"page",
"=",
"max",
"(",
"params_page",
",",
"1",
")",
... | Extract and build pagination from parameters | [
"Extract",
"and",
"build",
"pagination",
"from",
"parameters"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/search/query.py#L56-L71 | train |
opendatateam/udata | udata/search/query.py | SearchQuery.aggregate | def aggregate(self, search):
"""
Add aggregations representing the facets selected
"""
for f, facet in self.facets.items():
agg = facet.get_aggregation()
if isinstance(agg, Bucket):
search.aggs.bucket(f, agg)
elif isinstance(agg, Pipeli... | python | def aggregate(self, search):
"""
Add aggregations representing the facets selected
"""
for f, facet in self.facets.items():
agg = facet.get_aggregation()
if isinstance(agg, Bucket):
search.aggs.bucket(f, agg)
elif isinstance(agg, Pipeli... | [
"def",
"aggregate",
"(",
"self",
",",
"search",
")",
":",
"for",
"f",
",",
"facet",
"in",
"self",
".",
"facets",
".",
"items",
"(",
")",
":",
"agg",
"=",
"facet",
".",
"get_aggregation",
"(",
")",
"if",
"isinstance",
"(",
"agg",
",",
"Bucket",
")",... | Add aggregations representing the facets selected | [
"Add",
"aggregations",
"representing",
"the",
"facets",
"selected"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/search/query.py#L73-L84 | train |
opendatateam/udata | udata/search/query.py | SearchQuery.filter | def filter(self, search):
'''
Perform filtering instead of default post-filtering.
'''
if not self._filters:
return search
filters = Q('match_all')
for f in self._filters.values():
filters &= f
return search.filter(filters) | python | def filter(self, search):
'''
Perform filtering instead of default post-filtering.
'''
if not self._filters:
return search
filters = Q('match_all')
for f in self._filters.values():
filters &= f
return search.filter(filters) | [
"def",
"filter",
"(",
"self",
",",
"search",
")",
":",
"if",
"not",
"self",
".",
"_filters",
":",
"return",
"search",
"filters",
"=",
"Q",
"(",
"'match_all'",
")",
"for",
"f",
"in",
"self",
".",
"_filters",
".",
"values",
"(",
")",
":",
"filters",
... | Perform filtering instead of default post-filtering. | [
"Perform",
"filtering",
"instead",
"of",
"default",
"post",
"-",
"filtering",
"."
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/search/query.py#L86-L95 | train |
opendatateam/udata | udata/search/query.py | SearchQuery.query | def query(self, search, query):
'''
Customize the search query if necessary.
It handles the following features:
- negation support
- optional fuzziness
- optional analyzer
- optional match_type
'''
if not query:
return search
... | python | def query(self, search, query):
'''
Customize the search query if necessary.
It handles the following features:
- negation support
- optional fuzziness
- optional analyzer
- optional match_type
'''
if not query:
return search
... | [
"def",
"query",
"(",
"self",
",",
"search",
",",
"query",
")",
":",
"if",
"not",
"query",
":",
"return",
"search",
"included",
",",
"excluded",
"=",
"[",
"]",
",",
"[",
"]",
"for",
"term",
"in",
"query",
".",
"split",
"(",
"' '",
")",
":",
"if",
... | Customize the search query if necessary.
It handles the following features:
- negation support
- optional fuzziness
- optional analyzer
- optional match_type | [
"Customize",
"the",
"search",
"query",
"if",
"necessary",
"."
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/search/query.py#L114-L139 | train |
opendatateam/udata | udata/search/query.py | SearchQuery.to_url | def to_url(self, url=None, replace=False, **kwargs):
'''Serialize the query into an URL'''
params = copy.deepcopy(self.filter_values)
if self._query:
params['q'] = self._query
if self.page_size != DEFAULT_PAGE_SIZE:
params['page_size'] = self.page_size
if ... | python | def to_url(self, url=None, replace=False, **kwargs):
'''Serialize the query into an URL'''
params = copy.deepcopy(self.filter_values)
if self._query:
params['q'] = self._query
if self.page_size != DEFAULT_PAGE_SIZE:
params['page_size'] = self.page_size
if ... | [
"def",
"to_url",
"(",
"self",
",",
"url",
"=",
"None",
",",
"replace",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"filter_values",
")",
"if",
"self",
".",
"_query",
":",
"params",
"[",... | Serialize the query into an URL | [
"Serialize",
"the",
"query",
"into",
"an",
"URL"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/search/query.py#L169-L188 | train |
opendatateam/udata | udata/frontend/csv.py | safestr | def safestr(value):
'''Ensure type to string serialization'''
if not value or isinstance(value, (int, float, bool, long)):
return value
elif isinstance(value, (date, datetime)):
return value.isoformat()
else:
return unicode(value) | python | def safestr(value):
'''Ensure type to string serialization'''
if not value or isinstance(value, (int, float, bool, long)):
return value
elif isinstance(value, (date, datetime)):
return value.isoformat()
else:
return unicode(value) | [
"def",
"safestr",
"(",
"value",
")",
":",
"if",
"not",
"value",
"or",
"isinstance",
"(",
"value",
",",
"(",
"int",
",",
"float",
",",
"bool",
",",
"long",
")",
")",
":",
"return",
"value",
"elif",
"isinstance",
"(",
"value",
",",
"(",
"date",
",",
... | Ensure type to string serialization | [
"Ensure",
"type",
"to",
"string",
"serialization"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/frontend/csv.py#L30-L37 | train |
opendatateam/udata | udata/frontend/csv.py | yield_rows | def yield_rows(adapter):
'''Yield a dataset catalog line by line'''
csvfile = StringIO()
writer = get_writer(csvfile)
# Generate header
writer.writerow(adapter.header())
yield csvfile.getvalue()
del csvfile
for row in adapter.rows():
csvfile = StringIO()
writer = get_wri... | python | def yield_rows(adapter):
'''Yield a dataset catalog line by line'''
csvfile = StringIO()
writer = get_writer(csvfile)
# Generate header
writer.writerow(adapter.header())
yield csvfile.getvalue()
del csvfile
for row in adapter.rows():
csvfile = StringIO()
writer = get_wri... | [
"def",
"yield_rows",
"(",
"adapter",
")",
":",
"csvfile",
"=",
"StringIO",
"(",
")",
"writer",
"=",
"get_writer",
"(",
"csvfile",
")",
"# Generate header",
"writer",
".",
"writerow",
"(",
"adapter",
".",
"header",
"(",
")",
")",
"yield",
"csvfile",
".",
... | Yield a dataset catalog line by line | [
"Yield",
"a",
"dataset",
"catalog",
"line",
"by",
"line"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/frontend/csv.py#L206-L220 | train |
opendatateam/udata | udata/frontend/csv.py | stream | def stream(queryset_or_adapter, basename=None):
"""Stream a csv file from an object list,
a queryset or an instanciated adapter.
"""
if isinstance(queryset_or_adapter, Adapter):
adapter = queryset_or_adapter
elif isinstance(queryset_or_adapter, (list, tuple)):
if not queryset_or_ada... | python | def stream(queryset_or_adapter, basename=None):
"""Stream a csv file from an object list,
a queryset or an instanciated adapter.
"""
if isinstance(queryset_or_adapter, Adapter):
adapter = queryset_or_adapter
elif isinstance(queryset_or_adapter, (list, tuple)):
if not queryset_or_ada... | [
"def",
"stream",
"(",
"queryset_or_adapter",
",",
"basename",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"queryset_or_adapter",
",",
"Adapter",
")",
":",
"adapter",
"=",
"queryset_or_adapter",
"elif",
"isinstance",
"(",
"queryset_or_adapter",
",",
"(",
"lis... | Stream a csv file from an object list,
a queryset or an instanciated adapter. | [
"Stream",
"a",
"csv",
"file",
"from",
"an",
"object",
"list"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/frontend/csv.py#L223-L248 | train |
opendatateam/udata | udata/frontend/csv.py | NestedAdapter.header | def header(self):
'''Generate the CSV header row'''
return (super(NestedAdapter, self).header() +
[name for name, getter in self.get_nested_fields()]) | python | def header(self):
'''Generate the CSV header row'''
return (super(NestedAdapter, self).header() +
[name for name, getter in self.get_nested_fields()]) | [
"def",
"header",
"(",
"self",
")",
":",
"return",
"(",
"super",
"(",
"NestedAdapter",
",",
"self",
")",
".",
"header",
"(",
")",
"+",
"[",
"name",
"for",
"name",
",",
"getter",
"in",
"self",
".",
"get_nested_fields",
"(",
")",
"]",
")"
] | Generate the CSV header row | [
"Generate",
"the",
"CSV",
"header",
"row"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/frontend/csv.py#L114-L117 | train |
opendatateam/udata | udata/frontend/csv.py | NestedAdapter.rows | def rows(self):
'''Iterate over queryset objects'''
return (self.nested_row(o, n)
for o in self.queryset
for n in getattr(o, self.attribute, [])) | python | def rows(self):
'''Iterate over queryset objects'''
return (self.nested_row(o, n)
for o in self.queryset
for n in getattr(o, self.attribute, [])) | [
"def",
"rows",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"nested_row",
"(",
"o",
",",
"n",
")",
"for",
"o",
"in",
"self",
".",
"queryset",
"for",
"n",
"in",
"getattr",
"(",
"o",
",",
"self",
".",
"attribute",
",",
"[",
"]",
")",
")"
] | Iterate over queryset objects | [
"Iterate",
"over",
"queryset",
"objects"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/frontend/csv.py#L148-L152 | train |
opendatateam/udata | udata/frontend/csv.py | NestedAdapter.nested_row | def nested_row(self, obj, nested):
'''Convert an object into a flat csv row'''
row = self.to_row(obj)
for name, getter in self.get_nested_fields():
content = ''
if getter is not None:
try:
content = safestr(getter(nested))
... | python | def nested_row(self, obj, nested):
'''Convert an object into a flat csv row'''
row = self.to_row(obj)
for name, getter in self.get_nested_fields():
content = ''
if getter is not None:
try:
content = safestr(getter(nested))
... | [
"def",
"nested_row",
"(",
"self",
",",
"obj",
",",
"nested",
")",
":",
"row",
"=",
"self",
".",
"to_row",
"(",
"obj",
")",
"for",
"name",
",",
"getter",
"in",
"self",
".",
"get_nested_fields",
"(",
")",
":",
"content",
"=",
"''",
"if",
"getter",
"i... | Convert an object into a flat csv row | [
"Convert",
"an",
"object",
"into",
"a",
"flat",
"csv",
"row"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/frontend/csv.py#L154-L166 | train |
opendatateam/udata | udata/features/transfer/notifications.py | transfer_request_notifications | def transfer_request_notifications(user):
'''Notify user about pending transfer requests'''
orgs = [o for o in user.organizations if o.is_member(user)]
notifications = []
qs = Transfer.objects(recipient__in=[user] + orgs, status='pending')
# Only fetch required fields for notification serialization... | python | def transfer_request_notifications(user):
'''Notify user about pending transfer requests'''
orgs = [o for o in user.organizations if o.is_member(user)]
notifications = []
qs = Transfer.objects(recipient__in=[user] + orgs, status='pending')
# Only fetch required fields for notification serialization... | [
"def",
"transfer_request_notifications",
"(",
"user",
")",
":",
"orgs",
"=",
"[",
"o",
"for",
"o",
"in",
"user",
".",
"organizations",
"if",
"o",
".",
"is_member",
"(",
"user",
")",
"]",
"notifications",
"=",
"[",
"]",
"qs",
"=",
"Transfer",
".",
"obje... | Notify user about pending transfer requests | [
"Notify",
"user",
"about",
"pending",
"transfer",
"requests"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/features/transfer/notifications.py#L14-L35 | train |
opendatateam/udata | udata/mail.py | send | def send(subject, recipients, template_base, **kwargs):
'''
Send a given email to multiple recipients.
User prefered language is taken in account.
To translate the subject in the right language, you should ugettext_lazy
'''
sender = kwargs.pop('sender', None)
if not isinstance(recipients, (... | python | def send(subject, recipients, template_base, **kwargs):
'''
Send a given email to multiple recipients.
User prefered language is taken in account.
To translate the subject in the right language, you should ugettext_lazy
'''
sender = kwargs.pop('sender', None)
if not isinstance(recipients, (... | [
"def",
"send",
"(",
"subject",
",",
"recipients",
",",
"template_base",
",",
"*",
"*",
"kwargs",
")",
":",
"sender",
"=",
"kwargs",
".",
"pop",
"(",
"'sender'",
",",
"None",
")",
"if",
"not",
"isinstance",
"(",
"recipients",
",",
"(",
"list",
",",
"t... | Send a given email to multiple recipients.
User prefered language is taken in account.
To translate the subject in the right language, you should ugettext_lazy | [
"Send",
"a",
"given",
"email",
"to",
"multiple",
"recipients",
"."
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/mail.py#L40-L69 | train |
opendatateam/udata | udata/sentry.py | public_dsn | def public_dsn(dsn):
'''Transform a standard Sentry DSN into a public one'''
m = RE_DSN.match(dsn)
if not m:
log.error('Unable to parse Sentry DSN')
public = '{scheme}://{client_id}@{domain}/{site_id}'.format(
**m.groupdict())
return public | python | def public_dsn(dsn):
'''Transform a standard Sentry DSN into a public one'''
m = RE_DSN.match(dsn)
if not m:
log.error('Unable to parse Sentry DSN')
public = '{scheme}://{client_id}@{domain}/{site_id}'.format(
**m.groupdict())
return public | [
"def",
"public_dsn",
"(",
"dsn",
")",
":",
"m",
"=",
"RE_DSN",
".",
"match",
"(",
"dsn",
")",
"if",
"not",
"m",
":",
"log",
".",
"error",
"(",
"'Unable to parse Sentry DSN'",
")",
"public",
"=",
"'{scheme}://{client_id}@{domain}/{site_id}'",
".",
"format",
"... | Transform a standard Sentry DSN into a public one | [
"Transform",
"a",
"standard",
"Sentry",
"DSN",
"into",
"a",
"public",
"one"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/sentry.py#L24-L31 | train |
opendatateam/udata | tasks.py | update | def update(ctx, migrate=False):
'''Perform a development update'''
msg = 'Update all dependencies'
if migrate:
msg += ' and migrate data'
header(msg)
info('Updating Python dependencies')
lrun('pip install -r requirements/develop.pip')
lrun('pip install -e .')
info('Updating JavaS... | python | def update(ctx, migrate=False):
'''Perform a development update'''
msg = 'Update all dependencies'
if migrate:
msg += ' and migrate data'
header(msg)
info('Updating Python dependencies')
lrun('pip install -r requirements/develop.pip')
lrun('pip install -e .')
info('Updating JavaS... | [
"def",
"update",
"(",
"ctx",
",",
"migrate",
"=",
"False",
")",
":",
"msg",
"=",
"'Update all dependencies'",
"if",
"migrate",
":",
"msg",
"+=",
"' and migrate data'",
"header",
"(",
"msg",
")",
"info",
"(",
"'Updating Python dependencies'",
")",
"lrun",
"(",
... | Perform a development update | [
"Perform",
"a",
"development",
"update"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/tasks.py#L42-L55 | train |
opendatateam/udata | tasks.py | i18n | def i18n(ctx, update=False):
'''Extract translatable strings'''
header('Extract translatable strings')
info('Extract Python strings')
lrun('python setup.py extract_messages')
# Fix crowdin requiring Language with `2-digit` iso code in potfile
# to produce 2-digit iso code pofile
# Opening ... | python | def i18n(ctx, update=False):
'''Extract translatable strings'''
header('Extract translatable strings')
info('Extract Python strings')
lrun('python setup.py extract_messages')
# Fix crowdin requiring Language with `2-digit` iso code in potfile
# to produce 2-digit iso code pofile
# Opening ... | [
"def",
"i18n",
"(",
"ctx",
",",
"update",
"=",
"False",
")",
":",
"header",
"(",
"'Extract translatable strings'",
")",
"info",
"(",
"'Extract Python strings'",
")",
"lrun",
"(",
"'python setup.py extract_messages'",
")",
"# Fix crowdin requiring Language with `2-digit` i... | Extract translatable strings | [
"Extract",
"translatable",
"strings"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/tasks.py#L134-L197 | train |
opendatateam/udata | udata/api/__init__.py | output_json | def output_json(data, code, headers=None):
'''Use Flask JSON to serialize'''
resp = make_response(json.dumps(data), code)
resp.headers.extend(headers or {})
return resp | python | def output_json(data, code, headers=None):
'''Use Flask JSON to serialize'''
resp = make_response(json.dumps(data), code)
resp.headers.extend(headers or {})
return resp | [
"def",
"output_json",
"(",
"data",
",",
"code",
",",
"headers",
"=",
"None",
")",
":",
"resp",
"=",
"make_response",
"(",
"json",
".",
"dumps",
"(",
"data",
")",
",",
"code",
")",
"resp",
".",
"headers",
".",
"extend",
"(",
"headers",
"or",
"{",
"}... | Use Flask JSON to serialize | [
"Use",
"Flask",
"JSON",
"to",
"serialize"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/api/__init__.py#L191-L195 | train |
opendatateam/udata | udata/api/__init__.py | extract_name_from_path | def extract_name_from_path(path):
"""Return a readable name from a URL path.
Useful to log requests on Piwik with categories tree structure.
See: http://piwik.org/faq/how-to/#faq_62
"""
base_path, query_string = path.split('?')
infos = base_path.strip('/').split('/')[2:] # Removes api/version.... | python | def extract_name_from_path(path):
"""Return a readable name from a URL path.
Useful to log requests on Piwik with categories tree structure.
See: http://piwik.org/faq/how-to/#faq_62
"""
base_path, query_string = path.split('?')
infos = base_path.strip('/').split('/')[2:] # Removes api/version.... | [
"def",
"extract_name_from_path",
"(",
"path",
")",
":",
"base_path",
",",
"query_string",
"=",
"path",
".",
"split",
"(",
"'?'",
")",
"infos",
"=",
"base_path",
".",
"strip",
"(",
"'/'",
")",
".",
"split",
"(",
"'/'",
")",
"[",
"2",
":",
"]",
"# Remo... | Return a readable name from a URL path.
Useful to log requests on Piwik with categories tree structure.
See: http://piwik.org/faq/how-to/#faq_62 | [
"Return",
"a",
"readable",
"name",
"from",
"a",
"URL",
"path",
"."
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/api/__init__.py#L206-L221 | train |
opendatateam/udata | udata/api/__init__.py | handle_unauthorized_file_type | def handle_unauthorized_file_type(error):
'''Error occuring when the user try to upload a non-allowed file type'''
url = url_for('api.allowed_extensions', _external=True)
msg = (
'This file type is not allowed.'
'The allowed file type list is available at {url}'
).format(url=url)
ret... | python | def handle_unauthorized_file_type(error):
'''Error occuring when the user try to upload a non-allowed file type'''
url = url_for('api.allowed_extensions', _external=True)
msg = (
'This file type is not allowed.'
'The allowed file type list is available at {url}'
).format(url=url)
ret... | [
"def",
"handle_unauthorized_file_type",
"(",
"error",
")",
":",
"url",
"=",
"url_for",
"(",
"'api.allowed_extensions'",
",",
"_external",
"=",
"True",
")",
"msg",
"=",
"(",
"'This file type is not allowed.'",
"'The allowed file type list is available at {url}'",
")",
".",... | Error occuring when the user try to upload a non-allowed file type | [
"Error",
"occuring",
"when",
"the",
"user",
"try",
"to",
"upload",
"a",
"non",
"-",
"allowed",
"file",
"type"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/api/__init__.py#L259-L266 | train |
opendatateam/udata | udata/api/__init__.py | UDataApi.authentify | def authentify(self, func):
'''Authentify the user if credentials are given'''
@wraps(func)
def wrapper(*args, **kwargs):
if current_user.is_authenticated:
return func(*args, **kwargs)
apikey = request.headers.get(HEADER_API_KEY)
if apikey:
... | python | def authentify(self, func):
'''Authentify the user if credentials are given'''
@wraps(func)
def wrapper(*args, **kwargs):
if current_user.is_authenticated:
return func(*args, **kwargs)
apikey = request.headers.get(HEADER_API_KEY)
if apikey:
... | [
"def",
"authentify",
"(",
"self",
",",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"current_user",
".",
"is_authenticated",
":",
"return",
"func",
"(",
"*",
"args",
... | Authentify the user if credentials are given | [
"Authentify",
"the",
"user",
"if",
"credentials",
"are",
"given"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/api/__init__.py#L118-L137 | train |
opendatateam/udata | udata/api/__init__.py | UDataApi.validate | def validate(self, form_cls, obj=None):
'''Validate a form from the request and handle errors'''
if 'application/json' not in request.headers.get('Content-Type'):
errors = {'Content-Type': 'expecting application/json'}
self.abort(400, errors=errors)
form = form_cls.from_j... | python | def validate(self, form_cls, obj=None):
'''Validate a form from the request and handle errors'''
if 'application/json' not in request.headers.get('Content-Type'):
errors = {'Content-Type': 'expecting application/json'}
self.abort(400, errors=errors)
form = form_cls.from_j... | [
"def",
"validate",
"(",
"self",
",",
"form_cls",
",",
"obj",
"=",
"None",
")",
":",
"if",
"'application/json'",
"not",
"in",
"request",
".",
"headers",
".",
"get",
"(",
"'Content-Type'",
")",
":",
"errors",
"=",
"{",
"'Content-Type'",
":",
"'expecting appl... | Validate a form from the request and handle errors | [
"Validate",
"a",
"form",
"from",
"the",
"request",
"and",
"handle",
"errors"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/api/__init__.py#L139-L148 | train |
opendatateam/udata | udata/api/__init__.py | UDataApi.unauthorized | def unauthorized(self, response):
'''Override to change the WWW-Authenticate challenge'''
realm = current_app.config.get('HTTP_OAUTH_REALM', 'uData')
challenge = 'Bearer realm="{0}"'.format(realm)
response.headers['WWW-Authenticate'] = challenge
return response | python | def unauthorized(self, response):
'''Override to change the WWW-Authenticate challenge'''
realm = current_app.config.get('HTTP_OAUTH_REALM', 'uData')
challenge = 'Bearer realm="{0}"'.format(realm)
response.headers['WWW-Authenticate'] = challenge
return response | [
"def",
"unauthorized",
"(",
"self",
",",
"response",
")",
":",
"realm",
"=",
"current_app",
".",
"config",
".",
"get",
"(",
"'HTTP_OAUTH_REALM'",
",",
"'uData'",
")",
"challenge",
"=",
"'Bearer realm=\"{0}\"'",
".",
"format",
"(",
"realm",
")",
"response",
"... | Override to change the WWW-Authenticate challenge | [
"Override",
"to",
"change",
"the",
"WWW",
"-",
"Authenticate",
"challenge"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/api/__init__.py#L153-L159 | train |
opendatateam/udata | udata/core/followers/api.py | FollowAPI.get | def get(self, id):
'''List all followers for a given object'''
args = parser.parse_args()
model = self.model.objects.only('id').get_or_404(id=id)
qs = Follow.objects(following=model, until=None)
return qs.paginate(args['page'], args['page_size']) | python | def get(self, id):
'''List all followers for a given object'''
args = parser.parse_args()
model = self.model.objects.only('id').get_or_404(id=id)
qs = Follow.objects(following=model, until=None)
return qs.paginate(args['page'], args['page_size']) | [
"def",
"get",
"(",
"self",
",",
"id",
")",
":",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"model",
"=",
"self",
".",
"model",
".",
"objects",
".",
"only",
"(",
"'id'",
")",
".",
"get_or_404",
"(",
"id",
"=",
"id",
")",
"qs",
"=",
"Fol... | List all followers for a given object | [
"List",
"all",
"followers",
"for",
"a",
"given",
"object"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/followers/api.py#L47-L52 | train |
opendatateam/udata | udata/core/followers/api.py | FollowAPI.post | def post(self, id):
'''Follow an object given its ID'''
model = self.model.objects.only('id').get_or_404(id=id)
follow, created = Follow.objects.get_or_create(
follower=current_user.id, following=model, until=None)
count = Follow.objects.followers(model).count()
if no... | python | def post(self, id):
'''Follow an object given its ID'''
model = self.model.objects.only('id').get_or_404(id=id)
follow, created = Follow.objects.get_or_create(
follower=current_user.id, following=model, until=None)
count = Follow.objects.followers(model).count()
if no... | [
"def",
"post",
"(",
"self",
",",
"id",
")",
":",
"model",
"=",
"self",
".",
"model",
".",
"objects",
".",
"only",
"(",
"'id'",
")",
".",
"get_or_404",
"(",
"id",
"=",
"id",
")",
"follow",
",",
"created",
"=",
"Follow",
".",
"objects",
".",
"get_o... | Follow an object given its ID | [
"Follow",
"an",
"object",
"given",
"its",
"ID"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/followers/api.py#L56-L64 | train |
opendatateam/udata | udata/core/followers/api.py | FollowAPI.delete | def delete(self, id):
'''Unfollow an object given its ID'''
model = self.model.objects.only('id').get_or_404(id=id)
follow = Follow.objects.get_or_404(follower=current_user.id,
following=model,
until=None)
... | python | def delete(self, id):
'''Unfollow an object given its ID'''
model = self.model.objects.only('id').get_or_404(id=id)
follow = Follow.objects.get_or_404(follower=current_user.id,
following=model,
until=None)
... | [
"def",
"delete",
"(",
"self",
",",
"id",
")",
":",
"model",
"=",
"self",
".",
"model",
".",
"objects",
".",
"only",
"(",
"'id'",
")",
".",
"get_or_404",
"(",
"id",
"=",
"id",
")",
"follow",
"=",
"Follow",
".",
"objects",
".",
"get_or_404",
"(",
"... | Unfollow an object given its ID | [
"Unfollow",
"an",
"object",
"given",
"its",
"ID"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/followers/api.py#L68-L77 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.