INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
connect to peers. peers will be a 3 - tuples of the form: ( location north_addr east_addr ) as produced by | def connect(self, south_peer=None, west_peer=None):
"""connect to peers. `peers` will be a 3-tuples, of the form:
(location, north_addr, east_addr)
as produced by
"""
if south_peer is not None:
location, url, _ = south_peer
self.south.connect(disambiguate... |
convert. pyx extensions to. c | def _convert_pyx_sources_to_c(self):
"convert .pyx extensions to .c"
def pyx_to_c(source):
if source.endswith('.pyx'):
source = source[:-4] + '.c'
return source
self.sources = map(pyx_to_c, self.sources) |
watch iopub channel and print messages | def main(connection_file):
"""watch iopub channel, and print messages"""
ctx = zmq.Context.instance()
with open(connection_file) as f:
cfg = json.loads(f.read())
location = cfg['location']
reg_url = cfg['url']
session = Session(key=str_to_bytes(cfg['exec_key']))
q... |
decorator ( caller ) converts a caller function into a decorator ; decorator ( caller func ) decorates a function using a caller. | def decorator(caller, func=None):
"""
decorator(caller) converts a caller function into a decorator;
decorator(caller, func) decorates a function using a caller.
"""
if func is not None: # returns a decorated function
evaldict = func.func_globals.copy()
evaldict['_call_'] = caller
... |
Create a package finder appropriate to this install command. This method is meant to be overridden by subclasses not called directly. | def _build_package_finder(self, options, index_urls, session):
"""
Create a package finder appropriate to this install command.
This method is meant to be overridden by subclasses, not
called directly.
"""
return PackageFinder(
find_links=options.find_links,
... |
Method decorator for catching invalid config ( Trait/ ArgumentErrors ) during init. | def catch_config_error(method, app, *args, **kwargs):
"""Method decorator for catching invalid config (Trait/ArgumentErrors) during init.
On a TraitError (generally caused by bad config), this will print the trait's
message, and exit the app.
For use on init methods, to prevent invoking excepthook... |
Helper for building basic -- trait -- no - trait flags. | def boolean_flag(name, configurable, set_help='', unset_help=''):
"""Helper for building basic --trait, --no-trait flags.
Parameters
----------
name : str
The name of the flag.
configurable : str
The 'Class.trait' string of the trait to be set/unset with the flag
set_help : uni... |
Adjust the log level when log_level is set. | def _log_level_changed(self, name, old, new):
"""Adjust the log level when log_level is set."""
if isinstance(new, basestring):
new = getattr(logging, new)
self.log_level = new
self.log.setLevel(new) |
Start logging for this application. | def _log_default(self):
"""Start logging for this application.
The default is to log to stdout using a StreaHandler. The log level
starts at loggin.WARN, but this can be adjusted by setting the
``log_level`` attribute.
"""
log = logging.getLogger(self.__class__.__name__)... |
ensure flags dict is valid | def _flags_changed(self, name, old, new):
"""ensure flags dict is valid"""
for key,value in new.iteritems():
assert len(value) == 2, "Bad flag: %r:%s"%(key,value)
assert isinstance(value[0], (dict, Config)), "Bad flag: %r:%s"%(key,value)
assert isinstance(value[1], ba... |
Print the alias part of the help. | def print_alias_help(self):
"""Print the alias part of the help."""
if not self.aliases:
return
lines = []
classdict = {}
for cls in self.classes:
# include all parents (up to, but excluding Configurable) in available names
for c in cls.mro()[... |
Print the flag part of the help. | def print_flag_help(self):
"""Print the flag part of the help."""
if not self.flags:
return
lines = []
for m, (cfg,help) in self.flags.iteritems():
prefix = '--' if len(m) > 1 else '-'
lines.append(prefix+m)
lines.append(indent(dedent(help... |
Print the subcommand part of the help. | def print_subcommands(self):
"""Print the subcommand part of the help."""
if not self.subcommands:
return
lines = ["Subcommands"]
lines.append('-'*len(lines[0]))
lines.append('')
for p in wrap_paragraphs(self.subcommand_description):
lines.append(... |
Print the help for each Configurable class in self. classes. | def print_help(self, classes=False):
"""Print the help for each Configurable class in self.classes.
If classes=False (the default), only flags and aliases are printed.
"""
self.print_subcommands()
self.print_options()
if classes:
if self.classes:
... |
Print usage and examples. | def print_examples(self):
"""Print usage and examples.
This usage string goes at the end of the command line help string
and should contain examples of the application's usage.
"""
if self.examples:
print "Examples"
print "--------"
print
... |
Fire the traits events when the config is updated. | def update_config(self, config):
"""Fire the traits events when the config is updated."""
# Save a copy of the current config.
newconfig = deepcopy(self.config)
# Merge the new config into the current one.
newconfig._merge(config)
# Save the combined config as self.config... |
Initialize a subcommand with argv. | def initialize_subcommand(self, subc, argv=None):
"""Initialize a subcommand with argv."""
subapp,help = self.subcommands.get(subc)
if isinstance(subapp, basestring):
subapp = import_item(subapp)
# clear existing instances
self.__class__.clear_instance()
# i... |
flatten flags and aliases so cl - args override as expected. This prevents issues such as an alias pointing to InteractiveShell but a config file setting the same trait in TerminalInteraciveShell getting inappropriate priority over the command - line arg. | def flatten_flags(self):
"""flatten flags and aliases, so cl-args override as expected.
This prevents issues such as an alias pointing to InteractiveShell,
but a config file setting the same trait in TerminalInteraciveShell
getting inappropriate priority over the command-line ar... |
Parse the command line arguments. | def parse_command_line(self, argv=None):
"""Parse the command line arguments."""
argv = sys.argv[1:] if argv is None else argv
if argv and argv[0] == 'help':
# turn `ipython help notebook` into `ipython notebook -h`
argv = argv[1:] + ['-h']
if self.subco... |
Load a. py based config file by filename and path. | def load_config_file(self, filename, path=None):
"""Load a .py based config file by filename and path."""
loader = PyFileConfigLoader(filename, path=path)
try:
config = loader.load_config()
except ConfigFileNotFound:
# problem finding the file, raise
r... |
generate default config file from Configurables | def generate_config_file(self):
"""generate default config file from Configurables"""
lines = ["# Configuration file for %s."%self.name]
lines.append('')
lines.append('c = get_config()')
lines.append('')
for cls in self.classes:
lines.append(cls.class_config_s... |
Choose k random elements of array. | def downsample(array, k):
"""Choose k random elements of array."""
length = array.shape[0]
indices = random.sample(xrange(length), k)
return array[indices] |
Produce a sequence of formatted lines from info. | def info_formatter(info):
"""Produce a sequence of formatted lines from info.
`info` is a sequence of pairs (label, data). The produced lines are
nicely formatted, ready to print.
"""
label_len = max([len(l) for l, _d in info])
for label, data in info:
if data == []:
data ... |
Write a line of debug output. | def write(self, msg):
"""Write a line of debug output."""
if self.should('pid'):
msg = "pid %5d: %s" % (os.getpid(), msg)
self.output.write(msg+"\n")
self.output.flush() |
Update all the class traits having config = True as metadata. | def _config_changed(self, name, old, new):
"""Update all the class traits having ``config=True`` as metadata.
For any class trait with a ``config`` metadata attribute that is
``True``, we update the trait with the value of the corresponding
config entry.
"""
# Get all tr... |
Get the help string for this class in ReST format. If inst is given it s current trait values will be used in place of class defaults. | def class_get_help(cls, inst=None):
"""Get the help string for this class in ReST format.
If `inst` is given, it's current trait values will be used in place of
class defaults.
"""
assert inst is None or isinstance(inst, cls)
cls_traits = cls.class_traits(config=... |
Get the help string for a single trait. If inst is given it s current trait values will be used in place of the class default. | def class_get_trait_help(cls, trait, inst=None):
"""Get the help string for a single trait.
If `inst` is given, it's current trait values will be used in place of
the class default.
"""
assert inst is None or isinstance(inst, cls)
lines = []
header = "--%... |
Get the config class config section | def class_config_section(cls):
"""Get the config class config section"""
def c(s):
"""return a commented, wrapped block."""
s = '\n\n'.join(wrap_paragraphs(s, 78))
return '# ' + s.replace('\n', '\n# ')
# section header
breaker = '#' + '-'*78
... |
Walk the cls. mro () for parent classes that are also singletons | def _walk_mro(cls):
"""Walk the cls.mro() for parent classes that are also singletons
For use in instance()
"""
for subclass in cls.mro():
if issubclass(cls, subclass) and \
issubclass(subclass, SingletonConfigurable) and \
subclass !... |
unset _instance for this class and singleton parents. | def clear_instance(cls):
"""unset _instance for this class and singleton parents.
"""
if not cls.initialized():
return
for subclass in cls._walk_mro():
if isinstance(subclass._instance, cls):
# only clear instances that are instances
... |
Returns a global instance of this class. | def instance(cls, *args, **kwargs):
"""Returns a global instance of this class.
This method create a new instance if none have previously been created
and returns a previously created instance is one already exists.
The arguments and keyword arguments passed to this method are passed
... |
Configure plugin. | def configure(self, options, conf):
"""Configure plugin.
"""
if not self.can_configure:
return
self.enabled = options.detailedErrors
self.conf = conf |
Add detail from traceback inspection to error message of a failure. | def formatFailure(self, test, err):
"""Add detail from traceback inspection to error message of a failure.
"""
ec, ev, tb = err
tbinfo = inspect_traceback(tb)
test.tbinfo = tbinfo
return (ec, '\n'.join([str(ev), tbinfo]), tb) |
a light excepthook adding a small message to the usual traceback | def crash_handler_lite(etype, evalue, tb):
"""a light excepthook, adding a small message to the usual traceback"""
traceback.print_exception(etype, evalue, tb)
from IPython.core.interactiveshell import InteractiveShell
if InteractiveShell.initialized():
# we are in a Shell environment, give... |
Return a string containing a crash report. | def make_report(self,traceback):
"""Return a string containing a crash report."""
sec_sep = self.section_sep
report = ['*'*75+'\n\n'+'IPython post-mortem report\n\n']
rpt_add = report.append
rpt_add(sys_info())
try:
config = pformat(self.app.config)
... |
{ % setvar <var_name > to <var_value > % } | def setvar(parser, token):
""" {% setvar <var_name> to <var_value> %} """
try:
setvar, var_name, to_, var_value = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError('Invalid arguments for %r' % token.split_contents()[0])
return SetVarNode(var_name, var_value) |
Reimplemented to emit signals instead of making callbacks. | def call_handlers(self, msg):
""" Reimplemented to emit signals instead of making callbacks.
"""
# Emit the generic signal.
self.message_received.emit(msg)
# Emit signals for specialized message types.
msg_type = msg['header']['msg_type']
signal = getattr(self, m... |
Reimplemented to emit signals instead of making callbacks. | def call_handlers(self, msg):
""" Reimplemented to emit signals instead of making callbacks.
"""
# Emit the generic signal.
self.message_received.emit(msg)
# Emit signals for specialized message types.
msg_type = msg['header']['msg_type']
signal = getattr(self, ms... |
Reimplemented to ensure that signals are dispatched immediately. | def flush(self):
""" Reimplemented to ensure that signals are dispatched immediately.
"""
super(QtSubSocketChannel, self).flush()
QtCore.QCoreApplication.instance().processEvents() |
Reimplemented to emit signals instead of making callbacks. | def call_handlers(self, msg):
""" Reimplemented to emit signals instead of making callbacks.
"""
# Emit the generic signal.
self.message_received.emit(msg)
# Emit signals for specialized message types.
msg_type = msg['header']['msg_type']
if msg_type == 'input_re... |
Reimplemented for proper heartbeat management. | def start_kernel(self, *args, **kw):
""" Reimplemented for proper heartbeat management.
"""
if self._shell_channel is not None:
self._shell_channel.reset_first_reply()
super(QtKernelManager, self).start_kernel(*args, **kw)
self.started_kernel.emit() |
Reimplemented to emit signal. | def start_channels(self, *args, **kw):
""" Reimplemented to emit signal.
"""
super(QtKernelManager, self).start_channels(*args, **kw)
self.started_channels.emit() |
Reimplemented for proper heartbeat management. | def shell_channel(self):
""" Reimplemented for proper heartbeat management.
"""
if self._shell_channel is None:
self._shell_channel = super(QtKernelManager, self).shell_channel
self._shell_channel.first_reply.connect(self._first_reply)
return self._shell_channel |
Restore bytes of image data from unicode - only formats. Base64 encoding is handled elsewhere. Bytes objects in the notebook are always b64 - encoded. We DO NOT encode/ decode around file formats. | def restore_bytes(nb):
"""Restore bytes of image data from unicode-only formats.
Base64 encoding is handled elsewhere. Bytes objects in the notebook are
always b64-encoded. We DO NOT encode/decode around file formats.
"""
for ws in nb.worksheets:
for cell in ws.cells:
if ce... |
join lines that have been written by splitlines () Has logic to protect against splitlines () which should have been splitlines ( True ) | def _join_lines(lines):
"""join lines that have been written by splitlines()
Has logic to protect against `splitlines()`, which
should have been `splitlines(True)`
"""
if lines and lines[0].endswith(('\n', '\r')):
# created by splitlines(True)
return u''.join(lines)
else:
... |
rejoin multiline text into strings For reversing effects of split_lines ( nb ). This only rejoins lines that have been split so if text objects were not split they will pass through unchanged. Used when reading JSON files that may have been passed through split_lines. | def rejoin_lines(nb):
"""rejoin multiline text into strings
For reversing effects of ``split_lines(nb)``.
This only rejoins lines that have been split, so if text objects were not split
they will pass through unchanged.
Used when reading JSON files that may have been passed through sp... |
Restore all bytes objects in the notebook from base64 - encoded strings. Note: This is never used | def base64_decode(nb):
"""Restore all bytes objects in the notebook from base64-encoded strings.
Note: This is never used
"""
for ws in nb.worksheets:
for cell in ws.cells:
if cell.cell_type == 'code':
for output in cell.outputs:
if 'png' in o... |
Base64 encode all bytes objects in the notebook. These will be b64 - encoded unicode strings Note: This is never used | def base64_encode(nb):
"""Base64 encode all bytes objects in the notebook.
These will be b64-encoded unicode strings
Note: This is never used
"""
for ws in nb.worksheets:
for cell in ws.cells:
if cell.cell_type == 'code':
for output in cell.outputs:
... |
Read a notebook from a file like object | def read(self, fp, **kwargs):
"""Read a notebook from a file like object"""
nbs = fp.read()
if not py3compat.PY3 and not isinstance(nbs, unicode):
nbs = py3compat.str_to_unicode(nbs)
return self.reads(nbs, **kwargs) |
Write a notebook to a file like object | def write(self, nb, fp, **kwargs):
"""Write a notebook to a file like object"""
nbs = self.writes(nb,**kwargs)
if not py3compat.PY3 and not isinstance(nbs, unicode):
# this branch is likely only taken for JSON on Python 2
nbs = py3compat.str_to_unicode(nbs)
return... |
Return the list of mirrors from the last record found on the DNS entry:: | def get_mirrors(hostname=None):
"""Return the list of mirrors from the last record found on the DNS
entry::
>>> from pip.index import get_mirrors
>>> get_mirrors()
['a.pypi.python.org', 'b.pypi.python.org', 'c.pypi.python.org',
'd.pypi.python.org']
Originally written for the distutils2 pro... |
Read from a pipe ignoring EINTR errors. | def read_no_interrupt(p):
"""Read from a pipe ignoring EINTR errors.
This is necessary because when reading from pipes with GUI event loops
running in the background, often interrupts are raised that stop the
command from completing."""
import errno
try:
return p.read()
except IOEr... |
Open a command in a shell subprocess and execute a callback. | def process_handler(cmd, callback, stderr=subprocess.PIPE):
"""Open a command in a shell subprocess and execute a callback.
This function provides common scaffolding for creating subprocess.Popen()
calls. It creates a Popen object and then calls the callback with it.
Parameters
----------
cmd... |
Return standard output of executing cmd in a shell. | def getoutput(cmd):
"""Return standard output of executing cmd in a shell.
Accepts the same arguments as os.system().
Parameters
----------
cmd : str
A command to be executed in the system shell.
Returns
-------
stdout : str
"""
out = process_handler(cmd, lambda p: p.co... |
Return ( standard output standard error ) of executing cmd in a shell. | def getoutputerror(cmd):
"""Return (standard output, standard error) of executing cmd in a shell.
Accepts the same arguments as os.system().
Parameters
----------
cmd : str
A command to be executed in the system shell.
Returns
-------
stdout : str
stderr : str
"""
o... |
Split a command line s arguments in a shell - like manner. | def arg_split(s, posix=False, strict=True):
"""Split a command line's arguments in a shell-like manner.
This is a modified version of the standard library's shlex.split()
function, but with a default of posix=False for splitting, so that quotes
in inputs are respected.
if strict=False, then any er... |
TestSuite replacement entry point. Use anywhere you might use a unittest. TestSuite. The collector will by default load options from all config files and execute loader. loadTestsFromNames () on the configured testNames or. if no testNames are configured. | def collector():
"""TestSuite replacement entry point. Use anywhere you might use a
unittest.TestSuite. The collector will, by default, load options from
all config files and execute loader.loadTestsFromNames() on the
configured testNames, or '.' if no testNames are configured.
"""
# plugins tha... |
Compress a directory history into a new one with at most 20 entries. | def compress_dhist(dh):
"""Compress a directory history into a new one with at most 20 entries.
Return a new list made from the first and last 10 elements of dhist after
removal of duplicates.
"""
head, tail = dh[:-10], dh[-10:]
newhead = []
done = set()
for h in head:
if h in ... |
Class decorator for all subclasses of the main Magics class. | def magics_class(cls):
"""Class decorator for all subclasses of the main Magics class.
Any class that subclasses Magics *must* also apply this decorator, to
ensure that all the methods that have been decorated as line/cell magics
get correctly registered in the class instance. This is necessary becaus... |
Utility function to store a function as a magic of a specific kind. | def record_magic(dct, magic_kind, magic_name, func):
"""Utility function to store a function as a magic of a specific kind.
Parameters
----------
dct : dict
A dictionary with 'line' and 'cell' subdicts.
magic_kind : str
Kind of magic to be stored.
magic_name : str
Key to sto... |
Decorator factory for methods in Magics subclasses. | def _method_magic_marker(magic_kind):
"""Decorator factory for methods in Magics subclasses.
"""
validate_type(magic_kind)
# This is a closure to capture the magic_kind. We could also use a class,
# but it's overkill for just that one bit of state.
def magic_deco(arg):
call = lambda f... |
Decorator factory for standalone functions. | def _function_magic_marker(magic_kind):
"""Decorator factory for standalone functions.
"""
validate_type(magic_kind)
# This is a closure to capture the magic_kind. We could also use a class,
# but it's overkill for just that one bit of state.
def magic_deco(arg):
call = lambda f, *... |
Return dict of documentation of magic functions. | def lsmagic_docs(self, brief=False, missing=''):
"""Return dict of documentation of magic functions.
The return dict has the keys 'line' and 'cell', corresponding to the
two types of magics we support. Each value is a dict keyed by magic
name whose value is the function docstring. If a ... |
Register one or more instances of Magics. | def register(self, *magic_objects):
"""Register one or more instances of Magics.
Take one or more classes or instances of classes that subclass the main
`core.Magic` class, and register them with IPython to use the magic
functions they provide. The registration process will then ensur... |
Expose a standalone function as magic function for IPython. | def register_function(self, func, magic_kind='line', magic_name=None):
"""Expose a standalone function as magic function for IPython.
This will create an IPython magic (line, cell or both) from a
standalone function. The functions should have the following
signatures:
* For l... |
[ Deprecated ] Expose own function as magic function for IPython. | def define_magic(self, name, func):
"""[Deprecated] Expose own function as magic function for IPython.
Example::
def foo_impl(self, parameter_s=''):
'My very own magic!. (Use docstrings, IPython reads them).'
print 'Magic function. Passed parameter is betwee... |
Format a string for latex inclusion. | def format_latex(self, strng):
"""Format a string for latex inclusion."""
# Characters that need to be escaped for latex:
escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
# Magic command names as headers:
cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
... |
Parse options passed to an argument string. | def parse_options(self, arg_str, opt_str, *long_opts, **kw):
"""Parse options passed to an argument string.
The interface is similar to that of getopt(), but it returns back a
Struct with the options as keys and the stripped argument string still
as a string.
arg_str is quoted ... |
Make an entry in the options_table for fn with value optstr | def default_option(self, fn, optstr):
"""Make an entry in the options_table for fn, with value optstr"""
if fn not in self.lsmagic():
error("%s is not a magic function" % fn)
self.options_table[fn] = optstr |
Show a basic reference about the GUI Console. | def page_guiref(arg_s=None):
"""Show a basic reference about the GUI Console."""
from IPython.core import page
page.page(gui_reference, auto_html=True) |
Get a member from an object by ( string ) name | def get_member(thing_obj, member_string):
"""Get a member from an object by (string) name"""
mems = {x[0]: x[1] for x in inspect.getmembers(thing_obj)}
if member_string in mems:
return mems[member_string] |
Return a live function from a full dotted path. Must be either a plain function directly in a module a class function or a static function. ( No modules classes or instance methods since those can t be called as tasks. ) | def func_from_string(callable_str):
"""Return a live function from a full dotted path. Must be either a plain function
directly in a module, a class function, or a static function. (No modules, classes,
or instance methods, since those can't be called as tasks.)"""
components = callable_str.split('.')... |
Factory function to create a properly initialized task. | def task_with_callable(the_callable, label=None, schedule=DEFAULT_SCHEDULE, userdata=None, pk_override=None):
"""Factory function to create a properly initialized task."""
task = Task()
if isinstance(the_callable, str):
if pk_override is not None:
components = the_callable.split('.')
... |
Return task info dictionary from task label. Internal function pretty much only used in migrations since the model methods aren t there. | def taskinfo_with_label(label):
"""Return task info dictionary from task label. Internal function,
pretty much only used in migrations since the model methods aren't there."""
task = Task.objects.get(label=label)
info = json.loads(task._func_info)
return info |
Find and return a callable object from a task info dictionary | def func_from_info(self):
"""Find and return a callable object from a task info dictionary"""
info = self.funcinfo
functype = info['func_type']
if functype in ['instancemethod', 'classmethod', 'staticmethod']:
the_modelclass = get_module_member_by_dottedpath(info['class_path'... |
Internal task - runner class method called by: py: func: sisy. consumers. run_heartbeat | def run_tasks(cls):
"""Internal task-runner class method, called by :py:func:`sisy.consumers.run_heartbeat`"""
now = timezone.now()
tasks = cls.objects.filter(enabled=True)
for task in tasks:
if task.next_run == HAS_NOT_RUN:
task.calc_next_run()
if... |
Calculate next run time of this task | def calc_next_run(self):
"""Calculate next run time of this task"""
base_time = self.last_run
if self.last_run == HAS_NOT_RUN:
if self.wait_for_schedule is False:
self.next_run = timezone.now()
self.wait_for_schedule = False # reset so we don't run on ... |
Internal instance method to submit this task for running immediately. Does not handle any iteration end - date etc. processing. | def submit(self, timestamp):
"""Internal instance method to submit this task for running immediately.
Does not handle any iteration, end-date, etc., processing."""
Channel(RUN_TASK_CHANNEL).send({'id':self.pk, 'ts': timestamp.timestamp()}) |
Internal instance method run by worker process to actually run the task callable. | def run(self, message):
"""Internal instance method run by worker process to actually run the task callable."""
the_callable = self.func_from_info()
try:
task_message = dict(
task=self,
channel_message=message,
)
the_callable(ta... |
Instance method to run this task immediately. | def run_asap(self):
"""Instance method to run this task immediately."""
now = timezone.now()
self.last_run = now
self.calc_next_run()
self.save()
self.submit(now) |
Class method to run a callable with a specified number of iterations | def run_iterations(cls, the_callable, iterations=1, label=None, schedule='* * * * * *', userdata = None, run_immediately=False, delay_until=None):
"""Class method to run a callable with a specified number of iterations"""
task = task_with_callable(the_callable, label=label, schedule=schedule, userdata=u... |
Class method to run a one - shot task immediately. | def run_once(cls, the_callable, userdata=None, delay_until=None):
"""Class method to run a one-shot task, immediately."""
cls.run_iterations(the_callable, userdata=userdata, run_immediately=True, delay_until=delay_until) |
Set the url file. | def find_url_file(self):
"""Set the url file.
Here we don't try to actually see if it exists for is valid as that
is hadled by the connection logic.
"""
config = self.config
# Find the actual controller key file
if not self.url_file:
self.url_file = o... |
load config from a JSON connector file at a * lower * priority than command - line/ config files. | def load_connector_file(self):
"""load config from a JSON connector file,
at a *lower* priority than command-line/config files.
"""
self.log.info("Loading url_file %r", self.url_file)
config = self.config
with open(self.url_file) as f:
d = js... |
Promote engine to listening kernel accessible to frontends. | def bind_kernel(self, **kwargs):
"""Promote engine to listening kernel, accessible to frontends."""
if self.kernel_app is not None:
return
self.log.info("Opening ports for direct connections as an IPython kernel")
kernel = self.kernel
kwargs... |
Check whether pid exists in the current process table. | def pid_exists(pid):
"""Check whether pid exists in the current process table."""
if not isinstance(pid, int):
raise TypeError('an integer is required')
if pid < 0:
return False
try:
os.kill(pid, 0)
except OSError:
e = sys.exc_info()[1]
return e.errno == errno... |
Return disk usage associated with path. | def get_disk_usage(path):
"""Return disk usage associated with path."""
st = os.statvfs(path)
free = (st.f_bavail * st.f_frsize)
total = (st.f_blocks * st.f_frsize)
used = (st.f_blocks - st.f_bfree) * st.f_frsize
percent = usage_percent(used, total, _round=1)
# NB: the percentage is -5% than... |
Execute a test described by a YAML file. | def timid(ctxt, test, key=None, check=False, exts=None):
"""
Execute a test described by a YAML file.
:param ctxt: A ``timid.context.Context`` object.
:param test: The name of a YAML file containing the test
description. Note that the current working directory
set up ... |
A cli_tools processor function that interfaces between the command line and the timid () function. This function is responsible for allocating a timid. context. Context object and initializing the activated extensions and for calling those extensions finalize () method. | def _processor(args):
"""
A ``cli_tools`` processor function that interfaces between the
command line and the ``timid()`` function. This function is
responsible for allocating a ``timid.context.Context`` object and
initializing the activated extensions, and for calling those
extensions' ``final... |
>>> lang_instance = create_lang_instance () >>> lang_instance. aml_evaluate ( lang_instance. aml_compile ( 1 = 1 )) True >>> li = create_lang_instance () >>> c = li. aml_compile >>> e = li. aml_evaluate >>> p = li. aml_translate_python >>> s = li. aml_translate_sql >>> u = li. aml_suggest >>> e ( c ( 1 = 0 )) False >>>... | def create_lang_instance(var_map = None):
"""
>>> lang_instance = create_lang_instance()
>>> lang_instance.aml_evaluate(lang_instance.aml_compile('1 = 1'))
True
>>> li = create_lang_instance()
>>> c = li.aml_compile
>>> e = li.aml_evaluate
>>> p = li.aml_translate_python
>>> s = li.aml_translate_sql
>>> u = l... |
Create an interrupt event handle. | def create_interrupt_event():
""" Create an interrupt event handle.
The parent process should use this static method for creating the
interrupt event that is passed to the child process. It should store
this handle and use it with ``send_interrupt`` to interrupt the child
proces... |
Run the poll loop. This method never returns. | def run(self):
""" Run the poll loop. This method never returns.
"""
try:
from _winapi import WAIT_OBJECT_0, INFINITE
except ImportError:
from _subprocess import WAIT_OBJECT_0, INFINITE
# Build the list of handle to listen on.
handles = []
... |
Function to initialize settings from command line and/ or custom settings file: return: Returns str with operation type | def initialize():
"""
Function to initialize settings from command line and/or custom settings file
:return: Returns str with operation type
"""
if len(sys.argv) == 1:
usage()
sys.exit()
command = _get_command(sys.argv[1])
try:
opts, args = getopt.getopt(sys.argv[2:... |
Return dictionaries mapping lower case typename ( e. g. tuple ) to type objects from the types package and vice versa. | def create_typestr2type_dicts(dont_include_in_type2typestr=["lambda"]):
"""Return dictionaries mapping lower case typename (e.g. 'tuple') to type
objects from the types package, and vice versa."""
typenamelist = [tname for tname in dir(types) if tname.endswith("Type")]
typestr2type, type2typestr = {}, {... |
is_type ( obj typestr_or_type ) verifies if obj is of a certain type. It can take strings or actual python types for the second argument i. e. tuple < - > TupleType. all matches all types. | def is_type(obj, typestr_or_type):
"""is_type(obj, typestr_or_type) verifies if obj is of a certain type. It
can take strings or actual python types for the second argument, i.e.
'tuple'<->TupleType. 'all' matches all types.
TODO: Should be extended for choosing more than one type."""
if typestr_or... |
Produce a dictionary of an object s attributes. Builds on dir2 by checking that a getattr () call actually succeeds. | def dict_dir(obj):
"""Produce a dictionary of an object's attributes. Builds on dir2 by
checking that a getattr() call actually succeeds."""
ns = {}
for key in dir2(obj):
# This seemingly unnecessary try/except is actually needed
# because there is code out there with metaclasses that
... |
Filter a namespace dictionary by name pattern and item type. | def filter_ns(ns, name_pattern="*", type_pattern="all", ignore_case=True,
show_all=True):
"""Filter a namespace dictionary by name pattern and item type."""
pattern = name_pattern.replace("*",".*").replace("?",".")
if ignore_case:
reg = re.compile(pattern+"$", re.I)
else:
reg... |
Return dictionary of all objects in a namespace dictionary that match type_pattern and filter. | def list_namespace(namespace, type_pattern, filter, ignore_case=False, show_all=False):
"""Return dictionary of all objects in a namespace dictionary that match
type_pattern and filter."""
pattern_list=filter.split(".")
if len(pattern_list) == 1:
return filter_ns(namespace, name_pattern=pattern_l... |
Check for presence of mutually exclusive keys in a dict. | def mutex_opts(dict,ex_op):
"""Check for presence of mutually exclusive keys in a dict.
Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]"""
for op1,op2 in ex_op:
if op1 in dict and op2 in dict:
raise ValueError,'\n*** ERROR in Arguments *** '\
'Options '+op1+' and '+... |
map_method ( method object_list * args ** kw ) - > list | def map_method(method,object_list,*argseq,**kw):
"""map_method(method,object_list,*args,**kw) -> list
Return a list of the results of applying the methods to the items of the
argument sequence(s). If more than one sequence is given, the method is
called with an argument list consisting of the correspo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.