INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
The printing ( as opposed to the parsing part of a list command. | def print_list_lines(self, filename, first, last):
"""The printing (as opposed to the parsing part of a 'list'
command."""
try:
Colors = self.color_scheme_table.active_colors
ColorsNormal = Colors.Normal
tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNorm... |
The debugger interface to magic_pdef | def do_pdef(self, arg):
"""The debugger interface to magic_pdef"""
namespaces = [('Locals', self.curframe.f_locals),
('Globals', self.curframe.f_globals)]
self.shell.find_line_magic('pdef')(arg, namespaces=namespaces) |
Check whether specified line seems to be executable. | def checkline(self, filename, lineno):
"""Check whether specified line seems to be executable.
Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
line or EOF). Warning: testing is not comprehensive.
"""
##########################################################... |
Generates a multiplying factor used to convert two currencies | def conversion_factor(from_symbol, to_symbol, date):
"""
Generates a multiplying factor used to convert two currencies
"""
from_currency = Currency.objects.get(symbol=from_symbol)
try:
from_currency_price = CurrencyPrice.objects.get(currency=from_currency, date=date).mid_price
except Cu... |
Converts an amount of money from one currency to another on a specified date. | def convert_currency(from_symbol, to_symbol, value, date):
"""
Converts an amount of money from one currency to another on a specified date.
"""
if from_symbol == to_symbol:
return value
factor = conversion_factor(from_symbol, to_symbol, date)
if type(value) == float:
output = ... |
Compute the return of the currency between two dates | def compute_return(self, start_date, end_date, rate="MID"):
"""
Compute the return of the currency between two dates
"""
if rate not in ["MID", "ASK", "BID"]:
raise ValueError("Unknown rate type (%s)- must be 'MID', 'ASK' or 'BID'" % str(rate))
if end_date <= start_d... |
Generate a dataframe consisting of the currency prices ( specified by symbols ) from the start to end date | def generate_dataframe(self, symbols=None, date_index=None, price_type="mid"):
"""
Generate a dataframe consisting of the currency prices (specified by symbols)
from the start to end date
"""
# Set defaults if necessary
if symbols is None:
symbols = list(Curr... |
Sanitation checks | def save(self, *args, **kwargs):
"""
Sanitation checks
"""
if self.ask_price < 0:
raise ValidationError("Ask price must be greater than zero")
if self.bid_price < 0:
raise ValidationError("Bid price must be greater than zero")
if self.ask_price < s... |
Return the given stream s encoding or a default. | def get_stream_enc(stream, default=None):
"""Return the given stream's encoding or a default.
There are cases where sys.std* might not actually be a stream, so
check for the encoding attribute prior to returning it, and return
a default if it doesn't exist or evaluates as False. `default'
is None i... |
Return IPython s guess for the default encoding for bytes as text. | def getdefaultencoding():
"""Return IPython's guess for the default encoding for bytes as text.
Asks for stdin.encoding first, to match the calling Terminal, but that
is often None for subprocesses. Fall back on locale.getpreferredencoding()
which should be a sensible platform default (that respects L... |
Gets the username/ password from config. | def get_userpass_value(cli_value, config, key, prompt_strategy):
"""Gets the username / password from config.
Uses the following rules:
1. If it is specified on the cli (`cli_value`), use that.
2. If `config[key]` is specified, use that.
3. Otherwise prompt using `prompt_strategy`.
:param cli... |
load ip/ port/ hmac config from JSON connection file | def load_connection_file(self):
"""load ip/port/hmac config from JSON connection file"""
try:
fname = filefind(self.connection_file, ['.', self.profile_dir.security_dir])
except IOError:
self.log.debug("Connection file not found: %s", self.connection_file)
# T... |
write connection info to JSON file | def write_connection_file(self):
"""write connection info to JSON file"""
if os.path.basename(self.connection_file) == self.connection_file:
cf = os.path.join(self.profile_dir.security_dir, self.connection_file)
else:
cf = self.connection_file
write_connection_fil... |
start the heart beating | def init_heartbeat(self):
"""start the heart beating"""
# heartbeat doesn't share context, because it mustn't be blocked
# by the GIL, which is accessed by libzmq when freeing zero-copy messages
hb_ctx = zmq.Context()
self.heartbeat = Heartbeat(hb_ctx, (self.ip, self.hb_port))
... |
display connection info and store ports | def log_connection_info(self):
"""display connection info, and store ports"""
basename = os.path.basename(self.connection_file)
if basename == self.connection_file or \
os.path.dirname(self.connection_file) == self.profile_dir.security_dir:
# use shortname
tai... |
create our session object | def init_session(self):
"""create our session object"""
default_secure(self.config)
self.session = Session(config=self.config, username=u'kernel') |
redirects stdout/ stderr to devnull if necessary | def init_blackhole(self):
"""redirects stdout/stderr to devnull if necessary"""
if self.no_stdout or self.no_stderr:
blackhole = open(os.devnull, 'w')
if self.no_stdout:
sys.stdout = sys.__stdout__ = blackhole
if self.no_stderr:
sys.std... |
Redirect input streams and set a display hook. | def init_io(self):
"""Redirect input streams and set a display hook."""
if self.outstream_class:
outstream_factory = import_item(str(self.outstream_class))
sys.stdout = outstream_factory(self.session, self.iopub_socket, u'stdout')
sys.stderr = outstream_factory(self.s... |
Create the Kernel object itself | def init_kernel(self):
"""Create the Kernel object itself"""
kernel_factory = import_item(str(self.kernel_class))
self.kernel = kernel_factory(config=self.config, session=self.session,
shell_socket=self.shell_socket,
iopub_socket=se... |
construct connection function which handles tunnels. | def init_connector(self):
"""construct connection function, which handles tunnels."""
self.using_ssh = bool(self.sshkey or self.sshserver)
if self.sshkey and not self.sshserver:
# We are using ssh directly to the controller, tunneling localhost to localhost
self.sshserve... |
send the registration_request | def register(self):
"""send the registration_request"""
self.log.info("Registering with controller at %s"%self.url)
ctx = self.context
connect,maybe_tunnel = self.init_connector()
reg = ctx.socket(zmq.DEALER)
reg.setsockopt(zmq.IDENTITY, self.bident)
connect(reg,... |
Converts html content to plain text | def html_to_text(content):
""" Converts html content to plain text """
text = None
h2t = html2text.HTML2Text()
h2t.ignore_links = False
text = h2t.handle(content)
return text |
Converts markdown content to text | def md_to_text(content):
""" Converts markdown content to text """
text = None
html = markdown.markdown(content)
if html:
text = html_to_text(content)
return text |
Converts uri parts to valid uri. Example:/ memebers [ profile view ] = >/ memembers/ profile/ view | def parts_to_uri(base_uri, uri_parts):
"""
Converts uri parts to valid uri.
Example: /memebers, ['profile', 'view'] => /memembers/profile/view
"""
uri = "/".join(map(lambda x: str(x).rstrip('/'), [base_uri] + uri_parts))
return uri |
returns a fully qualified app domain name | def domain_to_fqdn(domain, proto=None):
""" returns a fully qualified app domain name """
from .generic import get_site_proto
proto = proto or get_site_proto()
fdqn = '{proto}://{domain}'.format(proto=proto, domain=domain)
return fdqn |
Define the command line options for the plugin. | def options(self, parser, env=os.environ):
"""Define the command line options for the plugin."""
super(NoseExclude, self).options(parser, env)
env_dirs = []
if 'NOSE_EXCLUDE_DIRS' in env:
exclude_dirs = env.get('NOSE_EXCLUDE_DIRS','')
env_dirs.extend(exclude_dirs.... |
Configure plugin based on command line options | def configure(self, options, conf):
"""Configure plugin based on command line options"""
super(NoseExclude, self).configure(options, conf)
self.exclude_dirs = {}
# preload directories from file
if options.exclude_dir_file:
if not options.exclude_dirs:
... |
Check if directory is eligible for test discovery | def wantDirectory(self, dirname):
"""Check if directory is eligible for test discovery"""
if dirname in self.exclude_dirs:
log.debug("excluded: %s" % dirname)
return False
else:
return None |
Return true if ext links to a dynamic lib in the same package | def links_to_dynamic(self, ext):
"""Return true if 'ext' links to a dynamic lib in the same package"""
# XXX this should check to ensure the lib is actually being built
# XXX as dynamic, and not just using a locally-found version or a
# XXX static-compiled version
libnames = dict... |
call each func from func list. | def call_each(funcs: list, *args, **kwargs):
'''
call each func from func list.
return the last func value or None if func list is empty.
'''
ret = None
for func in funcs:
ret = func(*args, **kwargs)
return ret |
call each func from reversed func list. | def call_each_reversed(funcs: list, *args, **kwargs):
'''
call each func from reversed func list.
return the last func value or None if func list is empty.
'''
ret = None
for func in reversed(funcs):
ret = func(*args, **kwargs)
return ret |
append func with given arguments and keywords. | def append_func(self, func, *args, **kwargs):
'''
append func with given arguments and keywords.
'''
wraped_func = partial(func, *args, **kwargs)
self.append(wraped_func) |
insert func with given arguments and keywords. | def insert_func(self, index, func, *args, **kwargs):
'''
insert func with given arguments and keywords.
'''
wraped_func = partial(func, *args, **kwargs)
self.insert(index, wraped_func) |
ensure there is only one newline between usage and the first heading if there is no description | def format_usage(self, usage):
"""
ensure there is only one newline between usage and the first heading
if there is no description
"""
msg = 'Usage: %s' % usage
if self.parser.description:
msg += '\n'
return msg |
initialize the app | def initialize(self, argv=None):
"""initialize the app"""
super(BaseParallelApplication, self).initialize(argv)
self.to_work_dir()
self.reinit_logging() |
Create a. pid file in the pid_dir with my pid. | def write_pid_file(self, overwrite=False):
"""Create a .pid file in the pid_dir with my pid.
This must be called after pre_construct, which sets `self.pid_dir`.
This raises :exc:`PIDFileError` if the pid file exists already.
"""
pid_file = os.path.join(self.profile_dir.pid_dir, ... |
Remove the pid file. | def remove_pid_file(self):
"""Remove the pid file.
This should be called at shutdown by registering a callback with
:func:`reactor.addSystemEventTrigger`. This needs to return
``None``.
"""
pid_file = os.path.join(self.profile_dir.pid_dir, self.name + u'.pid')
if... |
Get the pid from the pid file. | def get_pid_from_file(self):
"""Get the pid from the pid file.
If the pid file doesn't exist a :exc:`PIDFileError` is raised.
"""
pid_file = os.path.join(self.profile_dir.pid_dir, self.name + u'.pid')
if os.path.isfile(pid_file):
with open(pid_file, 'r') as f:
... |
Construct an argument parser using the function decorations. | def construct_parser(magic_func):
""" Construct an argument parser using the function decorations.
"""
kwds = getattr(magic_func, 'argcmd_kwds', {})
if 'description' not in kwds:
kwds['description'] = getattr(magic_func, '__doc__', None)
arg_name = real_name(magic_func)
parser = MagicArg... |
Find the real name of the magic. | def real_name(magic_func):
""" Find the real name of the magic.
"""
magic_name = magic_func.__name__
if magic_name.startswith('magic_'):
magic_name = magic_name[len('magic_'):]
return getattr(magic_func, 'argcmd_name', magic_name) |
Add this object s information to the parser. | def add_to_parser(self, parser, group):
""" Add this object's information to the parser.
"""
if group is not None:
parser = group
parser.add_argument(*self.args, **self.kwds)
return None |
Add this object s information to the parser. | def add_to_parser(self, parser, group):
""" Add this object's information to the parser.
"""
return parser.add_argument_group(*self.args, **self.kwds) |
Highlight a block of text. Reimplemented to highlight selectively. | def highlightBlock(self, string):
""" Highlight a block of text. Reimplemented to highlight selectively.
"""
if not self.highlighting_on:
return
# The input to this function is a unicode string that may contain
# paragraph break characters, non-breaking spaces, etc. ... |
Reimplemented to temporarily enable highlighting if disabled. | def rehighlightBlock(self, block):
""" Reimplemented to temporarily enable highlighting if disabled.
"""
old = self.highlighting_on
self.highlighting_on = True
super(FrontendHighlighter, self).rehighlightBlock(block)
self.highlighting_on = old |
Reimplemented to highlight selectively. | def setFormat(self, start, count, format):
""" Reimplemented to highlight selectively.
"""
start += self._current_offset
super(FrontendHighlighter, self).setFormat(start, count, format) |
Copy the currently selected text to the clipboard removing prompts. | def copy(self):
""" Copy the currently selected text to the clipboard, removing prompts.
"""
if self._page_control is not None and self._page_control.hasFocus():
self._page_control.copy()
elif self._control.hasFocus():
text = self._control.textCursor().selection()... |
Returns whether source can be completely processed and a new prompt created. When triggered by an Enter/ Return key press interactive is True ; otherwise it is False. | def _is_complete(self, source, interactive):
""" Returns whether 'source' can be completely processed and a new
prompt created. When triggered by an Enter/Return key press,
'interactive' is True; otherwise, it is False.
"""
complete = self._input_splitter.push(source)
... |
Execute source. If hidden do not show any output. | def _execute(self, source, hidden):
""" Execute 'source'. If 'hidden', do not show any output.
See parent class :meth:`execute` docstring for full details.
"""
msg_id = self.kernel_manager.shell_channel.execute(source, hidden)
self._request_info['execute'][msg_id] = self._Execut... |
Called immediately after a prompt is finished i. e. when some input will be processed and a new prompt displayed. | def _prompt_finished_hook(self):
""" Called immediately after a prompt is finished, i.e. when some input
will be processed and a new prompt displayed.
"""
# Flush all state from the input splitter so the next round of
# reading input starts with a clean buffer.
self._... |
Called when the tab key is pressed. Returns whether to continue processing the event. | def _tab_pressed(self):
""" Called when the tab key is pressed. Returns whether to continue
processing the event.
"""
# Perform tab completion if:
# 1) The cursor is in the input buffer.
# 2) There is a non-whitespace character before the cursor.
text = self._... |
Reimplemented to add an action for raw copy. | def _context_menu_make(self, pos):
""" Reimplemented to add an action for raw copy.
"""
menu = super(FrontendWidget, self)._context_menu_make(pos)
for before_action in menu.actions():
if before_action.shortcut().matches(QtGui.QKeySequence.Paste) == \
QtGui... |
Reimplemented for execution interruption and smart backspace. | def _event_filter_console_keypress(self, event):
""" Reimplemented for execution interruption and smart backspace.
"""
key = event.key()
if self._control_key_down(event.modifiers(), include_command=False):
if key == QtCore.Qt.Key_C and self._executing:
self.r... |
Reimplemented for auto - indentation. | def _insert_continuation_prompt(self, cursor):
""" Reimplemented for auto-indentation.
"""
super(FrontendWidget, self)._insert_continuation_prompt(cursor)
cursor.insertText(' ' * self._input_splitter.indent_spaces) |
Handle replies for tab completion. | def _handle_complete_reply(self, rep):
""" Handle replies for tab completion.
"""
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_header']['msg_id'] and \
... |
Silently execute expr in the kernel and call callback with reply | def _silent_exec_callback(self, expr, callback):
"""Silently execute `expr` in the kernel and call `callback` with reply
the `expr` is evaluated silently in the kernel (without) output in
the frontend. Call `callback` with the
`repr <http://docs.python.org/library/functions.html#repr> `... |
Execute callback corresponding to msg reply after _silent_exec_callback | def _handle_exec_callback(self, msg):
"""Execute `callback` corresponding to `msg` reply, after ``_silent_exec_callback``
Parameters
----------
msg : raw message send by the kernel containing an `user_expressions`
and having a 'silent_exec_callback' kind.
Notes
... |
Handles replies for code execution. | def _handle_execute_reply(self, msg):
""" Handles replies for code execution.
"""
self.log.debug("execute: %s", msg.get('content', ''))
msg_id = msg['parent_header']['msg_id']
info = self._request_info['execute'].get(msg_id)
# unset reading flag, because if execute finish... |
Handle requests for raw_input. | def _handle_input_request(self, msg):
""" Handle requests for raw_input.
"""
self.log.debug("input: %s", msg.get('content', ''))
if self._hidden:
raise RuntimeError('Request for raw input during hidden execution.')
# Make sure that all output from the SUB channel has... |
Handle the kernel s death by asking if the user wants to restart. | def _handle_kernel_died(self, since_last_heartbeat):
""" Handle the kernel's death by asking if the user wants to restart.
"""
self.log.debug("kernel died: %s", since_last_heartbeat)
if self.custom_restart:
self.custom_restart_kernel_died.emit(since_last_heartbeat)
el... |
Handle replies for call tips. | def _handle_object_info_reply(self, rep):
""" Handle replies for call tips.
"""
self.log.debug("oinfo: %s", rep.get('content', ''))
cursor = self._get_cursor()
info = self._request_info.get('call_tip')
if info and info.id == rep['parent_header']['msg_id'] and \
... |
Handle display hook output. | def _handle_pyout(self, msg):
""" Handle display hook output.
"""
self.log.debug("pyout: %s", msg.get('content', ''))
if not self._hidden and self._is_from_this_session(msg):
text = msg['content']['data']
self._append_plain_text(text + '\n', before_prompt=True) |
Handle stdout stderr and stdin. | def _handle_stream(self, msg):
""" Handle stdout, stderr, and stdin.
"""
self.log.debug("stream: %s", msg.get('content', ''))
if not self._hidden and self._is_from_this_session(msg):
# Most consoles treat tabs as being 8 space characters. Convert tabs
# to spaces ... |
Handle shutdown signal only if from other console. | def _handle_shutdown_reply(self, msg):
""" Handle shutdown signal, only if from other console.
"""
self.log.debug("shutdown: %s", msg.get('content', ''))
if not self._hidden and not self._is_from_this_session(msg):
if self._local_kernel:
if not msg['content'][... |
Attempts to execute file with path. If hidden no output is shown. | def execute_file(self, path, hidden=False):
""" Attempts to execute file with 'path'. If 'hidden', no output is
shown.
"""
self.execute('execfile(%r)' % path, hidden=hidden) |
Attempts to interrupt the running kernel. Also unsets _reading flag to avoid runtime errors if raw_input is called again. | def interrupt_kernel(self):
""" Attempts to interrupt the running kernel.
Also unsets _reading flag, to avoid runtime errors
if raw_input is called again.
"""
if self.custom_interrupt:
self._reading = False
self.custom_interrupt_requested.emit()
... |
Resets the widget to its initial state if clear parameter or clear_on_kernel_restart configuration setting is True otherwise prints a visual indication of the fact that the kernel restarted but does not clear the traces from previous usage of the kernel before it was restarted. With clear = True it is similar to %clear... | def reset(self, clear=False):
""" Resets the widget to its initial state if ``clear`` parameter or
``clear_on_kernel_restart`` configuration setting is True, otherwise
prints a visual indication of the fact that the kernel restarted, but
does not clear the traces from previous usage of t... |
Attempts to restart the running kernel. | def restart_kernel(self, message, now=False):
""" Attempts to restart the running kernel.
"""
# FIXME: now should be configurable via a checkbox in the dialog. Right
# now at least the heartbeat path sets it to True and the manual restart
# to False. But those should just be th... |
Shows a call tip if appropriate at the current cursor location. | def _call_tip(self):
""" Shows a call tip, if appropriate, at the current cursor location.
"""
# Decide if it makes sense to show a call tip
if not self.enable_calltips:
return False
cursor = self._get_cursor()
cursor.movePosition(QtGui.QTextCursor.Left)
... |
Performs completion at the current cursor location. | def _complete(self):
""" Performs completion at the current cursor location.
"""
context = self._get_context()
if context:
# Send the completion request to the kernel
msg_id = self.kernel_manager.shell_channel.complete(
'.'.join(context), ... |
Gets the context for the specified cursor ( or the current cursor if none is specified ). | def _get_context(self, cursor=None):
""" Gets the context for the specified cursor (or the current cursor
if none is specified).
"""
if cursor is None:
cursor = self._get_cursor()
cursor.movePosition(QtGui.QTextCursor.StartOfBlock,
QtGu... |
Process a reply for an execution request that resulted in an error. | def _process_execute_error(self, msg):
""" Process a reply for an execution request that resulted in an error.
"""
content = msg['content']
# If a SystemExit is passed along, this means exit() was called - also
# all the ipython %exit magic syntax of '-k' to be used to keep
... |
Process a reply for a successful execution request. | def _process_execute_ok(self, msg):
""" Process a reply for a successful execution request.
"""
payload = msg['content']['payload']
for item in payload:
if not self._process_execute_payload(item):
warning = 'Warning: received unknown payload of type %s'
... |
Called whenever the document s content changes. Display a call tip if appropriate. | def _document_contents_change(self, position, removed, added):
""" Called whenever the document's content changes. Display a call tip
if appropriate.
"""
# Calculate where the cursor should be *after* the change:
position += added
document = self._control.document()
... |
Add plugin to my list of plugins to call if it has the attribute I m bound to. | def addPlugin(self, plugin, call):
"""Add plugin to my list of plugins to call, if it has the attribute
I'm bound to.
"""
meth = getattr(plugin, call, None)
if meth is not None:
if call == 'loadTestsFromModule' and \
len(inspect.getargspec(meth)[0]... |
Call plugins in a chain where the result of each plugin call is sent to the next plugin as input. The final output result is returned. | def chain(self, *arg, **kw):
"""Call plugins in a chain, where the result of each plugin call is
sent to the next plugin as input. The final output result is returned.
"""
result = None
# extract the static arguments (if any) from arg so they can
# be passed to each plugi... |
Call all plugins yielding each item in each non - None result. | def generate(self, *arg, **kw):
"""Call all plugins, yielding each item in each non-None result.
"""
for p, meth in self.plugins:
result = None
try:
result = meth(*arg, **kw)
if result is not None:
for r in result:
... |
Call all plugins returning the first non - None result. | def simple(self, *arg, **kw):
"""Call all plugins, returning the first non-None result.
"""
for p, meth in self.plugins:
result = meth(*arg, **kw)
if result is not None:
return result |
extraplugins are maintained in a separate list and re - added by loadPlugins () to prevent their being overwritten by plugins added by a subclass of PluginManager | def addPlugins(self, plugins=(), extraplugins=()):
"""extraplugins are maintained in a separate list and
re-added by loadPlugins() to prevent their being overwritten
by plugins added by a subclass of PluginManager
"""
self._extraplugins = extraplugins
for plug in iterchai... |
Configure the set of plugins with the given options and config instance. After configuration disabled plugins are removed from the plugins list. | def configure(self, options, config):
"""Configure the set of plugins with the given options
and config instance. After configuration, disabled plugins
are removed from the plugins list.
"""
log.debug("Configuring plugins")
self.config = config
cfg = PluginProxy('... |
Load plugins by iterating the nose. plugins entry point. | def loadPlugins(self):
"""Load plugins by iterating the `nose.plugins` entry point.
"""
from pkg_resources import iter_entry_points
loaded = {}
for entry_point, adapt in self.entry_points:
for ep in iter_entry_points(entry_point):
if ep.name in loaded:... |
Load plugins in nose. plugins. builtin | def loadPlugins(self):
"""Load plugins in nose.plugins.builtin
"""
from nose.plugins import builtin
for plug in builtin.plugins:
self.addPlugin(plug())
super(BuiltinPluginManager, self).loadPlugins() |
Render a LaTeX string to PNG. | def latex_to_png(s, encode=False, backend='mpl'):
"""Render a LaTeX string to PNG.
Parameters
----------
s : str
The raw string containing valid inline LaTeX.
encode : bool, optional
Should the PNG data bebase64 encoded to make it JSON'able.
backend : {mpl, dvipng}
Backe... |
Render LaTeX to HTML with embedded PNG data using data URIs. | def latex_to_html(s, alt='image'):
"""Render LaTeX to HTML with embedded PNG data using data URIs.
Parameters
----------
s : str
The raw string containing valid inline LateX.
alt : str
The alt text to use for the HTML.
"""
base64_data = latex_to_png(s, encode=True)
if ba... |
Given a math expression renders it in a closely - clipped bounding box to an image file. | def math_to_image(s, filename_or_obj, prop=None, dpi=None, format=None):
"""
Given a math expression, renders it in a closely-clipped bounding
box to an image file.
*s*
A math expression. The math portion should be enclosed in
dollar signs.
*filename_or_obj*
A filepath or wri... |
Build wheels. | def build(self):
"""Build wheels."""
# unpack and constructs req set
self.requirement_set.prepare_files(self.finder)
reqset = self.requirement_set.requirements.values()
buildset = []
for req in reqset:
if req.is_wheel:
logger.info(
... |
Parses svn + http:// blahblah | def parse_editable(editable_req, default_vcs=None):
"""Parses svn+http://blahblah@rev#egg=Foobar into a requirement
(Foobar) and a URL"""
url = editable_req
extras = None
# If a file path is specified with extras, strip off the extras.
m = re.match(r'^(.+)(\[[^\]]+\])$', url)
if m:
... |
Uninstall the distribution currently satisfying this requirement. | def uninstall(self, auto_confirm=False):
"""
Uninstall the distribution currently satisfying this requirement.
Prompts before removing or modifying files unless
``auto_confirm`` is True.
Refuses to delete or modify files outside of ``sys.prefix`` -
thus uninstallation w... |
Find an installed distribution that satisfies or conflicts with this requirement and set self. satisfied_by or self. conflicts_with appropriately. | def check_if_exists(self):
"""Find an installed distribution that satisfies or conflicts
with this requirement, and set self.satisfied_by or
self.conflicts_with appropriately."""
if self.req is None:
return False
try:
self.satisfied_by = pkg_resources.get_... |
Clean up files remove builds. | def cleanup_files(self, bundle=False):
"""Clean up files, remove builds."""
logger.notify('Cleaning up...')
logger.indent += 2
for req in self.reqs_to_cleanup:
req.remove_temporary_source()
remove_dir = []
if self._pip_has_created_build_dir():
rem... |
Install everything in this set ( after having downloaded and unpacked the packages ) | def install(self, install_options, global_options=()):
"""Install everything in this set (after having downloaded and unpacked the packages)"""
to_install = [r for r in self.requirements.values()
if not r.satisfied_by]
if to_install:
logger.notify('Installing c... |
Return a generator yielding a Process class instance for all running processes on the local machine. | def process_iter():
"""Return a generator yielding a Process class instance for all
running processes on the local machine.
Every new Process instance is only created once and then cached
into an internal table which is updated every time this is used.
The sorting order in which processes are yiel... |
Return a float representing the current system - wide CPU utilization as a percentage. | def cpu_percent(interval=0.1, percpu=False):
"""Return a float representing the current system-wide CPU
utilization as a percentage.
When interval is > 0.0 compares system CPU times elapsed before
and after the interval (blocking).
When interval is 0.0 or None compares system CPU times elapsed
... |
Return system disk I/ O statistics as a namedtuple including the following attributes: | def disk_io_counters(perdisk=False):
"""Return system disk I/O statistics as a namedtuple including
the following attributes:
- read_count: number of reads
- write_count: number of writes
- read_bytes: number of bytes read
- write_bytes: number of bytes written
- read_time: time sp... |
Return network I/ O statistics as a namedtuple including the following attributes: | def network_io_counters(pernic=False):
"""Return network I/O statistics as a namedtuple including
the following attributes:
- bytes_sent: number of bytes sent
- bytes_recv: number of bytes received
- packets_sent: number of packets sent
- packets_recv: number of packets received
- ... |
Return the amount of total used and free physical memory on the system in bytes plus the percentage usage. Deprecated by psutil. virtual_memory (). | def phymem_usage():
"""Return the amount of total, used and free physical memory
on the system in bytes plus the percentage usage.
Deprecated by psutil.virtual_memory().
"""
mem = virtual_memory()
return _nt_sysmeminfo(mem.total, mem.used, mem.free, mem.percent) |
Utility method returning process information as a hashable dictionary. | def as_dict(self, attrs=[], ad_value=None):
"""Utility method returning process information as a hashable
dictionary.
If 'attrs' is specified it must be a list of strings reflecting
available Process class's attribute names (e.g. ['get_cpu_times',
'name']) else all public (read ... |
The process name. | def name(self):
"""The process name."""
name = self._platform_impl.get_process_name()
if os.name == 'posix':
# On UNIX the name gets truncated to the first 15 characters.
# If it matches the first part of the cmdline we return that
# one instead because it's u... |
The process executable path. May also be an empty string. | def exe(self):
"""The process executable path. May also be an empty string."""
def guess_it(fallback):
# try to guess exe from cmdline[0] in absence of a native
# exe representation
cmdline = self.cmdline
if cmdline and hasattr(os, 'access') and hasattr(os... |
The name of the user that owns the process. On UNIX this is calculated by using * real * process uid. | def username(self):
"""The name of the user that owns the process.
On UNIX this is calculated by using *real* process uid.
"""
if os.name == 'posix':
if pwd is None:
# might happen if python was installed from sources
raise ImportError("require... |
Return the children of this process as a list of Process objects. If recursive is True return all the parent descendants. | def get_children(self, recursive=False):
"""Return the children of this process as a list of Process
objects.
If recursive is True return all the parent descendants.
Example (A == this process):
A ββ
β
ββ B (child) ββ
β ββ X (gra... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.