INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Split the code object into a list of Chunk objects. | def _split_into_chunks(self):
"""Split the code object into a list of `Chunk` objects.
Each chunk is only entered at its first instruction, though there can
be many exits from a chunk.
Returns a list of `Chunk` objects.
"""
# The list of chunks so far, and the one we'r... |
Validate the rule that chunks have a single entrance. | def validate_chunks(self, chunks):
"""Validate the rule that chunks have a single entrance."""
# starts is the entrances to the chunks
starts = set([ch.byte for ch in chunks])
for ch in chunks:
assert all([(ex in starts or ex < 0) for ex in ch.exits]) |
Find the executable arcs in the code. | def _arcs(self):
"""Find the executable arcs in the code.
Yields pairs: (from,to). From and to are integer line numbers. If
from is < 0, then the arc is an entrance into the code object. If to
is < 0, the arc is an exit from the code object.
"""
chunks = self._split_... |
Returns a list of Chunk objects for this code and its children. | def _all_chunks(self):
"""Returns a list of `Chunk` objects for this code and its children.
See `_split_into_chunks` for details.
"""
chunks = []
for bp in self.child_parsers():
chunks.extend(bp._split_into_chunks())
return chunks |
Get the set of all arcs in this code object and its children. | def _all_arcs(self):
"""Get the set of all arcs in this code object and its children.
See `_arcs` for details.
"""
arcs = set()
for bp in self.child_parsers():
arcs.update(bp._arcs())
return arcs |
Add options to command line. | def options(self, parser, env):
"""
Add options to command line.
"""
super(Coverage, self).options(parser, env)
parser.add_option("--cover-package", action="append",
default=env.get('NOSE_COVER_PACKAGE'),
metavar="PACKAGE",
... |
Configure plugin. | def configure(self, options, conf):
"""
Configure plugin.
"""
try:
self.status.pop('active')
except KeyError:
pass
super(Coverage, self).configure(options, conf)
if conf.worker:
return
if self.enabled:
try:
... |
Begin recording coverage information. | def begin(self):
"""
Begin recording coverage information.
"""
log.debug("Coverage begin")
self.skipModules = sys.modules.keys()[:]
if self.coverErase:
log.debug("Clearing previously collected coverage statistics")
self.coverInstance.combine()
... |
Output code coverage report. | def report(self, stream):
"""
Output code coverage report.
"""
log.debug("Coverage report")
self.coverInstance.stop()
self.coverInstance.combine()
self.coverInstance.save()
modules = [module
for name, module in sys.modules.items()
... |
If inclusive coverage enabled return true for all source files in wanted packages. | def wantFile(self, file, package=None):
"""If inclusive coverage enabled, return true for all source files
in wanted packages.
"""
if self.coverInclusive:
if file.endswith(".py"):
if package and self.coverPackages:
for want in self.coverPac... |
Generate alternative interpretations of a source distro name | def interpret_distro_name(location, basename, metadata,
py_version=None, precedence=SOURCE_DIST, platform=None
):
"""Generate alternative interpretations of a source distro name
Note: if `location` is a filesystem filename, you should call
``pkg_resources.normalize_path()`` on it before passing it to t... |
A function compatible with Python 2. 3 - 3. 3 that will encode auth from a URL suitable for an HTTP header. >>> _encode_auth ( username%3Apassword ) u dXNlcm5hbWU6cGFzc3dvcmQ = | def _encode_auth(auth):
"""
A function compatible with Python 2.3-3.3 that will encode
auth from a URL suitable for an HTTP header.
>>> _encode_auth('username%3Apassword')
u'dXNlcm5hbWU6cGFzc3dvcmQ='
"""
auth_s = urllib2.unquote(auth)
# convert to bytes
auth_bytes = auth_s.encode()
... |
Open a urllib2 request handling HTTP authentication | def open_with_auth(url):
"""Open a urllib2 request, handling HTTP authentication"""
scheme, netloc, path, params, query, frag = urlparse.urlparse(url)
# Double scheme does not raise on Mac OS X as revealed by a
# failing test. We would expect "nonnumeric port". Refs #20.
if netloc.endswith(':'):
... |
Obtain a distribution suitable for fulfilling requirement | def fetch_distribution(self,
requirement, tmpdir, force_scan=False, source=False, develop_ok=False,
local_index=None
):
"""Obtain a distribution suitable for fulfilling `requirement`
`requirement` must be a ``pkg_resources.Requirement`` instance.
If necessary, or if the `for... |
customized repr (). | def jrepr(value):
'''customized `repr()`.'''
if value is None:
return repr(value)
t = type(value)
if t.__repr__ is not object.__repr__:
return repr(value)
return 'object ' + t.__name__ |
get parent from obj. | def get_parent(obj):
'''
get parent from obj.
'''
names = obj.__qualname__.split('.')[:-1]
if '<locals>' in names: # locals function
raise ValueError('cannot get parent from locals object.')
module = sys.modules[obj.__module__]
parent = module
while names:
parent = getatt... |
this is a property in case the handler is created before the engine gets registered with an id | def root_topic(self):
"""this is a property, in case the handler is created
before the engine gets registered with an id"""
if isinstance(getattr(self.engine, 'id', None), int):
return "engine.%i"%self.engine.id
else:
return "engine" |
Initialize a FakeModule instance __dict__. | def init_fakemod_dict(fm,adict=None):
"""Initialize a FakeModule instance __dict__.
Kept as a standalone function and not a method so the FakeModule API can
remain basically empty.
This should be considered for private IPython use, used in managing
namespaces for %run.
Parameters
--------... |
renders context aware template | def render_template(content, context):
""" renders context aware template """
rendered = Template(content).render(Context(context))
return rendered |
Configure plugin. Plugin is enabled by default. | def configure(self, options, conf):
"""Configure plugin. Plugin is enabled by default.
"""
self.conf = conf
if not options.capture:
self.enabled = False |
Add captured output to error report. | def formatError(self, test, err):
"""Add captured output to error report.
"""
test.capturedOutput = output = self.buffer
self._buf = None
if not output:
# Don't return None as that will prevent other
# formatters from formatting and remove earlier formatte... |
Turn a list to list of list | def splitBy(data, num):
""" Turn a list to list of list """
return [data[i:i + num] for i in range(0, len(data), num)] |
Convert a notebook to the v3 format. | def convert_to_this_nbformat(nb, orig_version=2, orig_minor=0):
"""Convert a notebook to the v3 format.
Parameters
----------
nb : NotebookNode
The Python representation of the notebook to convert.
orig_version : int
The original version of the notebook to convert.
orig_minor : ... |
Convert a hex color to rgb integer tuple. | def hex_to_rgb(color):
"""Convert a hex color to rgb integer tuple."""
if color.startswith('#'):
color = color[1:]
if len(color) == 3:
color = ''.join([c*2 for c in color])
if len(color) != 6:
return False
try:
r = int(color[:2],16)
g = int(color[2:4],16)
... |
Construct the keys to be used building the base stylesheet from a templatee. | def get_colors(stylename):
"""Construct the keys to be used building the base stylesheet
from a templatee."""
style = get_style_by_name(stylename)
fgcolor = style.style_for_token(Token.Text)['color'] or ''
if len(fgcolor) in (3,6):
# could be 'abcdef' or 'ace' hex, which needs '#' prefix
... |
Use one of the base templates and set bg/ fg/ select colors. | def sheet_from_template(name, colors='lightbg'):
"""Use one of the base templates, and set bg/fg/select colors."""
colors = colors.lower()
if colors=='lightbg':
return default_light_style_template%get_colors(name)
elif colors=='linux':
return default_dark_style_template%get_colors(name)
... |
Return a font of the requested family using fallback as alternative. | def get_font(family, fallback=None):
"""Return a font of the requested family, using fallback as alternative.
If a fallback is provided, it is used in case the requested family isn't
found. If no fallback is given, no alternative is chosen and Qt's internal
algorithms may automatically choose a fallba... |
Reimplemented to support IPython s improved completion machinery. | def _handle_complete_reply(self, rep):
""" Reimplemented to support IPython's improved completion machinery.
"""
self.log.debug("complete: %s", rep.get('content', ''))
cursor = self._get_cursor()
info = self._request_info.get('complete')
if info and info.id == rep['parent... |
Reimplemented to support prompt requests. | def _handle_execute_reply(self, msg):
""" Reimplemented to support prompt requests.
"""
msg_id = msg['parent_header'].get('msg_id')
info = self._request_info['execute'].get(msg_id)
if info and info.kind == 'prompt':
number = msg['content']['execution_count'] + 1
... |
Implemented to handle history tail replies which are only supported by the IPython kernel. | def _handle_history_reply(self, msg):
""" Implemented to handle history tail replies, which are only supported
by the IPython kernel.
"""
content = msg['content']
if 'history' not in content:
self.log.error("History request failed: %r"%content)
if cont... |
Reimplemented for IPython - style display hook. | def _handle_pyout(self, msg):
""" Reimplemented for IPython-style "display hook".
"""
self.log.debug("pyout: %s", msg.get('content', ''))
if not self._hidden and self._is_from_this_session(msg):
content = msg['content']
prompt_number = content.get('execution_count... |
The base handler for the display_data message. | def _handle_display_data(self, msg):
""" The base handler for the ``display_data`` message.
"""
self.log.debug("display: %s", msg.get('content', ''))
# For now, we don't display data from other frontends, but we
# eventually will as this allows all frontends to monitor the displa... |
Reimplemented to make a history request and load %guiref. | def _started_channels(self):
"""Reimplemented to make a history request and load %guiref."""
super(IPythonWidget, self)._started_channels()
self._load_guiref_magic()
self.kernel_manager.shell_channel.history(hist_access_type='tail',
n=100... |
Reimplemented to use the run magic. | def execute_file(self, path, hidden=False):
""" Reimplemented to use the 'run' magic.
"""
# Use forward slashes on Windows to avoid escaping each separator.
if sys.platform == 'win32':
path = os.path.normpath(path).replace('\\', '/')
# Perhaps we should not be using ... |
Reimplemented to support IPython s improved completion machinery. | def _complete(self):
""" Reimplemented to support IPython's improved completion machinery.
"""
# We let the kernel split the input line, so we *always* send an empty
# text field. Readline-based frontends do get a real text field which
# they can use.
text = ''
#... |
Reimplemented for IPython - style traceback formatting. | def _process_execute_error(self, msg):
""" Reimplemented for IPython-style traceback formatting.
"""
content = msg['content']
traceback = '\n'.join(content['traceback']) + '\n'
if False:
# FIXME: For now, tracebacks come as plain text, so we can't use
# th... |
Reimplemented to dispatch payloads to handler methods. | def _process_execute_payload(self, item):
""" Reimplemented to dispatch payloads to handler methods.
"""
handler = self._payload_handlers.get(item['source'])
if handler is None:
# We have no handler for this type of payload, simply ignore it
return False
e... |
Reimplemented for IPython - style prompts. | def _show_interpreter_prompt(self, number=None):
""" Reimplemented for IPython-style prompts.
"""
# If a number was not specified, make a prompt number request.
if number is None:
msg_id = self.kernel_manager.shell_channel.execute('', silent=True)
info = self._Exe... |
Reimplemented for IPython - style prompts. | def _show_interpreter_prompt_for_reply(self, msg):
""" Reimplemented for IPython-style prompts.
"""
# Update the old prompt number if necessary.
content = msg['content']
# abort replies do not have any keys:
if content['status'] == 'aborted':
if self._previous... |
Sets the widget style to the class defaults. | def set_default_style(self, colors='lightbg'):
""" Sets the widget style to the class defaults.
Parameters:
-----------
colors : str, optional (default lightbg)
Whether to use the default IPython light background or dark
background or B&W style.
"""
... |
Opens a Python script for editing. | def _edit(self, filename, line=None):
""" Opens a Python script for editing.
Parameters:
-----------
filename : str
A path to a local system file.
line : int, optional
A line of interest in the file.
"""
if self.custom_edit:
s... |
Given a prompt number returns an HTML In prompt. | def _make_in_prompt(self, number):
""" Given a prompt number, returns an HTML In prompt.
"""
try:
body = self.in_prompt % number
except TypeError:
# allow in_prompt to leave out number, e.g. '>>> '
body = self.in_prompt
return '<span class="in-... |
Given a plain text version of an In prompt returns an HTML continuation prompt. | def _make_continuation_prompt(self, prompt):
""" Given a plain text version of an In prompt, returns an HTML
continuation prompt.
"""
end_chars = '...: '
space_count = len(prompt.lstrip('\n')) - len(end_chars)
body = ' ' * space_count + end_chars
return '... |
Set the style sheets of the underlying widgets. | def _style_sheet_changed(self):
""" Set the style sheets of the underlying widgets.
"""
self.setStyleSheet(self.style_sheet)
if self._control is not None:
self._control.document().setDefaultStyleSheet(self.style_sheet)
bg_color = self._control.palette().window().c... |
Set the style for the syntax highlighter. | def _syntax_style_changed(self):
""" Set the style for the syntax highlighter.
"""
if self._highlighter is None:
# ignore premature calls
return
if self.syntax_style:
self._highlighter.set_style(self.syntax_style)
else:
self._highli... |
Async co - routine to perform requests to a CloudStackAPI. The parameters needs to include the command string which refers to the API to be called. In principle any available and future CloudStack API can be called. The ** kwargs magic allows us to all add supported parameters to the given API call. A list of all avail... | async def request(self, command: str, **kwargs) -> dict:
"""
Async co-routine to perform requests to a CloudStackAPI. The parameters needs to include the command string,
which refers to the API to be called. In principle any available and future CloudStack API can be called. The
`**kwarg... |
Handles the response returned from the CloudStack API. Some CloudStack API are implemented asynchronous which means that the API call returns just a job id. The actually expected API response is postponed and a specific asyncJobResults API has to be polled using the job id to get the final result once the API call has ... | async def _handle_response(self, response: aiohttp.client_reqrep.ClientResponse, await_final_result: bool) -> dict:
"""
Handles the response returned from the CloudStack API. Some CloudStack API are implemented asynchronous, which
means that the API call returns just a job id. The actually expec... |
According to the CloudStack documentation each request needs to be signed in order to authenticate the user account executing the API command. The signature is generated using a combination of the api secret and a SHA - 1 hash of the url parameters including the command string. In order to generate a unique identifier ... | def _sign(self, url_parameters: dict) -> dict:
"""
According to the CloudStack documentation, each request needs to be signed in order to authenticate the user
account executing the API command. The signature is generated using a combination of the api secret and a SHA-1
hash of the url ... |
Each CloudStack API call returns a nested dictionary structure. The first level contains only one key indicating the API that originated the response. This function removes that first level from the data returned to the caller. | def _transform_data(data: dict) -> dict:
"""
Each CloudStack API call returns a nested dictionary structure. The first level contains only one key indicating
the API that originated the response. This function removes that first level from the data returned to the
caller.
:param... |
System virtual memory as a namedutple. | def virtual_memory():
"""System virtual memory as a namedutple."""
mem = _psutil_bsd.get_virtual_mem()
total, free, active, inactive, wired, cached, buffers, shared = mem
avail = inactive + cached + free
used = active + wired + cached
percent = usage_percent((total - avail), total, _round=1)
... |
System swap memory as ( total used free sin sout ) namedtuple. | def swap_memory():
"""System swap memory as (total, used, free, sin, sout) namedtuple."""
total, used, free, sin, sout = \
[x * _PAGESIZE for x in _psutil_bsd.get_swap_mem()]
percent = usage_percent(used, total, _round=1)
return nt_swapmeminfo(total, used, free, percent, sin, sout) |
Return system per - CPU times as a named tuple | def get_system_cpu_times():
"""Return system per-CPU times as a named tuple"""
user, nice, system, idle, irq = _psutil_bsd.get_system_cpu_times()
return _cputimes_ntuple(user, nice, system, idle, irq) |
Return system CPU times as a named tuple | def get_system_per_cpu_times():
"""Return system CPU times as a named tuple"""
ret = []
for cpu_t in _psutil_bsd.get_system_per_cpu_times():
user, nice, system, idle, irq = cpu_t
item = _cputimes_ntuple(user, nice, system, idle, irq)
ret.append(item)
return ret |
Return real effective and saved user ids. | def get_process_uids(self):
"""Return real, effective and saved user ids."""
real, effective, saved = _psutil_bsd.get_process_uids(self.pid)
return nt_uids(real, effective, saved) |
Return real effective and saved group ids. | def get_process_gids(self):
"""Return real, effective and saved group ids."""
real, effective, saved = _psutil_bsd.get_process_gids(self.pid)
return nt_gids(real, effective, saved) |
return a tuple containing process user/ kernel time. | def get_cpu_times(self):
"""return a tuple containing process user/kernel time."""
user, system = _psutil_bsd.get_process_cpu_times(self.pid)
return nt_cputimes(user, system) |
Return a tuple with the process RSS and VMS size. | def get_memory_info(self):
"""Return a tuple with the process' RSS and VMS size."""
rss, vms = _psutil_bsd.get_process_memory_info(self.pid)[:2]
return nt_meminfo(rss, vms) |
Return the number of threads belonging to the process. | def get_process_threads(self):
"""Return the number of threads belonging to the process."""
rawlist = _psutil_bsd.get_process_threads(self.pid)
retlist = []
for thread_id, utime, stime in rawlist:
ntuple = nt_thread(thread_id, utime, stime)
retlist.append(ntuple)
... |
Return files opened by process as a list of namedtuples. | def get_open_files(self):
"""Return files opened by process as a list of namedtuples."""
# XXX - C implementation available on FreeBSD >= 8 only
# else fallback on lsof parser
if hasattr(_psutil_bsd, "get_process_open_files"):
rawlist = _psutil_bsd.get_process_open_files(self... |
Return the path to the connection file of an app Parameters ---------- app: KernelApp instance [ optional ] If unspecified the currently running app will be used | def get_connection_file(app=None):
"""Return the path to the connection file of an app
Parameters
----------
app : KernelApp instance [optional]
If unspecified, the currently running app will be used
"""
if app is None:
from IPython.zmq.ipkernel import IPKernelApp
if... |
find a connection file and return its absolute path. The current working directory and the profile s security directory will be searched for the file if it is not given by absolute path. If profile is unspecified then the current running application s profile will be used or default if not run from IPython. If the argu... | def find_connection_file(filename, profile=None):
"""find a connection file, and return its absolute path.
The current working directory and the profile's security
directory will be searched for the file if it is not given by
absolute path.
If profile is unspecified, then the current runni... |
Return the connection information for the current Kernel. Parameters ---------- connection_file: str [ optional ] The connection file to be used. Can be given by absolute path or IPython will search in the security directory of a given profile. If run from IPython If unspecified the connection file for the currently ru... | def get_connection_info(connection_file=None, unpack=False, profile=None):
"""Return the connection information for the current Kernel.
Parameters
----------
connection_file : str [optional]
The connection file to be used. Can be given by absolute path, or
IPython will search in the... |
Connect a qtconsole to the current kernel. This is useful for connecting a second qtconsole to a kernel or to a local notebook. Parameters ---------- connection_file: str [ optional ] The connection file to be used. Can be given by absolute path or IPython will search in the security directory of a given profile. If ru... | def connect_qtconsole(connection_file=None, argv=None, profile=None):
"""Connect a qtconsole to the current kernel.
This is useful for connecting a second qtconsole to a kernel, or to a
local notebook.
Parameters
----------
connection_file : str [optional]
The connection file t... |
tunnel connections to a kernel via ssh This will open four SSH tunnels from localhost on this machine to the ports associated with the kernel. They can be either direct localhost - localhost tunnels or if an intermediate server is necessary the kernel must be listening on a public IP. Parameters ---------- connection_i... | def tunnel_to_kernel(connection_info, sshserver, sshkey=None):
"""tunnel connections to a kernel via ssh
This will open four SSH tunnels from localhost on this machine to the
ports associated with the kernel. They can be either direct
localhost-localhost tunnels, or if an intermediate server is ne... |
strip frontend - specific aliases and flags from an argument list For use primarily in frontend apps that want to pass a subset of command - line arguments through to a subprocess where frontend - specific flags and aliases should be removed from the list. Parameters ---------- argv: list ( str ) The starting argv to b... | def swallow_argv(argv, aliases=None, flags=None):
"""strip frontend-specific aliases and flags from an argument list
For use primarily in frontend apps that want to pass a subset of command-line
arguments through to a subprocess, where frontend-specific flags and aliases
should be removed from the ... |
Get short form of commit hash given directory pkg_path | def pkg_commit_hash(pkg_path):
"""Get short form of commit hash given directory `pkg_path`
We get the commit hash from (in order of preference):
* IPython.utils._sysinfo.commit
* git output, if we are in a git repository
If these fail, we return a not-found placeholder tuple
Parameters
-... |
Return dict describing the context of this package | def pkg_info(pkg_path):
"""Return dict describing the context of this package
Parameters
----------
pkg_path : str
path containing __init__.py for package
Returns
-------
context : dict
with named parameters of interest
"""
src, hsh = pkg_commit_hash(pkg_path)
ret... |
Return useful information about IPython and the system as a string. | def sys_info():
"""Return useful information about IPython and the system, as a string.
Example
-------
In [2]: print sys_info()
{'commit_hash': '144fdae', # random
'commit_source': 'repository',
'ipython_path': '/home/fperez/usr/lib/python2.6/site-packages/IPython',
'ipython_ve... |
Return the number of active CPUs on a Darwin system. | def _num_cpus_darwin():
"""Return the number of active CPUs on a Darwin system."""
p = subprocess.Popen(['sysctl','-n','hw.ncpu'],stdout=subprocess.PIPE)
return p.stdout.read() |
Return the effective number of CPUs in the system as an integer. | def num_cpus():
"""Return the effective number of CPUs in the system as an integer.
This cross-platform function makes an attempt at finding the total number of
available CPUs in the system, as returned by various underlying system and
python calls.
If it can't find a sensible answer, it returns 1 (tho... |
[ 1 2 3 4 ] { accumulate: <built - in function max > } | def handle(self, integers, **options):
"""
[1, 2, 3, 4] {'accumulate': <built-in function max>}
"""
print integers, options
return super(Command, self).handle(integers, **options) |
Advance to the next result set. | def nextset(self):
"""Advance to the next result set.
Returns None if there are no more result sets.
"""
if self._executed:
self.fetchall()
del self.messages[:]
db = self._get_db()
nr = db.next_result()
if nr == -1:
return... |
Execute a query. query -- string query to execute on server args -- optional sequence or mapping parameters to use with query. | def execute(self, query, args=None):
"""Execute a query.
query -- string, query to execute on server
args -- optional sequence or mapping, parameters to use with query.
Note: If args is a sequence, then %s must be used as the
parameter placeholder in the query. If a ma... |
Execute a multi - row query. query -- string query to execute on server | def executemany(self, query, args):
"""Execute a multi-row query.
query -- string, query to execute on server
args
Sequence of sequences or mappings, parameters to use with
query.
Returns long integer rows affected, if any.
... |
Execute stored procedure procname with args procname -- string name of procedure to execute on server | def callproc(self, procname, args=()):
"""Execute stored procedure procname with args
procname -- string, name of procedure to execute on server
args -- Sequence of parameters to use with procedure
Returns the original args.
Compatibility warning: PEP-249 specifies t... |
Fetches a single row from the cursor. | def fetchone(self):
"""Fetches a single row from the cursor."""
self._check_executed()
r = self._fetch_row(1)
if not r:
self._warning_check()
return None
self.rownumber = self.rownumber + 1
return r[0] |
Fetch up to size rows from the cursor. Result set may be smaller than size. If size is not defined cursor. arraysize is used. | def fetchmany(self, size=None):
"""Fetch up to size rows from the cursor. Result set may be smaller
than size. If size is not defined, cursor.arraysize is used."""
self._check_executed()
r = self._fetch_row(size or self.arraysize)
self.rownumber = self.rownumber + len(r)
... |
Fetchs all available rows from the cursor. | def fetchall(self):
"""Fetchs all available rows from the cursor."""
self._check_executed()
r = self._fetch_row(0)
self.rownumber = self.rownumber + len(r)
self._warning_check()
return r |
Fetch several rows as a list of dictionaries. Deprecated: Use fetchmany () instead. Will be removed in 1. 3. | def fetchmanyDict(self, size=None):
"""Fetch several rows as a list of dictionaries. Deprecated:
Use fetchmany() instead. Will be removed in 1.3."""
from warnings import warn
warn("fetchmanyDict() is non-standard and will be removed in 1.3",
DeprecationWarning, 2)
re... |
this function will be called on the engines | def connect(com, peers, tree, pub_url, root_id):
"""this function will be called on the engines"""
com.connect(peers, tree, pub_url, root_id) |
Parse a string into a ( nbformat dict ) tuple. | def parse_json(s, **kwargs):
"""Parse a string into a (nbformat, dict) tuple."""
d = json.loads(s, **kwargs)
nbf = d.get('nbformat', 1)
nbm = d.get('nbformat_minor', 0)
return nbf, nbm, d |
Parse a string into a ( nbformat string ) tuple. | def parse_py(s, **kwargs):
"""Parse a string into a (nbformat, string) tuple."""
nbf = current_nbformat
nbm = current_nbformat_minor
pattern = r'# <nbformat>(?P<nbformat>\d+[\.\d+]*)</nbformat>'
m = re.search(pattern,s)
if m is not None:
digits = m.group('nbformat').split('.')
... |
Read a JSON notebook from a string and return the NotebookNode object. | def reads_json(s, **kwargs):
"""Read a JSON notebook from a string and return the NotebookNode object."""
nbf, minor, d = parse_json(s, **kwargs)
if nbf == 1:
nb = v1.to_notebook_json(d, **kwargs)
nb = v3.convert_to_this_nbformat(nb, orig_version=1)
elif nbf == 2:
nb = v2.to_note... |
Read a. py notebook from a string and return the NotebookNode object. | def reads_py(s, **kwargs):
"""Read a .py notebook from a string and return the NotebookNode object."""
nbf, nbm, s = parse_py(s, **kwargs)
if nbf == 2:
nb = v2.to_notebook_py(s, **kwargs)
elif nbf == 3:
nb = v3.to_notebook_py(s, **kwargs)
else:
raise NBFormatError('Unsupporte... |
Read a notebook from a string and return the NotebookNode object. | def reads(s, format, **kwargs):
"""Read a notebook from a string and return the NotebookNode object.
This function properly handles notebooks of any version. The notebook
returned will always be in the current version's format.
Parameters
----------
s : unicode
The raw unicode string t... |
Write a notebook to a string in a given format in the current nbformat version. | def writes(nb, format, **kwargs):
"""Write a notebook to a string in a given format in the current nbformat version.
This function always writes the notebook in the current nbformat version.
Parameters
----------
nb : NotebookNode
The notebook to write.
format : (u'json', u'ipynb', u'p... |
Write a notebook to a file in a given format in the current nbformat version. | def write(nb, fp, format, **kwargs):
"""Write a notebook to a file in a given format in the current nbformat version.
This function always writes the notebook in the current nbformat version.
Parameters
----------
nb : NotebookNode
The notebook to write.
fp : file
Any file-like... |
Convert to a notebook having notebook metadata. | def _convert_to_metadata():
"""Convert to a notebook having notebook metadata."""
import glob
for fname in glob.glob('*.ipynb'):
print('Converting file:',fname)
with open(fname,'r') as f:
nb = read(f,u'json')
md = new_metadata()
if u'name' in nb:
md.na... |
try load value from dict. if key is not exists mark as state unset. | def load_from_dict(self, src: dict, key):
'''
try load value from dict.
if key is not exists, mark as state unset.
'''
if key in src:
self.value = src[key]
else:
self.reset() |
Run the pyglet event loop by processing pending events only. | def inputhook_pyglet():
"""Run the pyglet event loop by processing pending events only.
This keeps processing pending events until stdin is ready. After
processing all pending events, a call to time.sleep is inserted. This is
needed, otherwise, CPU usage is at 100%. This sleep time should be tuned
... |
Does the name match my requirements? | def matches(self, name):
"""Does the name match my requirements?
To match, a name must match config.testMatch OR config.include
and it must not match config.exclude
"""
return ((self.match.search(name)
or (self.include and
filter(None,
... |
Is the class a wanted test class? | def wantClass(self, cls):
"""Is the class a wanted test class?
A class must be a unittest.TestCase subclass, or match test name
requirements. Classes that start with _ are always excluded.
"""
declared = getattr(cls, '__test__', None)
if declared is not None:
... |
Is the directory a wanted test directory? | def wantDirectory(self, dirname):
"""Is the directory a wanted test directory?
All package directories match, so long as they do not match exclude.
All other directories must match test requirements.
"""
tail = op_basename(dirname)
if ispackage(dirname):
wan... |
Is the file a wanted test file? | def wantFile(self, file):
"""Is the file a wanted test file?
The file must be a python source file and match testMatch or
include, and not match exclude. Files that match ignore are *never*
wanted, regardless of plugin, testMatch, include or exclude settings.
"""
# never... |
Is the function a test function? | def wantFunction(self, function):
"""Is the function a test function?
"""
try:
if hasattr(function, 'compat_func_name'):
funcname = function.compat_func_name
else:
funcname = function.__name__
except AttributeError:
# no... |
Is the method a test method? | def wantMethod(self, method):
"""Is the method a test method?
"""
try:
method_name = method.__name__
except AttributeError:
# not a method
return False
if method_name.startswith('_'):
# never collect 'private' methods
re... |
Is the module a test module? | def wantModule(self, module):
"""Is the module a test module?
The tail of the module name must match test requirements. One exception:
we always want __main__.
"""
declared = getattr(module, '__test__', None)
if declared is not None:
wanted = declared
... |
Make new_fn have old_fn s doc string. This is particularly useful for the do_... commands that hook into the help system. Adapted from from a comp. lang. python posting by Duncan Booth. | def decorate_fn_with_doc(new_fn, old_fn, additional_text=""):
"""Make new_fn have old_fn's doc string. This is particularly useful
for the do_... commands that hook into the help system.
Adapted from from a comp.lang.python posting
by Duncan Booth."""
def wrapper(*args, **kw):
return new_fn(... |
Return the contents of a named file as a list of lines. | def _file_lines(fname):
"""Return the contents of a named file as a list of lines.
This function never raises an IOError exception: if the file can't be
read, it simply returns an empty list."""
try:
outfile = open(fname)
except IOError:
return []
else:
out = outfile.re... |
List command to use if we have a newer pydb installed | def list_command_pydb(self, arg):
"""List command to use if we have a newer pydb installed"""
filename, first, last = OldPdb.parse_list_cmd(self, arg)
if filename is not None:
self.print_list_lines(filename, first, last) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.