Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function: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 | [] |
Please provide a description of the function:def redirect_territory(level, code):
territory = GeoZone.objects.valid_at(datetime.now()).filter(
code=code, level='fr:{level}'.format(level=level)).first()
return redirect(url_for('territories.territory', territory=territory)) | [
"\n Implicit redirect given the INSEE code.\n\n Optimistically redirect to the latest valid/known INSEE code.\n "
] |
Please provide a description of the function:def run(name, params, delay):
'''
Run the job <name>
Jobs args and kwargs are given as parameters without dashes.
Ex:
udata job run my-job arg1 arg2 key1=value key2=value
udata job run my-job -- arg1 arg2 key1=value key2=value
'''
ar... | [] |
Please provide a description of the function:def schedule(cron, name, params):
'''
Schedule the job <name> to run periodically given the <cron> expression.
Jobs args and kwargs are given as parameters without dashes.
Ex:
udata job schedule "* * 0 * *" my-job arg1 arg2 key1=value key2=value
... | [] |
Please provide a description of the function:def unschedule(name, params):
'''
Unschedule the job <name> with the given parameters.
Jobs args and kwargs are given as parameters without dashes.
Ex:
udata job unschedule my-job arg1 arg2 key1=value key2=value
'''
if name not in celery.tas... | [] |
Please provide a description of the function: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.for... | [] |
Please provide a description of the function: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('Purg... | [] |
Please provide a description of the function:def clean_parameters(self, params):
'''Only keep known parameters'''
return {k: v for k, v in params.items() if k in self.adapter.facets} | [] |
Please provide a description of the function: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 (... | [] |
Please provide a description of the function: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 parse... | [] |
Please provide a description of the function:def aggregate(self, search):
for f, facet in self.facets.items():
agg = facet.get_aggregation()
if isinstance(agg, Bucket):
search.aggs.bucket(f, agg)
elif isinstance(agg, Pipeline):
search.... | [
"\n Add aggregations representing the facets selected\n "
] |
Please provide a description of the function: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
r... | [] |
Please provide a description of the function:def search(self):
s = Search(doc_type=self.doc_types, using=es.client,
index=es.index_name)
# don't return any fields, just the metadata
s = s.fields([])
# Sort from parameters
s = s.sort(*self.sorts)
... | [
"\n Construct the Search object.\n "
] |
Please provide a description of the function: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
'''
... | [] |
Please provide a description of the function: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:
par... | [] |
Please provide a description of the function: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) | [] |
Please provide a description of the function: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():
... | [] |
Please provide a description of the function:def stream(queryset_or_adapter, basename=None):
if isinstance(queryset_or_adapter, Adapter):
adapter = queryset_or_adapter
elif isinstance(queryset_or_adapter, (list, tuple)):
if not queryset_or_adapter:
raise ValueError(
... | [
"Stream a csv file from an object list,\n\n a queryset or an instanciated adapter.\n "
] |
Please provide a description of the function:def header(self):
'''Generate the CSV header row'''
return (super(NestedAdapter, self).header() +
[name for name, getter in self.get_nested_fields()]) | [] |
Please provide a description of the function: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, [])) | [] |
Please provide a description of the function: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:
co... | [] |
Please provide a description of the function: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 r... | [] |
Please provide a description of the function: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('sende... | [] |
Please provide a description of the function: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 publi... | [] |
Please provide a description of the function:def clean(ctx, node=False, translations=False, all=False):
'''Cleanup all build artifacts'''
header('Clean all build artifacts')
patterns = [
'build', 'dist', 'cover', 'docs/_build',
'**/*.pyc', '*.egg-info', '.tox', 'udata/static/*'
]
if ... | [] |
Please provide a description of the function: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... | [] |
Please provide a description of the function:def cover(ctx, html=False):
'''Run tests suite with coverage'''
header('Run tests suite with coverage')
cmd = 'pytest --cov udata --cov-report term'
if html:
cmd = ' '.join((cmd, '--cov-report html:reports/python/cover'))
with ctx.cd(ROOT):
... | [] |
Please provide a description of the function:def qa(ctx):
'''Run a quality report'''
header('Performing static analysis')
info('Python static analysis')
flake8_results = lrun('flake8 udata --jobs 1', pty=True, warn=True)
info('JavaScript static analysis')
eslint_results = lrun('npm -s run lint',... | [] |
Please provide a description of the function: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 p... | [] |
Please provide a description of the function: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 | [] |
Please provide a description of the function:def extract_name_from_path(path):
base_path, query_string = path.split('?')
infos = base_path.strip('/').split('/')[2:] # Removes api/version.
if len(infos) > 1: # This is an object.
name = '{category} / {name}'.format(
category=infos[0... | [
"Return a readable name from a URL path.\n\n Useful to log requests on Piwik with categories tree structure.\n See: http://piwik.org/faq/how-to/#faq_62\n "
] |
Please provide a description of the function: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 avai... | [] |
Please provide a description of the function:def secure(self, func):
'''Enforce authentication on a given method/verb
and optionally check a given permission
'''
if isinstance(func, basestring):
return self._apply_permission(Permission(RoleNeed(func)))
elif isinstance... | [] |
Please provide a description of the function:def _apply_secure(self, func, permission=None):
'''Enforce authentication on a given method/verb'''
self._handle_api_doc(func, {'security': 'apikey'})
@wraps(func)
def wrapper(*args, **kwargs):
if not current_user.is_authenticated... | [] |
Please provide a description of the function: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.... | [] |
Please provide a description of the function: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, ... | [] |
Please provide a description of the function: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'] = challe... | [] |
Please provide a description of the function:def check_resources(self, number):
'''Check <number> of URLs that have not been (recently) checked'''
if not current_app.config.get('LINKCHECKING_ENABLED'):
log.error('Link checking is disabled.')
return
base_pipeline = [
{'$match': {'res... | [] |
Please provide a description of the function:def render():
'''Force (re)rendering stored images'''
from udata.core.organization.models import Organization
from udata.core.post.models import Post
from udata.core.reuse.models import Reuse
from udata.core.user.models import User
header('Rendering ... | [] |
Please provide a description of the function: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['p... | [] |
Please provide a description of the function: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.o... | [] |
Please provide a description of the function: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,
... | [] |
Please provide a description of the function:def header(msg):
'''Display an header'''
echo(' '.join((yellow(HEADER), white(safe_unicode(msg)), yellow(HEADER)))) | [] |
Please provide a description of the function: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(m... | [] |
Please provide a description of the function:def exit_with_error(msg, details=None, code=-1):
'''Exit with error'''
error(msg, details)
sys.exit(code) | [] |
Please provide a description of the function:def formatException(self, ei):
'''Indent traceback info for better readability'''
out = super(CliFormatter, self).formatException(ei)
return b'│' + format_multiline(out) | [] |
Please provide a description of the function:def load_udata_commands(self, ctx):
'''
Load udata commands from:
- `udata.commands.*` module
- known internal modules with commands
- plugins exporting a `udata.commands` entrypoint
'''
if self._udata_commands_loaded:
... | [] |
Please provide a description of the function: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=... | [] |
Please provide a description of the function:def get_enabled(name, app):
'''
Get (and load) entrypoints registered on name
and enabled for the given app.
'''
plugins = app.config['PLUGINS']
return dict(_ep_to_kv(e) for e in iter_all(name) if e.name in plugins) | [] |
Please provide a description of the function:def _ep_to_kv(entrypoint):
'''
Transform an entrypoint into a key-value tuple where:
- key is the entrypoint name
- value is the entrypoint class with the name attribute
matching from entrypoint name
'''
cls = entrypoint.load()
cls.name = en... | [] |
Please provide a description of the function:def known_dists():
'''Return a list of all Distributions exporting udata.* entrypoints'''
return (
dist for dist in pkg_resources.working_set
if any(k in ENTRYPOINTS for k in dist.get_entry_map().keys())
) | [] |
Please provide a description of the function: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 ... | [] |
Please provide a description of the function:def get_roots(app=None):
'''
Returns the list of root packages/modules exposing endpoints.
If app is provided, only returns those of enabled plugins
'''
roots = set()
plugins = app.config['PLUGINS'] if app else None
for name in ENTRYPOINTS.keys()... | [] |
Please provide a description of the function: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... | [] |
Please provide a description of the function:def to_python(self, value):
if '/' not in value:
return
level, code = value.split('/')[:2] # Ignore optional slug
geoid = GeoZone.SEPARATOR.join([level, code])
zone = GeoZone.objects.resolve(geoid)
if not zone ... | [
"\n `value` has slashs in it, that's why we inherit from `PathConverter`.\n\n E.g.: `commune/13200@latest/`, `departement/13@1860-07-01/` or\n `region/76@2016-01-01/Auvergne-Rhone-Alpes/`.\n\n Note that the slug is not significative but cannot be omitted.\n "
] |
Please provide a description of the function: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 = getattr(obj, 'code', None)
slug = getattr(obj, 'slug', None)
... | [
"\n Reconstruct the URL from level name, code or datagouv id and slug.\n "
] |
Please provide a description of the function:def router(name, args, kwargs, options, task=None, **kw):
'''
A celery router using the predeclared :class:`ContextTask`
attributes (`router` or `default_queue` and/or `default routing_key`).
'''
# Fetch task by name if necessary
task = task or celery... | [] |
Please provide a description of the function:def job(name, **kwargs):
'''A shortcut decorator for declaring jobs'''
return task(name=name, schedulable=True, base=JobTask,
bind=True, **kwargs) | [] |
Please provide a description of the function: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 | [] |
Please provide a description of the function: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_ap... | [] |
Please provide a description of the function: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':
... | [] |
Please provide a description of the function: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()
... | [] |
Please provide a description of the function: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... | [] |
Please provide a description of the function: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.identifie... | [] |
Please provide a description of the function: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) | [] |
Please provide a description of the function:def context(name):
'''A decorator for theme context processors'''
def wrapper(func):
g.theme.context_processors[name] = func
return func
return wrapper | [] |
Please provide a description of the function: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:
r... | [] |
Please provide a description of the function: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) | [] |
Please provide a description of the function:def rdf(dataset):
'''Root RDF endpoint with content negociation handling'''
format = RDF_EXTENSIONS[negociate_content()]
url = url_for('datasets.rdf_format', dataset=dataset.id, format=format)
return redirect(url) | [] |
Please provide a description of the function:def group_resources_by_type(resources):
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[rtype]:
... | [
"Group a list of `resources` by `type` with order"
] |
Please provide a description of the function: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'... | [] |
Please provide a description of the function: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) | [] |
Please provide a description of the function:def create_source(name, url, backend,
description=None,
frequency=DEFAULT_HARVEST_FREQUENCY,
owner=None,
organization=None,
config=None,
):
'''Create a new harvest... | [] |
Please provide a description of the function:def update_source(ident, data):
'''Update an harvest source'''
source = get_source(ident)
source.modify(**data)
signals.harvest_source_updated.send(source)
return source | [] |
Please provide a description of the function: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_us... | [] |
Please provide a description of the function: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_auth... | [] |
Please provide a description of the function: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 | [] |
Please provide a description of the function: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() | [] |
Please provide a description of the function: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_item... | [] |
Please provide a description of the function:def preview_from_config(name, url, backend,
description=None,
frequency=DEFAULT_HARVEST_FREQUENCY,
owner=None,
organization=None,
config=None,
... | [] |
Please provide a description of the function: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_yea... | [] |
Please provide a description of the function: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()... | [] |
Please provide a description of the function: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 ID... | [] |
Please provide a description of the function:def user_to_rdf(user, graph=None):
'''
Map a Resource domain model to a DCAT/RDF graph
'''
graph = graph or Graph(namespace_manager=namespace_manager)
if user.id:
user_url = url_for('users.show_redirect',
user=user.id,
... | [] |
Please provide a description of the function: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)
... | [] |
Please provide a description of the function:def create():
'''Create a new user'''
data = {
'first_name': click.prompt('First name'),
'last_name': click.prompt('Last name'),
'email': click.prompt('Email'),
'password': click.prompt('Password', hide_input=True),
'password_c... | [] |
Please provide a description of the function:def activate():
'''Activate an existing user (validate their email confirmation)'''
email = click.prompt('Email')
user = User.objects(email=email).first()
if not user:
exit_with_error('Invalid user')
if user.confirmed_at is not None:
exit_... | [] |
Please provide a description of the function: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') | [] |
Please provide a description of the function: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)
suc... | [] |
Please provide a description of the function: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 = ar... | [] |
Please provide a description of the function:def parse_uploaded_image(field):
'''Parse an uploaded image and save into a db.ImageField()'''
args = image_parser.parse_args()
image = args['file']
if image.mimetype not in IMAGES_MIMETYPES:
api.abort(400, 'Unsupported image format')
bbox = args... | [] |
Please provide a description of the function: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 specifi... | [] |
Please provide a description of the function:def generate_fixtures(datasets, reuses):
'''Build sample fixture data (users, datasets and reuses).'''
user = UserFactory()
log.info('Generated user "{user.email}".'.format(user=user))
organization = OrganizationFactory(members=[Member(user=user)])
log.i... | [] |
Please provide a description of the function: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... | [] |
Please provide a description of the function:def daterange_with_details(value):
'''Display a date range in the shorter possible maner.'''
delta = value.end - value.start
start, end = None, None
if is_first_year_day(value.start) and is_last_year_day(value.end):
start = value.start.year
if... | [] |
Please provide a description of the function:def daterange(value, details=False):
'''Display a date range in the shorter possible maner.'''
if not isinstance(value, db.DateRange):
raise ValueError('daterange only accept db.DateRange as parameter')
if details:
return daterange_with_details(v... | [] |
Please provide a description of the function:def i18n_alternate_links():
if (not request.endpoint or
not current_app.url_map.is_endpoint_expecting(request.endpoint,
'lang_code')):
return Markup('')
try:
LINK_PATTERN = (
... | [
"Render the <link rel=\"alternate\" hreflang />\n\n if page is in a I18nBlueprint\n "
] |
Please provide a description of the function: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" % (va... | [] |
Please provide a description of the function: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) | [] |
Please provide a description of the function: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 i... | [] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.