_id
stringlengths 2
7
| title
stringlengths 1
88
| partition
stringclasses 3
values | text
stringlengths 31
13.1k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q280600
|
coverage._source_for_file
|
test
|
def _source_for_file(self, filename):
"""Return the source file for `filename`."""
if not filename.endswith(".py"):
if filename[-4:-1] == ".py":
filename = filename[:-1]
|
python
|
{
"resource": ""
}
|
q280601
|
coverage._should_trace_with_reason
|
test
|
def _should_trace_with_reason(self, filename, frame):
"""Decide whether to trace execution in `filename`, with a reason.
This function is called from the trace function. As each new file name
is encountered, this function determines whether it is traced or not.
Returns a pair of values: the first indicates whether the file should
be traced: it's a canonicalized filename if it should be traced, None
if it should not. The second value is a string, the resason for the
decision.
"""
if not filename:
# Empty string is pretty useless
return None, "empty string isn't a filename"
if filename.startswith('<'):
# Lots of non-file execution is represented with artificial
# filenames like "<string>", "<doctest readme.txt[0]>", or
# "<exec_function>". Don't ever trace these executions, since we
# can't do anything with the data later anyway.
return None, "not a real filename"
self._check_for_packages()
# Compiled Python files have two filenames: frame.f_code.co_filename is
# the filename at the time the .pyc was compiled. The second name is
# __file__, which is where the .pyc was actually loaded from. Since
#
|
python
|
{
"resource": ""
}
|
q280602
|
coverage._should_trace
|
test
|
def _should_trace(self, filename, frame):
"""Decide whether to trace execution in `filename`.
Calls `_should_trace_with_reason`, and returns just the decision.
"""
canonical, reason = self._should_trace_with_reason(filename, frame)
if self.debug.should('trace'):
if not canonical:
|
python
|
{
"resource": ""
}
|
q280603
|
coverage._warn
|
test
|
def _warn(self, msg):
"""Use `msg` as a warning."""
|
python
|
{
"resource": ""
}
|
q280604
|
coverage._check_for_packages
|
test
|
def _check_for_packages(self):
"""Update the source_match matcher with latest imported packages."""
# Our self.source_pkgs attribute is a list of package names we want to
# measure. Each time through here, we see if we've imported any of
# them yet. If so, we add its file to source_match, and we don't have
# to look for that package any more.
if self.source_pkgs:
found = []
for pkg in self.source_pkgs:
try:
mod = sys.modules[pkg]
except KeyError:
continue
found.append(pkg)
try:
pkg_file = mod.__file__
except AttributeError:
pkg_file = None
else:
d, f = os.path.split(pkg_file)
if f.startswith('__init__'):
|
python
|
{
"resource": ""
}
|
q280605
|
coverage.start
|
test
|
def start(self):
"""Start measuring code coverage.
Coverage measurement actually occurs in functions called after `start`
is invoked. Statements in the same scope as `start` won't be measured.
Once you invoke `start`, you must also call `stop` eventually, or your
process might not shut down cleanly.
"""
if self.run_suffix:
# Calling start() means we're running code, so use the run_suffix
# as the data_suffix when we eventually save the data.
self.data_suffix = self.run_suffix
if self.auto_data:
self.load()
# Create the matchers we need for _should_trace
if self.source or self.source_pkgs:
self.source_match = TreeMatcher(self.source)
else:
if self.cover_dir:
self.cover_match = TreeMatcher([self.cover_dir])
if self.pylib_dirs:
self.pylib_match = TreeMatcher(self.pylib_dirs)
if self.include:
self.include_match = FnmatchMatcher(self.include)
if self.omit:
|
python
|
{
"resource": ""
}
|
q280606
|
coverage._atexit
|
test
|
def _atexit(self):
"""Clean up on process shutdown."""
if self._started:
|
python
|
{
"resource": ""
}
|
q280607
|
coverage.exclude
|
test
|
def exclude(self, regex, which='exclude'):
"""Exclude source lines from execution consideration.
A number of lists of regular expressions are maintained. Each list
selects lines that are treated differently during reporting.
`which` determines which list is modified. The "exclude" list selects
|
python
|
{
"resource": ""
}
|
q280608
|
coverage._exclude_regex
|
test
|
def _exclude_regex(self, which):
"""Return a compiled regex for the given exclusion list."""
if which not in self._exclude_re:
excl_list = getattr(self.config, which
|
python
|
{
"resource": ""
}
|
q280609
|
coverage.save
|
test
|
def save(self):
"""Save the collected coverage data to the data file."""
data_suffix = self.data_suffix
if data_suffix is True:
# If data_suffix was a simple true value, then make a suffix with
# plenty of distinguishing information. We do this here in
# `save()` at the last minute so that the pid will be correct even
# if the process forks.
extra = ""
if _TEST_NAME_FILE:
f = open(_TEST_NAME_FILE)
|
python
|
{
"resource": ""
}
|
q280610
|
coverage.combine
|
test
|
def combine(self):
"""Combine together a number of similarly-named coverage data files.
All coverage data files whose name starts with `data_file` (from the
coverage() constructor) will be read, and combined together into the
|
python
|
{
"resource": ""
}
|
q280611
|
coverage._harvest_data
|
test
|
def _harvest_data(self):
"""Get the collected data and reset the collector.
Also warn about various problems collecting data.
"""
if not self._measured:
return
self.data.add_line_data(self.collector.get_line_data())
self.data.add_arc_data(self.collector.get_arc_data())
self.collector.reset()
# If there are still entries in the source_pkgs list, then we never
# encountered those packages.
if self._warn_unimported_source:
|
python
|
{
"resource": ""
}
|
q280612
|
coverage.analysis
|
test
|
def analysis(self, morf):
"""Like `analysis2` but doesn't return excluded
|
python
|
{
"resource": ""
}
|
q280613
|
coverage.analysis2
|
test
|
def analysis2(self, morf):
"""Analyze a module.
`morf` is a module or a filename. It will be analyzed to determine
its coverage statistics. The return value is a 5-tuple:
* The filename for the module.
* A list of line numbers of executable statements.
* A list of line numbers of excluded statements.
* A list of line numbers of statements not run (missing from
execution).
* A readable formatted string of the missing line numbers.
The analysis uses the source file itself and the current measured
|
python
|
{
"resource": ""
}
|
q280614
|
coverage._analyze
|
test
|
def _analyze(self, it):
"""Analyze a single morf or code unit.
Returns an `Analysis` object.
|
python
|
{
"resource": ""
}
|
q280615
|
coverage.report
|
test
|
def report(self, morfs=None, show_missing=True, ignore_errors=None,
file=None, # pylint: disable=W0622
omit=None, include=None
):
"""Write a summary report to `file`.
Each module in `morfs` is listed, with counts of statements, executed
statements, missing statements, and a list of lines missed.
`include` is a list of filename patterns. Modules whose filenames
match those patterns will be included in the report. Modules matching
`omit` will not be included in the report.
Returns a float, the total percentage covered.
|
python
|
{
"resource": ""
}
|
q280616
|
coverage.annotate
|
test
|
def annotate(self, morfs=None, directory=None, ignore_errors=None,
omit=None, include=None):
"""Annotate a list of modules.
Each module in `morfs` is annotated. The source is written to a new
file, named with a ",cover" suffix, with each line prefixed with a
|
python
|
{
"resource": ""
}
|
q280617
|
coverage.html_report
|
test
|
def html_report(self, morfs=None, directory=None, ignore_errors=None,
omit=None, include=None, extra_css=None, title=None):
"""Generate an HTML report.
The HTML is written to `directory`. The file "index.html" is the
overview starting point, with links to more detailed pages for
individual modules.
`extra_css` is a path to a file of other CSS to apply on the page.
It will be copied into the HTML directory.
`title` is a text string (not HTML) to use as the title of the HTML
report.
See `coverage.report()` for other arguments.
|
python
|
{
"resource": ""
}
|
q280618
|
coverage.xml_report
|
test
|
def xml_report(self, morfs=None, outfile=None, ignore_errors=None,
omit=None, include=None):
"""Generate an XML report of coverage results.
The report is compatible with Cobertura reports.
Each module in `morfs` is included in the report. `outfile` is the
path to write the file to, "-" will write to stdout.
See `coverage.report()` for other arguments.
Returns a float, the total percentage covered.
"""
self._harvest_data()
self.config.from_args(
ignore_errors=ignore_errors, omit=omit, include=include,
xml_output=outfile,
)
file_to_close = None
delete_file = False
if self.config.xml_output:
if self.config.xml_output == '-':
outfile = sys.stdout
else:
outfile = open(self.config.xml_output, "w")
|
python
|
{
"resource": ""
}
|
q280619
|
display
|
test
|
def display(*objs, **kwargs):
"""Display a Python object in all frontends.
By default all representations will be computed and sent to the frontends.
Frontends can decide which representation is used and how.
Parameters
----------
objs : tuple of objects
The Python objects to display.
include : list or tuple, optional
A list of format type strings (MIME types) to include in the
format data dict. If this is set *only* the format types included
in this list will be computed.
exclude : list or tuple, optional
A list of format type string (MIME types) to exclue in the format
data dict. If this is set all format types will be computed,
|
python
|
{
"resource": ""
}
|
q280620
|
display_html
|
test
|
def display_html(*objs, **kwargs):
"""Display the HTML representation of an object.
Parameters
----------
objs : tuple of objects
The Python objects to display, or if raw=True raw HTML data to
display.
raw : bool
Are the data objects raw data or Python objects that need to be
|
python
|
{
"resource": ""
}
|
q280621
|
display_svg
|
test
|
def display_svg(*objs, **kwargs):
"""Display the SVG representation of an object.
Parameters
----------
objs : tuple of objects
The Python objects to display, or if raw=True raw svg data to
display.
raw : bool
Are the data objects raw data or Python objects that need to be
|
python
|
{
"resource": ""
}
|
q280622
|
display_png
|
test
|
def display_png(*objs, **kwargs):
"""Display the PNG representation of an object.
Parameters
----------
objs : tuple of objects
The Python objects to display, or if raw=True raw png data to
display.
raw : bool
Are the data objects raw data or Python objects that need to be
|
python
|
{
"resource": ""
}
|
q280623
|
display_jpeg
|
test
|
def display_jpeg(*objs, **kwargs):
"""Display the JPEG representation of an object.
Parameters
----------
objs : tuple of objects
The Python objects to display, or if raw=True raw JPEG data to
display.
raw : bool
Are the data objects raw data or Python objects that need to be
|
python
|
{
"resource": ""
}
|
q280624
|
display_latex
|
test
|
def display_latex(*objs, **kwargs):
"""Display the LaTeX representation of an object.
Parameters
----------
objs : tuple of objects
The Python objects to display, or if raw=True raw latex data to
display.
raw : bool
Are the data objects raw data or Python objects that need to be
|
python
|
{
"resource": ""
}
|
q280625
|
display_json
|
test
|
def display_json(*objs, **kwargs):
"""Display the JSON representation of an object.
Note that not many frontends support displaying JSON.
Parameters
----------
objs : tuple of objects
The Python objects to display, or if raw=True raw json data to
display.
raw : bool
Are the data objects raw data
|
python
|
{
"resource": ""
}
|
q280626
|
display_javascript
|
test
|
def display_javascript(*objs, **kwargs):
"""Display the Javascript representation of an object.
Parameters
----------
objs : tuple of objects
The Python objects to display, or if raw=True raw javascript data to
display.
raw : bool
Are the data objects raw data or Python objects that need to
|
python
|
{
"resource": ""
}
|
q280627
|
DisplayObject.reload
|
test
|
def reload(self):
"""Reload the raw data from file or URL."""
if self.filename is not None:
with open(self.filename, self._read_flags) as f:
self.data = f.read()
elif self.url is not None:
try:
import urllib2
response = urllib2.urlopen(self.url)
self.data = response.read()
|
python
|
{
"resource": ""
}
|
q280628
|
_find_cmd
|
test
|
def _find_cmd(cmd):
"""Find the full path to a command using which."""
path = sp.Popen(['/usr/bin/env', 'which', cmd],
|
python
|
{
"resource": ""
}
|
q280629
|
ProcessHandler.system
|
test
|
def system(self, cmd):
"""Execute a command in a subshell.
Parameters
----------
cmd : str
A command to be executed in the system shell.
Returns
-------
int : child's exitstatus
"""
# Get likely encoding for the output.
enc = DEFAULT_ENCODING
# Patterns to match on the output, for pexpect. We read input and
# allow either a short timeout or EOF
patterns = [pexpect.TIMEOUT, pexpect.EOF]
# the index of the EOF pattern in the list.
# even though we know it's 1, this call means we don't have to worry if
# we change the above list, and forget to change this value:
EOF_index = patterns.index(pexpect.EOF)
# The size of the output stored so far in the process output buffer.
# Since pexpect only appends to this buffer, each time we print we
# record how far we've printed, so that next time we only print *new*
# content from the buffer.
out_size = 0
try:
# Since we're not really searching the buffer for text patterns, we
# can set pexpect's search window to be tiny and it won't matter.
# We only search for the 'patterns' timeout or EOF, which aren't in
# the text itself.
#child = pexpect.spawn(pcmd, searchwindowsize=1)
if hasattr(pexpect, 'spawnb'):
child = pexpect.spawnb(self.sh, args=['-c', cmd]) # Pexpect-U
else:
child = pexpect.spawn(self.sh, args=['-c', cmd]) # Vanilla Pexpect
flush = sys.stdout.flush
while True:
# res is the index of the pattern that caused the match, so we
# know whether we've finished (if we matched EOF) or not
res_idx = child.expect_list(patterns, self.read_timeout)
print(child.before[out_size:].decode(enc, 'replace'), end='')
flush()
if res_idx==EOF_index:
|
python
|
{
"resource": ""
}
|
q280630
|
forward_read_events
|
test
|
def forward_read_events(fd, context=None):
"""Forward read events from an FD over a socket.
This method wraps a file in a socket pair, so it can
be polled for read events by select (specifically zmq.eventloop.ioloop)
"""
if context is None:
context = zmq.Context.instance()
push = context.socket(zmq.PUSH)
push.setsockopt(zmq.LINGER,
|
python
|
{
"resource": ""
}
|
q280631
|
ForwarderThread.run
|
test
|
def run(self):
"""Loop through lines in self.fd, and send them over self.sock."""
line = self.fd.readline()
# allow for files opened in unicode mode
if isinstance(line, unicode):
send = self.sock.send_unicode
else:
|
python
|
{
"resource": ""
}
|
q280632
|
find_launcher_class
|
test
|
def find_launcher_class(clsname, kind):
"""Return a launcher for a given clsname and kind.
Parameters
==========
clsname : str
The full name of the launcher class, either with or without the
module path, or an abbreviation (MPI, SSH, SGE, PBS, LSF,
WindowsHPC).
kind : str
Either 'EngineSet' or 'Controller'.
"""
if '.' not in clsname:
# not a module, presume it's the raw name in apps.launcher
if kind and kind not in clsname:
|
python
|
{
"resource": ""
}
|
q280633
|
IPClusterStop.start
|
test
|
def start(self):
"""Start the app for the stop subcommand."""
try:
pid = self.get_pid_from_file()
except PIDFileError:
self.log.critical(
'Could not read pid file, cluster is probably not running.'
)
# Here I exit with a unusual exit status that other processes
# can watch for to learn how I existed.
self.remove_pid_file()
self.exit(ALREADY_STOPPED)
if not self.check_pid(pid):
self.log.critical(
'Cluster [pid=%r] is not running.' % pid
)
self.remove_pid_file()
# Here I exit with a unusual exit status that other processes
# can watch for to learn how I existed.
self.exit(ALREADY_STOPPED)
elif os.name=='posix':
sig = self.signal
self.log.info(
"Stopping cluster [pid=%r] with [signal=%r]" % (pid, sig)
)
|
python
|
{
"resource": ""
}
|
q280634
|
IPClusterEngines.build_launcher
|
test
|
def build_launcher(self, clsname, kind=None):
"""import and instantiate a Launcher based on importstring"""
try:
klass = find_launcher_class(clsname, kind)
except (ImportError, KeyError):
self.log.fatal("Could not import launcher class: %r"%clsname)
self.exit(1)
|
python
|
{
"resource": ""
}
|
q280635
|
IPClusterEngines.start
|
test
|
def start(self):
"""Start the app for the engines subcommand."""
self.log.info("IPython cluster: started")
# First see if the cluster is already running
# Now log and daemonize
self.log.info(
'Starting engines with [daemon=%r]' % self.daemonize
)
# TODO: Get daemonize working on Windows or as a Windows Server.
if self.daemonize:
if os.name=='posix':
daemonize()
dc = ioloop.DelayedCallback(self.start_engines, 0, self.loop)
dc.start()
|
python
|
{
"resource": ""
}
|
q280636
|
IPClusterStart.start
|
test
|
def start(self):
"""Start the app for the start subcommand."""
# First see if the cluster is already running
try:
pid = self.get_pid_from_file()
except PIDFileError:
pass
else:
if self.check_pid(pid):
self.log.critical(
'Cluster is already running with [pid=%s]. '
'use "ipcluster stop" to stop the cluster.' % pid
)
# Here I exit with a unusual exit status that other processes
# can watch for to learn how I existed.
self.exit(ALREADY_STARTED)
else:
self.remove_pid_file()
# Now log and daemonize
self.log.info(
'Starting ipcluster with [daemon=%r]' % self.daemonize
)
# TODO: Get daemonize working on Windows or as a Windows Server.
if self.daemonize:
if os.name=='posix':
daemonize()
|
python
|
{
"resource": ""
}
|
q280637
|
get_app_wx
|
test
|
def get_app_wx(*args, **kwargs):
"""Create a new wx app or return an exiting one."""
import wx
app = wx.GetApp()
|
python
|
{
"resource": ""
}
|
q280638
|
is_event_loop_running_wx
|
test
|
def is_event_loop_running_wx(app=None):
"""Is the wx event loop running."""
if app is None:
app = get_app_wx()
if hasattr(app, '_in_event_loop'):
|
python
|
{
"resource": ""
}
|
q280639
|
start_event_loop_wx
|
test
|
def start_event_loop_wx(app=None):
"""Start the wx event loop in a consistent manner."""
if app is None:
app = get_app_wx()
if not is_event_loop_running_wx(app):
app._in_event_loop =
|
python
|
{
"resource": ""
}
|
q280640
|
get_app_qt4
|
test
|
def get_app_qt4(*args, **kwargs):
"""Create a new qt4 app or return an existing one."""
from IPython.external.qt_for_kernel import QtGui
app = QtGui.QApplication.instance()
if app is None:
|
python
|
{
"resource": ""
}
|
q280641
|
is_event_loop_running_qt4
|
test
|
def is_event_loop_running_qt4(app=None):
"""Is the qt4 event loop running."""
if app is None:
app = get_app_qt4([''])
|
python
|
{
"resource": ""
}
|
q280642
|
start_event_loop_qt4
|
test
|
def start_event_loop_qt4(app=None):
"""Start the qt4 event loop in a consistent manner."""
if app is None:
app = get_app_qt4([''])
if not is_event_loop_running_qt4(app):
app._in_event_loop =
|
python
|
{
"resource": ""
}
|
q280643
|
Canvas.blank_canvas
|
test
|
def blank_canvas(width, height):
"""Return a blank canvas to annotate.
:param width: xdim (int)
:param height: ydim (int)
:returns: :class:`jicbioimage.illustrate.Canvas`
|
python
|
{
"resource": ""
}
|
q280644
|
Canvas.draw_cross
|
test
|
def draw_cross(self, position, color=(255, 0, 0), radius=4):
"""Draw a cross on the canvas.
:param position: (row, col) tuple
:param color: RGB tuple
:param radius: radius of the cross (int)
"""
y, x = position
for xmod in np.arange(-radius, radius+1, 1):
xpos = x + xmod
if xpos < 0:
continue # Negative indices will draw on the opposite side.
if xpos >= self.shape[1]:
continue # Out of bounds.
|
python
|
{
"resource": ""
}
|
q280645
|
Canvas.draw_line
|
test
|
def draw_line(self, pos1, pos2, color=(255, 0, 0)):
"""Draw a line between pos1 and pos2 on the canvas.
:param pos1: position 1 (row, col) tuple
:param pos2: position 2 (row, col) tuple
:param color: RGB tuple
"""
r1, c1
|
python
|
{
"resource": ""
}
|
q280646
|
Canvas.text_at
|
test
|
def text_at(self, text, position, color=(255, 255, 255),
size=12, antialias=False, center=False):
"""Write text at x, y top left corner position.
By default the x and y coordinates represent the top left hand corner
of the text. The text can be centered vertically and horizontally by
using setting the ``center`` option to ``True``.
:param text: text to write
:param position: (row, col) tuple
:param color: RGB tuple
:param size: font size
:param antialias: whether or not the text should be antialiased
:param center: whether or not the text should be centered on the
input coordinate
"""
def antialias_value(value, normalisation):
return int(round(value * normalisation))
def antialias_rgb(color, normalisation):
return tuple([antialias_value(v, normalisation) for v in color])
def set_color(xpos, ypos, color):
try:
self[ypos, xpos] = color
except IndexError:
pass
y, x = position
|
python
|
{
"resource": ""
}
|
q280647
|
AnnotatedImage.from_grayscale
|
test
|
def from_grayscale(im, channels_on=(True, True, True)):
"""Return a canvas from a grayscale image.
:param im: single channel image
:channels_on: channels to populate with input image
:returns: :class:`jicbioimage.illustrate.Canvas`
"""
xdim, ydim = im.shape
|
python
|
{
"resource": ""
}
|
q280648
|
get_uuid
|
test
|
def get_uuid(length=32, version=1):
"""
Returns a unique ID of a given length.
User `version=2` for cross-systems uniqueness.
"""
if version == 1:
|
python
|
{
"resource": ""
}
|
q280649
|
get_unique_key_from_get
|
test
|
def get_unique_key_from_get(get_dict):
"""
Build a unique key from get data
"""
site = Site.objects.get_current()
key = get_dict_to_encoded_url(get_dict)
|
python
|
{
"resource": ""
}
|
q280650
|
get_domain
|
test
|
def get_domain(url):
""" Returns domain name portion of a URL """
if 'http' not in url.lower():
|
python
|
{
"resource": ""
}
|
q280651
|
get_url_args
|
test
|
def get_url_args(url):
""" Returns a dictionary from a URL params """
url_data = urllib.parse.urlparse(url)
|
python
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.