code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def get_identity(self, provider):
"""Return the first user identity which matches the given provider.
:param provider: The id of the provider in question
:return: The requested identity, or `None` if none is found
"""
return next(
(ident for ident in self.identities ... | Return the first user identity which matches the given provider.
:param provider: The id of the provider in question
:return: The requested identity, or `None` if none is found
| get_identity | python | indico/indico | indico/modules/users/models/users.py | https://github.com/indico/indico/blob/master/indico/modules/users/models/users.py | MIT |
def can_get_all_multipass_groups(self):
"""Check whether it is possible to get all multipass groups the user is in."""
return all(multipass.identity_providers[x.provider].supports_get_identity_groups
for x in self.identities
if x.provider != 'indico' and x.provider ... | Check whether it is possible to get all multipass groups the user is in. | can_get_all_multipass_groups | python | indico/indico | indico/modules/users/models/users.py | https://github.com/indico/indico/blob/master/indico/modules/users/models/users.py | MIT |
def iter_all_multipass_groups(self):
"""Iterate over all multipass groups the user is in."""
return itertools.chain.from_iterable(multipass.identity_providers[x.provider].get_identity_groups(x.identifier)
for x in self.identities
... | Iterate over all multipass groups the user is in. | iter_all_multipass_groups | python | indico/indico | indico/modules/users/models/users.py | https://github.com/indico/indico/blob/master/indico/modules/users/models/users.py | MIT |
def make_email_primary(self, email):
"""Promote a secondary email address to the primary email address.
:param email: an email address that is currently a secondary email
"""
secondary = next((x for x in self._secondary_emails if x.email == email), None)
if secondary is None:
... | Promote a secondary email address to the primary email address.
:param email: an email address that is currently a secondary email
| make_email_primary | python | indico/indico | indico/modules/users/models/users.py | https://github.com/indico/indico/blob/master/indico/modules/users/models/users.py | MIT |
def query_personal_tokens(self, *, include_revoked=False):
"""Query the personal tokens of the user.
:param include_revoked: whether to query revoked tokens as well
"""
query = self.personal_tokens
if not include_revoked:
query = query.filter_by(revoked_dt=None)
... | Query the personal tokens of the user.
:param include_revoked: whether to query revoked tokens as well
| query_personal_tokens | python | indico/indico | indico/modules/users/models/users.py | https://github.com/indico/indico/blob/master/indico/modules/users/models/users.py | MIT |
def synchronize_data(self, refresh=False, silent=False):
"""Synchronize the fields of the user from the sync identity.
This will take only into account :attr:`synced_fields`.
:param refresh: bool -- Whether to refresh the synced identity
with the sync provider before in... | Synchronize the fields of the user from the sync identity.
This will take only into account :attr:`synced_fields`.
:param refresh: bool -- Whether to refresh the synced identity
with the sync provider before instead of using
the stored data. (Only if the... | synchronize_data | python | indico/indico | indico/modules/users/models/users.py | https://github.com/indico/indico/blob/master/indico/modules/users/models/users.py | MIT |
def get_merged_from_users_recursive(self):
"""Get the users merged into this users recursively."""
user_alias = db.aliased(User)
cte_query = (select([user_alias.id.label('merged_from_id')])
.where(user_alias.merged_into_id == self.id)
.cte(recursive=True... | Get the users merged into this users recursively. | get_merged_from_users_recursive | python | indico/indico | indico/modules/users/models/users.py | https://github.com/indico/indico/blob/master/indico/modules/users/models/users.py | MIT |
def force_user_locale(self):
"""Temporarily override the locale to the locale of the user."""
locale = self.settings.get('lang')
with force_locale(locale):
yield | Temporarily override the locale to the locale of the user. | force_user_locale | python | indico/indico | indico/modules/users/models/users.py | https://github.com/indico/indico/blob/master/indico/modules/users/models/users.py | MIT |
def dummy_reg_with_file_field(db, dummy_event, dummy_regform, dummy_user, create_file):
"""Create a dummy registration which includes an uploaded file."""
from indico.modules.events.registration.controllers.management.fields import _fill_form_field_with_data
def create_file_field():
field_data = {'... | Create a dummy registration which includes an uploaded file. | dummy_reg_with_file_field | python | indico/indico | indico/modules/users/testing/fixtures.py | https://github.com/indico/indico/blob/master/indico/modules/users/testing/fixtures.py | MIT |
def notify_created(plugin, room, room_assoc, event, user):
"""Notify about the creation of a vc_room.
:param room: the vc_room
:param event: the event
:param user: the user performing the action
"""
name = get_overridable_template_name('emails/created.html', plugin, core_prefix='vc/')
with ... | Notify about the creation of a vc_room.
:param room: the vc_room
:param event: the event
:param user: the user performing the action
| notify_created | python | indico/indico | indico/modules/vc/notifications.py | https://github.com/indico/indico/blob/master/indico/modules/vc/notifications.py | MIT |
def notify_deleted(plugin, room, room_assoc, event, user):
"""Notify about the deletion of a vc_room from the system.
:param room: the vc_room
:param event: the event
:param user: the user performing the action
"""
name = get_overridable_template_name('emails/deleted.html', plugin, core_prefix=... | Notify about the deletion of a vc_room from the system.
:param room: the vc_room
:param event: the event
:param user: the user performing the action
| notify_deleted | python | indico/indico | indico/modules/vc/notifications.py | https://github.com/indico/indico/blob/master/indico/modules/vc/notifications.py | MIT |
def render_info_box(self, vc_room, event_vc_room, event, **kwargs):
"""Render the information shown in the expandable box of a VC room row.
:param vc_room: the VC room object
:param event_vc_room: the association of an event and a VC room
:param event: the event with the current VC room... | Render the information shown in the expandable box of a VC room row.
:param vc_room: the VC room object
:param event_vc_room: the association of an event and a VC room
:param event: the event with the current VC room attached to it
:param kwargs: arguments passed to the template
... | render_info_box | python | indico/indico | indico/modules/vc/plugins.py | https://github.com/indico/indico/blob/master/indico/modules/vc/plugins.py | MIT |
def render_manage_event_info_box(self, vc_room, event_vc_room, event, **kwargs):
"""
Render the information shown in the expandable box on a
VC room in the management area.
:param vc_room: the VC room object
:param event_vc_room: the association of an event and a VC room
... |
Render the information shown in the expandable box on a
VC room in the management area.
:param vc_room: the VC room object
:param event_vc_room: the association of an event and a VC room
:param event: the event with the current VC room attached to it
:param kwargs: argu... | render_manage_event_info_box | python | indico/indico | indico/modules/vc/plugins.py | https://github.com/indico/indico/blob/master/indico/modules/vc/plugins.py | MIT |
def render_buttons(self, vc_room, event_vc_room, **kwargs):
"""
Render a list of plugin specific buttons (eg: Join URL, etc)
in the management area.
:param vc_room: the VC room object
:param event_vc_room: the association of an event and a VC room
:param kwargs: argument... |
Render a list of plugin specific buttons (eg: Join URL, etc)
in the management area.
:param vc_room: the VC room object
:param event_vc_room: the association of an event and a VC room
:param kwargs: arguments passed to the template
| render_buttons | python | indico/indico | indico/modules/vc/plugins.py | https://github.com/indico/indico/blob/master/indico/modules/vc/plugins.py | MIT |
def render_event_buttons(self, vc_room, event_vc_room, **kwargs):
"""
Render a list of plugin specific buttons (eg: Join URL, etc)
in the event page.
:param vc_room: the VC room object
:param event_vc_room: the association of an event and a VC room
:param kwargs: argumen... |
Render a list of plugin specific buttons (eg: Join URL, etc)
in the event page.
:param vc_room: the VC room object
:param event_vc_room: the association of an event and a VC room
:param kwargs: arguments passed to the template
| render_event_buttons | python | indico/indico | indico/modules/vc/plugins.py | https://github.com/indico/indico/blob/master/indico/modules/vc/plugins.py | MIT |
def create_form(self, event, existing_vc_room=None, existing_event_vc_room=None):
"""Create the videoconference room form.
:param event: the event the videoconference room is for
:param existing_vc_room: a vc_room from which to retrieve data for the form
:return: an instance of an :clas... | Create the videoconference room form.
:param event: the event the videoconference room is for
:param existing_vc_room: a vc_room from which to retrieve data for the form
:return: an instance of an :class:`IndicoForm` subclass
| create_form | python | indico/indico | indico/modules/vc/plugins.py | https://github.com/indico/indico/blob/master/indico/modules/vc/plugins.py | MIT |
def update_data_association(self, event: Event, vc_room: VCRoom, event_vc_room: VCRoomEventAssociation, data: dict):
"""Update the `VCRoomEventAssociation`'s linked object based on the data coming from the UI form."""
contribution_id = data.pop('contribution')
block_id = data.pop('block')
... | Update the `VCRoomEventAssociation`'s linked object based on the data coming from the UI form. | update_data_association | python | indico/indico | indico/modules/vc/plugins.py | https://github.com/indico/indico/blob/master/indico/modules/vc/plugins.py | MIT |
def can_manage_vc_rooms(self, user, event):
"""Check if a user can manage vc rooms on an event."""
if self.can_manage_vc(user):
return True
if not self.settings.acls.get('acl'): # everyone has access
return True
return self.settings.acls.contains_user('acl', use... | Check if a user can manage vc rooms on an event. | can_manage_vc_rooms | python | indico/indico | indico/modules/vc/plugins.py | https://github.com/indico/indico/blob/master/indico/modules/vc/plugins.py | MIT |
def can_manage_vc_room(self, user, room):
"""Check if a user can manage a vc room."""
return (user.is_admin or
self.can_manage_vc(user) or
any(evt_assoc.event.can_manage(user) for evt_assoc in room.events)) | Check if a user can manage a vc room. | can_manage_vc_room | python | indico/indico | indico/modules/vc/plugins.py | https://github.com/indico/indico/blob/master/indico/modules/vc/plugins.py | MIT |
def can_manage_vc(self, user):
"""Check if a user has management rights on this VC system."""
if user.is_admin:
return True
return self.settings.acls.contains_user('managers', user) | Check if a user has management rights on this VC system. | can_manage_vc | python | indico/indico | indico/modules/vc/plugins.py | https://github.com/indico/indico/blob/master/indico/modules/vc/plugins.py | MIT |
def get_vc_plugins():
"""Return a dict containing the available videoconference plugins."""
from indico.modules.vc import VCPluginMixin
return {p.service_name: p for p in plugin_engine.get_active_plugins().values() if isinstance(p, VCPluginMixin)} | Return a dict containing the available videoconference plugins. | get_vc_plugins | python | indico/indico | indico/modules/vc/util.py | https://github.com/indico/indico/blob/master/indico/modules/vc/util.py | MIT |
def find_event_vc_rooms(from_dt=None, to_dt=None, distinct=False):
"""Find VC rooms matching certain criteria.
:param from_dt: earliest event/contribution to include
:param to_dt: latest event/contribution to include
:param distinct: if True, never return the same ``(event, vcroom)``
... | Find VC rooms matching certain criteria.
:param from_dt: earliest event/contribution to include
:param to_dt: latest event/contribution to include
:param distinct: if True, never return the same ``(event, vcroom)``
more than once (even if it's linked more than once to
... | find_event_vc_rooms | python | indico/indico | indico/modules/vc/util.py | https://github.com/indico/indico/blob/master/indico/modules/vc/util.py | MIT |
def delete(self, user: User, event: Event | None = None):
"""Delete a VC room and all its associations.
:param user: the user performing the deletion
:param event: the event in which the deletion happened
"""
for assoc in self.events[:]:
Logger.get('modules.vc').info... | Delete a VC room and all its associations.
:param user: the user performing the deletion
:param event: the event in which the deletion happened
| delete | python | indico/indico | indico/modules/vc/models/vc_rooms.py | https://github.com/indico/indico/blob/master/indico/modules/vc/models/vc_rooms.py | MIT |
def find_for_event(cls, event, include_hidden=False, include_deleted=False, only_linked_to_event=False, **kwargs):
"""Return a Query that retrieves the videoconference rooms for an event.
:param event: an indico Event
:param only_linked_to_event: only retrieve the vc rooms linked to the whole e... | Return a Query that retrieves the videoconference rooms for an event.
:param event: an indico Event
:param only_linked_to_event: only retrieve the vc rooms linked to the whole event
:param kwargs: extra kwargs to pass to ``filter_by()``
| find_for_event | python | indico/indico | indico/modules/vc/models/vc_rooms.py | https://github.com/indico/indico/blob/master/indico/modules/vc/models/vc_rooms.py | MIT |
def delete(self, user: User, *, check_vc_room: bool = True):
"""Delete a VC room from an event.
If the room is not used anywhere else, the room itself is also deleted.
:param user: the user performing the deletion
:param check_vc_room: whether to check as well if the VCRoom can be dele... | Delete a VC room from an event.
If the room is not used anywhere else, the room itself is also deleted.
:param user: the user performing the deletion
:param check_vc_room: whether to check as well if the VCRoom can be deleted
(no more associations left)
| delete | python | indico/indico | indico/modules/vc/models/vc_rooms.py | https://github.com/indico/indico/blob/master/indico/modules/vc/models/vc_rooms.py | MIT |
def bool_matrix(template, mask=None, expect=None):
"""Create a boolean matrix suitable for parametrized tests.
This function lets you create a boolean matrix with certain columns being
fixed to a static value or certain combinations being skipped. It also adds
a last column with a value that's either f... | Create a boolean matrix suitable for parametrized tests.
This function lets you create a boolean matrix with certain columns being
fixed to a static value or certain combinations being skipped. It also adds
a last column with a value that's either fixed or depending on the other values.
By default any... | bool_matrix | python | indico/indico | indico/testing/util.py | https://github.com/indico/indico/blob/master/indico/testing/util.py | MIT |
def extract_emails(smtp, required=True, count=None, one=False, regex=False, **kwargs):
"""Extract emails from an smtp outbox.
:param smtp: The `smtp` fixture from the testcase
:param required: Fail if no matching emails were found
:param count: Require exactly `count` emails to be found
:param one:... | Extract emails from an smtp outbox.
:param smtp: The `smtp` fixture from the testcase
:param required: Fail if no matching emails were found
:param count: Require exactly `count` emails to be found
:param one: Require exactly one email to be found
:param kwargs: Header values to match against
:... | extract_emails | python | indico/indico | indico/testing/util.py | https://github.com/indico/indico/blob/master/indico/testing/util.py | MIT |
def extract_logs(caplog, required=True, count=None, one=False, regex=False, **kwargs):
"""Extract log records from python's logging system.
:param caplog: The `caplog` fixture from the testcase
:param required: Fail if no matching records were found
:param count: Require exactly `count` records to be f... | Extract log records from python's logging system.
:param caplog: The `caplog` fixture from the testcase
:param required: Fail if no matching records were found
:param count: Require exactly `count` records to be found
:param one: Require exactly one record to be found
:param kwargs: LogRecord attri... | extract_logs | python | indico/indico | indico/testing/util.py | https://github.com/indico/indico/blob/master/indico/testing/util.py | MIT |
def assert_email_snapshot(snapshot, template, snapshot_filename):
"""Assert that an email matches a snapshot.
This verifies that both the subject and the body match the snapshots.
:param snapshot: The pytest snapshot fixture
:param template: The email template module
:param snapshot_filename: The ... | Assert that an email matches a snapshot.
This verifies that both the subject and the body match the snapshots.
:param snapshot: The pytest snapshot fixture
:param template: The email template module
:param snapshot_filename: The filename for the snapshot
| assert_email_snapshot | python | indico/indico | indico/testing/util.py | https://github.com/indico/indico/blob/master/indico/testing/util.py | MIT |
def assert_json_snapshot(snapshot, obj, snapshot_filename):
"""Assert that a json object matches a snapshot.
:param snapshot: The pytest snapshot fixture
:param obj: The json object to compare
:param snapshot_filename: The filename for the snapshot
"""
__tracebackhide__ = True
snapshot.asse... | Assert that a json object matches a snapshot.
:param snapshot: The pytest snapshot fixture
:param obj: The json object to compare
:param snapshot_filename: The filename for the snapshot
| assert_json_snapshot | python | indico/indico | indico/testing/util.py | https://github.com/indico/indico/blob/master/indico/testing/util.py | MIT |
def assert_yaml_snapshot(snapshot, obj, snapshot_filename, *, strip_dynamic_data=False):
"""Assert that a yaml object matches a snapshot.
:param snapshot: The pytest snapshot fixture
:param obj: The yaml object to compare
:param snapshot_filename: The filename for the snapshot
:param strip_dynamic_... | Assert that a yaml object matches a snapshot.
:param snapshot: The pytest snapshot fixture
:param obj: The yaml object to compare
:param snapshot_filename: The filename for the snapshot
:param strip_dynamic_data: Whether to replace likely-dynamic data like IDs and
dates w... | assert_yaml_snapshot | python | indico/indico | indico/testing/util.py | https://github.com/indico/indico/blob/master/indico/testing/util.py | MIT |
def remove_dynamic_data(yaml_string):
"""Remove data that appears dynamic (IDs, dates) from a YAML string."""
yaml_string = re.sub(r'(?<=_date: )(?!null$).+$', '<timestamp>', yaml_string, flags=re.MULTILINE)
yaml_string = re.sub(r'(?<=_dt: )(?!null$).+$', '<timestamp>', yaml_string, flags=re.MULTILINE)
... | Remove data that appears dynamic (IDs, dates) from a YAML string. | remove_dynamic_data | python | indico/indico | indico/testing/util.py | https://github.com/indico/indico/blob/master/indico/testing/util.py | MIT |
def create_abstract(db):
"""Return a callable that lets you create an abstract."""
def _create_abstract(event, title, **kwargs):
abstract = Abstract(event=event, title=title, **kwargs)
db.session.add(abstract)
db.session.flush()
return abstract
return _create_abstract | Return a callable that lets you create an abstract. | create_abstract | python | indico/indico | indico/testing/fixtures/abstract.py | https://github.com/indico/indico/blob/master/indico/testing/fixtures/abstract.py | MIT |
def create_abstract_file():
"""Return a callable which lets you create an abstract file."""
def _create_abstract_file(abstract, filename, content_type, data, **kwargs):
file_ = AbstractFile(filename=filename, content_type=content_type, abstract=abstract, **kwargs)
file_.save(data.encode())
... | Return a callable which lets you create an abstract file. | create_abstract_file | python | indico/indico | indico/testing/fixtures/abstract.py | https://github.com/indico/indico/blob/master/indico/testing/fixtures/abstract.py | MIT |
def create_category(db):
"""Return a callable which lets you create dummy events."""
def _create_category(id_=None, **kwargs):
kwargs.setdefault('title', f'cat#{id_}' if id_ is not None else 'dummy')
kwargs.setdefault('timezone', 'UTC')
if 'parent' not in kwargs:
kwargs['par... | Return a callable which lets you create dummy events. | create_category | python | indico/indico | indico/testing/fixtures/category.py | https://github.com/indico/indico/blob/master/indico/testing/fixtures/category.py | MIT |
def create_contribution(db):
"""Return a callable that lets you create a contribution."""
def _create_contribution(event, title, duration=timedelta(minutes=20), **kwargs):
entry = Contribution(event=event, title=title, duration=duration, **kwargs)
db.session.add(entry)
db.session.flush(... | Return a callable that lets you create a contribution. | create_contribution | python | indico/indico | indico/testing/fixtures/contribution.py | https://github.com/indico/indico/blob/master/indico/testing/fixtures/contribution.py | MIT |
def create_subcontribution(db):
"""Return a callable that lets you create a subcontribution."""
def _create_subcontribution(contribution, title, duration=timedelta(minutes=10), **kwargs):
entry = SubContribution(contribution=contribution, title=title, duration=duration, **kwargs)
db.session.add(... | Return a callable that lets you create a subcontribution. | create_subcontribution | python | indico/indico | indico/testing/fixtures/contribution.py | https://github.com/indico/indico/blob/master/indico/testing/fixtures/contribution.py | MIT |
def postgresql():
"""Provide a clean temporary PostgreSQL server/database.
If the environment variable `INDICO_TEST_DATABASE_URI` is set, this fixture
will do nothing and simply return the connection string from that variable
"""
# Use existing database
if 'INDICO_TEST_DATABASE_URI' in os.envir... | Provide a clean temporary PostgreSQL server/database.
If the environment variable `INDICO_TEST_DATABASE_URI` is set, this fixture
will do nothing and simply return the connection string from that variable
| postgresql | python | indico/indico | indico/testing/fixtures/database.py | https://github.com/indico/indico/blob/master/indico/testing/fixtures/database.py | MIT |
def database(app, postgresql):
"""Create a test database which is destroyed afterwards.
Used only internally, if you need to access the database use `db` instead to ensure
your modifications are not persistent!
"""
app.config['SQLALCHEMY_DATABASE_URI'] = postgresql
configure_db(app)
if 'IND... | Create a test database which is destroyed afterwards.
Used only internally, if you need to access the database use `db` instead to ensure
your modifications are not persistent!
| database | python | indico/indico | indico/testing/fixtures/database.py | https://github.com/indico/indico/blob/master/indico/testing/fixtures/database.py | MIT |
def db(database, monkeypatch):
"""Provide database access and ensure changes do not persist."""
# Prevent database/session modifications
monkeypatch.setattr(database.session, 'commit', database.session.flush)
monkeypatch.setattr(database.session, 'remove', lambda: None)
rollback = database.session.r... | Provide database access and ensure changes do not persist. | db | python | indico/indico | indico/testing/fixtures/database.py | https://github.com/indico/indico/blob/master/indico/testing/fixtures/database.py | MIT |
def count_queries():
"""Provide a query counter.
Usage::
with count_queries() as count:
do_stuff()
assert count() == number_of_queries
"""
def _after_cursor_execute(*args, **kwargs):
if active_counter[0]:
active_counter[0][0] += 1
@contextmanager
... | Provide a query counter.
Usage::
with count_queries() as count:
do_stuff()
assert count() == number_of_queries
| count_queries | python | indico/indico | indico/testing/fixtures/database.py | https://github.com/indico/indico/blob/master/indico/testing/fixtures/database.py | MIT |
def disallow_emails(monkeypatch):
"""Prevent any code from connecting to a SMTP server.
Return a set where you can add `(host, port)` combinations that
should be exempt from the SMTP restriction.
"""
orig_connect = SMTP.connect
allowed = set()
def _connect(self, host='localhost', port=0):
... | Prevent any code from connecting to a SMTP server.
Return a set where you can add `(host, port)` combinations that
should be exempt from the SMTP restriction.
| disallow_emails | python | indico/indico | indico/testing/fixtures/disallow.py | https://github.com/indico/indico/blob/master/indico/testing/fixtures/disallow.py | MIT |
def create_editable(db):
"""Return a callable which lets you create editables."""
def _create_editable(contribution, type, **kwargs):
editable = Editable(contribution=contribution, type=type, **kwargs)
db.session.flush()
return editable
return _create_editable | Return a callable which lets you create editables. | create_editable | python | indico/indico | indico/testing/fixtures/editing.py | https://github.com/indico/indico/blob/master/indico/testing/fixtures/editing.py | MIT |
def create_editing_revision(db):
"""Return a callable which lets you create editing revisions."""
def _create_editing_revision(editable, user, type, created_dt, **kwargs):
revision = EditingRevision(editable=editable, user=user, type=type, created_dt=created_dt, **kwargs)
db.session.flush()
... | Return a callable which lets you create editing revisions. | create_editing_revision | python | indico/indico | indico/testing/fixtures/editing.py | https://github.com/indico/indico/blob/master/indico/testing/fixtures/editing.py | MIT |
def create_editing_file_type(db):
"""Return a callable which lets you create editing file types."""
def _create_editing_file_type(name, extensions, type, **kwargs):
file_type = EditingFileType(name=name, extensions=extensions, type=type, **kwargs)
db.session.add(file_type)
db.session.flu... | Return a callable which lets you create editing file types. | create_editing_file_type | python | indico/indico | indico/testing/fixtures/editing.py | https://github.com/indico/indico/blob/master/indico/testing/fixtures/editing.py | MIT |
def create_editing_revision_file(db):
"""Return a callable which lets you create editing revision files."""
def _create_paper_file(revision, file, **kwargs):
revision_file = EditingRevisionFile(revision=revision, file=file, **kwargs)
file.claim()
db.session.flush()
return revisio... | Return a callable which lets you create editing revision files. | create_editing_revision_file | python | indico/indico | indico/testing/fixtures/editing.py | https://github.com/indico/indico/blob/master/indico/testing/fixtures/editing.py | MIT |
def create_label(db):
"""Return a callable which lets you create dummy labels."""
def _create_label(title, color='red'):
label = EventLabel(title=title, color=color)
db.session.add(label)
db.session.flush()
return label
return _create_label | Return a callable which lets you create dummy labels. | create_label | python | indico/indico | indico/testing/fixtures/event.py | https://github.com/indico/indico/blob/master/indico/testing/fixtures/event.py | MIT |
def create_application(db):
"""Return a callable which lets you create applications."""
def _create_application(name, **params):
params.setdefault('client_id', str(uuid4()))
params.setdefault('allowed_scopes', ['read:legacy_api', 'write:legacy_api', 'read:user'])
params.setdefault('redi... | Return a callable which lets you create applications. | create_application | python | indico/indico | indico/testing/fixtures/oauth.py | https://github.com/indico/indico/blob/master/indico/testing/fixtures/oauth.py | MIT |
def dummy_app_link(db, dummy_application, dummy_user):
"""Return an app link for the dummy user."""
link = OAuthApplicationUserLink(application=dummy_application, user=dummy_user,
scopes=['read:legacy_api', 'read:user'])
db.session.add(link)
db.session.flush()
ret... | Return an app link for the dummy user. | dummy_app_link | python | indico/indico | indico/testing/fixtures/oauth.py | https://github.com/indico/indico/blob/master/indico/testing/fixtures/oauth.py | MIT |
def dummy_token(db, dummy_app_link):
"""Return a token for the dummy app/user."""
token_string = TOKEN_PREFIX_OAUTH + generate_token()
token = OAuthToken(access_token=token_string, app_user_link=dummy_app_link, scopes=['read:legacy_api', 'read:user'])
token._plaintext_token = token_string
db.session... | Return a token for the dummy app/user. | dummy_token | python | indico/indico | indico/testing/fixtures/oauth.py | https://github.com/indico/indico/blob/master/indico/testing/fixtures/oauth.py | MIT |
def dummy_personal_token(db, dummy_user):
"""Return a personal token for the dummy user."""
token = PersonalToken(name='dummy', user=dummy_user, scopes=['read:legacy_api', 'read:user'])
token._plaintext_token = token.generate_token()
db.session.add(token)
db.session.flush()
return token | Return a personal token for the dummy user. | dummy_personal_token | python | indico/indico | indico/testing/fixtures/oauth.py | https://github.com/indico/indico/blob/master/indico/testing/fixtures/oauth.py | MIT |
def create_paper_revision(db):
"""Return a callable which lets you create paper revisions."""
def _create_paper_revision(paper, submitter):
revision = PaperRevision(paper=paper, submitter=submitter)
db.session.flush()
return revision
return _create_paper_revision | Return a callable which lets you create paper revisions. | create_paper_revision | python | indico/indico | indico/testing/fixtures/paper.py | https://github.com/indico/indico/blob/master/indico/testing/fixtures/paper.py | MIT |
def create_paper_file(db):
"""Return a callable which lets you create paper files."""
def _create_paper_file(revision, file, **kwargs):
paper_file = PaperFile(filename=file.filename, content_type=file.content_type,
paper_revision=revision,
_c... | Return a callable which lets you create paper files. | create_paper_file | python | indico/indico | indico/testing/fixtures/paper.py | https://github.com/indico/indico/blob/master/indico/testing/fixtures/paper.py | MIT |
def create_event_person(db):
"""Return a callable which lets you create event persons."""
def _create(event, user=None, first_name=None, last_name=None, email=None, affiliation=None, title=None):
person = EventPerson(event=event,
user=user,
first... | Return a callable which lets you create event persons. | create_event_person | python | indico/indico | indico/testing/fixtures/person.py | https://github.com/indico/indico/blob/master/indico/testing/fixtures/person.py | MIT |
def create_location(db):
"""Return a callable which lets you create locations."""
def _create_location(name, **params):
location = Location(name=name, **params)
db.session.add(location)
db.session.flush()
return location
return _create_location | Return a callable which lets you create locations. | create_location | python | indico/indico | indico/testing/fixtures/rb.py | https://github.com/indico/indico/blob/master/indico/testing/fixtures/rb.py | MIT |
def create_reservation(db, dummy_room, dummy_user):
"""Return a callable which lets you create reservations."""
def _create_reservation(*, allow_admin=False, **params):
params.setdefault('start_dt', date.today() + relativedelta(hour=8, minute=30))
params.setdefault('end_dt', date.today() + relat... | Return a callable which lets you create reservations. | create_reservation | python | indico/indico | indico/testing/fixtures/rb.py | https://github.com/indico/indico/blob/master/indico/testing/fixtures/rb.py | MIT |
def create_occurrence(create_reservation):
"""Return a callable which lets you create reservation occurrences."""
def _create_occurrence(start_dt=None, end_dt=None, room=None):
params = {}
if start_dt is not None:
params['start_dt'] = start_dt
if end_dt is not None:
... | Return a callable which lets you create reservation occurrences. | create_occurrence | python | indico/indico | indico/testing/fixtures/rb.py | https://github.com/indico/indico/blob/master/indico/testing/fixtures/rb.py | MIT |
def create_room(db, dummy_location, dummy_user):
"""Return a callable which lets you create rooms."""
def _create_room(**params):
params.setdefault('building', '1')
params.setdefault('floor', '2')
params.setdefault('number', '3')
params.setdefault('owner', dummy_user)
par... | Return a callable which lets you create rooms. | create_room | python | indico/indico | indico/testing/fixtures/rb.py | https://github.com/indico/indico/blob/master/indico/testing/fixtures/rb.py | MIT |
def create_room_attribute(db):
"""Return a callable which let you create room attributes."""
def _create_attribute(name):
attr = RoomAttribute(name=name, title=name)
db.session.add(attr)
db.session.flush()
return attr
return _create_attribute | Return a callable which let you create room attributes. | create_room_attribute | python | indico/indico | indico/testing/fixtures/rb.py | https://github.com/indico/indico/blob/master/indico/testing/fixtures/rb.py | MIT |
def create_equipment_type(db):
"""Return a callable which let you create equipment types."""
def _create_equipment_type(name):
eq = EquipmentType(name=name)
db.session.add(eq)
db.session.flush()
return eq
return _create_equipment_type | Return a callable which let you create equipment types. | create_equipment_type | python | indico/indico | indico/testing/fixtures/rb.py | https://github.com/indico/indico/blob/master/indico/testing/fixtures/rb.py | MIT |
def create_blocking(db, dummy_room, dummy_user):
"""Return a callable which lets you create blockings."""
def _create_blocking(**params):
room = params.pop('room', dummy_room)
state = params.pop('state', BlockedRoom.State.pending)
params.setdefault('start_date', date.today())
par... | Return a callable which lets you create blockings. | create_blocking | python | indico/indico | indico/testing/fixtures/rb.py | https://github.com/indico/indico/blob/master/indico/testing/fixtures/rb.py | MIT |
def create_session(db):
"""Return a callable that lets you create a session."""
def _create_session(event, title, **kwargs):
sess = Session(event=event, title=title, **kwargs)
db.session.add(sess)
db.session.flush()
return sess
return _create_session | Return a callable that lets you create a session. | create_session | python | indico/indico | indico/testing/fixtures/session.py | https://github.com/indico/indico/blob/master/indico/testing/fixtures/session.py | MIT |
def create_session_block(db, create_timetable_entry):
"""Return a callable that lets you create a session block."""
def _create_session_block(session, title, duration, start_dt, **kwargs):
block = SessionBlock(session=session, title=title, duration=duration, **kwargs)
db.session.add(block)
... | Return a callable that lets you create a session block. | create_session_block | python | indico/indico | indico/testing/fixtures/session.py | https://github.com/indico/indico/blob/master/indico/testing/fixtures/session.py | MIT |
def smtp(disallow_emails, smtpserver, app):
"""Wrapper for the `smtpserver` fixture which updates the Indico config
and disables the SMTP autofail logic for that smtp server.
"""
old_email_host = app.config['EMAIL_HOST']
old_email_port = app.config['EMAIL_PORT']
app.config['EMAIL_HOST'] = smtpse... | Wrapper for the `smtpserver` fixture which updates the Indico config
and disables the SMTP autofail logic for that smtp server.
| smtp | python | indico/indico | indico/testing/fixtures/smtp.py | https://github.com/indico/indico/blob/master/indico/testing/fixtures/smtp.py | MIT |
def create_attachment(db):
"""Return a callable which lets you create attachments."""
def _create_attachment(user, object, title, attachment_folder_id=None, attachment_file_id=None, **kwargs):
folder = AttachmentFolder(id=attachment_folder_id, object=object, title='dummy_folder',
... | Return a callable which lets you create attachments. | create_attachment | python | indico/indico | indico/testing/fixtures/storage.py | https://github.com/indico/indico/blob/master/indico/testing/fixtures/storage.py | MIT |
def create_file(db):
"""Return a callable which lets you create (unclaimed) files."""
def _create_file(filename, content_type, context, data, **kwargs):
file = File(filename=filename, content_type=content_type, **kwargs)
file.save(context, data.encode())
db.session.add(file)
db.s... | Return a callable which lets you create (unclaimed) files. | create_file | python | indico/indico | indico/testing/fixtures/storage.py | https://github.com/indico/indico/blob/master/indico/testing/fixtures/storage.py | MIT |
def create_timetable_entry(db):
"""Return a callable that lets you create a timetable entry."""
def _create_timetable_entry(event, obj, start_dt, parent=None):
if isinstance(obj, SessionBlock):
entry_type = TimetableEntryType.SESSION_BLOCK
elif isinstance(obj, Contribution):
... | Return a callable that lets you create a timetable entry. | create_timetable_entry | python | indico/indico | indico/testing/fixtures/timetable.py | https://github.com/indico/indico/blob/master/indico/testing/fixtures/timetable.py | MIT |
def create_user(db):
"""Return a callable which lets you create dummy users."""
def _create_user(id_, first_name='Guinea', last_name='Pig', rb_admin=False, admin=False, email=None, groups=None):
user = User.get(id_)
if user:
return user
user = User()
user.id = id_
... | Return a callable which lets you create dummy users. | create_user | python | indico/indico | indico/testing/fixtures/user.py | https://github.com/indico/indico/blob/master/indico/testing/fixtures/user.py | MIT |
def create_group(db):
"""Return a callable which lets you create dummy groups."""
def _create_group(id_, group_name=None):
group = LocalGroup()
group.id = id_
group.name = group_name or f'dummy-{id_}'
db.session.add(group)
db.session.flush()
return group.proxy
... | Return a callable which lets you create dummy groups. | create_group | python | indico/indico | indico/testing/fixtures/user.py | https://github.com/indico/indico/blob/master/indico/testing/fixtures/user.py | MIT |
def create_identity(db):
"""Return a callable which lets you create dummy identities."""
def _create_identity(user, provider, identifier, **kwargs):
identity = Identity(user=user, provider=provider, identifier=identifier, **kwargs)
db.session.flush()
return identity
return _create_i... | Return a callable which lets you create dummy identities. | create_identity | python | indico/indico | indico/testing/fixtures/user.py | https://github.com/indico/indico/blob/master/indico/testing/fixtures/user.py | MIT |
def monkeypatch_methods(monkeypatch):
"""Monkeypatch all methods from `cls` onto `target`.
This utility lets you easily mock multiple methods in an existing class.
In case of classmethods the binding will not be changed, i.e. `cls` will
keep pointing to the source class and not the target class.
""... | Monkeypatch all methods from `cls` onto `target`.
This utility lets you easily mock multiple methods in an existing class.
In case of classmethods the binding will not be changed, i.e. `cls` will
keep pointing to the source class and not the target class.
| monkeypatch_methods | python | indico/indico | indico/testing/fixtures/util.py | https://github.com/indico/indico/blob/master/indico/testing/fixtures/util.py | MIT |
def freeze_time(monkeypatch):
"""Return a function that freezes the current time.
It affects datetime.now, date.today, etc. and also SQLAlchemy's `func.now()`
which simply returns the current time from `datetime.now()` instead of
retrieving it using the actual `now()` function of PostgreSQL.
"""
... | Return a function that freezes the current time.
It affects datetime.now, date.today, etc. and also SQLAlchemy's `func.now()`
which simply returns the current time from `datetime.now()` instead of
retrieving it using the actual `now()` function of PostgreSQL.
| freeze_time | python | indico/indico | indico/testing/fixtures/util.py | https://github.com/indico/indico/blob/master/indico/testing/fixtures/util.py | MIT |
def memoize_request(f):
"""Memoize a function during the current request."""
@wraps(f)
def memoizer(*args, **kwargs):
if not has_request_context() or current_app.config['TESTING'] or current_app.config.get('REPL'):
# No memoization outside request context
return f(*args, **kw... | Memoize a function during the current request. | memoize_request | python | indico/indico | indico/util/caching.py | https://github.com/indico/indico/blob/master/indico/util/caching.py | MIT |
def memoize_redis(ttl, *, versioned=False):
"""Memoize a function in redis.
The cached value can be cleared by calling the method
``clear_cached()`` of the decorated function with the same
arguments that were used during the function call. To check
whether a value has been cached call ``is_cached(... | Memoize a function in redis.
The cached value can be cleared by calling the method
``clear_cached()`` of the decorated function with the same
arguments that were used during the function call. To check
whether a value has been cached call ``is_cached()`` in the
same way.
:param ttl: How long ... | memoize_redis | python | indico/indico | indico/util/caching.py | https://github.com/indico/indico/blob/master/indico/util/caching.py | MIT |
def generate_contrast_colors(seed):
"""Generates a background and text colors with sufficient contrast given a seed."""
hue = 1.0 / (1.0 + seed % 20)
saturation = 1.0 / (1.0 + seed % 4)
if saturation < 0.5:
saturation += 0.5
brightness = 1.0 / (1.0 + seed % 3)
if brightness < 0.5:
... | Generates a background and text colors with sufficient contrast given a seed. | generate_contrast_colors | python | indico/indico | indico/util/colors.py | https://github.com/indico/indico/blob/master/indico/util/colors.py | MIT |
def verbose_iterator(iterable, total, get_id=None, get_title=None, print_every=10, print_total_time=False):
"""Iterate large iterables verbosely.
:param iterable: An iterable
:param total: The number of items in `iterable`
:param get_id: callable to retrieve the ID of an item
:param get_title: call... | Iterate large iterables verbosely.
:param iterable: An iterable
:param total: The number of items in `iterable`
:param get_id: callable to retrieve the ID of an item
:param get_title: callable to retrieve the title of an item
:param print_every: after which number of items to update the progress
... | verbose_iterator | python | indico/indico | indico/util/console.py | https://github.com/indico/indico/blob/master/indico/util/console.py | MIT |
def cformat(string):
"""Replace %{color} and %{color,bgcolor} with ansi colors.
Bold foreground can be achieved by suffixing the color with a '!'.
"""
reset = Color('{/all}')
string = string.replace('%{reset}', reset)
string = re.sub(r'%\{(?P<fg>[a-z]+)(?P<fg_bold>!?)(?:,(?P<bg>[a-z]+))?}', _cf... | Replace %{color} and %{color,bgcolor} with ansi colors.
Bold foreground can be achieved by suffixing the color with a '!'.
| cformat | python | indico/indico | indico/util/console.py | https://github.com/indico/indico/blob/master/indico/util/console.py | MIT |
def get_country_reverse(name, locale=None, case_sensitive=True):
"""Get the country code from a country name.
Note: You almost certainly should not use this but rather store
the country code and use it directly.
The only reason this util exists is that the friendly_data handling
for registration fo... | Get the country code from a country name.
Note: You almost certainly should not use this but rather store
the country code and use it directly.
The only reason this util exists is that the friendly_data handling
for registration form fields is one big mess (human-friendly vs
machine-friendly)...
... | get_country_reverse | python | indico/indico | indico/util/countries.py | https://github.com/indico/indico/blob/master/indico/util/countries.py | MIT |
def get_countries_regex(locale=None):
"""Get a regex to search for country names in a string."""
if locale is None:
locale = get_current_locale()
return _get_countries_regex(locale) | Get a regex to search for country names in a string. | get_countries_regex | python | indico/indico | indico/util/countries.py | https://github.com/indico/indico/blob/master/indico/util/countries.py | MIT |
def now_utc(exact=True):
"""Get the current date/time in UTC.
:param exact: Set to ``False`` to set seconds/microseconds to 0.
:return: A timezone-aware `datetime` object
"""
now = datetime.now(pytz.UTC)
if not exact:
now = now.replace(second=0, microsecond=0)
return now | Get the current date/time in UTC.
:param exact: Set to ``False`` to set seconds/microseconds to 0.
:return: A timezone-aware `datetime` object
| now_utc | python | indico/indico | indico/util/date_time.py | https://github.com/indico/indico/blob/master/indico/util/date_time.py | MIT |
def as_utc(dt):
"""Return the given naive datetime with tzinfo=UTC."""
if dt.tzinfo and dt.tzinfo != pytz.utc:
raise ValueError(f'{dt} already contains non-UTC tzinfo data')
return pytz.utc.localize(dt) if dt.tzinfo is None else dt | Return the given naive datetime with tzinfo=UTC. | as_utc | python | indico/indico | indico/util/date_time.py | https://github.com/indico/indico/blob/master/indico/util/date_time.py | MIT |
def _adjust_skeleton(format, skeleton):
"""If possible, expand pattern fields to match the requested skeleton.
For example if the requested skeleton is 'yMM' and the format is 'yM' we can expand
this back to 'yMM'. Note that we are not allowed to expand numeric fields to
alphanumeric fields and vice ve... | If possible, expand pattern fields to match the requested skeleton.
For example if the requested skeleton is 'yMM' and the format is 'yM' we can expand
this back to 'yMM'. Note that we are not allowed to expand numeric fields to
alphanumeric fields and vice versa.
For example, 'MM' cannot be expanded ... | _adjust_skeleton | python | indico/indico | indico/util/date_time.py | https://github.com/indico/indico/blob/master/indico/util/date_time.py | MIT |
def format_human_timedelta(delta, granularity='seconds', narrow=False, *, weeks=False):
"""Format a timedelta in a human-readable way.
:param delta: the timedelta to format
:param granularity: the granularity, i.e. the lowest unit that is
still displayed. when set e.g. to 'minutes',... | Format a timedelta in a human-readable way.
:param delta: the timedelta to format
:param granularity: the granularity, i.e. the lowest unit that is
still displayed. when set e.g. to 'minutes',
the output will never contain seconds unless
t... | format_human_timedelta | python | indico/indico | indico/util/date_time.py | https://github.com/indico/indico/blob/master/indico/util/date_time.py | MIT |
def format_human_date(dt, format='medium', locale=None):
"""
Return the date in a human-like format for yesterday, today and tomorrow.
Format the date otherwise.
"""
today = now_utc().date()
oneday = timedelta(days=1)
if not locale:
locale = get_current_locale()
if dt == today... |
Return the date in a human-like format for yesterday, today and tomorrow.
Format the date otherwise.
| format_human_date | python | indico/indico | indico/util/date_time.py | https://github.com/indico/indico/blob/master/indico/util/date_time.py | MIT |
def format_pretty_date(dt, locale=None, tzinfo=None):
"""Format a date in a pretty way using relative units if possible.
:param dt: a date or datetime object. if a date is provided, its
time is assumed to be midnight
:param locale: the locale to use for formatting
:param tzinfo: the time... | Format a date in a pretty way using relative units if possible.
:param dt: a date or datetime object. if a date is provided, its
time is assumed to be midnight
:param locale: the locale to use for formatting
:param tzinfo: the timezone to use
| format_pretty_date | python | indico/indico | indico/util/date_time.py | https://github.com/indico/indico/blob/master/indico/util/date_time.py | MIT |
def format_pretty_datetime(dt, locale=None, tzinfo=None):
"""
Format a datetime in a pretty way using relative units for the
date if possible.
:param dt: a datetime object
:param locale: the locale to use for formatting
:param tzinfo: the timezone to use
"""
return _format_pretty_dateti... |
Format a datetime in a pretty way using relative units for the
date if possible.
:param dt: a datetime object
:param locale: the locale to use for formatting
:param tzinfo: the timezone to use
| format_pretty_datetime | python | indico/indico | indico/util/date_time.py | https://github.com/indico/indico/blob/master/indico/util/date_time.py | MIT |
def timedelta_split(delta):
"""
Decompose a timedelta into hours, minutes and seconds
(timedelta only stores days and seconds).
"""
sec = delta.seconds + delta.days * 24 * 3600
hours, remainder = divmod(sec, 3600)
minutes, seconds = divmod(remainder, 60)
return hours, minutes, seconds |
Decompose a timedelta into hours, minutes and seconds
(timedelta only stores days and seconds).
| timedelta_split | python | indico/indico | indico/util/date_time.py | https://github.com/indico/indico/blob/master/indico/util/date_time.py | MIT |
def get_day_start(day, tzinfo=None):
"""Return the earliest datetime for a given day.
:param day: A `date` or `datetime`.
:param tzinfo: The timezone to display the resulting datetime. Not valid for
non-naive `datetime` objects.
"""
if isinstance(day, datetime):
if day.tz... | Return the earliest datetime for a given day.
:param day: A `date` or `datetime`.
:param tzinfo: The timezone to display the resulting datetime. Not valid for
non-naive `datetime` objects.
| get_day_start | python | indico/indico | indico/util/date_time.py | https://github.com/indico/indico/blob/master/indico/util/date_time.py | MIT |
def get_day_end(day, tzinfo=None):
"""Return the latest datetime for a given day.
:param day: A `date` or `datetime`.
:param tzinfo: The timezone to display the resulting datetime. Not valid for
non-naive `datetime` objects.
"""
if isinstance(day, datetime):
if day.tzinfo... | Return the latest datetime for a given day.
:param day: A `date` or `datetime`.
:param tzinfo: The timezone to display the resulting datetime. Not valid for
non-naive `datetime` objects.
| get_day_end | python | indico/indico | indico/util/date_time.py | https://github.com/indico/indico/blob/master/indico/util/date_time.py | MIT |
def strftime_all_years(dt, fmt):
"""Exactly like datetime.strftime but supports year<1900."""
assert '%%Y' not in fmt # unlikely but just in case
if dt.year >= 1900:
return dt.strftime(fmt)
else:
return dt.replace(year=1900).strftime(fmt.replace('%Y', '%%Y')).replace('%Y', str(dt.year)) | Exactly like datetime.strftime but supports year<1900. | strftime_all_years | python | indico/indico | indico/util/date_time.py | https://github.com/indico/indico/blob/master/indico/util/date_time.py | MIT |
def truncate_path(full_path, chars=30, skip_first=True):
"""Truncate the path of a category to the number of character.
Only the path is truncated by removing nodes, but the nodes
themselves are never truncated.
If the last node is longer than the ``chars`` constraint, then it is
returned as is (w... | Truncate the path of a category to the number of character.
Only the path is truncated by removing nodes, but the nodes
themselves are never truncated.
If the last node is longer than the ``chars`` constraint, then it is
returned as is (with ``None`` for the first and inner nodes.)
This is the onl... | truncate_path | python | indico/indico | indico/util/event.py | https://github.com/indico/indico/blob/master/indico/util/event.py | MIT |
def secure_filename(filename, fallback):
"""Return a secure version of a filename.
This removes possibly dangerous characters and also converts the
filename to plain ASCII for maximum compatibility. It should only
be used for file system storage, since especially filenames written
in asian language... | Return a secure version of a filename.
This removes possibly dangerous characters and also converts the
filename to plain ASCII for maximum compatibility. It should only
be used for file system storage, since especially filenames written
in asian languages likely become useless when stripping anything
... | secure_filename | python | indico/indico | indico/util/fs.py | https://github.com/indico/indico/blob/master/indico/util/fs.py | MIT |
def secure_client_filename(filename, fallback='file'):
"""Return a secure version of filename for clients.
This removes possibly dangerous characters (which would result in
unexpected behavior in URLs or archive paths).
It should never be used to sanitize filenames for server-side storage;
use :fun... | Return a secure version of filename for clients.
This removes possibly dangerous characters (which would result in
unexpected behavior in URLs or archive paths).
It should never be used to sanitize filenames for server-side storage;
use :func:`secure_filename` in that case.
:param filename: A file... | secure_client_filename | python | indico/indico | indico/util/fs.py | https://github.com/indico/indico/blob/master/indico/util/fs.py | MIT |
def removedirs(base, name):
"""Delete the leaf dir and try deleting all parents.
:param base: The base dir `name` is relative to.
:param name: The path to the directory to be deleted.
This basically ``rmdir -p`` and acts like :func:`os.removedirs`
except that it will not ascend above `base`.
"... | Delete the leaf dir and try deleting all parents.
:param base: The base dir `name` is relative to.
:param name: The path to the directory to be deleted.
This basically ``rmdir -p`` and acts like :func:`os.removedirs`
except that it will not ascend above `base`.
| removedirs | python | indico/indico | indico/util/fs.py | https://github.com/indico/indico/blob/master/indico/util/fs.py | MIT |
def cleanup_dir(path, min_age, dry_run=False, exclude=None):
"""Delete old files from a directory.
This recurses into subdirectories and will also delete any empty
subdirectories.
:param path: The directory to clean up
:param min_age: A timedelta specifying how old files need to be
... | Delete old files from a directory.
This recurses into subdirectories and will also delete any empty
subdirectories.
:param path: The directory to clean up
:param min_age: A timedelta specifying how old files need to be
so they are deleted.
:param dry_run: If true, this function... | cleanup_dir | python | indico/indico | indico/util/fs.py | https://github.com/indico/indico/blob/master/indico/util/fs.py | MIT |
def chmod_umask(path, execute=False):
"""Change the permissions of a file to the umask-based default.
:param path: The path to the file/directory
:param execute: Whether the x-bit may be set
"""
# XXX: umask cannot be read except when changing it,
# so we change it and immediately restore it...... | Change the permissions of a file to the umask-based default.
:param path: The path to the file/directory
:param execute: Whether the x-bit may be set
| chmod_umask | python | indico/indico | indico/util/fs.py | https://github.com/indico/indico/blob/master/indico/util/fs.py | MIT |
def _wrap(*args, **kwargs):
"""
Return either a translated string or a lazy-translatable object,
depending on whether there is a session language or not (respectively).
"""
if has_request_context() or func_name not in {'gettext', 'pgettext'}:
# straight translation
... |
Return either a translated string or a lazy-translatable object,
depending on whether there is a session language or not (respectively).
| _wrap | python | indico/indico | indico/util/i18n.py | https://github.com/indico/indico/blob/master/indico/util/i18n.py | MIT |
def force_locale(locale, *, default=True):
"""Temporarily override the locale.
Use this as a context manager in a ``with`` block.
`locale` can be set to ``None`` to avoid translation and thus
use the hardcoded string which is en_US.
:param locale: The locale to force
:param default: Whether to... | Temporarily override the locale.
Use this as a context manager in a ``with`` block.
`locale` can be set to ``None`` to avoid translation and thus
use the hardcoded string which is en_US.
:param locale: The locale to force
:param default: Whether to use the server default instead of en_US
... | force_locale | python | indico/indico | indico/util/i18n.py | https://github.com/indico/indico/blob/master/indico/util/i18n.py | MIT |
def set_best_lang(check_session=True):
"""Get the best language/locale for the current user.
This means that first the session will be checked, and then in the
absence of an explicitly-set language, we will try to guess it from
the browser settings and only after that fall back to
the server's defa... | Get the best language/locale for the current user.
This means that first the session will be checked, and then in the
absence of an explicitly-set language, we will try to guess it from
the browser settings and only after that fall back to
the server's default.
| set_best_lang | python | indico/indico | indico/util/i18n.py | https://github.com/indico/indico/blob/master/indico/util/i18n.py | MIT |
def get_all_locales():
"""List all available locales/names e.g. ``{'pt_PT': ('Portuguese', 'Portugal', True)}``."""
if not has_app_context():
return {}
else:
missing = object()
languages = {
str(t): config.CUSTOM_LANGUAGES.get(str(t), (t.language_name.title(), t.territory... | List all available locales/names e.g. ``{'pt_PT': ('Portuguese', 'Portugal', True)}``. | get_all_locales | python | indico/indico | indico/util/i18n.py | https://github.com/indico/indico/blob/master/indico/util/i18n.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.