Search is not available for this dataset
text stringlengths 75 104k |
|---|
def render(self, context=None):
"""Render this template by applying it to `context`.
`context` is a dictionary of values to use in this rendering.
"""
# Make the complete context we'll use.
ctx = dict(self.context)
if context:
ctx.update(context)
ret... |
def do_dots(self, value, *dots):
"""Evaluate dotted expressions at runtime."""
for dot in dots:
try:
value = getattr(value, dot)
except AttributeError:
value = value[dot]
if hasattr(value, '__call__'):
value = value()
... |
def render_template(tpl, context):
'''
A shortcut function to render a partial template with context and return
the output.
'''
templates = [tpl] if type(tpl) != list else tpl
tpl_instance = None
for tpl in templates:
try:
tpl_instance = template.loader.get_t... |
def format_display_data(obj, include=None, exclude=None):
"""Return a format data dict for an object.
By default all format types will be computed.
The following MIME types are currently implemented:
* text/plain
* text/html
* text/latex
* application/json
* application/javascript
... |
def _formatters_default(self):
"""Activate the default formatters."""
formatter_classes = [
PlainTextFormatter,
HTMLFormatter,
SVGFormatter,
PNGFormatter,
JPEGFormatter,
LatexFormatter,
JSONFormatter,
Javascr... |
def format(self, obj, include=None, exclude=None):
"""Return a format data dict for an object.
By default all format types will be computed.
The following MIME types are currently implemented:
* text/plain
* text/html
* text/latex
* application/json
* a... |
def for_type(self, typ, func):
"""Add a format function for a given type.
Parameters
-----------
typ : class
The class of the object that will be formatted using `func`.
func : callable
The callable that will be called to compute the format data. The
... |
def for_type_by_name(self, type_module, type_name, func):
"""Add a format function for a type specified by the full dotted
module and name of the type, rather than the type of the object.
Parameters
----------
type_module : str
The full dotted name of the module the ... |
def _in_deferred_types(self, cls):
"""
Check if the given class is specified in the deferred type registry.
Returns the printer from the registry if it exists, and None if the
class is not in the registry. Successful matches will be moved to the
regular type registry for future ... |
def _float_precision_changed(self, name, old, new):
"""float_precision changed, set float_format accordingly.
float_precision can be set by int or str.
This will set float_format, after interpreting input.
If numpy has been imported, numpy print precision will also be set.
inte... |
def user_config_files():
"""Return path to any existing user config files
"""
return filter(os.path.exists,
map(os.path.expanduser, config_files)) |
def flag(val):
"""Does the value look like an on/off flag?"""
if val == 1:
return True
elif val == 0:
return False
val = str(val)
if len(val) > 5:
return False
return val.upper() in ('1', '0', 'F', 'T', 'TRUE', 'FALSE', 'ON', 'OFF') |
def configure(self, argv=None, doc=None):
"""Configure the nose running environment. Execute configure before
collecting tests with nose.TestCollector to enable output capture and
other features.
"""
env = self.env
if argv is None:
argv = sys.argv
cfg... |
def configureLogging(self):
"""Configure logging for nose, or optionally other packages. Any logger
name may be set with the debug option, and that logger will be set to
debug level and be assigned the same handler as the nose loggers, unless
it already has a handler.
"""
... |
def configureWhere(self, where):
"""Configure the working directory or directories for the test run.
"""
from nose.importer import add_path
self.workingDir = None
where = tolist(where)
warned = False
for path in where:
if not self.workingDir:
... |
def getParser(self, doc=None):
"""Get the command line option parser.
"""
if self.parser:
return self.parser
env = self.env
parser = self.parserClass(doc)
parser.add_option(
"-V","--version", action="store_true",
dest="version", default... |
def page_dumb(strng, start=0, screen_lines=25):
"""Very dumb 'pager' in Python, for when nothing else works.
Only moves forward, same interface as page(), except for pager_cmd and
mode."""
out_ln = strng.splitlines()[start:]
screens = chop(out_ln,screen_lines-1)
if len(screens) == 1:
... |
def _detect_screen_size(use_curses, screen_lines_def):
"""Attempt to work out the number of lines on the screen.
This is called by page(). It can raise an error (e.g. when run in the
test suite), so it's separated out so it can easily be called in a try block.
"""
TERM = os.environ.get('TERM',N... |
def page(strng, start=0, screen_lines=0, pager_cmd=None):
"""Print a string, piping through a pager after a certain length.
The screen_lines parameter specifies the number of *usable* lines of your
terminal screen (total lines minus lines you need to reserve to show other
information).
If you set ... |
def page_file(fname, start=0, pager_cmd=None):
"""Page a file, using an optional pager command and starting line.
"""
pager_cmd = get_pager_cmd(pager_cmd)
pager_cmd += ' ' + get_pager_start(pager_cmd,start)
try:
if os.environ['TERM'] in ['emacs','dumb']:
raise EnvironmentError
... |
def get_pager_cmd(pager_cmd=None):
"""Return a pager command.
Makes some attempts at finding an OS-correct one.
"""
if os.name == 'posix':
default_pager_cmd = 'less -r' # -r for color control sequences
elif os.name in ['nt','dos']:
default_pager_cmd = 'type'
if pager_cmd is No... |
def get_pager_start(pager, start):
"""Return the string for paging files with an offset.
This is the '+N' argument which less and more (under Unix) accept.
"""
if pager in ['less','more']:
if start:
start_string = '+' + str(start)
else:
start_string = ''
els... |
def snip_print(str,width = 75,print_full = 0,header = ''):
"""Print a string snipping the midsection to fit in width.
print_full: mode control:
- 0: only snip long strings
- 1: send to page() directly.
- 2: snip long strings and ask for full length viewing with page()
Return 1 if snipping... |
def timings_out(reps,func,*args,**kw):
"""timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output)
Execute a function reps times, return a tuple with the elapsed total
CPU time in seconds, the time per call and the function's output.
Under Unix, the return value is the sum of user+system time ... |
def timings(reps,func,*args,**kw):
"""timings(reps,func,*args,**kw) -> (t_total,t_per_call)
Execute a function reps times, return a tuple with the elapsed total CPU
time in seconds and the time per call. These are just the first two values
in timings_out()."""
return timings_out(reps,func,*args,**... |
def print_basic_unicode(o, p, cycle):
"""A function to pretty print sympy Basic objects."""
if cycle:
return p.text('Basic(...)')
out = pretty(o, use_unicode=True)
if '\n' in out:
p.text(u'\n')
p.text(out) |
def print_png(o):
"""
A function to display sympy expression using inline style LaTeX in PNG.
"""
s = latex(o, mode='inline')
# mathtext does not understand certain latex flags, so we try to replace
# them with suitable subs.
s = s.replace('\\operatorname','')
s = s.replace('\\overline',... |
def print_display_png(o):
"""
A function to display sympy expression using display style LaTeX in PNG.
"""
s = latex(o, mode='plain')
s = s.strip('$')
# As matplotlib does not support display style, dvipng backend is
# used here.
png = latex_to_png('$$%s$$' % s, backend='dvipng')
ret... |
def can_print_latex(o):
"""
Return True if type o can be printed with LaTeX.
If o is a container type, this is True if and only if every element of o
can be printed with LaTeX.
"""
import sympy
if isinstance(o, (list, tuple, set, frozenset)):
return all(can_print_latex(i) for i in o... |
def print_latex(o):
"""A function to generate the latex representation of sympy
expressions."""
if can_print_latex(o):
s = latex(o, mode='plain')
s = s.replace('\\dag','\\dagger')
s = s.strip('$')
return '$$%s$$' % s
# Fallback to the string printer
return None |
def load_ipython_extension(ip):
"""Load the extension in IPython."""
import sympy
# sympyprinting extension has been moved to SymPy as of 0.7.2, if it
# exists there, warn the user and import it
try:
import sympy.interactive.ipythonprinting
except ImportError:
pass
else:
... |
def str2tokens(string, delimiter):
"""
Usage:
{% with 'this, is a, string'|str2tokens:',' as token_list %}do something{% endwith %}
"""
token_list = [token.strip() for token in string.split(delimiter)]
return token_list |
def str2tokenstags(string, delimiter):
"""
Usage:
{% str2tokens 'a/b/c/d' '/' as token_list %}
"""
token_list = [token.strip() for token in string.split(delimiter)]
return token_list |
def add_options(self, parser, env=None):
"""Non-camel-case version of func name for backwards compatibility.
.. warning ::
DEPRECATED: Do not use this method,
use :meth:`options <nose.plugins.base.IPluginInterface.options>`
instead.
"""
# FIXME raise d... |
def options(self, parser, env):
"""Register commandline options.
Implement this method for normal options behavior with protection from
OptionConflictErrors. If you override this method and want the default
--with-$name option to be registered, be sure to call super().
"""
... |
def configure(self, options, conf):
"""Configure the plugin and system, based on selected options.
The base plugin class sets the plugin to enabled if the enable option
for the plugin (self.enableOpt) is true.
"""
if not self.can_configure:
return
self.conf =... |
def validate_string_list(lst):
"""Validate that the input is a list of strings.
Raises ValueError if not."""
if not isinstance(lst, list):
raise ValueError('input %r must be a list' % lst)
for x in lst:
if not isinstance(x, basestring):
raise ValueError('element %r in list m... |
def validate_string_dict(dct):
"""Validate that the input is a dict with string keys and values.
Raises ValueError if not."""
for k,v in dct.iteritems():
if not isinstance(k, basestring):
raise ValueError('key %r in dict must be a string' % k)
if not isinstance(v, basestring):
... |
def _run_loop(self):
"""Run my loop, ignoring EINTR events in the poller"""
while True:
try:
self.ioloop.start()
except ZMQError as e:
if e.errno == errno.EINTR:
continue
else:
raise
... |
def _queue_send(self, msg):
"""Queue a message to be sent from the IOLoop's thread.
Parameters
----------
msg : message to send
This is threadsafe, as it uses IOLoop.add_callback to give the loop's
thread control of the action.
"""
def th... |
def _handle_recv(self, msg):
"""callback for stream.on_recv
unpacks message, and calls handlers with it.
"""
ident,smsg = self.session.feed_identities(msg)
self.call_handlers(self.session.unserialize(smsg)) |
def run(self):
"""The thread's main activity. Call start() instead."""
self.socket = self.context.socket(zmq.DEALER)
self.socket.setsockopt(zmq.IDENTITY, self.session.bsession)
self.socket.connect('tcp://%s:%i' % self.address)
self.stream = zmqstream.ZMQStream(self.socket, self.... |
def execute(self, code, silent=False,
user_variables=None, user_expressions=None, allow_stdin=None):
"""Execute code in the kernel.
Parameters
----------
code : str
A string of Python code.
silent : bool, optional (default False)
If set, ... |
def complete(self, text, line, cursor_pos, block=None):
"""Tab complete text in the kernel's namespace.
Parameters
----------
text : str
The text to complete.
line : str
The full line of text that is the surrounding context for the
text to com... |
def object_info(self, oname, detail_level=0):
"""Get metadata information about an object.
Parameters
----------
oname : str
A string specifying the object name.
detail_level : int, optional
The level of detail for the introspection (0-2)
Returns... |
def history(self, raw=True, output=False, hist_access_type='range', **kwargs):
"""Get entries from the history list.
Parameters
----------
raw : bool
If True, return the raw input.
output : bool
If True, then return the output as well.
hist_access... |
def shutdown(self, restart=False):
"""Request an immediate kernel shutdown.
Upon receipt of the (empty) reply, client code can safely assume that
the kernel has shut down and it's safe to forcefully terminate it if
it's still alive.
The kernel will send the reply via a function... |
def flush(self, timeout=1.0):
"""Immediately processes all pending messages on the SUB channel.
Callers should use this method to ensure that :method:`call_handlers`
has been called for all messages that have been received on the
0MQ SUB socket of this channel.
This method is t... |
def input(self, string):
"""Send a string of raw input to the kernel."""
content = dict(value=string)
msg = self.session.msg('input_reply', content)
self._queue_send(msg) |
def _poll(self, start_time):
"""poll for heartbeat replies until we reach self.time_to_dead
Ignores interrupts, and returns the result of poll(), which
will be an empty list if no messages arrived before the timeout,
or the event tuple if there is a message to receive.
"... |
def run(self):
"""The thread's main activity. Call start() instead."""
self._create_socket()
self._running = True
self._beating = True
while self._running:
if self._pause:
# just sleep, and skip the rest of the loop
time.sleep... |
def is_beating(self):
"""Is the heartbeat running and responsive (and not paused)."""
if self.is_alive() and not self._pause and self._beating:
return True
else:
return False |
def start_channels(self, shell=True, sub=True, stdin=True, hb=True):
"""Starts the channels for this kernel.
This will create the channels if they do not exist and then start
them. If port numbers of 0 are being used (random ports) then you
must first call :method:`start_kernel`. If the... |
def stop_channels(self):
"""Stops all the running channels for this kernel.
"""
if self.shell_channel.is_alive():
self.shell_channel.stop()
if self.sub_channel.is_alive():
self.sub_channel.stop()
if self.stdin_channel.is_alive():
self.stdin_cha... |
def channels_running(self):
"""Are any of the channels created and running?"""
return (self.shell_channel.is_alive() or self.sub_channel.is_alive() or
self.stdin_channel.is_alive() or self.hb_channel.is_alive()) |
def cleanup_connection_file(self):
"""cleanup connection file *if we wrote it*
Will not raise if the connection file was already removed somehow.
"""
if self._connection_file_written:
# cleanup connection files on full shutdown of kernel we started
self._... |
def load_connection_file(self):
"""load connection info from JSON dict in self.connection_file"""
with open(self.connection_file) as f:
cfg = json.loads(f.read())
self.ip = cfg['ip']
self.shell_port = cfg['shell_port']
self.stdin_port = cfg['stdin_port']
... |
def write_connection_file(self):
"""write connection info to JSON dict in self.connection_file"""
if self._connection_file_written:
return
self.connection_file,cfg = write_connection_file(self.connection_file,
ip=self.ip, key=self.session.key,
stdin_port=self.... |
def start_kernel(self, **kw):
"""Starts a kernel process and configures the manager to use it.
If random ports (port=0) are being used, this method must be called
before the channels are created.
Parameters:
-----------
launcher : callable, optional (default None)
... |
def shutdown_kernel(self, restart=False):
""" Attempts to the stop the kernel process cleanly. If the kernel
cannot be stopped, it is killed, if possible.
"""
# FIXME: Shutdown does not work on Windows due to ZMQ errors!
if sys.platform == 'win32':
self.kill_kernel()
... |
def restart_kernel(self, now=False, **kw):
"""Restarts a kernel with the arguments that were used to launch it.
If the old kernel was launched with random ports, the same ports will be
used for the new kernel.
Parameters
----------
now : bool, optional
If Tr... |
def kill_kernel(self):
""" Kill the running kernel. """
if self.has_kernel:
# Pause the heart beat channel if it exists.
if self._hb_channel is not None:
self._hb_channel.pause()
# Attempt to kill the kernel.
try:
self.kern... |
def interrupt_kernel(self):
""" Interrupts the kernel. Unlike ``signal_kernel``, this operation is
well supported on all platforms.
"""
if self.has_kernel:
if sys.platform == 'win32':
from parentpoller import ParentPollerWindows as Poller
Polle... |
def signal_kernel(self, signum):
""" Sends a signal to the kernel. Note that since only SIGTERM is
supported on Windows, this function is only useful on Unix systems.
"""
if self.has_kernel:
self.kernel.send_signal(signum)
else:
raise RuntimeError("Cannot ... |
def is_alive(self):
"""Is the kernel process still running?"""
if self.has_kernel:
if self.kernel.poll() is None:
return True
else:
return False
elif self._hb_channel is not None:
# We didn't start the kernel with this KernelMan... |
def shell_channel(self):
"""Get the REQ socket channel object to make requests of the kernel."""
if self._shell_channel is None:
self._shell_channel = self.shell_channel_class(self.context,
self.session,
... |
def sub_channel(self):
"""Get the SUB socket channel object."""
if self._sub_channel is None:
self._sub_channel = self.sub_channel_class(self.context,
self.session,
(self.ip, self.io... |
def stdin_channel(self):
"""Get the REP socket channel object to handle stdin (raw_input)."""
if self._stdin_channel is None:
self._stdin_channel = self.stdin_channel_class(self.context,
self.session,
... |
def hb_channel(self):
"""Get the heartbeat socket channel object to check that the
kernel is alive."""
if self._hb_channel is None:
self._hb_channel = self.hb_channel_class(self.context,
self.session,
... |
def bind_kernel(**kwargs):
"""Bind an Engine's Kernel to be used as a full IPython kernel.
This allows a running Engine to be used simultaneously as a full IPython kernel
with the QtConsole or other frontends.
This function returns immediately.
"""
from IPython.zmq.ipkernel import IPKe... |
def debug(self, level, message):
"""
Emit a debugging message depending on the debugging level.
:param level: The debugging level.
:param message: The message to emit.
"""
if self._debug >= level:
print(message, file=sys.stderr) |
def _get_extension_classes(cls):
"""
Retrieve the extension classes in priority order.
:returns: A list of extension classes, in proper priority
order.
"""
if cls._extension_classes is None:
exts = {}
# Iterate over the entrypoints
... |
def prepare(cls, parser):
"""
Prepare all the extensions. Extensions are prepared during
argument parser preparation. An extension implementing the
``prepare()`` method is able to add command line arguments
specific for that extension.
:param parser: The argument parse... |
def activate(cls, ctxt, args):
"""
Initialize the extensions. This loops over each extension
invoking its ``activate()`` method; those extensions that
return an object are considered "activated" and will be called
at later phases of extension processing.
:param ctxt: An... |
def read_steps(self, ctxt, steps):
"""
Called after reading steps, prior to adding them to the list of
test steps. Extensions are able to alter the list (in place).
:param ctxt: An instance of ``timid.context.Context``.
:param steps: A list of ``timid.steps.Step`` instances.
... |
def pre_step(self, ctxt, step, idx):
"""
Called prior to executing a step.
:param ctxt: An instance of ``timid.context.Context``.
:param step: An instance of ``timid.steps.Step`` describing
the step to be executed.
:param idx: The index of the step in the li... |
def post_step(self, ctxt, step, idx, result):
"""
Called after executing a step.
:param ctxt: An instance of ``timid.context.Context``.
:param step: An instance of ``timid.steps.Step`` describing
the step that was executed.
:param idx: The index of the step ... |
def finalize(self, ctxt, result):
"""
Called at the end of processing. This call allows extensions to
emit any additional data, such as timing information, prior to
``timid``'s exit. Extensions may also alter the return value.
:param ctxt: An instance of ``timid.context.Contex... |
def walk_egg(egg_dir):
"""Walk an unpacked egg's contents, skipping the metadata directory"""
walker = os.walk(egg_dir)
base,dirs,files = walker.next()
if 'EGG-INFO' in dirs:
dirs.remove('EGG-INFO')
yield base,dirs,files
for bdf in walker:
yield bdf |
def scan_module(egg_dir, base, name, stubs):
"""Check whether module possibly uses unsafe-for-zipfile stuff"""
filename = os.path.join(base,name)
if filename[:-1] in stubs:
return True # Extension module
pkg = base[len(egg_dir)+1:].replace(os.sep,'.')
module = pkg+(pkg and '.' or '')+os... |
def make_init_files(self):
"""Create missing package __init__ files"""
init_files = []
for base,dirs,files in walk_egg(self.bdist_dir):
if base==self.bdist_dir:
# don't put an __init__ in the root
continue
for name in files:
... |
def launch_new_instance():
"""Create and run the IPython controller"""
if sys.platform == 'win32':
# make sure we don't get called from a multiprocessing subprocess
# this can result in infinite Controllers being started on Windows
# which doesn't have a proper fork, so multiprocessing i... |
def save_connection_dict(self, fname, cdict):
"""save a connection dict to json file."""
c = self.config
url = cdict['url']
location = cdict['location']
if not location:
try:
proto,ip,port = split_url(url)
except AssertionError:
... |
def load_config_from_json(self):
"""load config from existing json connector files."""
c = self.config
self.log.debug("loading config from JSON")
# load from engine config
fname = os.path.join(self.profile_dir.security_dir, self.engine_json_file)
self.log.info("loading co... |
def load_secondary_config(self):
"""secondary config, loading from JSON and setting defaults"""
if self.reuse_files:
try:
self.load_config_from_json()
except (AssertionError,IOError) as e:
self.log.error("Could not load config from JSON: %s" % e)
... |
def script_args(f):
"""single decorator for adding script args"""
args = [
magic_arguments.argument(
'--out', type=str,
help="""The variable in which to store stdout from the script.
If the script is backgrounded, this will be the stdout *pipe*,
instead of... |
def exec_args(f):
"""decorator for adding block/targets args for execution
applied to %pxconfig and %%px
"""
args = [
magic_arguments.argument('-b', '--block', action="store_const",
const=True, dest='block',
help="use blocking (sync) execution",
),
ma... |
def output_args(f):
"""decorator for output-formatting args
applied to %pxresult and %%px
"""
args = [
magic_arguments.argument('-r', action="store_const", dest='groupby',
const='order',
help="collate outputs in order (same as group-outputs=order)"
),
... |
def pxconfig(self, line):
"""configure default targets/blocking for %px magics"""
args = magic_arguments.parse_argstring(self.pxconfig, line)
if args.targets:
self.view.targets = self._eval_target_str(args.targets)
if args.block is not None:
self.view.block = args... |
def result(self, line=''):
"""Print the result of the last asynchronous %px command.
This lets you recall the results of %px computations after
asynchronous submission (block=False).
Examples
--------
::
In [23]: %px os.getpid()
Async pa... |
def parallel_execute(self, cell, block=None, groupby='type', save_name=None):
"""implementation used by %px and %%parallel"""
# defaults:
block = self.view.block if block is None else block
base = "Parallel" if block else "Async parallel"
targets = self.view.ta... |
def cell_px(self, line='', cell=None):
"""Executes the cell in parallel.
Examples
--------
::
In [24]: %%px --noblock
....: a = os.getpid()
Async parallel execution on engine(s): all
In [25]: %%px
..... |
def _enable_autopx(self):
"""Enable %autopx mode by saving the original run_cell and installing
pxrun_cell.
"""
# override run_cell
self._original_run_cell = self.shell.run_cell
self.shell.run_cell = self.pxrun_cell
self._autopx = True
print "%autopx enab... |
def _disable_autopx(self):
"""Disable %autopx by restoring the original InteractiveShell.run_cell.
"""
if self._autopx:
self.shell.run_cell = self._original_run_cell
self._autopx = False
print "%autopx disabled" |
def pxrun_cell(self, raw_cell, store_history=False, silent=False):
"""drop-in replacement for InteractiveShell.run_cell.
This executes code remotely, instead of in the local namespace.
See InteractiveShell.run_cell for details.
"""
if (not raw_cell) or raw_cell.isspace():
... |
def run_heartbeat(message):
"""Internal ``CLOCK_CHANNEL`` consumer to process task runs"""
then = arrow.get(message['time'])
now = arrow.get()
if (now - then) > timezone.timedelta(seconds=(TICK_FREQ+1)):
pass # discard old ticks
else:
Task.run_tasks() |
def run_task(message):
"""Internal ``RUN_TASK`` consumer to run the task's callable"""
task = Task.objects.get(pk=message['id'])
if task.allow_overlap:
task.run(message)
else:
if not task.running:
task.running = True
task.save()
try:
ta... |
def remove_task(message):
"""Internal ``KILL_TASK`` consumer to remove retired tasks"""
task = Task.objects.get(pk=message['id'])
task.delete() |
def patch_protocol_for_agent(protocol):
"""
Patch the protocol's makeConnection and connectionLost methods to make the
protocol and its transport behave more like what `Agent` expects.
While `Agent` is the driving force behind this, other clients and servers
will no doubt have similar requirements.... |
def patch_if_missing(obj, name, method):
"""
Patch a method onto an object if it isn't already there.
"""
setattr(obj, name, getattr(obj, name, method)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.