_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q24300
_resizer.resize_file_to
train
def resize_file_to(self, in_path, out_path, keep_filename=False): """ Given a filename, resize and save the image per the specification into out_path :param in_path: path to image file to save. Must be supported by PIL :param out_path: path to the directory root for the outputted thumbnails to...
python
{ "resource": "" }
q24301
run_graphviz
train
def run_graphviz(program, code, options=[], format='png'): """ Runs graphviz programs and returns image data Copied from https://github.com/tkf/ipython-hierarchymagic/blob/master/hierarchymagic.py """ import os from subprocess import Popen, PIPE dot_args = [program] + options + ['-T', form...
python
{ "resource": "" }
q24302
graphviz_parser
train
def graphviz_parser(preprocessor, tag, markup): """ Simple Graphviz parser """ # Parse the markup string m = DOT_BLOCK_RE.search(markup) if m: # Get program and DOT code code = m.group('code') program = m.group('program').strip() # Run specified program with our markup ...
python
{ "resource": "" }
q24303
inline_markdown_extension
train
def inline_markdown_extension(pelicanobj, config): """Instantiates a customized Markdown extension""" # Instantiate Markdown extension and append it to the current extensions try: if isinstance(pelicanobj.settings.get('MD_EXTENSIONS'), list): # pelican 3.6.3 and earlier
python
{ "resource": "" }
q24304
group_content
train
def group_content(generator, content_type): """ Assembles articles and pages into lists based on each article or page's content. These lists are available through the global context passed to the template engine. When multiple categories are present, splits category names based on commas and tr...
python
{ "resource": "" }
q24305
ImportMixin.has_import_permission
train
def has_import_permission(self, request): """ Returns whether a request has import permission. """ IMPORT_PERMISSION_CODE = getattr(settings, 'IMPORT_EXPORT_IMPORT_PERMISSION_CODE', None) if IMPORT_PERMISSION_CODE is None: return True
python
{ "resource": "" }
q24306
ImportMixin.get_import_data_kwargs
train
def get_import_data_kwargs(self, request, *args, **kwargs): """ Prepare kwargs for import_data. """ form
python
{ "resource": "" }
q24307
ImportMixin.import_action
train
def import_action(self, request, *args, **kwargs): """ Perform a dry_run of the import to make sure the import will not result in errors. If there where no error, save the user uploaded file to a local temp file that will be used by 'process_import' for the actual import. ...
python
{ "resource": "" }
q24308
ExportMixin.has_export_permission
train
def has_export_permission(self, request): """ Returns whether a request has export permission. """ EXPORT_PERMISSION_CODE = getattr(settings, 'IMPORT_EXPORT_EXPORT_PERMISSION_CODE', None) if EXPORT_PERMISSION_CODE is None: return True
python
{ "resource": "" }
q24309
ExportMixin.get_export_queryset
train
def get_export_queryset(self, request): """ Returns export queryset. Default implementation respects applied search and filters. """ list_display = self.get_list_display(request) list_display_links = self.get_list_display_links(request, list_display) list_filter ...
python
{ "resource": "" }
q24310
ExportMixin.get_export_data
train
def get_export_data(self, file_format, queryset, *args, **kwargs): """ Returns file_format representation for given queryset. """ request = kwargs.pop("request") if not self.has_export_permission(request): raise PermissionDenied resource_class = self.get_expo...
python
{ "resource": "" }
q24311
ExportActionMixin.export_admin_action
train
def export_admin_action(self, request, queryset): """ Exports the selected rows using file_format. """ export_format = request.POST.get('file_format') if not export_format: messages.warning(request, _('You must select an export format.')) else: fo...
python
{ "resource": "" }
q24312
modelresource_factory
train
def modelresource_factory(model, resource_class=ModelResource): """ Factory for creating ``ModelResource`` class for given Django model. """ attrs = {'model': model}
python
{ "resource": "" }
q24313
Resource.get_field_name
train
def get_field_name(self, field): """ Returns the field name for a given field. """ for field_name, f in self.fields.items(): if f == field: return field_name
python
{ "resource": "" }
q24314
Resource.get_or_init_instance
train
def get_or_init_instance(self, instance_loader, row): """ Either fetches an already existing instance or initializes a new one.
python
{ "resource": "" }
q24315
Resource.save_instance
train
def save_instance(self, instance, using_transactions=True, dry_run=False): """ Takes care of saving the object to the database. Keep in mind that this is done by calling ``instance.save()``, so objects are not created in bulk! """ self.before_save_instance(instance, usin...
python
{ "resource": "" }
q24316
Resource.save_m2m
train
def save_m2m(self, obj, data, using_transactions, dry_run): """ Saves m2m fields. Model instance need to have a primary key value before a many-to-many relationship can be used. """ if not using_transactions and dry_run:
python
{ "resource": "" }
q24317
Resource.skip_row
train
def skip_row(self, instance, original): """ Returns ``True`` if ``row`` importing should be skipped. Default implementation returns ``False`` unless skip_unchanged == True. Override this method to handle skipping rows meeting certain conditions. Use ``super`` if you wan...
python
{ "resource": "" }
q24318
Resource.export
train
def export(self, queryset=None, *args, **kwargs): """ Exports a resource. """ self.before_export(queryset, *args, **kwargs) if queryset is None: queryset = self.get_queryset() headers = self.get_export_headers() data = tablib.Dataset(headers=headers)...
python
{ "resource": "" }
q24319
ModelResource.get_m2m_widget
train
def get_m2m_widget(cls, field): """ Prepare widget for m2m field """ return functools.partial(
python
{ "resource": "" }
q24320
ModelResource.get_fk_widget
train
def get_fk_widget(cls, field): """ Prepare widget for fk and o2o fields
python
{ "resource": "" }
q24321
ModelResource.widget_from_django_field
train
def widget_from_django_field(cls, f, default=widgets.Widget): """ Returns the widget that would likely be associated with each Django type. Includes mapping of Postgres Array and JSON fields. In the case that psycopg2 is not installed, we consume the error and process the field ...
python
{ "resource": "" }
q24322
ModelResource.widget_kwargs_for_field
train
def widget_kwargs_for_field(self, field_name): """ Returns widget kwargs for given field_name. """
python
{ "resource": "" }
q24323
ModelResource.field_from_django_field
train
def field_from_django_field(cls, field_name, django_field, readonly): """ Returns a Resource Field instance for the given Django model field. """ FieldWidget = cls.widget_from_django_field(django_field) widget_kwargs = cls.widget_kwargs_for_field(field_name) field = cls....
python
{ "resource": "" }
q24324
ModelResource.after_import
train
def after_import(self, dataset, result, using_transactions, dry_run, **kwargs): """ Reset the SQL sequences after new objects are imported """ # Adapted from django's loaddata if not dry_run and any(r.import_type == RowResult.IMPORT_TYPE_NEW for r in result.rows): con...
python
{ "resource": "" }
q24325
Field.clean
train
def clean(self, data): """ Translates the value stored in the imported datasource to an appropriate Python object and returns it. """ try: value = data[self.column_name] except KeyError: raise KeyError("Column '%s' not found in dataset. Available
python
{ "resource": "" }
q24326
Field.get_value
train
def get_value(self, obj): """ Returns the value of the object's attribute. """ if self.attribute is None: return None attrs = self.attribute.split('__') value = obj for attr in attrs: try: value = getattr(value, attr, None...
python
{ "resource": "" }
q24327
Field.export
train
def export(self, obj): """ Returns value from the provided object converted to export
python
{ "resource": "" }
q24328
InvalidRow.field_specific_errors
train
def field_specific_errors(self): """Returns a dictionary of field-specific validation errors for this row.""" return {
python
{ "resource": "" }
q24329
InvalidRow.error_count
train
def error_count(self): """Returns the total number of validation errors for this row.""" count = 0
python
{ "resource": "" }
q24330
export_action_form_factory
train
def export_action_form_factory(formats): """ Returns an ActionForm subclass containing a ChoiceField populated with the given formats. """ class _ExportActionForm(ActionForm): """ Action form with export format ChoiceField. """
python
{ "resource": "" }
q24331
ForeignKeyWidget.get_queryset
train
def get_queryset(self, value, row, *args, **kwargs): """ Returns a queryset of all objects for this Model. Overwrite this method if you want to limit the pool of objects from which the related object is retrieved. :param value: The field's value in the datasource. :para...
python
{ "resource": "" }
q24332
get_config_dir
train
def get_config_dir(): """ Return tmuxp configuration directory. ``TMUXP_CONFIGDIR`` environmental variable has precedence if set. We also evaluate XDG default directory from XDG_CONFIG_HOME environmental variable if set or its default. Then the old default ~/.tmuxp is returned for compatibil...
python
{ "resource": "" }
q24333
get_tmuxinator_dir
train
def get_tmuxinator_dir(): """ Return tmuxinator configuration directory. Checks for ``TMUXINATOR_CONFIG`` environmental variable. Returns ------- str : absolute path to
python
{ "resource": "" }
q24334
_validate_choices
train
def _validate_choices(options): """ Callback wrapper for validating click.prompt input. Parameters ---------- options : list List of allowed choices Returns ------- :func:`callable` callback function for value_proc in :func:`click.prompt`. Raises ------ :cl...
python
{ "resource": "" }
q24335
set_layout_hook
train
def set_layout_hook(session, hook_name): """Set layout hooks to normalize layout. References: - tmuxp issue: https://github.com/tmux-python/tmuxp/issues/309 - tmux issue: https://github.com/tmux/tmux/issues/1106 tmux 2.6+ requires that the window be viewed with the client before selec...
python
{ "resource": "" }
q24336
is_pure_name
train
def is_pure_name(path): """ Return True if path is a name and not a file path. Parameters ---------- path : str Path (can be absolute, relative, etc.) Returns ------- bool True if path is a name of config in config dir, not file path.
python
{ "resource": "" }
q24337
scan_config
train
def scan_config(config, config_dir=None): """ Return the real config path or raise an exception. If config is directory, scan for .tmuxp.{yaml,yml,json} in directory. If one or more found, it will warn and pick the first. If config is ".", "./" or None, it will scan current directory. If conf...
python
{ "resource": "" }
q24338
load_workspace
train
def load_workspace( config_file, socket_name=None, socket_path=None, colors=None, detached=False, answer_yes=False, ): """ Load a tmux "workspace" session via tmuxp file. Parameters ---------- config_file : str absolute path to config file socket_name : str, opti...
python
{ "resource": "" }
q24339
cli
train
def cli(log_level): """Manage tmux sessions. Pass the "--help" argument to any command to see detailed help. See detailed documentation and examples at: http://tmuxp.readthedocs.io/en/latest/""" try: has_minimum_version() except TmuxCommandNotFound: click.echo('tmux not found. t...
python
{ "resource": "" }
q24340
command_freeze
train
def command_freeze(session_name, socket_name, socket_path): """Snapshot a session into a config. If SESSION_NAME is provided, snapshot that session. Otherwise, use the current session.""" t = Server(socket_name=socket_name, socket_path=socket_path) try: session = t.find_where({'session_na...
python
{ "resource": "" }
q24341
command_load
train
def command_load(ctx, config, socket_name, socket_path, answer_yes, detached, colors): """Load a tmux workspace from each CONFIG. CONFIG is a specifier for a configuration file. If CONFIG is a path to a directory, tmuxp will search it for ".tmuxp.{yaml,yml,json}". If CONFIG is has no directory co...
python
{ "resource": "" }
q24342
command_convert
train
def command_convert(config): """Convert a tmuxp config between JSON and YAML.""" _, ext = os.path.splitext(config) if 'json' in ext: if click.confirm('convert to <%s> to yaml?' % config): configparser = kaptan.Kaptan() configparser.import_config(config) newfile =...
python
{ "resource": "" }
q24343
WorkspaceBuilder.build
train
def build(self, session=None): """ Build tmux workspace in session. Optionally accepts ``session`` to build with only session object. Without ``session``, it will use :class:`libmtux.Server` at ``self.server`` passed in on initialization to create a new Session object. ...
python
{ "resource": "" }
q24344
WorkspaceBuilder.config_after_window
train
def config_after_window(self, w, wconf): """Actions to apply to window after window and pane finished. When building a tmux session, sometimes its easier to postpone things like setting options until after things are already structurally prepared. Parameters ---------- ...
python
{ "resource": "" }
q24345
validate_schema
train
def validate_schema(sconf): """ Return True if config schema is correct. Parameters ---------- sconf : dict session configuration Returns ------- bool """ # verify session_name if 'session_name' not in sconf: raise exc.ConfigError('config requires "session_...
python
{ "resource": "" }
q24346
is_config_file
train
def is_config_file(filename, extensions=['.yml', '.yaml', '.json']): """ Return True if file has a valid config file type. Parameters ---------- filename : str filename to check (e.g. ``mysession.json``). extensions : str or list filetypes to check (e.g. ``['.yaml', '.json']``)....
python
{ "resource": "" }
q24347
in_cwd
train
def in_cwd(): """ Return list of configs in current working directory. If filename is ``.tmuxp.py``, ``.tmuxp.json``, ``.tmuxp.yaml``. Returns ------- list configs in current working directory """ configs = [] for
python
{ "resource": "" }
q24348
import_tmuxinator
train
def import_tmuxinator(sconf): """Return tmuxp config from a `tmuxinator`_ yaml config. .. _tmuxinator: https://github.com/aziz/tmuxinator Parameters ---------- sconf : dict python dict for session configuration. Returns ------- dict """ tmuxp_config = {} if 'proj...
python
{ "resource": "" }
q24349
import_teamocil
train
def import_teamocil(sconf): """Return tmuxp config from a `teamocil`_ yaml config. .. _teamocil: https://github.com/remiprev/teamocil Parameters ---------- sconf : dict python dict for session configuration Notes ----- Todos: - change 'root' to a cd or start_directory ...
python
{ "resource": "" }
q24350
oh_my_zsh_auto_title
train
def oh_my_zsh_auto_title(): """Give warning and offer to fix ``DISABLE_AUTO_TITLE``. see: https://github.com/robbyrussell/oh-my-zsh/pull/257 """ if 'SHELL' in os.environ and 'zsh' in os.environ.get('SHELL'): if os.path.exists(os.path.expanduser('~/.oh-my-zsh')): # oh-my-zsh exists...
python
{ "resource": "" }
q24351
setup
train
def setup(): """ Install handlers for Mitogen loggers to redirect them into the Ansible display framework. Ansible installs its own logging framework handlers when C.DEFAULT_LOG_PATH is set, therefore disable propagation for our handlers. """ l_mitogen = logging.getLogger('mitogen') l_mitoge...
python
{ "resource": "" }
q24352
Connection.get_default_env
train
def get_default_env(self): """ Vanilla Ansible local commands execute with an environment inherited from WorkerProcess, we must emulate that. """ return dict_diff(
python
{ "resource": "" }
q24353
_stdlib_paths
train
def _stdlib_paths(): """Return a set of paths from which Python imports the standard library. """ attr_candidates = [ 'prefix', 'real_prefix', # virtualenv: only set inside a virtual environment. 'base_prefix', # venv: always set, equal to prefix if outside. ] prefixes = (g...
python
{ "resource": "" }
q24354
get_child_modules
train
def get_child_modules(path): """Return the suffixes of submodules directly neated beneath of the package directory at `path`. :param str path: Path to the module's source code on disk, or some PEP-302-recognized equivalent. Usually this is the module's ``__file__`` attribute, but is...
python
{ "resource": "" }
q24355
scan_code_imports
train
def scan_code_imports(co): """ Given a code object `co`, scan its bytecode yielding any ``IMPORT_NAME`` and associated prior ``LOAD_CONST`` instructions representing an `Import` statement or `ImportFrom` statement. :return: Generator producing `(level, modname, namelist)` tuples, where: ...
python
{ "resource": "" }
q24356
ThreadWatcher._reset
train
def _reset(cls): """If we have forked since the watch dictionaries were initialized, all that has is garbage, so clear it.""" if os.getpid() != cls._cls_pid:
python
{ "resource": "" }
q24357
ModuleFinder.add_source_override
train
def add_source_override(self, fullname, path, source, is_pkg): """ Explicitly install a source cache entry, preventing usual lookup methods from being used. Beware the value of `path` is critical when `is_pkg` is specified, since it directs where submodules are searched for. ...
python
{ "resource": "" }
q24358
ModuleFinder.get_module_source
train
def get_module_source(self, fullname): """Given the name of a loaded module `fullname`, attempt to find its source code. :returns: Tuple of `(module path, source text, is package?)`, or :data:`None` if the source cannot be found. """ tup = self._found_cac...
python
{ "resource": "" }
q24359
ModuleFinder.resolve_relpath
train
def resolve_relpath(self, fullname, level): """Given an ImportFrom AST node, guess the prefix that should be tacked on to an alias name to produce a canonical name. `fullname` is the name of the module in which the ImportFrom appears. """ mod = sys.modules.get(fullname, None) ...
python
{ "resource": "" }
q24360
ModuleFinder.find_related_imports
train
def find_related_imports(self, fullname): """ Return a list of non-stdlib modules that are directly imported by `fullname`, plus their parents. The list is determined by retrieving the source code of `fullname`, compiling it, and examining all IMPORT_NAME ops. :param fu...
python
{ "resource": "" }
q24361
ModuleFinder.find_related
train
def find_related(self, fullname): """ Return a list of non-stdlib modules that are imported directly or indirectly by `fullname`, plus their parents. This method is like :py:meth:`find_related_imports`, but also recursively searches any modules which are imported by `fullname`. ...
python
{ "resource": "" }
q24362
Router.get_stats
train
def get_stats(self): """ Return performance data for the module responder. :returns: Dict containing keys: * `get_module_count`: Integer count of :data:`mitogen.core.GET_MODULE` messages received. * `get_module_secs`: Floating point total seco...
python
{ "resource": "" }
q24363
Corker._cork_one
train
def _cork_one(self, s, obj): """ Construct a socketpair, saving one side of it, and passing the other to `obj` to be written to by one of its threads. """ rsock, wsock = mitogen.parent.create_socketpair(size=4096) mitogen.core.set_cloexec(rsock.fileno())
python
{ "resource": "" }
q24364
Corker.cork
train
def cork(self): """ Arrange for any associated brokers and pools to be paused with no locks held. This will not return until each thread acknowledges it has ceased execution. """ s = mitogen.core.b('CORK') * ((128 // 4) * 1024) self._rsocks = [] # Pools m...
python
{ "resource": "" }
q24365
get_fullname
train
def get_fullname(module): """ Reconstruct a Module's canonical path by recursing through its parents. """ bits = [str(module.name)] while module.parent:
python
{ "resource": "" }
q24366
get_code
train
def get_code(module): """ Compile and return a Module's code object. """ fp = open(module.path) try:
python
{ "resource": "" }
q24367
find
train
def find(name, path=(), parent=None): """ Return a Module instance describing the first matching module found on the search path. :param str name: Module name. :param list path: List of directory names to search for the module. :param Module parent: Optional module paren...
python
{ "resource": "" }
q24368
main
train
def main(router): """ Main program entry point. @mitogen.main() is just a helper to handle reliable setup/destruction of Broker, Router and the logging package. """ argv = sys.argv[1:] if not len(argv): print('mitop: Need a list of SSH hosts to connect to.') sys.exit(1) dela...
python
{ "resource": "" }
q24369
key_from_dict
train
def key_from_dict(**kwargs): """ Return a unique string representation of a dict as quickly as possible. Used to generated deduplication keys from a request. """ out = [] stack = [kwargs] while stack: obj = stack.pop() if isinstance(obj, dict):
python
{ "resource": "" }
q24370
ContextService.put
train
def put(self, context): """ Return a reference, making it eligable for recycling once its reference count reaches zero. """ LOG.debug('%r.put(%r)', self, context) self._lock.acquire() try: if self._refs_by_context.get(context, 0) == 0:
python
{ "resource": "" }
q24371
ContextService._produce_response
train
def _produce_response(self, key, response): """ Reply to every waiting request matching a configuration key with a response dictionary, deleting the list of waiters when done. :param str key: Result of :meth:`key_from_dict` :param dict response: Response ...
python
{ "resource": "" }
q24372
ContextService._shutdown_unlocked
train
def _shutdown_unlocked(self, context, lru=None, new_context=None): """ Arrange for `context` to be shut down, and optionally add `new_context` to the LRU list while holding the lock. """ LOG.info('%r._shutdown_unlocked(): shutting down %r', self,
python
{ "resource": "" }
q24373
ContextService.dump
train
def dump(self): """ For testing, return a list of dicts describing every currently connected context. """ return [ { 'context_name': context.name,
python
{ "resource": "" }
q24374
ContextService.shutdown_all
train
def shutdown_all(self): """ For testing use, arrange for all connections to be shut down. """ self._lock.acquire()
python
{ "resource": "" }
q24375
ContextService._on_context_disconnect
train
def _on_context_disconnect(self, context): """ Respond to Context disconnect event by deleting any record of the no longer reachable context. This method runs in the Broker thread and must not to block. """ self._lock.acquire()
python
{ "resource": "" }
q24376
ContextService._connect
train
def _connect(self, key, spec, via=None): """ Actual connect implementation. Arranges for the Mitogen connection to be created and enqueues an asynchronous call to start the forked task parent in the remote context. :param key: Deduplication key representing the conne...
python
{ "resource": "" }
q24377
ContextService.get
train
def get(self, msg, stack): """ Return a Context referring to an established connection with the given configuration, establishing new connections as necessary. :param list stack: Connection descriptions. Each element is a dict containing 'method' and 'kwargs' key...
python
{ "resource": "" }
q24378
Message._find_global
train
def _find_global(self, module, func): """Return the class implementing `module_name.class_name` or raise `StreamError` if the module is not whitelisted.""" if module == __name__: if func == '_unpickle_call_error' or func == 'CallError': return _unpickle_call_error ...
python
{ "resource": "" }
q24379
Message.dead
train
def dead(cls, reason=None, **kwargs): """ Syntax helper to construct a dead message. """
python
{ "resource": "" }
q24380
Sender.send
train
def send(self, data): """ Send `data` to the remote end. """ _vv and IOLOG.debug('%r.send(%r..)', self, repr(data)[:100])
python
{ "resource": "" }
q24381
Receiver.get
train
def get(self, timeout=None, block=True, throw_dead=True): """ Sleep waiting for a message to arrive on this receiver. :param float timeout: If not :data:`None`, specifies a timeout in seconds. :raises mitogen.core.ChannelError: The remote end indicated the chann...
python
{ "resource": "" }
q24382
Stream.on_transmit
train
def on_transmit(self, broker): """Transmit buffered messages.""" _vv and IOLOG.debug('%r.on_transmit()', self) if self._output_buf: buf = self._output_buf.popleft() written = self.transmit_side.write(buf) if not written: _v and LOG.debug('%r.o...
python
{ "resource": "" }
q24383
Stream.send
train
def send(self, msg): """Send `data` to `handle`, and tell the broker we
python
{ "resource": "" }
q24384
Poller.stop_receive
train
def stop_receive(self, fd): """ Stop yielding readability events for `fd`. Redundant calls
python
{ "resource": "" }
q24385
Poller.stop_transmit
train
def stop_transmit(self, fd): """ Stop yielding writeability events for `fd`. Redundant calls
python
{ "resource": "" }
q24386
Poller.poll
train
def poll(self, timeout=None): """ Block the calling thread until one or more FDs are ready for IO. :param float timeout: If not :data:`None`, seconds to wait without an event before returning an empty iterable. :returns:
python
{ "resource": "" }
q24387
Latch._on_fork
train
def _on_fork(cls): """ Clean up any files belonging to the parent process after a fork. """
python
{ "resource": "" }
q24388
Latch._get_socketpair
train
def _get_socketpair(self): """ Return an unused socketpair, creating one if none exist. """ try: return self._cls_idle_socketpairs.pop() # pop() must be atomic except IndexError: rsock, wsock = socket.socketpair()
python
{ "resource": "" }
q24389
Latch._make_cookie
train
def _make_cookie(self): """ Return a string encoding the ID of the process, instance and thread. This disambiguates legitimate wake-ups, accidental writes to the FD, and buggy internal FD sharing. """
python
{ "resource": "" }
q24390
Latch.get
train
def get(self, timeout=None, block=True): """ Return the next enqueued object, or sleep waiting for one. :param float timeout: If not :data:`None`, specifies a timeout in seconds. :param bool block: If :data:`False`, immediately raise :class:`mitogen....
python
{ "resource": "" }
q24391
Latch.put
train
def put(self, obj=None): """ Enqueue an object, waking the first thread waiting for a result, if one exists. :param obj: Object to enqueue. Defaults to :data:`None` as a convenience when using :class:`Latch` only for synchronization. :raises mitogen.core....
python
{ "resource": "" }
q24392
Waker.keep_alive
train
def keep_alive(self): """ Prevent immediate Broker shutdown while deferred functions remain. """ self._lock.acquire() try:
python
{ "resource": "" }
q24393
Waker._wake
train
def _wake(self): """ Wake the multiplexer by writing a byte. If Broker is midway through teardown, the FD may already be closed, so ignore EBADF. """ try: self.transmit_side.write(b(' '))
python
{ "resource": "" }
q24394
IoLogger.on_shutdown
train
def on_shutdown(self, broker): """Shut down the write end of the logging socket.""" _v and LOG.debug('%r.on_shutdown()', self) if not IS_WSL: # #333: WSL generates invalid readiness indication on shutdown()
python
{ "resource": "" }
q24395
Router.del_handler
train
def del_handler(self, handle): """ Remove the handle registered for `handle` :raises KeyError: The handle wasn't registered. """
python
{ "resource": "" }
q24396
Router._async_route
train
def _async_route(self, msg, in_stream=None): """ Arrange for `msg` to be forwarded towards its destination. If its destination is the local context, then arrange for it to be dispatched using the local handlers. This is a lower overhead version of :meth:`route` that may only be ...
python
{ "resource": "" }
q24397
Broker.shutdown
train
def shutdown(self): """ Request broker gracefully disconnect streams and stop. Safe to call from any thread. """ _v and LOG.debug('%r.shutdown()', self) def _shutdown():
python
{ "resource": "" }
q24398
filter_debug
train
def filter_debug(stream, it): """ Read line chunks from it, either yielding them directly, or building up and logging individual lines if they look like SSH debug output. This contains the mess of dealing with both line-oriented input, and partial lines such as the password prompt. Yields `(li...
python
{ "resource": "" }
q24399
run
train
def run(dest, router, args, deadline=None, econtext=None): """ Run the command specified by `args` such that ``PATH`` searches for SSH by the command will cause its attempt to use SSH to execute a remote program to be redirected to use mitogen to execute that program using the context `dest` instead...
python
{ "resource": "" }