_id
stringlengths 2
7
| title
stringlengths 1
88
| partition
stringclasses 3
values | text
stringlengths 75
19.8k
| 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]
elif filename.endswith("$py.class"): # jython
filename = filename[:-9] + ".py"
return filename
|
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
# .pyc files can be moved after compilation (for example, by being
# installed), we look for __file__ in the frame and prefer it to the
# co_filename value.
dunder_file = frame.f_globals.get('__file__')
if dunder_file:
filename = self._source_for_file(dunder_file)
# Jython reports the .class file to the tracer, use the source file.
if filename.endswith("$py.class"):
filename = filename[:-9] + ".py"
canonical = self.file_locator.canonical_filename(filename)
# If the user specified source or include, then that's authoritative
# about the outer bound of what to measure and we don't have to apply
# any canned exclusions. If they didn't, then we have to exclude the
# stdlib and coverage.py directories.
if self.source_match:
if not self.source_match.match(canonical):
return None, "falls outside the --source trees"
elif self.include_match:
if not self.include_match.match(canonical):
return None, "falls outside the --include trees"
else:
# If we aren't supposed to trace installed code, then check if this
# is near the Python standard library and skip it if so.
if self.pylib_match and self.pylib_match.match(canonical):
return None, "is in the stdlib"
# We exclude the coverage code itself, since a little of it will be
# measured otherwise.
if self.cover_match and self.cover_match.match(canonical):
return None, "is part of coverage.py"
# Check the file against the omit pattern.
if self.omit_match and self.omit_match.match(canonical):
return None, "is inside an --omit pattern"
return canonical, "because we love you"
|
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:
msg = "Not tracing %r: %s" % (filename, reason)
else:
msg = "Tracing %r" % (filename,)
self.debug.write(msg)
return canonical
|
python
|
{
"resource": ""
}
|
q280603
|
coverage._warn
|
test
|
def _warn(self, msg):
"""Use `msg` as a warning."""
self._warnings.append(msg)
sys.stderr.write("Coverage.py warning: %s\n" % msg)
|
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__'):
# This is actually a package, return the directory.
pkg_file = d
else:
pkg_file = self._source_for_file(pkg_file)
pkg_file = self.file_locator.canonical_filename(pkg_file)
if not os.path.exists(pkg_file):
pkg_file = None
if pkg_file:
self.source.append(pkg_file)
self.source_match.add(pkg_file)
else:
self._warn("Module %s has no Python source." % pkg)
for pkg in found:
self.source_pkgs.remove(pkg)
|
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:
self.omit_match = FnmatchMatcher(self.omit)
# The user may want to debug things, show info if desired.
if self.debug.should('config'):
self.debug.write("Configuration values:")
config_info = sorted(self.config.__dict__.items())
self.debug.write_formatted_info(config_info)
if self.debug.should('sys'):
self.debug.write("Debugging info:")
self.debug.write_formatted_info(self.sysinfo())
self.collector.start()
self._started = True
self._measured = True
|
python
|
{
"resource": ""
}
|
q280606
|
coverage._atexit
|
test
|
def _atexit(self):
"""Clean up on process shutdown."""
if self._started:
self.stop()
if self.auto_data:
self.save()
|
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
lines that are not considered executable at all. The "partial" list
indicates lines with branches that are not taken.
`regex` is a regular expression. The regex is added to the specified
list. If any of the regexes in the list is found in a line, the line
is marked for special treatment during reporting.
"""
excl_list = getattr(self.config, which + "_list")
excl_list.append(regex)
self._exclude_regex_stale()
|
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 + "_list")
self._exclude_re[which] = join_regex(excl_list)
return self._exclude_re[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)
test_name = f.read()
f.close()
extra = "." + test_name
data_suffix = "%s%s.%s.%06d" % (
socket.gethostname(), extra, os.getpid(),
random.randint(0, 999999)
)
self._harvest_data()
self.data.write(suffix=data_suffix)
|
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
current measurements.
"""
aliases = None
if self.config.paths:
aliases = PathAliases(self.file_locator)
for paths in self.config.paths.values():
result = paths[0]
for pattern in paths[1:]:
aliases.add(pattern, result)
self.data.combine_parallel_data(aliases=aliases)
|
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:
for pkg in self.source_pkgs:
self._warn("Module %s was never imported." % pkg)
# Find out if we got any data.
summary = self.data.summary()
if not summary and self._warn_no_data:
self._warn("No data was collected.")
# Find files that were never executed at all.
for src in self.source:
for py_file in find_python_files(src):
py_file = self.file_locator.canonical_filename(py_file)
if self.omit_match and self.omit_match.match(py_file):
# Turns out this file was omitted, so don't pull it back
# in as unexecuted.
continue
self.data.touch_file(py_file)
self._measured = False
|
python
|
{
"resource": ""
}
|
q280612
|
coverage.analysis
|
test
|
def analysis(self, morf):
"""Like `analysis2` but doesn't return excluded line numbers."""
f, s, _, m, mf = self.analysis2(morf)
return f, s, m, mf
|
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
coverage data.
"""
analysis = self._analyze(morf)
return (
analysis.filename,
sorted(analysis.statements),
sorted(analysis.excluded),
sorted(analysis.missing),
analysis.missing_formatted(),
)
|
python
|
{
"resource": ""
}
|
q280614
|
coverage._analyze
|
test
|
def _analyze(self, it):
"""Analyze a single morf or code unit.
Returns an `Analysis` object.
"""
self._harvest_data()
if not isinstance(it, CodeUnit):
it = code_unit_factory(it, self.file_locator)[0]
return Analysis(self, it)
|
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.
"""
self._harvest_data()
self.config.from_args(
ignore_errors=ignore_errors, omit=omit, include=include,
show_missing=show_missing,
)
reporter = SummaryReporter(self, self.config)
return reporter.report(morfs, outfile=file)
|
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
marker to indicate the coverage of the line. Covered lines have ">",
excluded lines have "-", and missing lines have "!".
See `coverage.report()` for other arguments.
"""
self._harvest_data()
self.config.from_args(
ignore_errors=ignore_errors, omit=omit, include=include
)
reporter = AnnotateReporter(self, self.config)
reporter.report(morfs, directory=directory)
|
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.
Returns a float, the total percentage covered.
"""
self._harvest_data()
self.config.from_args(
ignore_errors=ignore_errors, omit=omit, include=include,
html_dir=directory, extra_css=extra_css, html_title=title,
)
reporter = HtmlReporter(self, self.config)
return reporter.report(morfs)
|
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")
file_to_close = outfile
try:
try:
reporter = XmlReporter(self, self.config)
return reporter.report(morfs, outfile=outfile)
except CoverageException:
delete_file = True
raise
finally:
if file_to_close:
file_to_close.close()
if delete_file:
file_be_gone(self.config.xml_output)
|
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,
except for those included in this argument.
"""
include = kwargs.get('include')
exclude = kwargs.get('exclude')
from IPython.core.interactiveshell import InteractiveShell
inst = InteractiveShell.instance()
format = inst.display_formatter.format
publish = inst.display_pub.publish
for obj in objs:
format_dict = format(obj, include=include, exclude=exclude)
publish('IPython.core.display.display', format_dict)
|
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
formatted before display? [default: False]
"""
raw = kwargs.pop('raw',False)
if raw:
for obj in objs:
publish_html(obj)
else:
display(*objs, include=['text/plain','text/html'])
|
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
formatted before display? [default: False]
"""
raw = kwargs.pop('raw',False)
if raw:
for obj in objs:
publish_svg(obj)
else:
display(*objs, include=['text/plain','image/svg+xml'])
|
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
formatted before display? [default: False]
"""
raw = kwargs.pop('raw',False)
if raw:
for obj in objs:
publish_png(obj)
else:
display(*objs, include=['text/plain','image/png'])
|
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
formatted before display? [default: False]
"""
raw = kwargs.pop('raw',False)
if raw:
for obj in objs:
publish_jpeg(obj)
else:
display(*objs, include=['text/plain','image/jpeg'])
|
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
formatted before display? [default: False]
"""
raw = kwargs.pop('raw',False)
if raw:
for obj in objs:
publish_latex(obj)
else:
display(*objs, include=['text/plain','text/latex'])
|
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 or Python objects that need to be
formatted before display? [default: False]
"""
raw = kwargs.pop('raw',False)
if raw:
for obj in objs:
publish_json(obj)
else:
display(*objs, include=['text/plain','application/json'])
|
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 be
formatted before display? [default: False]
"""
raw = kwargs.pop('raw',False)
if raw:
for obj in objs:
publish_javascript(obj)
else:
display(*objs, include=['text/plain','application/javascript'])
|
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()
# extract encoding from header, if there is one:
encoding = None
for sub in response.headers['content-type'].split(';'):
sub = sub.strip()
if sub.startswith('charset'):
encoding = sub.split('=')[-1].strip()
break
# decode data, if an encoding was specified
if encoding:
self.data = self.data.decode(encoding, 'replace')
except:
self.data = None
|
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],
stdout=sp.PIPE, stderr=sp.PIPE).communicate()[0]
return py3compat.bytes_to_str(path)
|
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:
break
# Update the pointer to what we've already printed
out_size = len(child.before)
except KeyboardInterrupt:
# We need to send ^C to the process. The ascii code for '^C' is 3
# (the character is known as ETX for 'End of Text', see
# curses.ascii.ETX).
child.sendline(chr(3))
# Read and print any more output the program might produce on its
# way out.
try:
out_size = len(child.before)
child.expect_list(patterns, self.terminate_timeout)
print(child.before[out_size:].decode(enc, 'replace'), end='')
sys.stdout.flush()
except KeyboardInterrupt:
# Impatient users tend to type it multiple times
pass
finally:
# Ensure the subprocess really is terminated
child.terminate(force=True)
# add isalive check, to ensure exitstatus is set:
child.isalive()
return child.exitstatus
|
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, -1)
pull = context.socket(zmq.PULL)
addr='inproc://%s'%uuid.uuid4()
push.bind(addr)
pull.connect(addr)
forwarder = ForwarderThread(push, fd)
forwarder.start()
return pull
|
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:
send = self.sock.send
while line:
send(line)
line = self.fd.readline()
# line == '' means EOF
self.fd.close()
self.sock.close()
|
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:
# doesn't match necessary full class name, assume it's
# just 'PBS' or 'MPI' prefix:
clsname = clsname + kind + 'Launcher'
clsname = 'IPython.parallel.apps.launcher.'+clsname
klass = import_item(clsname)
return klass
|
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)
)
try:
os.kill(pid, sig)
except OSError:
self.log.error("Stopping cluster failed, assuming already dead.",
exc_info=True)
self.remove_pid_file()
elif os.name=='nt':
try:
# kill the whole tree
p = check_call(['taskkill', '-pid', str(pid), '-t', '-f'], stdout=PIPE,stderr=PIPE)
except (CalledProcessError, OSError):
self.log.error("Stopping cluster failed, assuming already dead.",
exc_info=True)
self.remove_pid_file()
|
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)
launcher = klass(
work_dir=u'.', config=self.config, log=self.log,
profile_dir=self.profile_dir.location, cluster_id=self.cluster_id,
)
return launcher
|
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()
# Now write the new pid file AFTER our new forked pid is active.
# self.write_pid_file()
try:
self.loop.start()
except KeyboardInterrupt:
pass
except zmq.ZMQError as e:
if e.errno == errno.EINTR:
pass
else:
raise
|
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()
dc = ioloop.DelayedCallback(self.start_controller, 0, self.loop)
dc.start()
dc = ioloop.DelayedCallback(self.start_engines, 1000*self.delay, self.loop)
dc.start()
# Now write the new pid file AFTER our new forked pid is active.
self.write_pid_file()
try:
self.loop.start()
except KeyboardInterrupt:
pass
except zmq.ZMQError as e:
if e.errno == errno.EINTR:
pass
else:
raise
finally:
self.remove_pid_file()
|
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()
if app is None:
if not kwargs.has_key('redirect'):
kwargs['redirect'] = False
app = wx.PySimpleApp(*args, **kwargs)
return app
|
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'):
return app._in_event_loop
else:
return app.IsMainLoopRunning()
|
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 = True
app.MainLoop()
app._in_event_loop = False
else:
app._in_event_loop = True
|
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:
if not args:
args = ([''],)
app = QtGui.QApplication(*args, **kwargs)
return app
|
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([''])
if hasattr(app, '_in_event_loop'):
return app._in_event_loop
else:
# Does qt4 provide a other way to detect this?
return False
|
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 = True
app.exec_()
app._in_event_loop = False
else:
app._in_event_loop = True
|
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`
"""
canvas = np.zeros((height, width, 3), dtype=np.uint8)
return canvas.view(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.
self[int(y), int(xpos)] = color
for ymod in np.arange(-radius, radius+1, 1):
ypos = y + ymod
if ypos < 0:
continue # Negative indices will draw on the opposite side.
if ypos >= self.shape[0]:
continue # Out of bounds.
self[int(ypos), int(x)] = color
|
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 = tuple([int(round(i, 0)) for i in pos1])
r2, c2 = tuple([int(round(i, 0)) for i in pos2])
rr, cc = skimage.draw.line(r1, c1, r2, c2)
self[rr, cc] = color
|
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
font = PIL.ImageFont.truetype(DEFAULT_FONT_PATH, size=size)
mask = font.getmask(text)
width, height = mask.size
if center:
x = x - (width // 2)
y = y - (height // 2)
for ystep in range(height):
for xstep in range(width):
normalisation = mask[ystep * width + xstep] / 255.
if antialias:
if normalisation != 0:
rgb_color = antialias_rgb(color, normalisation)
set_color(x + xstep, y+ystep, rgb_color)
else:
if normalisation > .5:
set_color(x + xstep, y + ystep, color)
|
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
canvas = np.zeros((xdim, ydim, 3), dtype=np.uint8)
for i, include in enumerate(channels_on):
if include:
canvas[:, :, i] = im
return canvas.view(AnnotatedImage)
|
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:
return uuid.uuid1().hex[:length]
else:
return uuid.uuid4().hex[:length]
|
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)
cache_key = '{}_{}'.format(site.domain, key)
return hashlib.md5(cache_key).hexdigest()
|
python
|
{
"resource": ""
}
|
q280650
|
get_domain
|
test
|
def get_domain(url):
""" Returns domain name portion of a URL """
if 'http' not in url.lower():
url = 'http://{}'.format(url)
return urllib.parse.urlparse(url).hostname
|
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)
arg_dict = urllib.parse.parse_qs(url_data.query)
return arg_dict
|
python
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.