id
int32
0
252k
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
14,400
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
14,401
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
14,402
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
14,403
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
14,404
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
14,405
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
14,406
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
14,407
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
14,408
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
14,409
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
14,410
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
14,411
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
14,412
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
14,413
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
14,414
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
14,415
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
14,416
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
14,417
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
14,418
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
14,419
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
14,420
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
14,421
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
14,422
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
14,423
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
14,424
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
14,425
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
14,426
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
14,427
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
14,428
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
14,429
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
14,430
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
14,431
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
14,432
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
14,433
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
14,434
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
14,435
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
14,436
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
14,437
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
14,438
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
14,439
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
14,440
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
14,441
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
14,442
opendatateam/udata
udata/commands/__init__.py
error
def error(msg, details=None): '''Display an error message with optional details''' msg = '{0} {1}'.format(red(KO), white(safe_unicode(msg))) msg = safe_unicode(msg) if details: msg = b'\n'.join((msg, safe_unicode(details))) echo(format_multiline(msg))
python
def error(msg, details=None): '''Display an error message with optional details''' msg = '{0} {1}'.format(red(KO), white(safe_unicode(msg))) msg = safe_unicode(msg) if details: msg = b'\n'.join((msg, safe_unicode(details))) echo(format_multiline(msg))
[ "def", "error", "(", "msg", ",", "details", "=", "None", ")", ":", "msg", "=", "'{0} {1}'", ".", "format", "(", "red", "(", "KO", ")", ",", "white", "(", "safe_unicode", "(", "msg", ")", ")", ")", "msg", "=", "safe_unicode", "(", "msg", ")", "if"...
Display an error message with optional details
[ "Display", "an", "error", "message", "with", "optional", "details" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/commands/__init__.py#L62-L68
14,443
opendatateam/udata
udata/commands/__init__.py
UdataGroup.main
def main(self, *args, **kwargs): ''' Instanciate ScriptInfo before parent does to ensure the `settings` parameters is available to `create_app ''' obj = kwargs.get('obj') if obj is None: obj = ScriptInfo(create_app=self.create_app) # This is the import...
python
def main(self, *args, **kwargs): ''' Instanciate ScriptInfo before parent does to ensure the `settings` parameters is available to `create_app ''' obj = kwargs.get('obj') if obj is None: obj = ScriptInfo(create_app=self.create_app) # This is the import...
[ "def", "main", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "obj", "=", "kwargs", ".", "get", "(", "'obj'", ")", "if", "obj", "is", "None", ":", "obj", "=", "ScriptInfo", "(", "create_app", "=", "self", ".", "create_app", ")"...
Instanciate ScriptInfo before parent does to ensure the `settings` parameters is available to `create_app
[ "Instanciate", "ScriptInfo", "before", "parent", "does", "to", "ensure", "the", "settings", "parameters", "is", "available", "to", "create_app" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/commands/__init__.py#L240-L251
14,444
opendatateam/udata
udata/entrypoints.py
get_plugins_dists
def get_plugins_dists(app, name=None): '''Return a list of Distributions with enabled udata plugins''' if name: plugins = set(e.name for e in iter_all(name) if e.name in app.config['PLUGINS']) else: plugins = set(app.config['PLUGINS']) return [ d for d in known_dists() if...
python
def get_plugins_dists(app, name=None): '''Return a list of Distributions with enabled udata plugins''' if name: plugins = set(e.name for e in iter_all(name) if e.name in app.config['PLUGINS']) else: plugins = set(app.config['PLUGINS']) return [ d for d in known_dists() if...
[ "def", "get_plugins_dists", "(", "app", ",", "name", "=", "None", ")", ":", "if", "name", ":", "plugins", "=", "set", "(", "e", ".", "name", "for", "e", "in", "iter_all", "(", "name", ")", "if", "e", ".", "name", "in", "app", ".", "config", "[", ...
Return a list of Distributions with enabled udata plugins
[ "Return", "a", "list", "of", "Distributions", "with", "enabled", "udata", "plugins" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/entrypoints.py#L64-L73
14,445
opendatateam/udata
udata/routing.py
lazy_raise_or_redirect
def lazy_raise_or_redirect(): ''' Raise exception lazily to ensure request.endpoint is set Also perform redirect if needed ''' if not request.view_args: return for name, value in request.view_args.items(): if isinstance(value, NotFound): request.routing_exception = va...
python
def lazy_raise_or_redirect(): ''' Raise exception lazily to ensure request.endpoint is set Also perform redirect if needed ''' if not request.view_args: return for name, value in request.view_args.items(): if isinstance(value, NotFound): request.routing_exception = va...
[ "def", "lazy_raise_or_redirect", "(", ")", ":", "if", "not", "request", ".", "view_args", ":", "return", "for", "name", ",", "value", "in", "request", ".", "view_args", ".", "items", "(", ")", ":", "if", "isinstance", "(", "value", ",", "NotFound", ")", ...
Raise exception lazily to ensure request.endpoint is set Also perform redirect if needed
[ "Raise", "exception", "lazily", "to", "ensure", "request", ".", "endpoint", "is", "set", "Also", "perform", "redirect", "if", "needed" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/routing.py#L199-L214
14,446
opendatateam/udata
udata/routing.py
TerritoryConverter.to_python
def to_python(self, value): """ `value` has slashs in it, that's why we inherit from `PathConverter`. E.g.: `commune/13200@latest/`, `departement/13@1860-07-01/` or `region/76@2016-01-01/Auvergne-Rhone-Alpes/`. Note that the slug is not significative but cannot be omitted. ...
python
def to_python(self, value): """ `value` has slashs in it, that's why we inherit from `PathConverter`. E.g.: `commune/13200@latest/`, `departement/13@1860-07-01/` or `region/76@2016-01-01/Auvergne-Rhone-Alpes/`. Note that the slug is not significative but cannot be omitted. ...
[ "def", "to_python", "(", "self", ",", "value", ")", ":", "if", "'/'", "not", "in", "value", ":", "return", "level", ",", "code", "=", "value", ".", "split", "(", "'/'", ")", "[", ":", "2", "]", "# Ignore optional slug", "geoid", "=", "GeoZone", ".", ...
`value` has slashs in it, that's why we inherit from `PathConverter`. E.g.: `commune/13200@latest/`, `departement/13@1860-07-01/` or `region/76@2016-01-01/Auvergne-Rhone-Alpes/`. Note that the slug is not significative but cannot be omitted.
[ "value", "has", "slashs", "in", "it", "that", "s", "why", "we", "inherit", "from", "PathConverter", "." ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/routing.py#L152-L175
14,447
opendatateam/udata
udata/routing.py
TerritoryConverter.to_url
def to_url(self, obj): """ Reconstruct the URL from level name, code or datagouv id and slug. """ level_name = getattr(obj, 'level_name', None) if not level_name: raise ValueError('Unable to serialize "%s" to url' % obj) code = getattr(obj, 'code', None) ...
python
def to_url(self, obj): """ Reconstruct the URL from level name, code or datagouv id and slug. """ level_name = getattr(obj, 'level_name', None) if not level_name: raise ValueError('Unable to serialize "%s" to url' % obj) code = getattr(obj, 'code', None) ...
[ "def", "to_url", "(", "self", ",", "obj", ")", ":", "level_name", "=", "getattr", "(", "obj", ",", "'level_name'", ",", "None", ")", "if", "not", "level_name", ":", "raise", "ValueError", "(", "'Unable to serialize \"%s\" to url'", "%", "obj", ")", "code", ...
Reconstruct the URL from level name, code or datagouv id and slug.
[ "Reconstruct", "the", "URL", "from", "level", "name", "code", "or", "datagouv", "id", "and", "slug", "." ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/routing.py#L177-L196
14,448
opendatateam/udata
udata/tasks.py
job
def job(name, **kwargs): '''A shortcut decorator for declaring jobs''' return task(name=name, schedulable=True, base=JobTask, bind=True, **kwargs)
python
def job(name, **kwargs): '''A shortcut decorator for declaring jobs''' return task(name=name, schedulable=True, base=JobTask, bind=True, **kwargs)
[ "def", "job", "(", "name", ",", "*", "*", "kwargs", ")", ":", "return", "task", "(", "name", "=", "name", ",", "schedulable", "=", "True", ",", "base", "=", "JobTask", ",", "bind", "=", "True", ",", "*", "*", "kwargs", ")" ]
A shortcut decorator for declaring jobs
[ "A", "shortcut", "decorator", "for", "declaring", "jobs" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/tasks.py#L80-L83
14,449
opendatateam/udata
udata/tasks.py
Scheduler.apply_async
def apply_async(self, entry, **kwargs): '''A MongoScheduler storing the last task_id''' result = super(Scheduler, self).apply_async(entry, **kwargs) entry._task.last_run_id = result.id return result
python
def apply_async(self, entry, **kwargs): '''A MongoScheduler storing the last task_id''' result = super(Scheduler, self).apply_async(entry, **kwargs) entry._task.last_run_id = result.id return result
[ "def", "apply_async", "(", "self", ",", "entry", ",", "*", "*", "kwargs", ")", ":", "result", "=", "super", "(", "Scheduler", ",", "self", ")", ".", "apply_async", "(", "entry", ",", "*", "*", "kwargs", ")", "entry", ".", "_task", ".", "last_run_id",...
A MongoScheduler storing the last task_id
[ "A", "MongoScheduler", "storing", "the", "last", "task_id" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/tasks.py#L40-L44
14,450
opendatateam/udata
udata/commands/info.py
config
def config(): '''Display some details about the local configuration''' if hasattr(current_app, 'settings_file'): log.info('Loaded configuration from %s', current_app.settings_file) log.info(white('Current configuration')) for key in sorted(current_app.config): if key.startswith('__') or...
python
def config(): '''Display some details about the local configuration''' if hasattr(current_app, 'settings_file'): log.info('Loaded configuration from %s', current_app.settings_file) log.info(white('Current configuration')) for key in sorted(current_app.config): if key.startswith('__') or...
[ "def", "config", "(", ")", ":", "if", "hasattr", "(", "current_app", ",", "'settings_file'", ")", ":", "log", ".", "info", "(", "'Loaded configuration from %s'", ",", "current_app", ".", "settings_file", ")", "log", ".", "info", "(", "white", "(", "'Current ...
Display some details about the local configuration
[ "Display", "some", "details", "about", "the", "local", "configuration" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/commands/info.py#L34-L43
14,451
opendatateam/udata
udata/commands/info.py
plugins
def plugins(): '''Display some details about the local plugins''' plugins = current_app.config['PLUGINS'] for name, description in entrypoints.ENTRYPOINTS.items(): echo('{0} ({1})'.format(white(description), name)) if name == 'udata.themes': actives = [current_app.config['THEME']...
python
def plugins(): '''Display some details about the local plugins''' plugins = current_app.config['PLUGINS'] for name, description in entrypoints.ENTRYPOINTS.items(): echo('{0} ({1})'.format(white(description), name)) if name == 'udata.themes': actives = [current_app.config['THEME']...
[ "def", "plugins", "(", ")", ":", "plugins", "=", "current_app", ".", "config", "[", "'PLUGINS'", "]", "for", "name", ",", "description", "in", "entrypoints", ".", "ENTRYPOINTS", ".", "items", "(", ")", ":", "echo", "(", "'{0} ({1})'", ".", "format", "(",...
Display some details about the local plugins
[ "Display", "some", "details", "about", "the", "local", "plugins" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/commands/info.py#L47-L59
14,452
opendatateam/udata
udata/frontend/views.py
BaseView.can
def can(self, *args, **kwargs): '''Overwrite this method to implement custom contextual permissions''' if isinstance(self.require, auth.Permission): return self.require.can() elif callable(self.require): return self.require() elif isinstance(self.require, bool): ...
python
def can(self, *args, **kwargs): '''Overwrite this method to implement custom contextual permissions''' if isinstance(self.require, auth.Permission): return self.require.can() elif callable(self.require): return self.require() elif isinstance(self.require, bool): ...
[ "def", "can", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "self", ".", "require", ",", "auth", ".", "Permission", ")", ":", "return", "self", ".", "require", ".", "can", "(", ")", "elif", "callable", ...
Overwrite this method to implement custom contextual permissions
[ "Overwrite", "this", "method", "to", "implement", "custom", "contextual", "permissions" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/frontend/views.py#L36-L45
14,453
opendatateam/udata
udata/core/storages/utils.py
extension
def extension(filename): '''Properly extract the extension from filename''' filename = os.path.basename(filename) extension = None while '.' in filename: filename, ext = os.path.splitext(filename) if ext.startswith('.'): ext = ext[1:] extension = ext if not extension...
python
def extension(filename): '''Properly extract the extension from filename''' filename = os.path.basename(filename) extension = None while '.' in filename: filename, ext = os.path.splitext(filename) if ext.startswith('.'): ext = ext[1:] extension = ext if not extension...
[ "def", "extension", "(", "filename", ")", ":", "filename", "=", "os", ".", "path", ".", "basename", "(", "filename", ")", "extension", "=", "None", "while", "'.'", "in", "filename", ":", "filename", ",", "ext", "=", "os", ".", "path", ".", "splitext", ...
Properly extract the extension from filename
[ "Properly", "extract", "the", "extension", "from", "filename" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/storages/utils.py#L48-L59
14,454
opendatateam/udata
udata/theme/__init__.py
theme_static_with_version
def theme_static_with_version(ctx, filename, external=False): '''Override the default theme static to add cache burst''' if current_app.theme_manager.static_folder: url = assets.cdn_for('_themes.static', filename=current.identifier + '/' + filename, ...
python
def theme_static_with_version(ctx, filename, external=False): '''Override the default theme static to add cache burst''' if current_app.theme_manager.static_folder: url = assets.cdn_for('_themes.static', filename=current.identifier + '/' + filename, ...
[ "def", "theme_static_with_version", "(", "ctx", ",", "filename", ",", "external", "=", "False", ")", ":", "if", "current_app", ".", "theme_manager", ".", "static_folder", ":", "url", "=", "assets", ".", "cdn_for", "(", "'_themes.static'", ",", "filename", "=",...
Override the default theme static to add cache burst
[ "Override", "the", "default", "theme", "static", "to", "add", "cache", "burst" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/theme/__init__.py#L48-L65
14,455
opendatateam/udata
udata/theme/__init__.py
render
def render(template, **context): ''' Render a template with uData frontend specifics * Theme ''' theme = current_app.config['THEME'] return render_theme_template(get_theme(theme), template, **context)
python
def render(template, **context): ''' Render a template with uData frontend specifics * Theme ''' theme = current_app.config['THEME'] return render_theme_template(get_theme(theme), template, **context)
[ "def", "render", "(", "template", ",", "*", "*", "context", ")", ":", "theme", "=", "current_app", ".", "config", "[", "'THEME'", "]", "return", "render_theme_template", "(", "get_theme", "(", "theme", ")", ",", "template", ",", "*", "*", "context", ")" ...
Render a template with uData frontend specifics * Theme
[ "Render", "a", "template", "with", "uData", "frontend", "specifics" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/theme/__init__.py#L141-L148
14,456
opendatateam/udata
udata/theme/__init__.py
context
def context(name): '''A decorator for theme context processors''' def wrapper(func): g.theme.context_processors[name] = func return func return wrapper
python
def context(name): '''A decorator for theme context processors''' def wrapper(func): g.theme.context_processors[name] = func return func return wrapper
[ "def", "context", "(", "name", ")", ":", "def", "wrapper", "(", "func", ")", ":", "g", ".", "theme", ".", "context_processors", "[", "name", "]", "=", "func", "return", "func", "return", "wrapper" ]
A decorator for theme context processors
[ "A", "decorator", "for", "theme", "context", "processors" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/theme/__init__.py#L159-L164
14,457
opendatateam/udata
udata/theme/__init__.py
ConfigurableTheme.variant
def variant(self): '''Get the current theme variant''' variant = current_app.config['THEME_VARIANT'] if variant not in self.variants: log.warning('Unkown theme variant: %s', variant) return 'default' else: return variant
python
def variant(self): '''Get the current theme variant''' variant = current_app.config['THEME_VARIANT'] if variant not in self.variants: log.warning('Unkown theme variant: %s', variant) return 'default' else: return variant
[ "def", "variant", "(", "self", ")", ":", "variant", "=", "current_app", ".", "config", "[", "'THEME_VARIANT'", "]", "if", "variant", "not", "in", "self", ".", "variants", ":", "log", ".", "warning", "(", "'Unkown theme variant: %s'", ",", "variant", ")", "...
Get the current theme variant
[ "Get", "the", "current", "theme", "variant" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/theme/__init__.py#L110-L117
14,458
opendatateam/udata
udata/core/dataset/views.py
resource_redirect
def resource_redirect(id): ''' Redirect to the latest version of a resource given its identifier. ''' resource = get_resource(id) return redirect(resource.url.strip()) if resource else abort(404)
python
def resource_redirect(id): ''' Redirect to the latest version of a resource given its identifier. ''' resource = get_resource(id) return redirect(resource.url.strip()) if resource else abort(404)
[ "def", "resource_redirect", "(", "id", ")", ":", "resource", "=", "get_resource", "(", "id", ")", "return", "redirect", "(", "resource", ".", "url", ".", "strip", "(", ")", ")", "if", "resource", "else", "abort", "(", "404", ")" ]
Redirect to the latest version of a resource given its identifier.
[ "Redirect", "to", "the", "latest", "version", "of", "a", "resource", "given", "its", "identifier", "." ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/dataset/views.py#L130-L135
14,459
opendatateam/udata
udata/core/dataset/views.py
group_resources_by_type
def group_resources_by_type(resources): """Group a list of `resources` by `type` with order""" groups = defaultdict(list) for resource in resources: groups[getattr(resource, 'type')].append(resource) ordered = OrderedDict() for rtype, rtype_label in RESOURCE_TYPES.items(): if groups[...
python
def group_resources_by_type(resources): """Group a list of `resources` by `type` with order""" groups = defaultdict(list) for resource in resources: groups[getattr(resource, 'type')].append(resource) ordered = OrderedDict() for rtype, rtype_label in RESOURCE_TYPES.items(): if groups[...
[ "def", "group_resources_by_type", "(", "resources", ")", ":", "groups", "=", "defaultdict", "(", "list", ")", "for", "resource", "in", "resources", ":", "groups", "[", "getattr", "(", "resource", ",", "'type'", ")", "]", ".", "append", "(", "resource", ")"...
Group a list of `resources` by `type` with order
[ "Group", "a", "list", "of", "resources", "by", "type", "with", "order" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/dataset/views.py#L166-L175
14,460
opendatateam/udata
udata/core/metrics/__init__.py
Metric.aggregate
def aggregate(self, start, end): ''' This method encpsualte the metric aggregation logic. Override this method when you inherit this class. By default, it takes the last value. ''' last = self.objects( level='daily', date__lte=self.iso(end), date__...
python
def aggregate(self, start, end): ''' This method encpsualte the metric aggregation logic. Override this method when you inherit this class. By default, it takes the last value. ''' last = self.objects( level='daily', date__lte=self.iso(end), date__...
[ "def", "aggregate", "(", "self", ",", "start", ",", "end", ")", ":", "last", "=", "self", ".", "objects", "(", "level", "=", "'daily'", ",", "date__lte", "=", "self", ".", "iso", "(", "end", ")", ",", "date__gte", "=", "self", ".", "iso", "(", "s...
This method encpsualte the metric aggregation logic. Override this method when you inherit this class. By default, it takes the last value.
[ "This", "method", "encpsualte", "the", "metric", "aggregation", "logic", ".", "Override", "this", "method", "when", "you", "inherit", "this", "class", ".", "By", "default", "it", "takes", "the", "last", "value", "." ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/metrics/__init__.py#L92-L101
14,461
opendatateam/udata
udata/harvest/actions.py
paginate_sources
def paginate_sources(owner=None, page=1, page_size=DEFAULT_PAGE_SIZE): '''Paginate harvest sources''' sources = _sources_queryset(owner=owner) page = max(page or 1, 1) return sources.paginate(page, page_size)
python
def paginate_sources(owner=None, page=1, page_size=DEFAULT_PAGE_SIZE): '''Paginate harvest sources''' sources = _sources_queryset(owner=owner) page = max(page or 1, 1) return sources.paginate(page, page_size)
[ "def", "paginate_sources", "(", "owner", "=", "None", ",", "page", "=", "1", ",", "page_size", "=", "DEFAULT_PAGE_SIZE", ")", ":", "sources", "=", "_sources_queryset", "(", "owner", "=", "owner", ")", "page", "=", "max", "(", "page", "or", "1", ",", "1...
Paginate harvest sources
[ "Paginate", "harvest", "sources" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/harvest/actions.py#L45-L49
14,462
opendatateam/udata
udata/harvest/actions.py
update_source
def update_source(ident, data): '''Update an harvest source''' source = get_source(ident) source.modify(**data) signals.harvest_source_updated.send(source) return source
python
def update_source(ident, data): '''Update an harvest source''' source = get_source(ident) source.modify(**data) signals.harvest_source_updated.send(source) return source
[ "def", "update_source", "(", "ident", ",", "data", ")", ":", "source", "=", "get_source", "(", "ident", ")", "source", ".", "modify", "(", "*", "*", "data", ")", "signals", ".", "harvest_source_updated", ".", "send", "(", "source", ")", "return", "source...
Update an harvest source
[ "Update", "an", "harvest", "source" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/harvest/actions.py#L90-L95
14,463
opendatateam/udata
udata/harvest/actions.py
validate_source
def validate_source(ident, comment=None): '''Validate a source for automatic harvesting''' source = get_source(ident) source.validation.on = datetime.now() source.validation.comment = comment source.validation.state = VALIDATION_ACCEPTED if current_user.is_authenticated: source.validatio...
python
def validate_source(ident, comment=None): '''Validate a source for automatic harvesting''' source = get_source(ident) source.validation.on = datetime.now() source.validation.comment = comment source.validation.state = VALIDATION_ACCEPTED if current_user.is_authenticated: source.validatio...
[ "def", "validate_source", "(", "ident", ",", "comment", "=", "None", ")", ":", "source", "=", "get_source", "(", "ident", ")", "source", ".", "validation", ".", "on", "=", "datetime", ".", "now", "(", ")", "source", ".", "validation", ".", "comment", "...
Validate a source for automatic harvesting
[ "Validate", "a", "source", "for", "automatic", "harvesting" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/harvest/actions.py#L98-L109
14,464
opendatateam/udata
udata/harvest/actions.py
reject_source
def reject_source(ident, comment): '''Reject a source for automatic harvesting''' source = get_source(ident) source.validation.on = datetime.now() source.validation.comment = comment source.validation.state = VALIDATION_REFUSED if current_user.is_authenticated: source.validation.by = cur...
python
def reject_source(ident, comment): '''Reject a source for automatic harvesting''' source = get_source(ident) source.validation.on = datetime.now() source.validation.comment = comment source.validation.state = VALIDATION_REFUSED if current_user.is_authenticated: source.validation.by = cur...
[ "def", "reject_source", "(", "ident", ",", "comment", ")", ":", "source", "=", "get_source", "(", "ident", ")", "source", ".", "validation", ".", "on", "=", "datetime", ".", "now", "(", ")", "source", ".", "validation", ".", "comment", "=", "comment", ...
Reject a source for automatic harvesting
[ "Reject", "a", "source", "for", "automatic", "harvesting" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/harvest/actions.py#L112-L121
14,465
opendatateam/udata
udata/harvest/actions.py
delete_source
def delete_source(ident): '''Delete an harvest source''' source = get_source(ident) source.deleted = datetime.now() source.save() signals.harvest_source_deleted.send(source) return source
python
def delete_source(ident): '''Delete an harvest source''' source = get_source(ident) source.deleted = datetime.now() source.save() signals.harvest_source_deleted.send(source) return source
[ "def", "delete_source", "(", "ident", ")", ":", "source", "=", "get_source", "(", "ident", ")", "source", ".", "deleted", "=", "datetime", ".", "now", "(", ")", "source", ".", "save", "(", ")", "signals", ".", "harvest_source_deleted", ".", "send", "(", ...
Delete an harvest source
[ "Delete", "an", "harvest", "source" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/harvest/actions.py#L124-L130
14,466
opendatateam/udata
udata/harvest/actions.py
run
def run(ident): '''Launch or resume an harvesting for a given source if none is running''' source = get_source(ident) cls = backends.get(current_app, source.backend) backend = cls(source) backend.harvest()
python
def run(ident): '''Launch or resume an harvesting for a given source if none is running''' source = get_source(ident) cls = backends.get(current_app, source.backend) backend = cls(source) backend.harvest()
[ "def", "run", "(", "ident", ")", ":", "source", "=", "get_source", "(", "ident", ")", "cls", "=", "backends", ".", "get", "(", "current_app", ",", "source", ".", "backend", ")", "backend", "=", "cls", "(", "source", ")", "backend", ".", "harvest", "(...
Launch or resume an harvesting for a given source if none is running
[ "Launch", "or", "resume", "an", "harvesting", "for", "a", "given", "source", "if", "none", "is", "running" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/harvest/actions.py#L138-L143
14,467
opendatateam/udata
udata/harvest/actions.py
preview
def preview(ident): '''Preview an harvesting for a given source''' source = get_source(ident) cls = backends.get(current_app, source.backend) max_items = current_app.config['HARVEST_PREVIEW_MAX_ITEMS'] backend = cls(source, dryrun=True, max_items=max_items) return backend.harvest()
python
def preview(ident): '''Preview an harvesting for a given source''' source = get_source(ident) cls = backends.get(current_app, source.backend) max_items = current_app.config['HARVEST_PREVIEW_MAX_ITEMS'] backend = cls(source, dryrun=True, max_items=max_items) return backend.harvest()
[ "def", "preview", "(", "ident", ")", ":", "source", "=", "get_source", "(", "ident", ")", "cls", "=", "backends", ".", "get", "(", "current_app", ",", "source", ".", "backend", ")", "max_items", "=", "current_app", ".", "config", "[", "'HARVEST_PREVIEW_MAX...
Preview an harvesting for a given source
[ "Preview", "an", "harvesting", "for", "a", "given", "source" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/harvest/actions.py#L151-L157
14,468
opendatateam/udata
udata/harvest/actions.py
preview_from_config
def preview_from_config(name, url, backend, description=None, frequency=DEFAULT_HARVEST_FREQUENCY, owner=None, organization=None, config=None, ): '''Preview an harvesting f...
python
def preview_from_config(name, url, backend, description=None, frequency=DEFAULT_HARVEST_FREQUENCY, owner=None, organization=None, config=None, ): '''Preview an harvesting f...
[ "def", "preview_from_config", "(", "name", ",", "url", ",", "backend", ",", "description", "=", "None", ",", "frequency", "=", "DEFAULT_HARVEST_FREQUENCY", ",", "owner", "=", "None", ",", "organization", "=", "None", ",", "config", "=", "None", ",", ")", "...
Preview an harvesting from a source created with the given parameters
[ "Preview", "an", "harvesting", "from", "a", "source", "created", "with", "the", "given", "parameters" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/harvest/actions.py#L160-L187
14,469
opendatateam/udata
udata/harvest/actions.py
schedule
def schedule(ident, cron=None, minute='*', hour='*', day_of_week='*', day_of_month='*', month_of_year='*'): '''Schedule an harvesting on a source given a crontab''' source = get_source(ident) if cron: minute, hour, day_of_month, month_of_year, day_of_week = cron.split() crontab = ...
python
def schedule(ident, cron=None, minute='*', hour='*', day_of_week='*', day_of_month='*', month_of_year='*'): '''Schedule an harvesting on a source given a crontab''' source = get_source(ident) if cron: minute, hour, day_of_month, month_of_year, day_of_week = cron.split() crontab = ...
[ "def", "schedule", "(", "ident", ",", "cron", "=", "None", ",", "minute", "=", "'*'", ",", "hour", "=", "'*'", ",", "day_of_week", "=", "'*'", ",", "day_of_month", "=", "'*'", ",", "month_of_year", "=", "'*'", ")", ":", "source", "=", "get_source", "...
Schedule an harvesting on a source given a crontab
[ "Schedule", "an", "harvesting", "on", "a", "source", "given", "a", "crontab" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/harvest/actions.py#L190-L218
14,470
opendatateam/udata
udata/harvest/actions.py
unschedule
def unschedule(ident): '''Unschedule an harvesting on a source''' source = get_source(ident) if not source.periodic_task: msg = 'Harvesting on source {0} is ot scheduled'.format(source.name) raise ValueError(msg) source.periodic_task.delete() signals.harvest_source_unscheduled.send(...
python
def unschedule(ident): '''Unschedule an harvesting on a source''' source = get_source(ident) if not source.periodic_task: msg = 'Harvesting on source {0} is ot scheduled'.format(source.name) raise ValueError(msg) source.periodic_task.delete() signals.harvest_source_unscheduled.send(...
[ "def", "unschedule", "(", "ident", ")", ":", "source", "=", "get_source", "(", "ident", ")", "if", "not", "source", ".", "periodic_task", ":", "msg", "=", "'Harvesting on source {0} is ot scheduled'", ".", "format", "(", "source", ".", "name", ")", "raise", ...
Unschedule an harvesting on a source
[ "Unschedule", "an", "harvesting", "on", "a", "source" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/harvest/actions.py#L221-L230
14,471
opendatateam/udata
udata/harvest/actions.py
attach
def attach(domain, filename): '''Attach existing dataset to their harvest remote id before harvesting. The expected csv file format is the following: - a column with header "local" and the local IDs or slugs - a column with header "remote" and the remote IDs The delimiter should be ";". columns o...
python
def attach(domain, filename): '''Attach existing dataset to their harvest remote id before harvesting. The expected csv file format is the following: - a column with header "local" and the local IDs or slugs - a column with header "remote" and the remote IDs The delimiter should be ";". columns o...
[ "def", "attach", "(", "domain", ",", "filename", ")", ":", "count", "=", "0", "errors", "=", "0", "with", "open", "(", "filename", ")", "as", "csvfile", ":", "reader", "=", "csv", ".", "DictReader", "(", "csvfile", ",", "delimiter", "=", "b';'", ",",...
Attach existing dataset to their harvest remote id before harvesting. The expected csv file format is the following: - a column with header "local" and the local IDs or slugs - a column with header "remote" and the remote IDs The delimiter should be ";". columns order and extras columns does not ...
[ "Attach", "existing", "dataset", "to", "their", "harvest", "remote", "id", "before", "harvesting", "." ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/harvest/actions.py#L236-L276
14,472
opendatateam/udata
udata/models/extras_fields.py
ExtrasField.register
def register(self, key, dbtype): '''Register a DB type to add constraint on a given extra key''' if not issubclass(dbtype, (BaseField, EmbeddedDocument)): msg = 'ExtrasField can only register MongoEngine fields' raise TypeError(msg) self.registered[key] = dbtype
python
def register(self, key, dbtype): '''Register a DB type to add constraint on a given extra key''' if not issubclass(dbtype, (BaseField, EmbeddedDocument)): msg = 'ExtrasField can only register MongoEngine fields' raise TypeError(msg) self.registered[key] = dbtype
[ "def", "register", "(", "self", ",", "key", ",", "dbtype", ")", ":", "if", "not", "issubclass", "(", "dbtype", ",", "(", "BaseField", ",", "EmbeddedDocument", ")", ")", ":", "msg", "=", "'ExtrasField can only register MongoEngine fields'", "raise", "TypeError", ...
Register a DB type to add constraint on a given extra key
[ "Register", "a", "DB", "type", "to", "add", "constraint", "on", "a", "given", "extra", "key" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/models/extras_fields.py#L22-L27
14,473
opendatateam/udata
udata/core/user/commands.py
delete
def delete(): '''Delete an existing user''' email = click.prompt('Email') user = User.objects(email=email).first() if not user: exit_with_error('Invalid user') user.delete() success('User deleted successfully')
python
def delete(): '''Delete an existing user''' email = click.prompt('Email') user = User.objects(email=email).first() if not user: exit_with_error('Invalid user') user.delete() success('User deleted successfully')
[ "def", "delete", "(", ")", ":", "email", "=", "click", ".", "prompt", "(", "'Email'", ")", "user", "=", "User", ".", "objects", "(", "email", "=", "email", ")", ".", "first", "(", ")", "if", "not", "user", ":", "exit_with_error", "(", "'Invalid user'...
Delete an existing user
[ "Delete", "an", "existing", "user" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/user/commands.py#L66-L73
14,474
opendatateam/udata
udata/core/user/commands.py
set_admin
def set_admin(email): '''Set an user as administrator''' user = datastore.get_user(email) log.info('Adding admin role to user %s (%s)', user.fullname, user.email) role = datastore.find_or_create_role('admin') datastore.add_role_to_user(user, role) success('User %s (%s) is now administrator' % (u...
python
def set_admin(email): '''Set an user as administrator''' user = datastore.get_user(email) log.info('Adding admin role to user %s (%s)', user.fullname, user.email) role = datastore.find_or_create_role('admin') datastore.add_role_to_user(user, role) success('User %s (%s) is now administrator' % (u...
[ "def", "set_admin", "(", "email", ")", ":", "user", "=", "datastore", ".", "get_user", "(", "email", ")", "log", ".", "info", "(", "'Adding admin role to user %s (%s)'", ",", "user", ".", "fullname", ",", "user", ".", "email", ")", "role", "=", "datastore"...
Set an user as administrator
[ "Set", "an", "user", "as", "administrator" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/user/commands.py#L78-L84
14,475
opendatateam/udata
udata/core/storages/api.py
combine_chunks
def combine_chunks(storage, args, prefix=None): ''' Combine a chunked file into a whole file again. Goes through each part, in order, and appends that part's bytes to another destination file. Chunks are stored in the chunks storage. ''' uuid = args['uuid'] # Normalize filename including...
python
def combine_chunks(storage, args, prefix=None): ''' Combine a chunked file into a whole file again. Goes through each part, in order, and appends that part's bytes to another destination file. Chunks are stored in the chunks storage. ''' uuid = args['uuid'] # Normalize filename including...
[ "def", "combine_chunks", "(", "storage", ",", "args", ",", "prefix", "=", "None", ")", ":", "uuid", "=", "args", "[", "'uuid'", "]", "# Normalize filename including extension", "target", "=", "utils", ".", "normalize", "(", "args", "[", "'filename'", "]", ")...
Combine a chunked file into a whole file again. Goes through each part, in order, and appends that part's bytes to another destination file. Chunks are stored in the chunks storage.
[ "Combine", "a", "chunked", "file", "into", "a", "whole", "file", "again", ".", "Goes", "through", "each", "part", "in", "order", "and", "appends", "that", "part", "s", "bytes", "to", "another", "destination", "file", ".", "Chunks", "are", "stored", "in", ...
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/storages/api.py#L111-L129
14,476
opendatateam/udata
udata/models/__init__.py
UDataMongoEngine.resolve_model
def resolve_model(self, model): ''' Resolve a model given a name or dict with `class` entry. :raises ValueError: model specification is wrong or does not exists ''' if not model: raise ValueError('Unsupported model specifications') if isinstance(model, basest...
python
def resolve_model(self, model): ''' Resolve a model given a name or dict with `class` entry. :raises ValueError: model specification is wrong or does not exists ''' if not model: raise ValueError('Unsupported model specifications') if isinstance(model, basest...
[ "def", "resolve_model", "(", "self", ",", "model", ")", ":", "if", "not", "model", ":", "raise", "ValueError", "(", "'Unsupported model specifications'", ")", "if", "isinstance", "(", "model", ",", "basestring", ")", ":", "classname", "=", "model", "elif", "...
Resolve a model given a name or dict with `class` entry. :raises ValueError: model specification is wrong or does not exists
[ "Resolve", "a", "model", "given", "a", "name", "or", "dict", "with", "class", "entry", "." ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/models/__init__.py#L60-L79
14,477
opendatateam/udata
udata/frontend/helpers.py
tooltip_ellipsis
def tooltip_ellipsis(source, length=0): ''' return the plain text representation of markdown encoded text. That is the texted without any html tags. If ``length`` is 0 then it will not be truncated.''' try: length = int(length) except ValueError: # invalid literal for int() return...
python
def tooltip_ellipsis(source, length=0): ''' return the plain text representation of markdown encoded text. That is the texted without any html tags. If ``length`` is 0 then it will not be truncated.''' try: length = int(length) except ValueError: # invalid literal for int() return...
[ "def", "tooltip_ellipsis", "(", "source", ",", "length", "=", "0", ")", ":", "try", ":", "length", "=", "int", "(", "length", ")", "except", "ValueError", ":", "# invalid literal for int()", "return", "source", "# Fail silently.", "ellipsis", "=", "'<a href v-to...
return the plain text representation of markdown encoded text. That is the texted without any html tags. If ``length`` is 0 then it will not be truncated.
[ "return", "the", "plain", "text", "representation", "of", "markdown", "encoded", "text", ".", "That", "is", "the", "texted", "without", "any", "html", "tags", ".", "If", "length", "is", "0", "then", "it", "will", "not", "be", "truncated", "." ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/frontend/helpers.py#L254-L264
14,478
opendatateam/udata
udata/frontend/helpers.py
filesize
def filesize(value): '''Display a human readable filesize''' suffix = 'o' for unit in '', 'K', 'M', 'G', 'T', 'P', 'E', 'Z': if abs(value) < 1024.0: return "%3.1f%s%s" % (value, unit, suffix) value /= 1024.0 return "%.1f%s%s" % (value, 'Y', suffix)
python
def filesize(value): '''Display a human readable filesize''' suffix = 'o' for unit in '', 'K', 'M', 'G', 'T', 'P', 'E', 'Z': if abs(value) < 1024.0: return "%3.1f%s%s" % (value, unit, suffix) value /= 1024.0 return "%.1f%s%s" % (value, 'Y', suffix)
[ "def", "filesize", "(", "value", ")", ":", "suffix", "=", "'o'", "for", "unit", "in", "''", ",", "'K'", ",", "'M'", ",", "'G'", ",", "'T'", ",", "'P'", ",", "'E'", ",", "'Z'", ":", "if", "abs", "(", "value", ")", "<", "1024.0", ":", "return", ...
Display a human readable filesize
[ "Display", "a", "human", "readable", "filesize" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/frontend/helpers.py#L399-L406
14,479
opendatateam/udata
udata/rdf.py
negociate_content
def negociate_content(default='json-ld'): '''Perform a content negociation on the format given the Accept header''' mimetype = request.accept_mimetypes.best_match(ACCEPTED_MIME_TYPES.keys()) return ACCEPTED_MIME_TYPES.get(mimetype, default)
python
def negociate_content(default='json-ld'): '''Perform a content negociation on the format given the Accept header''' mimetype = request.accept_mimetypes.best_match(ACCEPTED_MIME_TYPES.keys()) return ACCEPTED_MIME_TYPES.get(mimetype, default)
[ "def", "negociate_content", "(", "default", "=", "'json-ld'", ")", ":", "mimetype", "=", "request", ".", "accept_mimetypes", ".", "best_match", "(", "ACCEPTED_MIME_TYPES", ".", "keys", "(", ")", ")", "return", "ACCEPTED_MIME_TYPES", ".", "get", "(", "mimetype", ...
Perform a content negociation on the format given the Accept header
[ "Perform", "a", "content", "negociation", "on", "the", "format", "given", "the", "Accept", "header" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/rdf.py#L97-L100
14,480
opendatateam/udata
udata/rdf.py
url_from_rdf
def url_from_rdf(rdf, prop): ''' Try to extract An URL from a resource property. It can be expressed in many forms as a URIRef or a Literal ''' value = rdf.value(prop) if isinstance(value, (URIRef, Literal)): return value.toPython() elif isinstance(value, RdfResource): return...
python
def url_from_rdf(rdf, prop): ''' Try to extract An URL from a resource property. It can be expressed in many forms as a URIRef or a Literal ''' value = rdf.value(prop) if isinstance(value, (URIRef, Literal)): return value.toPython() elif isinstance(value, RdfResource): return...
[ "def", "url_from_rdf", "(", "rdf", ",", "prop", ")", ":", "value", "=", "rdf", ".", "value", "(", "prop", ")", "if", "isinstance", "(", "value", ",", "(", "URIRef", ",", "Literal", ")", ")", ":", "return", "value", ".", "toPython", "(", ")", "elif"...
Try to extract An URL from a resource property. It can be expressed in many forms as a URIRef or a Literal
[ "Try", "to", "extract", "An", "URL", "from", "a", "resource", "property", ".", "It", "can", "be", "expressed", "in", "many", "forms", "as", "a", "URIRef", "or", "a", "Literal" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/rdf.py#L224-L233
14,481
opendatateam/udata
udata/rdf.py
graph_response
def graph_response(graph, format): ''' Return a proper flask response for a RDF resource given an expected format. ''' fmt = guess_format(format) if not fmt: abort(404) headers = { 'Content-Type': RDF_MIME_TYPES[fmt] } kwargs = {} if fmt == 'json-ld': kwargs['...
python
def graph_response(graph, format): ''' Return a proper flask response for a RDF resource given an expected format. ''' fmt = guess_format(format) if not fmt: abort(404) headers = { 'Content-Type': RDF_MIME_TYPES[fmt] } kwargs = {} if fmt == 'json-ld': kwargs['...
[ "def", "graph_response", "(", "graph", ",", "format", ")", ":", "fmt", "=", "guess_format", "(", "format", ")", "if", "not", "fmt", ":", "abort", "(", "404", ")", "headers", "=", "{", "'Content-Type'", ":", "RDF_MIME_TYPES", "[", "fmt", "]", "}", "kwar...
Return a proper flask response for a RDF resource given an expected format.
[ "Return", "a", "proper", "flask", "response", "for", "a", "RDF", "resource", "given", "an", "expected", "format", "." ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/rdf.py#L236-L251
14,482
opendatateam/udata
udata/core/spatial/models.py
GeoZoneQuerySet.valid_at
def valid_at(self, valid_date): '''Limit current QuerySet to zone valid at a given date''' is_valid = db.Q(validity__end__gt=valid_date, validity__start__lte=valid_date) no_validity = db.Q(validity=None) return self(is_valid | no_validity)
python
def valid_at(self, valid_date): '''Limit current QuerySet to zone valid at a given date''' is_valid = db.Q(validity__end__gt=valid_date, validity__start__lte=valid_date) no_validity = db.Q(validity=None) return self(is_valid | no_validity)
[ "def", "valid_at", "(", "self", ",", "valid_date", ")", ":", "is_valid", "=", "db", ".", "Q", "(", "validity__end__gt", "=", "valid_date", ",", "validity__start__lte", "=", "valid_date", ")", "no_validity", "=", "db", ".", "Q", "(", "validity", "=", "None"...
Limit current QuerySet to zone valid at a given date
[ "Limit", "current", "QuerySet", "to", "zone", "valid", "at", "a", "given", "date" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/spatial/models.py#L44-L49
14,483
opendatateam/udata
udata/core/spatial/models.py
GeoZoneQuerySet.resolve
def resolve(self, geoid, id_only=False): ''' Resolve a GeoZone given a GeoID. The start date is resolved from the given GeoID, ie. it find there is a zone valid a the geoid validity, resolve the `latest` alias or use `latest` when no validity is given. If `id_on...
python
def resolve(self, geoid, id_only=False): ''' Resolve a GeoZone given a GeoID. The start date is resolved from the given GeoID, ie. it find there is a zone valid a the geoid validity, resolve the `latest` alias or use `latest` when no validity is given. If `id_on...
[ "def", "resolve", "(", "self", ",", "geoid", ",", "id_only", "=", "False", ")", ":", "level", ",", "code", ",", "validity", "=", "geoids", ".", "parse", "(", "geoid", ")", "qs", "=", "self", "(", "level", "=", "level", ",", "code", "=", "code", "...
Resolve a GeoZone given a GeoID. The start date is resolved from the given GeoID, ie. it find there is a zone valid a the geoid validity, resolve the `latest` alias or use `latest` when no validity is given. If `id_only` is True, the result will be the resolved GeoID ...
[ "Resolve", "a", "GeoZone", "given", "a", "GeoID", "." ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/spatial/models.py#L60-L81
14,484
opendatateam/udata
udata/core/spatial/models.py
GeoZone.keys_values
def keys_values(self): """Key values might be a list or not, always return a list.""" keys_values = [] for value in self.keys.values(): if isinstance(value, list): keys_values += value elif isinstance(value, basestring) and not value.startswith('-'): ...
python
def keys_values(self): """Key values might be a list or not, always return a list.""" keys_values = [] for value in self.keys.values(): if isinstance(value, list): keys_values += value elif isinstance(value, basestring) and not value.startswith('-'): ...
[ "def", "keys_values", "(", "self", ")", ":", "keys_values", "=", "[", "]", "for", "value", "in", "self", ".", "keys", ".", "values", "(", ")", ":", "if", "isinstance", "(", "value", ",", "list", ")", ":", "keys_values", "+=", "value", "elif", "isinst...
Key values might be a list or not, always return a list.
[ "Key", "values", "might", "be", "a", "list", "or", "not", "always", "return", "a", "list", "." ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/spatial/models.py#L134-L146
14,485
opendatateam/udata
udata/core/spatial/models.py
GeoZone.level_i18n_name
def level_i18n_name(self): """In use within templates for dynamic translations.""" for level, name in spatial_granularities: if self.level == level: return name return self.level_name
python
def level_i18n_name(self): """In use within templates for dynamic translations.""" for level, name in spatial_granularities: if self.level == level: return name return self.level_name
[ "def", "level_i18n_name", "(", "self", ")", ":", "for", "level", ",", "name", "in", "spatial_granularities", ":", "if", "self", ".", "level", "==", "level", ":", "return", "name", "return", "self", ".", "level_name" ]
In use within templates for dynamic translations.
[ "In", "use", "within", "templates", "for", "dynamic", "translations", "." ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/spatial/models.py#L164-L169
14,486
opendatateam/udata
udata/core/spatial/models.py
GeoZone.ancestors_objects
def ancestors_objects(self): """Ancestors objects sorted by name.""" ancestors_objects = [] for ancestor in self.ancestors: try: ancestor_object = GeoZone.objects.get(id=ancestor) except GeoZone.DoesNotExist: continue ancestors_...
python
def ancestors_objects(self): """Ancestors objects sorted by name.""" ancestors_objects = [] for ancestor in self.ancestors: try: ancestor_object = GeoZone.objects.get(id=ancestor) except GeoZone.DoesNotExist: continue ancestors_...
[ "def", "ancestors_objects", "(", "self", ")", ":", "ancestors_objects", "=", "[", "]", "for", "ancestor", "in", "self", ".", "ancestors", ":", "try", ":", "ancestor_object", "=", "GeoZone", ".", "objects", ".", "get", "(", "id", "=", "ancestor", ")", "ex...
Ancestors objects sorted by name.
[ "Ancestors", "objects", "sorted", "by", "name", "." ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/spatial/models.py#L172-L182
14,487
opendatateam/udata
udata/core/spatial/models.py
GeoZone.child_level
def child_level(self): """Return the child level given handled levels.""" HANDLED_LEVELS = current_app.config.get('HANDLED_LEVELS') try: return HANDLED_LEVELS[HANDLED_LEVELS.index(self.level) - 1] except (IndexError, ValueError): return None
python
def child_level(self): """Return the child level given handled levels.""" HANDLED_LEVELS = current_app.config.get('HANDLED_LEVELS') try: return HANDLED_LEVELS[HANDLED_LEVELS.index(self.level) - 1] except (IndexError, ValueError): return None
[ "def", "child_level", "(", "self", ")", ":", "HANDLED_LEVELS", "=", "current_app", ".", "config", ".", "get", "(", "'HANDLED_LEVELS'", ")", "try", ":", "return", "HANDLED_LEVELS", "[", "HANDLED_LEVELS", ".", "index", "(", "self", ".", "level", ")", "-", "1...
Return the child level given handled levels.
[ "Return", "the", "child", "level", "given", "handled", "levels", "." ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/spatial/models.py#L185-L191
14,488
opendatateam/udata
udata/harvest/backends/base.py
BaseBackend.harvest
def harvest(self): '''Start the harvesting process''' if self.perform_initialization() is not None: self.process_items() self.finalize() return self.job
python
def harvest(self): '''Start the harvesting process''' if self.perform_initialization() is not None: self.process_items() self.finalize() return self.job
[ "def", "harvest", "(", "self", ")", ":", "if", "self", ".", "perform_initialization", "(", ")", "is", "not", "None", ":", "self", ".", "process_items", "(", ")", "self", ".", "finalize", "(", ")", "return", "self", ".", "job" ]
Start the harvesting process
[ "Start", "the", "harvesting", "process" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/harvest/backends/base.py#L127-L132
14,489
opendatateam/udata
udata/harvest/backends/base.py
BaseBackend.perform_initialization
def perform_initialization(self): '''Initialize the harvesting for a given job''' log.debug('Initializing backend') factory = HarvestJob if self.dryrun else HarvestJob.objects.create self.job = factory(status='initializing', started=datetime.now(), ...
python
def perform_initialization(self): '''Initialize the harvesting for a given job''' log.debug('Initializing backend') factory = HarvestJob if self.dryrun else HarvestJob.objects.create self.job = factory(status='initializing', started=datetime.now(), ...
[ "def", "perform_initialization", "(", "self", ")", ":", "log", ".", "debug", "(", "'Initializing backend'", ")", "factory", "=", "HarvestJob", "if", "self", ".", "dryrun", "else", "HarvestJob", ".", "objects", ".", "create", "self", ".", "job", "=", "factory...
Initialize the harvesting for a given job
[ "Initialize", "the", "harvesting", "for", "a", "given", "job" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/harvest/backends/base.py#L134-L172
14,490
opendatateam/udata
udata/harvest/backends/base.py
BaseBackend.validate
def validate(self, data, schema): '''Perform a data validation against a given schema. :param data: an object to validate :param schema: a Voluptous schema to validate against ''' try: return schema(data) except MultipleInvalid as ie: errors = [] ...
python
def validate(self, data, schema): '''Perform a data validation against a given schema. :param data: an object to validate :param schema: a Voluptous schema to validate against ''' try: return schema(data) except MultipleInvalid as ie: errors = [] ...
[ "def", "validate", "(", "self", ",", "data", ",", "schema", ")", ":", "try", ":", "return", "schema", "(", "data", ")", "except", "MultipleInvalid", "as", "ie", ":", "errors", "=", "[", "]", "for", "error", "in", "ie", ".", "errors", ":", "if", "er...
Perform a data validation against a given schema. :param data: an object to validate :param schema: a Voluptous schema to validate against
[ "Perform", "a", "data", "validation", "against", "a", "given", "schema", "." ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/harvest/backends/base.py#L265-L304
14,491
opendatateam/udata
udata/core/badges/api.py
add
def add(obj): ''' Handle a badge add API. - Expecting badge_fieds as payload - Return the badge as payload - Return 200 if the badge is already - Return 201 if the badge is added ''' Form = badge_form(obj.__class__) form = api.validate(Form) kind = form.kind.data badge = obj...
python
def add(obj): ''' Handle a badge add API. - Expecting badge_fieds as payload - Return the badge as payload - Return 200 if the badge is already - Return 201 if the badge is added ''' Form = badge_form(obj.__class__) form = api.validate(Form) kind = form.kind.data badge = obj...
[ "def", "add", "(", "obj", ")", ":", "Form", "=", "badge_form", "(", "obj", ".", "__class__", ")", "form", "=", "api", ".", "validate", "(", "Form", ")", "kind", "=", "form", ".", "kind", ".", "data", "badge", "=", "obj", ".", "get_badge", "(", "k...
Handle a badge add API. - Expecting badge_fieds as payload - Return the badge as payload - Return 200 if the badge is already - Return 201 if the badge is added
[ "Handle", "a", "badge", "add", "API", "." ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/badges/api.py#L16-L32
14,492
opendatateam/udata
udata/core/badges/api.py
remove
def remove(obj, kind): ''' Handle badge removal API - Returns 404 if the badge for this kind is absent - Returns 204 on success ''' if not obj.get_badge(kind): api.abort(404, 'Badge does not exists') obj.remove_badge(kind) return '', 204
python
def remove(obj, kind): ''' Handle badge removal API - Returns 404 if the badge for this kind is absent - Returns 204 on success ''' if not obj.get_badge(kind): api.abort(404, 'Badge does not exists') obj.remove_badge(kind) return '', 204
[ "def", "remove", "(", "obj", ",", "kind", ")", ":", "if", "not", "obj", ".", "get_badge", "(", "kind", ")", ":", "api", ".", "abort", "(", "404", ",", "'Badge does not exists'", ")", "obj", ".", "remove_badge", "(", "kind", ")", "return", "''", ",", ...
Handle badge removal API - Returns 404 if the badge for this kind is absent - Returns 204 on success
[ "Handle", "badge", "removal", "API" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/badges/api.py#L35-L45
14,493
opendatateam/udata
udata/features/territories/__init__.py
check_for_territories
def check_for_territories(query): """ Return a geozone queryset of territories given the `query`. Results are sorted by population and area (biggest first). """ if not query or not current_app.config.get('ACTIVATE_TERRITORIES'): return [] dbqs = db.Q() query = query.lower() is_...
python
def check_for_territories(query): """ Return a geozone queryset of territories given the `query`. Results are sorted by population and area (biggest first). """ if not query or not current_app.config.get('ACTIVATE_TERRITORIES'): return [] dbqs = db.Q() query = query.lower() is_...
[ "def", "check_for_territories", "(", "query", ")", ":", "if", "not", "query", "or", "not", "current_app", ".", "config", ".", "get", "(", "'ACTIVATE_TERRITORIES'", ")", ":", "return", "[", "]", "dbqs", "=", "db", ".", "Q", "(", ")", "query", "=", "quer...
Return a geozone queryset of territories given the `query`. Results are sorted by population and area (biggest first).
[ "Return", "a", "geozone", "queryset", "of", "territories", "given", "the", "query", "." ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/features/territories/__init__.py#L9-L50
14,494
opendatateam/udata
udata/core/spatial/geoids.py
build
def build(level, code, validity=None): '''Serialize a GeoID from its parts''' spatial = ':'.join((level, code)) if not validity: return spatial elif isinstance(validity, basestring): return '@'.join((spatial, validity)) elif isinstance(validity, datetime): return '@'.join((sp...
python
def build(level, code, validity=None): '''Serialize a GeoID from its parts''' spatial = ':'.join((level, code)) if not validity: return spatial elif isinstance(validity, basestring): return '@'.join((spatial, validity)) elif isinstance(validity, datetime): return '@'.join((sp...
[ "def", "build", "(", "level", ",", "code", ",", "validity", "=", "None", ")", ":", "spatial", "=", "':'", ".", "join", "(", "(", "level", ",", "code", ")", ")", "if", "not", "validity", ":", "return", "spatial", "elif", "isinstance", "(", "validity",...
Serialize a GeoID from its parts
[ "Serialize", "a", "GeoID", "from", "its", "parts" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/spatial/geoids.py#L41-L54
14,495
opendatateam/udata
udata/core/spatial/geoids.py
from_zone
def from_zone(zone): '''Build a GeoID from a given zone''' validity = zone.validity.start if zone.validity else None return build(zone.level, zone.code, validity)
python
def from_zone(zone): '''Build a GeoID from a given zone''' validity = zone.validity.start if zone.validity else None return build(zone.level, zone.code, validity)
[ "def", "from_zone", "(", "zone", ")", ":", "validity", "=", "zone", ".", "validity", ".", "start", "if", "zone", ".", "validity", "else", "None", "return", "build", "(", "zone", ".", "level", ",", "zone", ".", "code", ",", "validity", ")" ]
Build a GeoID from a given zone
[ "Build", "a", "GeoID", "from", "a", "given", "zone" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/spatial/geoids.py#L57-L60
14,496
opendatateam/udata
udata/core/dataset/rdf.py
temporal_from_rdf
def temporal_from_rdf(period_of_time): '''Failsafe parsing of a temporal coverage''' try: if isinstance(period_of_time, Literal): return temporal_from_literal(str(period_of_time)) elif isinstance(period_of_time, RdfResource): return temporal_from_resource(period_of_time) ...
python
def temporal_from_rdf(period_of_time): '''Failsafe parsing of a temporal coverage''' try: if isinstance(period_of_time, Literal): return temporal_from_literal(str(period_of_time)) elif isinstance(period_of_time, RdfResource): return temporal_from_resource(period_of_time) ...
[ "def", "temporal_from_rdf", "(", "period_of_time", ")", ":", "try", ":", "if", "isinstance", "(", "period_of_time", ",", "Literal", ")", ":", "return", "temporal_from_literal", "(", "str", "(", "period_of_time", ")", ")", "elif", "isinstance", "(", "period_of_ti...
Failsafe parsing of a temporal coverage
[ "Failsafe", "parsing", "of", "a", "temporal", "coverage" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/dataset/rdf.py#L284-L295
14,497
opendatateam/udata
udata/core/dataset/rdf.py
title_from_rdf
def title_from_rdf(rdf, url): ''' Try to extract a distribution title from a property. As it's not a mandatory property, it fallback on building a title from the URL then the format and in last ressort a generic resource name. ''' title = rdf_value(rdf, DCT.title) if title: retur...
python
def title_from_rdf(rdf, url): ''' Try to extract a distribution title from a property. As it's not a mandatory property, it fallback on building a title from the URL then the format and in last ressort a generic resource name. ''' title = rdf_value(rdf, DCT.title) if title: retur...
[ "def", "title_from_rdf", "(", "rdf", ",", "url", ")", ":", "title", "=", "rdf_value", "(", "rdf", ",", "DCT", ".", "title", ")", "if", "title", ":", "return", "title", "if", "url", ":", "last_part", "=", "url", ".", "split", "(", "'/'", ")", "[", ...
Try to extract a distribution title from a property. As it's not a mandatory property, it fallback on building a title from the URL then the format and in last ressort a generic resource name.
[ "Try", "to", "extract", "a", "distribution", "title", "from", "a", "property", ".", "As", "it", "s", "not", "a", "mandatory", "property", "it", "fallback", "on", "building", "a", "title", "from", "the", "URL", "then", "the", "format", "and", "in", "last"...
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/dataset/rdf.py#L313-L333
14,498
opendatateam/udata
udata/core/reuse/forms.py
check_url_does_not_exists
def check_url_does_not_exists(form, field): '''Ensure a reuse URL is not yet registered''' if field.data != field.object_data and Reuse.url_exists(field.data): raise validators.ValidationError(_('This URL is already registered'))
python
def check_url_does_not_exists(form, field): '''Ensure a reuse URL is not yet registered''' if field.data != field.object_data and Reuse.url_exists(field.data): raise validators.ValidationError(_('This URL is already registered'))
[ "def", "check_url_does_not_exists", "(", "form", ",", "field", ")", ":", "if", "field", ".", "data", "!=", "field", ".", "object_data", "and", "Reuse", ".", "url_exists", "(", "field", ".", "data", ")", ":", "raise", "validators", ".", "ValidationError", "...
Ensure a reuse URL is not yet registered
[ "Ensure", "a", "reuse", "URL", "is", "not", "yet", "registered" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/reuse/forms.py#L13-L16
14,499
opendatateam/udata
udata/search/fields.py
obj_to_string
def obj_to_string(obj): '''Render an object into a unicode string if possible''' if not obj: return None elif isinstance(obj, bytes): return obj.decode('utf-8') elif isinstance(obj, basestring): return obj elif is_lazy_string(obj): return obj.value elif hasattr(ob...
python
def obj_to_string(obj): '''Render an object into a unicode string if possible''' if not obj: return None elif isinstance(obj, bytes): return obj.decode('utf-8') elif isinstance(obj, basestring): return obj elif is_lazy_string(obj): return obj.value elif hasattr(ob...
[ "def", "obj_to_string", "(", "obj", ")", ":", "if", "not", "obj", ":", "return", "None", "elif", "isinstance", "(", "obj", ",", "bytes", ")", ":", "return", "obj", ".", "decode", "(", "'utf-8'", ")", "elif", "isinstance", "(", "obj", ",", "basestring",...
Render an object into a unicode string if possible
[ "Render", "an", "object", "into", "a", "unicode", "string", "if", "possible" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/search/fields.py#L41-L54