_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q241100 | limit_gen | train | def limit_gen(limit, iterable):
'''A generator that applies a count `limit`.'''
limit = int(limit)
assert limit >= 0, 'negative limit'
for item in iterable:
if limit <= 0:
break
yield item
limit -= 1 | python | {
"resource": ""
} |
q241101 | offset_gen | train | def offset_gen(offset, iterable, skip_signal=None):
'''A generator that applies an `offset`, skipping `offset` elements from
`iterable`. If skip_signal is a callable, it will be called with every
skipped element.
'''
offset = int(offset)
assert offset >= 0, 'negative offset'
for item in iterable:
if ... | python | {
"resource": ""
} |
q241102 | Filter.valuePasses | train | def valuePasses(self, value):
'''Returns whether this value passes this filter'''
return self._conditional_cmp[self.op](value, self.value) | python | {
"resource": ""
} |
q241103 | Filter.filter | train | def filter(cls, filters, iterable):
'''Returns the elements in `iterable` that pass given `filters`'''
if isinstance(filters, Filter):
filters = [filters]
for filter in filters:
iterable = filter.generator(iterable)
return iterable | python | {
"resource": ""
} |
q241104 | Order.multipleOrderComparison | train | def multipleOrderComparison(cls, orders):
'''Returns a function that will compare two items according to `orders`'''
comparers = [ (o.keyfn, 1 if o.isAscending() else -1) for o in orders]
def cmpfn(a, b):
for keyfn, ascOrDesc in comparers:
comparison = cmp(keyfn(a), keyfn(b)) * ascOrDesc
... | python | {
"resource": ""
} |
q241105 | Order.sorted | train | def sorted(cls, items, orders):
'''Returns the elements in `items` sorted according to `orders`'''
return sorted(items, cmp=cls.multipleOrderComparison(orders)) | python | {
"resource": ""
} |
q241106 | Query.order | train | def order(self, order):
'''Adds an Order to this query.
Args:
see :py:class:`Order <datastore.query.Order>` constructor
Returns self for JS-like method chaining::
query.order('+age').order('-home')
'''
order = order if isinstance(order, Order) else Order(order)
# ensure order ge... | python | {
"resource": ""
} |
q241107 | Query.filter | train | def filter(self, *args):
'''Adds a Filter to this query.
Args:
see :py:class:`Filter <datastore.query.Filter>` constructor
Returns self for JS-like method chaining::
query.filter('age', '>', 18).filter('sex', '=', 'Female')
'''
if len(args) == 1 and isinstance(args[0], Filter):
... | python | {
"resource": ""
} |
q241108 | Query.copy | train | def copy(self):
'''Returns a copy of this query.'''
if self.object_getattr is Query.object_getattr:
other = Query(self.key)
else:
other = Query(self.key, object_getattr=self.object_getattr)
other.limit = self.limit
other.offset = self.offset
other.offset_key = self.offset_key
oth... | python | {
"resource": ""
} |
q241109 | Query.dict | train | def dict(self):
'''Returns a dictionary representing this query.'''
d = dict()
d['key'] = str(self.key)
if self.limit is not None:
d['limit'] = self.limit
if self.offset > 0:
d['offset'] = self.offset
if self.offset_key:
d['offset_key'] = str(self.offset_key)
if len(self.f... | python | {
"resource": ""
} |
q241110 | Query.from_dict | train | def from_dict(cls, dictionary):
'''Constructs a query from a dictionary.'''
query = cls(Key(dictionary['key']))
for key, value in dictionary.items():
if key == 'order':
for order in value:
query.order(order)
elif key == 'filter':
for filter in value:
if not... | python | {
"resource": ""
} |
q241111 | Cursor.next | train | def next(self):
'''Iterator next. Build up count of returned elements during iteration.'''
# if iteration has not begun, begin it.
if not self._iterator:
self.__iter__()
next = self._iterator.next()
if next is not StopIteration:
self._returned_inc(next)
return next | python | {
"resource": ""
} |
q241112 | Cursor.apply_filter | train | def apply_filter(self):
'''Naively apply query filters.'''
self._ensure_modification_is_safe()
if len(self.query.filters) > 0:
self._iterable = Filter.filter(self.query.filters, self._iterable) | python | {
"resource": ""
} |
q241113 | Cursor.apply_order | train | def apply_order(self):
'''Naively apply query orders.'''
self._ensure_modification_is_safe()
if len(self.query.orders) > 0:
self._iterable = Order.sorted(self._iterable, self.query.orders) | python | {
"resource": ""
} |
q241114 | Cursor.apply_offset | train | def apply_offset(self):
'''Naively apply query offset.'''
self._ensure_modification_is_safe()
if self.query.offset != 0:
self._iterable = \
offset_gen(self.query.offset, self._iterable, self._skipped_inc) | python | {
"resource": ""
} |
q241115 | Cursor.apply_limit | train | def apply_limit(self):
'''Naively apply query limit.'''
self._ensure_modification_is_safe()
if self.query.limit is not None:
self._iterable = limit_gen(self.query.limit, self._iterable) | python | {
"resource": ""
} |
q241116 | run_transaction | train | def run_transaction(transactor, callback):
"""Run a transaction with retries.
``callback()`` will be called with one argument to execute the
transaction. ``callback`` may be called more than once; it should have
no side effects other than writes to the database on the given
connection. ``callback``... | python | {
"resource": ""
} |
q241117 | _txn_retry_loop | train | def _txn_retry_loop(conn, callback):
"""Inner transaction retry loop.
``conn`` may be either a Connection or a Session, but they both
have compatible ``begin()`` and ``begin_nested()`` methods.
"""
with conn.begin():
while True:
try:
with _NestedTransaction(conn)... | python | {
"resource": ""
} |
q241118 | Tree._get | train | def _get(self, pos):
"""loads widget at given position; handling invalid arguments"""
res = None, None
if pos is not None:
try:
res = self[pos], pos
except (IndexError, KeyError):
pass
return res | python | {
"resource": ""
} |
q241119 | Tree._next_of_kin | train | def _next_of_kin(self, pos):
"""
looks up the next sibling of the closest ancestor with not-None next
siblings.
"""
candidate = None
parent = self.parent_position(pos)
if parent is not None:
candidate = self.next_sibling_position(parent)
if... | python | {
"resource": ""
} |
q241120 | Tree._last_in_direction | train | def _last_in_direction(starting_pos, direction):
"""
move in the tree in given direction and return the last position.
:param starting_pos: position to start at
:param direction: callable that transforms a position into a position.
"""
cur_pos = None
next_pos = s... | python | {
"resource": ""
} |
q241121 | Tree.depth | train | def depth(self, pos):
"""determine depth of node at pos"""
parent = self.parent_position(pos)
if parent is None:
return 0
else:
return self.depth(parent) + 1 | python | {
"resource": ""
} |
q241122 | Tree.next_position | train | def next_position(self, pos):
"""returns the next position in depth-first order"""
candidate = None
if pos is not None:
candidate = self.first_child_position(pos)
if candidate is None:
candidate = self.next_sibling_position(pos)
if candidat... | python | {
"resource": ""
} |
q241123 | Tree.prev_position | train | def prev_position(self, pos):
"""returns the previous position in depth-first order"""
candidate = None
if pos is not None:
prevsib = self.prev_sibling_position(pos) # is None if first
if prevsib is not None:
candidate = self.last_decendant(prevsib)
... | python | {
"resource": ""
} |
q241124 | Tree.positions | train | def positions(self, reverse=False):
"""returns a generator that walks the positions of this tree in DFO"""
def Posgen(reverse):
if reverse:
lastrootsib = self.last_sibling_position(self.root)
current = self.last_decendant(lastrootsib)
while cur... | python | {
"resource": ""
} |
q241125 | SimpleTree._get_substructure | train | def _get_substructure(self, treelist, pos):
"""recursive helper to look up node-tuple for `pos` in `treelist`"""
subtree = None
if len(pos) > 1:
subtree = self._get_substructure(treelist[pos[0]][1], pos[1:])
else:
try:
subtree = treelist[pos[0]]
... | python | {
"resource": ""
} |
q241126 | SimpleTree._get_node | train | def _get_node(self, treelist, pos):
"""
look up widget at `pos` of `treelist`; default to None if
nonexistent.
"""
node = None
if pos is not None:
subtree = self._get_substructure(treelist, pos)
if subtree is not None:
node = subtre... | python | {
"resource": ""
} |
q241127 | SimpleTree._confirm_pos | train | def _confirm_pos(self, pos):
"""look up widget for pos and default to None"""
candidate = None
if self._get_node(self._treelist, pos) is not None:
candidate = pos
return candidate | python | {
"resource": ""
} |
q241128 | DirectoryTree._list_dir | train | def _list_dir(self, path):
"""returns absolute paths for all entries in a directory"""
try:
elements = [
os.path.join(path, x) for x in os.listdir(path)
] if os.path.isdir(path) else []
elements.sort()
except OSError:
elements = Non... | python | {
"resource": ""
} |
q241129 | DirectoryTree._get_siblings | train | def _get_siblings(self, pos):
"""lists the parent directory of pos """
parent = self.parent_position(pos)
siblings = [pos]
if parent is not None:
siblings = self._list_dir(parent)
return siblings | python | {
"resource": ""
} |
q241130 | OrderableAdmin.reorder_view | train | def reorder_view(self, request):
"""The 'reorder' admin view for this model."""
model = self.model
if not self.has_change_permission(request):
raise PermissionDenied
if request.method == "POST":
object_pks = request.POST.getlist('neworder[]')
model.o... | python | {
"resource": ""
} |
q241131 | CollapseMixin.is_collapsed | train | def is_collapsed(self, pos):
"""checks if given position is currently collapsed"""
collapsed = self._initially_collapsed(pos)
if pos in self._divergent_positions:
collapsed = not collapsed
return collapsed | python | {
"resource": ""
} |
q241132 | ArrowTree._construct_spacer | train | def _construct_spacer(self, pos, acc):
"""
build a spacer that occupies the horizontally indented space between
pos's parent and the root node. It will return a list of tuples to be
fed into a Columns widget.
"""
parent = self._tree.parent_position(pos)
if parent ... | python | {
"resource": ""
} |
q241133 | ArrowTree._construct_connector | train | def _construct_connector(self, pos):
"""
build widget to be used as "connector" bit between the vertical bar
between siblings and their respective horizontal bars leading to the
arrow tip
"""
# connector symbol, either L or |- shaped.
connectorw = None
con... | python | {
"resource": ""
} |
q241134 | ArrowTree._construct_first_indent | train | def _construct_first_indent(self, pos):
"""
build spacer to occupy the first indentation level from pos to the
left. This is separate as it adds arrowtip and sibling connector.
"""
cols = []
void = urwid.AttrMap(urwid.SolidFill(' '), self._arrow_att)
available_wid... | python | {
"resource": ""
} |
q241135 | TreeBox.collapse_focussed | train | def collapse_focussed(self):
"""
Collapse currently focussed position; works only if the underlying
tree allows it.
"""
if implementsCollapseAPI(self._tree):
w, focuspos = self.get_focus()
self._tree.collapse(focuspos)
self._walker.clear_cache(... | python | {
"resource": ""
} |
q241136 | TreeBox.expand_focussed | train | def expand_focussed(self):
"""
Expand currently focussed position; works only if the underlying
tree allows it.
"""
if implementsCollapseAPI(self._tree):
w, focuspos = self.get_focus()
self._tree.expand(focuspos)
self._walker.clear_cache()
... | python | {
"resource": ""
} |
q241137 | TreeBox.collapse_all | train | def collapse_all(self):
"""
Collapse all positions; works only if the underlying tree allows it.
"""
if implementsCollapseAPI(self._tree):
self._tree.collapse_all()
self.set_focus(self._tree.root)
self._walker.clear_cache()
self.refresh() | python | {
"resource": ""
} |
q241138 | TreeBox.expand_all | train | def expand_all(self):
"""
Expand all positions; works only if the underlying tree allows it.
"""
if implementsCollapseAPI(self._tree):
self._tree.expand_all()
self._walker.clear_cache()
self.refresh() | python | {
"resource": ""
} |
q241139 | TreeBox.focus_parent | train | def focus_parent(self):
"""move focus to parent node of currently focussed one"""
w, focuspos = self.get_focus()
parent = self._tree.parent_position(focuspos)
if parent is not None:
self.set_focus(parent) | python | {
"resource": ""
} |
q241140 | TreeBox.focus_first_child | train | def focus_first_child(self):
"""move focus to first child of currently focussed one"""
w, focuspos = self.get_focus()
child = self._tree.first_child_position(focuspos)
if child is not None:
self.set_focus(child) | python | {
"resource": ""
} |
q241141 | TreeBox.focus_last_child | train | def focus_last_child(self):
"""move focus to last child of currently focussed one"""
w, focuspos = self.get_focus()
child = self._tree.last_child_position(focuspos)
if child is not None:
self.set_focus(child) | python | {
"resource": ""
} |
q241142 | TreeBox.focus_next_sibling | train | def focus_next_sibling(self):
"""move focus to next sibling of currently focussed one"""
w, focuspos = self.get_focus()
sib = self._tree.next_sibling_position(focuspos)
if sib is not None:
self.set_focus(sib) | python | {
"resource": ""
} |
q241143 | TreeBox.focus_prev_sibling | train | def focus_prev_sibling(self):
"""move focus to previous sibling of currently focussed one"""
w, focuspos = self.get_focus()
sib = self._tree.prev_sibling_position(focuspos)
if sib is not None:
self.set_focus(sib) | python | {
"resource": ""
} |
q241144 | Orderable.get_unique_fields | train | def get_unique_fields(self):
"""List field names that are unique_together with `sort_order`."""
for unique_together in self._meta.unique_together:
if 'sort_order' in unique_together:
unique_fields = list(unique_together)
unique_fields.remove('sort_order')
... | python | {
"resource": ""
} |
q241145 | Orderable._is_sort_order_unique_together_with_something | train | def _is_sort_order_unique_together_with_something(self):
"""
Is the sort_order field unique_together with something
"""
unique_together = self._meta.unique_together
for fields in unique_together:
if 'sort_order' in fields and len(fields) > 1:
return Tr... | python | {
"resource": ""
} |
q241146 | Orderable._update | train | def _update(qs):
"""
Increment the sort_order in a queryset.
Handle IntegrityErrors caused by unique constraints.
"""
try:
with transaction.atomic():
qs.update(sort_order=models.F('sort_order') + 1)
except IntegrityError:
for obj i... | python | {
"resource": ""
} |
q241147 | Orderable.save | train | def save(self, *args, **kwargs):
"""Keep the unique order in sync."""
objects = self.get_filtered_manager()
old_pos = getattr(self, '_original_sort_order', None)
new_pos = self.sort_order
if old_pos is None and self._unique_togethers_changed():
self.sort_order = None... | python | {
"resource": ""
} |
q241148 | OrderableQueryset.set_orders | train | def set_orders(self, object_pks):
"""
Perform a mass update of sort_orders across the full queryset.
Accepts a list, object_pks, of the intended order for the objects.
Works as follows:
- Compile a list of all sort orders in the queryset. Leave out anything that
isn't ... | python | {
"resource": ""
} |
q241149 | TranslationQuerySet.order_by_json_path | train | def order_by_json_path(self, json_path, language_code=None, order='asc'):
"""
Orders a queryset by the value of the specified `json_path`.
More about the `#>>` operator and the `json_path` arg syntax:
https://www.postgresql.org/docs/current/static/functions-json.html
More about... | python | {
"resource": ""
} |
q241150 | VoteQuerySet.delete | train | def delete(self, *args, **kwargs):
"""Handles updating the related `votes` and `score` fields attached to the model."""
# XXX: circular import
from fields import RatingField
qs = self.distinct().values_list('content_type', 'object_id').order_by('content_type')
to_update = [... | python | {
"resource": ""
} |
q241151 | _BaseServo.set_pulse_width_range | train | def set_pulse_width_range(self, min_pulse=750, max_pulse=2250):
"""Change min and max pulse widths."""
self._min_duty = int((min_pulse * self._pwm_out.frequency) / 1000000 * 0xffff)
max_duty = (max_pulse * self._pwm_out.frequency) / 1000000 * 0xffff
self._duty_range = int(max_duty - self... | python | {
"resource": ""
} |
q241152 | StepperMotor.onestep | train | def onestep(self, *, direction=FORWARD, style=SINGLE):
"""Performs one step of a particular style. The actual rotation amount will vary by style.
`SINGLE` and `DOUBLE` will normal cause a full step rotation. `INTERLEAVE` will normally
do a half step rotation. `MICROSTEP` will perform the s... | python | {
"resource": ""
} |
q241153 | merge_records | train | def merge_records(env, model_name, record_ids, target_record_id,
field_spec=None, method='orm', delete=True,
exclude_columns=None):
"""Merge several records into the target one.
NOTE: This should be executed in end migration scripts for assuring that
all the possible rel... | python | {
"resource": ""
} |
q241154 | allow_pgcodes | train | def allow_pgcodes(cr, *codes):
"""Context manager that will omit specified error codes.
E.g., suppose you expect a migration to produce unique constraint
violations and you want to ignore them. Then you could just do::
with allow_pgcodes(cr, psycopg2.errorcodes.UNIQUE_VIOLATION):
cr.ex... | python | {
"resource": ""
} |
q241155 | check_values_selection_field | train | def check_values_selection_field(cr, table_name, field_name, allowed_values):
"""
check if the field selection 'field_name' of the table 'table_name'
has only the values 'allowed_values'.
If not return False and log an error.
If yes, return True.
.. versionadded:: 8.0
"""
... | python | {
"resource": ""
} |
q241156 | load_data | train | def load_data(cr, module_name, filename, idref=None, mode='init'):
"""
Load an xml, csv or yml data file from your post script. The usual case for
this is the
occurrence of newly added essential or useful data in the module that is
marked with "noupdate='1'" and without "forcecreate='1'" so that it ... | python | {
"resource": ""
} |
q241157 | _get_existing_records | train | def _get_existing_records(cr, fp, module_name):
"""yield file like objects per 'leaf' node in the xml file that exists.
This is for not trying to create a record with partial data in case the
record was removed in the database."""
def yield_element(node, path=None):
if node.tag not in ['openerp'... | python | {
"resource": ""
} |
q241158 | rename_columns | train | def rename_columns(cr, column_spec):
"""
Rename table columns. Typically called in the pre script.
:param column_spec: a hash with table keys, with lists of tuples as \
values. Tuples consist of (old_name, new_name). Use None for new_name \
to trigger a conversion of old_name using get_legacy_name(... | python | {
"resource": ""
} |
q241159 | rename_tables | train | def rename_tables(cr, table_spec):
"""
Rename tables. Typically called in the pre script.
This function also renames the id sequence if it exists and if it is
not modified in the same run.
:param table_spec: a list of tuples (old table name, new table name). Use \
None for new_name to trigger a... | python | {
"resource": ""
} |
q241160 | update_workflow_workitems | train | def update_workflow_workitems(cr, pool, ref_spec_actions):
"""Find all the workflow items from the target state to set them to
the wanted state.
When a workflow action is removed, from model, the objects whose states
are in these actions need to be set to another to be able to continue the
workflow... | python | {
"resource": ""
} |
q241161 | logged_query | train | def logged_query(cr, query, args=None, skip_no_result=False):
"""
Logs query and affected rows at level DEBUG.
:param query: a query string suitable to pass to cursor.execute()
:param args: a list, tuple or dictionary passed as substitution values
to cursor.execute().
:param skip_no_result: I... | python | {
"resource": ""
} |
q241162 | update_module_names | train | def update_module_names(cr, namespec, merge_modules=False):
"""Deal with changed module names, making all the needed changes on the
related tables, like XML-IDs, translations, and so on.
:param namespec: list of tuples of (old name, new name)
:param merge_modules: Specify if the operation should be a m... | python | {
"resource": ""
} |
q241163 | add_ir_model_fields | train | def add_ir_model_fields(cr, columnspec):
"""
Typically, new columns on ir_model_fields need to be added in a very
early stage in the upgrade process of the base module, in raw sql
as they need to be in place before any model gets initialized.
Do not use for fields with additional SQL constraints, su... | python | {
"resource": ""
} |
q241164 | m2o_to_m2m | train | def m2o_to_m2m(cr, model, table, field, source_field):
"""
Recreate relations in many2many fields that were formerly
many2one fields. Use rename_columns in your pre-migrate
script to retain the column's old value, then call m2o_to_m2m
in your post-migrate script.
:param model: The target model ... | python | {
"resource": ""
} |
q241165 | message | train | def message(cr, module, table, column,
message, *args, **kwargs):
"""
Log handler for non-critical notifications about the upgrade.
To be extended with logging to a table for reporting purposes.
:param module: the module name that the message concerns
:param table: the model that this m... | python | {
"resource": ""
} |
q241166 | reactivate_workflow_transitions | train | def reactivate_workflow_transitions(cr, transition_conditions):
"""
Reactivate workflow transition previously deactivated by
deactivate_workflow_transitions.
:param transition_conditions: a dictionary returned by \
deactivate_workflow_transitions
.. versionadded:: 7.0
.. deprecated:: 11.0
... | python | {
"resource": ""
} |
q241167 | convert_field_to_html | train | def convert_field_to_html(cr, table, field_name, html_field_name):
"""
Convert field value to HTML value.
.. versionadded:: 7.0
"""
if version_info[0] < 7:
logger.error("You cannot use this method in an OpenUpgrade version "
"prior to 7.0.")
return
cr.execut... | python | {
"resource": ""
} |
q241168 | lift_constraints | train | def lift_constraints(cr, table, column):
"""Lift all constraints on column in table.
Typically, you use this in a pre-migrate script where you adapt references
for many2one fields with changed target objects.
If everything went right, the constraints will be recreated"""
cr.execute(
'select ... | python | {
"resource": ""
} |
q241169 | savepoint | train | def savepoint(cr):
"""return a context manager wrapping postgres savepoints"""
if hasattr(cr, 'savepoint'):
with cr.savepoint():
yield
else:
name = uuid.uuid1().hex
cr.execute('SAVEPOINT "%s"' % name)
try:
yield
cr.execute('RELEASE SAVEPOIN... | python | {
"resource": ""
} |
q241170 | rename_property | train | def rename_property(cr, model, old_name, new_name):
"""Rename property old_name owned by model to new_name. This should happen
in a pre-migration script."""
cr.execute(
"update ir_model_fields f set name=%s "
"from ir_model m "
"where m.id=f.model_id and m.model=%s and f.name=%s "
... | python | {
"resource": ""
} |
q241171 | delete_records_safely_by_xml_id | train | def delete_records_safely_by_xml_id(env, xml_ids):
"""This removes in the safest possible way the records whose XML-IDs are
passed as argument.
:param xml_ids: List of XML-ID string identifiers of the records to remove.
"""
for xml_id in xml_ids:
logger.debug('Deleting record for XML-ID %s'... | python | {
"resource": ""
} |
q241172 | chunked | train | def chunked(records, single=True):
""" Memory and performance friendly method to iterate over a potentially
large number of records. Yields either a whole chunk or a single record
at the time. Don't nest calls to this method. """
if version_info[0] > 10:
invalidate = records.env.cache.invalidate... | python | {
"resource": ""
} |
q241173 | get_last_post_for_model | train | def get_last_post_for_model(cr, uid, ids, model_pool):
"""
Given a set of ids and a model pool, return a dict of each object ids with
their latest message date as a value.
To be called in post-migration scripts
:param cr: database cursor
:param uid: user id, assumed to be openerp.SUPERUSER_ID
... | python | {
"resource": ""
} |
q241174 | set_message_last_post | train | def set_message_last_post(cr, uid, pool, models):
"""
Given a list of models, set their 'message_last_post' fields to an
estimated last post datetime.
To be called in post-migration scripts
:param cr: database cursor
:param uid: user id, assumed to be openerp.SUPERUSER_ID
:param pool: orm p... | python | {
"resource": ""
} |
q241175 | column_exists | train | def column_exists(cr, table, column):
""" Check whether a certain column exists """
cr.execute(
'SELECT count(attname) FROM pg_attribute '
'WHERE attrelid = '
'( SELECT oid FROM pg_class WHERE relname = %s ) '
'AND attname = %s',
(table, column))
return cr.fetchone()[... | python | {
"resource": ""
} |
q241176 | start_logging | train | def start_logging(out=_stdout, level='info'):
"""
Begin logging.
:param out: if provided, a file-like object to log to. By default, this is
stdout.
:param level: the maximum log-level to emit (a string)
"""
global _log_level, _loggers, _started_logging
if level not in log_le... | python | {
"resource": ""
} |
q241177 | _AsyncioApi.create_failure | train | def create_failure(self, exception=None):
"""
This returns an object implementing IFailedFuture.
If exception is None (the default) we MUST be called within an
"except" block (such that sys.exc_info() returns useful
information).
"""
if exception:
ret... | python | {
"resource": ""
} |
q241178 | _AsyncioApi.gather | train | def gather(self, futures, consume_exceptions=True):
"""
This returns a Future that waits for all the Futures in the list
``futures``
:param futures: a list of Futures (or coroutines?)
:param consume_exceptions: if True, any errors are eaten and
returned in the result li... | python | {
"resource": ""
} |
q241179 | _use_framework | train | def _use_framework(module):
"""
Internal helper, to set this modules methods to a specified
framework helper-methods.
"""
import txaio
for method_name in __all__:
if method_name in ['use_twisted', 'use_asyncio']:
continue
setattr(txaio, method_name,
ge... | python | {
"resource": ""
} |
q241180 | start_logging | train | def start_logging(out=_stdout, level='info'):
"""
Start logging to the file-like object in ``out``. By default, this
is stdout.
"""
global _loggers, _observer, _log_level, _started_logging
if level not in log_levels:
raise RuntimeError(
"Invalid log level '{0}'; valid are: {... | python | {
"resource": ""
} |
q241181 | Logger.set_log_level | train | def set_log_level(self, level, keep=True):
"""
Set the log level. If keep is True, then it will not change along with
global log changes.
"""
self._set_log_level(level)
self._log_level_set_explicitly = keep | python | {
"resource": ""
} |
q241182 | _TxApi.sleep | train | def sleep(self, delay):
"""
Inline sleep for use in co-routines.
:param delay: Time to sleep in seconds.
:type delay: float
"""
d = Deferred()
self._get_loop().callLater(delay, d.callback, None)
return d | python | {
"resource": ""
} |
q241183 | _BatchedTimer._notify_bucket | train | def _notify_bucket(self, real_time):
"""
Internal helper. This 'does' the callbacks in a particular bucket.
:param real_time: the bucket to do callbacks on
"""
(delayed_call, calls) = self._buckets[real_time]
del self._buckets[real_time]
errors = []
def ... | python | {
"resource": ""
} |
q241184 | check_ab | train | def check_ab(ab, verb):
r"""Check source-receiver configuration.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
ab : int
Source-receiver con... | python | {
"resource": ""
} |
q241185 | check_dipole | train | def check_dipole(inp, name, verb):
r"""Check dipole parameters.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
inp : list of floats or arrays
... | python | {
"resource": ""
} |
q241186 | check_frequency | train | def check_frequency(freq, res, aniso, epermH, epermV, mpermH, mpermV, verb):
r"""Calculate frequency-dependent parameters.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Paramet... | python | {
"resource": ""
} |
q241187 | check_opt | train | def check_opt(opt, loop, ht, htarg, verb):
r"""Check optimization parameters.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
opt : {None, 'parallel... | python | {
"resource": ""
} |
q241188 | check_time_only | train | def check_time_only(time, signal, verb):
r"""Check time and signal parameters.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
time : array_like
... | python | {
"resource": ""
} |
q241189 | check_solution | train | def check_solution(solution, signal, ab, msrc, mrec):
r"""Check required solution with parameters.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
so... | python | {
"resource": ""
} |
q241190 | get_abs | train | def get_abs(msrc, mrec, srcazm, srcdip, recazm, recdip, verb):
r"""Get required ab's for given angles.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
... | python | {
"resource": ""
} |
q241191 | get_geo_fact | train | def get_geo_fact(ab, srcazm, srcdip, recazm, recdip, msrc, mrec):
r"""Get required geometrical scaling factor for given angles.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Pa... | python | {
"resource": ""
} |
q241192 | get_layer_nr | train | def get_layer_nr(inp, depth):
r"""Get number of layer in which inp resides.
Note:
If zinp is on a layer interface, the layer above the interface is chosen.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description... | python | {
"resource": ""
} |
q241193 | get_off_ang | train | def get_off_ang(src, rec, nsrc, nrec, verb):
r"""Get depths, offsets, angles, hence spatial input parameters.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
-----... | python | {
"resource": ""
} |
q241194 | printstartfinish | train | def printstartfinish(verb, inp=None, kcount=None):
r"""Print start and finish with time measure and kernel count."""
if inp:
if verb > 1:
ttxt = str(timedelta(seconds=default_timer() - inp))
ktxt = ' '
if kcount:
ktxt += str(kcount) + ' kernel call(s)'... | python | {
"resource": ""
} |
q241195 | set_minimum | train | def set_minimum(min_freq=None, min_time=None, min_off=None, min_res=None,
min_angle=None):
r"""
Set minimum values of parameters.
The given parameters are set to its minimum value if they are smaller.
Parameters
----------
min_freq : float, optional
Minimum frequency [H... | python | {
"resource": ""
} |
q241196 | get_minimum | train | def get_minimum():
r"""
Return the current minimum values.
Returns
-------
min_vals : dict
Dictionary of current minimum values with keys
- min_freq : float
- min_time : float
- min_off : float
- min_res : float
- min_angle : float
... | python | {
"resource": ""
} |
q241197 | _check_var | train | def _check_var(var, dtype, ndmin, name, shape=None, shape2=None):
r"""Return variable as array of dtype, ndmin; shape-checked."""
if var is None:
raise ValueError
var = np.array(var, dtype=dtype, copy=True, ndmin=ndmin)
if shape:
_check_shape(var, name, shape, shape2)
return var | python | {
"resource": ""
} |
q241198 | _strvar | train | def _strvar(a, prec='{:G}'):
r"""Return variable as a string to print, with given precision."""
return ' '.join([prec.format(i) for i in np.atleast_1d(a)]) | python | {
"resource": ""
} |
q241199 | _check_min | train | def _check_min(par, minval, name, unit, verb):
r"""Check minimum value of parameter."""
scalar = False
if par.shape == ():
scalar = True
par = np.atleast_1d(par)
if minval is not None:
ipar = np.where(par < minval)
par[ipar] = minval
if verb > 0 and np.size(ipar) ... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.