Search is not available for this dataset
text stringlengths 75 104k |
|---|
def undefined_subcmd(self, cmd, subcmd):
"""Error message when subcommand asked for but doesn't exist"""
self.proc.intf[-1].errmsg(('Undefined "%s" subcommand: "%s". ' +
'Try "help %s *".') % (cmd, subcmd, cmd))
return |
def runcode(obj, code_obj):
"""Execute a code object.
When an exception occurs, self.showtraceback() is called to
display a traceback. All exceptions are caught except
SystemExit, which is reraised.
A note about KeyboardInterrupt: this exception may occur
elsewhere in this code, and may not a... |
def run(self, args):
"""**down** [*count*]
Move the current frame down in the stack trace (to a newer frame). 0
is the most recent frame. If no count is given, move down 1.
See also:
---------
`up` and `frame`."""
Mframe.adjust_relative(self.proc, self.name, args, self.signum)
return False |
def resolve_location(proc, location):
"""Expand fields in Location namedtuple. If:
'.': get fields from stack
function/module: get fields from evaluation/introspection
location file and line number: use that
"""
curframe = proc.curframe
if location == '.':
if not curframe:
... |
def resolve_address_location(proc, location):
"""Expand fields in Location namedtuple. If:
'.': get fields from stack
function/module: get fields from evaluation/introspection
location file and line number: use that
"""
curframe = proc.curframe
if location == '.':
filename ... |
def find_and_set_debugged_frame(self, frame, thread_id):
'''The dance we have to do to set debugger frame state to
*frame*, which is in the thread with id *thread_id*. We may
need to the hide initial debugger frames.
'''
thread = threading._active[thread_id]
thread_name =... |
def one_arg_run(self, position_str):
'''The simple case: thread frame switching has been done or is
not needed and we have an explicit position number as a string'''
frame_num = self.proc.get_an_int(position_str,
("The 'frame' command requires a" +
... |
def get_from_thread_name_or_id(self, name_or_id, report_error=True):
'''See if *name_or_id* is either a thread name or a thread id.
The frame of that id/name is returned, or None if name_or_id is
invalid.'''
thread_id = self.proc.get_int_noerr(name_or_id)
if thread_id is None:
... |
def run(self, args):
'''Run a frame command. This routine is a little complex
because we allow a number parameter variations.'''
if len(args) == 1:
# Form is: "frame" which means "frame 0"
position_str = '0'
elif len(args) == 2:
# Form is: "frame {pos... |
def pprint_simple_array(val, displaywidth, msg_nocr, msg, lineprefix=''):
'''Try to pretty print a simple case where a list is not nested.
Return True if we can do it and False if not. '''
if type(val) != list:
return False
numeric = True
for i in range(len(val)):
if not (type(val[... |
def main(dbg=None, sys_argv=list(sys.argv)):
"""Routine which gets run if we were invoked directly"""
global __title__
# Save the original just for use in the restart that works via exec.
orig_sys_argv = list(sys_argv)
opts, dbg_opts, sys_argv = Moptions.process_options(__title__,
... |
def open(self, output, opts=None):
"""Use this to set where to write to. output can be a
file object or a string. This code raises IOError on error."""
if isinstance(output, io.TextIOWrapper) or \
isinstance(output, io.StringIO) or \
output == sys.stdout:
pass
... |
def write(self, msg):
""" This method the debugger uses to write. In contrast to
writeline, no newline is added to the end to `str'.
"""
if self.output.closed:
raise IOError("writing %s on a closed file" % msg)
self.output.write(msg)
if self.flush_after_write:... |
def lookup_signame(num):
"""Find the corresponding signal name for 'num'. Return None
if 'num' is invalid."""
signames = signal.__dict__
num = abs(num)
for signame in list(signames.keys()):
if signame.startswith('SIG') and signames[signame] == num:
return signame
pass
... |
def lookup_signum(name):
"""Find the corresponding signal number for 'name'. Return None
if 'name' is invalid."""
uname = name.upper()
if (uname.startswith('SIG') and hasattr(signal, uname)):
return getattr(signal, uname)
else:
uname = "SIG"+uname
if hasattr(signal, uname):
... |
def canonic_signame(name_num):
"""Return a signal name for a signal name or signal
number. Return None is name_num is an int but not a valid signal
number and False if name_num is a not number. If name_num is a
signal name or signal number, the canonic if name is returned."""
signum = lookup_signum... |
def set_signal_replacement(self, signum, handle):
"""A replacement for signal.signal which chains the signal behind
the debugger's handler"""
signame = lookup_signame(signum)
if signame is None:
self.dbgr.intf[-1].errmsg(("%s is not a signal number"
... |
def check_and_adjust_sighandler(self, signame, sigs):
"""
Check to see if a single signal handler that we are interested
in has changed or has not been set initially. On return
self.sigs[signame] should have our signal handler. True is
returned if the same or adjusted, False or N... |
def check_and_adjust_sighandlers(self):
"""Check to see if any of the signal handlers we are interested in have
changed or is not initially set. Change any that are not right. """
for signame in list(self.sigs.keys()):
if not self.check_and_adjust_sighandler(signame, self.sigs):
... |
def print_info_signal_entry(self, signame):
"""Print status for a single signal name (signame)"""
if signame in signal_description:
description=signal_description[signame]
else:
description=""
pass
if signame not in list(self.sigs.keys()):
... |
def info_signal(self, args):
"""Print information about a signal"""
if len(args) == 0: return None
signame = args[0]
if signame in ['handle', 'signal']:
# This has come from dbgr's info command
if len(args) == 1:
# Show all signal handlers
... |
def action(self, arg):
"""Delegate the actions specified in 'arg' to another
method.
"""
if not arg:
self.info_signal(['handle'])
return True
args = arg.split()
signame = args[0]
signame = self.is_name_or_number(args[0])
if not sign... |
def handle_print_stack(self, signame, print_stack):
"""Set whether we stop or not when this signal is caught.
If 'set_stop' is True your program will stop when this signal
happens."""
self.sigs[signame].print_stack = print_stack
return print_stack |
def handle_stop(self, signame, set_stop):
"""Set whether we stop or not when this signal is caught.
If 'set_stop' is True your program will stop when this signal
happens."""
if set_stop:
self.sigs[signame].b_stop = True
# stop keyword implies print AND nopas... |
def handle_pass(self, signame, set_pass):
"""Set whether we pass this signal to the program (or not)
when this signal is caught. If set_pass is True, Dbgr should allow
your program to see this signal.
"""
self.sigs[signame].pass_along = set_pass
if set_pass:
#... |
def handle_print(self, signame, set_print):
"""Set whether we print or not when this signal is caught."""
if set_print:
self.sigs[signame].print_method = self.dbgr.intf[-1].msg
else:
self.sigs[signame].print_method = None
pass
return set_print |
def handle(self, signum, frame):
"""This method is called when a signal is received."""
if self.print_method:
self.print_method('\nProgram received signal %s.'
% self.signame)
if self.print_stack:
import traceback
strings = traceb... |
def is_ok_line_for_breakpoint(filename, lineno, errmsg_fn):
"""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.
"""
line = linecache.getline(filename, lineno)
if not lin... |
def file2module(filename):
"""Given a file name, extract the most likely module name. """
basename = osp.basename(filename)
if '.' in basename:
pos = basename.rfind('.')
return basename[:pos]
else:
return basename
return None |
def search_file(filename, directories, cdir):
"""Return a full pathname for filename if we can find one. path
is a list of directories to prepend to filename. If no file is
found we'll return None"""
for trydir in directories:
# Handle $cwd and $cdir
if trydir =='$cwd': trydir='.'
... |
def whence_file(py_script, dirnames=None):
"""Do a shell-like path lookup for py_script and return the results.
If we can't find anything return py_script"""
if py_script.find(os.sep) != -1:
# Don't search since this name has path separator components
return py_script
if dirnames is None... |
def print_obj(arg, frame, format=None, short=False):
"""Return a string representation of an object """
try:
if not frame:
# ?? Should we have set up a dummy globals
# to have persistence?
obj = eval(arg, None, None)
else:
obj = eval(arg, frame.f_g... |
def pyfiles(callername, level=2):
"All python files caller's dir without the path and trailing .py"
d = os.path.dirname(callername)
# Get the name of our directory.
# A glob pattern that will get all *.py files but not __init__.py
glob(os.path.join(d, '[a-zA-Z]*.py'))
py_files = glob(os.path.joi... |
def adjust_frame(self, pos, absolute_pos):
"""Adjust stack frame by pos positions. If absolute_pos then
pos is an absolute number. Otherwise it is a relative number.
A negative number indexes from the other end."""
if not self.curframe:
Mmsg.errmsg(self, "No stack.")
... |
def ok_for_running(self, cmd_obj, name, cmd_hash):
'''We separate some of the common debugger command checks here:
whether it makes sense to run the command in this execution state,
if the command has the right number of arguments and so on.
'''
if hasattr(cmd_obj, 'execution_set... |
def setup(self):
"""Initialization done before entering the debugger-command
loop. In particular we set up the call stack used for local
variable lookup and frame/up/down commands.
We return True if we should NOT enter the debugger-command
loop."""
self.forget()
... |
def _populate_commands(self):
""" Create an instance of each of the debugger
commands. Commands are found by importing files in the
directory 'command'. Some files are excluded via an array set
in __init__. For each of the remaining files, we import them
and scan for class names... |
def _populate_cmd_lists(self):
""" Populate self.commands"""
self.commands = {}
for cmd_instance in self.cmd_instances:
cmd_name = cmd_instance.name
self.commands[cmd_name] = cmd_instance
pass
return |
def format_location(proc_obj):
"""Show where we are. GUI's and front-end interfaces often
use this to update displays. So it is helpful to make sure
we give at least some place that's located in a file.
"""
i_stack = proc_obj.curindex
if i_stack is None or proc_obj.stack is None:
return ... |
def msg(self, msg):
""" used to write to a debugger that is connected to this
server; `str' written will have a newline added to it
"""
if hasattr(self.output, 'writeline'):
self.output.writeline(msg)
elif hasattr(self.output, 'writelines'):
self.output.wr... |
def run(self, args):
"""Execution status of the program."""
mainfile = self.core.filename(None)
if self.core.is_running():
if mainfile:
part1 = "Python program '%s' is stopped" % mainfile
else:
part1 = 'Program is stopped'
p... |
def columnize_commands(self, commands):
"""List commands arranged in an aligned columns"""
commands.sort()
width = self.debugger.settings['width']
return columnize.columnize(commands, displaywidth=width,
lineprefix=' ') |
def confirm(self, msg, default=False):
""" Convenience short-hand for self.debugger.intf[-1].confirm """
return self.debugger.intf[-1].confirm(msg, default) |
def errmsg(self, msg, opts={}):
""" Convenience short-hand for self.debugger.intf[-1].errmsg """
try:
return(self.debugger.intf[-1].errmsg(msg))
except EOFError:
# FIXME: what do we do here?
pass
return None |
def msg(self, msg, opts={}):
""" Convenience short-hand for self.debugger.intf[-1].msg """
try:
return(self.debugger.intf[-1].msg(msg))
except EOFError:
# FIXME: what do we do here?
pass
return None |
def msg_nocr(self, msg, opts={}):
""" Convenience short-hand for self.debugger.intf[-1].msg_nocr """
try:
return(self.debugger.intf[-1].msg_nocr(msg))
except EOFError:
# FIXME: what do we do here?
pass
return None |
def rst_msg(self, text, opts={}):
"""Convert ReStructuredText and run through msg()"""
text = Mformat.rst_text(text,
'plain' == self.debugger.settings['highlight'],
self.debugger.settings['width'])
return self.msg(text) |
def get_last_or_frame_exception():
"""Intended to be used going into post mortem routines. If
sys.last_traceback is set, we will return that and assume that
this is what post-mortem will want. If sys.last_traceback has not
been set, then perhaps we *about* to raise an error and are
fielding an exce... |
def post_mortem(exc=None, frameno=1, dbg=None):
"""Enter debugger read loop after your program has crashed.
exc is a triple like you get back from sys.exc_info. If no exc
parameter, is supplied, the values from sys.last_type,
sys.last_value, sys.last_traceback are used. And if these don't
exist ei... |
def close(self):
""" Closes both socket and server connection. """
self.state = 'closing'
if self.inout:
self.inout.close()
pass
self.state = 'closing connection'
if self.conn:
self.conn.close()
self.state = 'disconnected'
retur... |
def write(self, msg):
""" This method the debugger uses to write. In contrast to
writeline, no newline is added to the end to `str'. Also
msg doesn't have to be a string.
"""
if self.state != 'connected':
self.wait_for_connect()
pass
buffer = Mtcpf... |
def complete_token_filtered(aliases, prefix, expanded):
"""Find all starting matches in dictionary *aliases* that start
with *prefix*, but filter out any matches already in
*expanded*."""
complete_ary = list(aliases.keys())
results = [cmd for cmd in
complete_ary if cmd.startswith(pr... |
def complete_identifier(cmd, prefix):
'''Complete an arbitrary expression.'''
if not cmd.proc.curframe: return [None]
# Collect globals and locals. It is usually not really sensible to also
# complete builtins, and they clutter the namespace quite heavily, so we
# leave them out.
ns = cmd.proc.... |
def errmsg(self, message, opts={}):
""" Convenience short-hand for self.intf[-1].errmsg """
if 'plain' != self.debugger.settings['highlight']:
message = colorize('standout', message)
pass
return(self.intf[-1].errmsg(message)) |
def rst_msg(self, text, opts={}):
"""Convert ReStructuredText and run through msg()"""
from trepan.lib.format import rst_text
text = rst_text(text,
'plain' == self.debugger.settings['highlight'],
self.debugger.settings['width'])
return self... |
def dbgr(self, string):
'''Invoke a debugger command from inside a python shell called inside
the debugger.
'''
print('')
self.proc.cmd_queue.append(string)
self.proc.process_command()
return |
def nothread_quit(self, arg):
""" quit command when there's just one thread. """
self.debugger.core.stop()
self.debugger.core.execution_status = 'Quit command'
self.proc.response['event'] = 'terminated'
self.proc.response['name'] = 'status'
self.proc.intf[-1].msg(self.p... |
def parse_addr_list_cmd(proc, args, listsize=40):
"""Parses arguments for the "list" command and returns the tuple:
(filename, first line number, last line number)
or sets these to None if there was some problem."""
text = proc.current_command[len(args[0])+1:].strip()
if text in frozenset(('', '.'... |
def add_ignore(self, *frames_or_fns):
"""Add `frame_or_fn' to the list of functions that are not to
be debugged"""
for frame_or_fn in frames_or_fns:
rc = self.ignore_filter.add_include(frame_or_fn)
pass
return rc |
def canonic(self, filename):
""" Turns `filename' into its canonic representation and returns this
string. This allows a user to refer to a given file in one of several
equivalent ways.
Relative filenames need to be fully resolved, since the current working
directory might chang... |
def filename(self, filename=None):
"""Return filename or the basename of that depending on the
basename setting"""
if filename is None:
if self.debugger.mainpyfile:
filename = self.debugger.mainpyfile
else:
return None
if self.debug... |
def is_started(self):
'''Return True if debugging is in progress.'''
return (tracer.is_started() and
not self.trace_hook_suspend
and tracer.find_hook(self.trace_dispatch)) |
def start(self, opts=None):
""" We've already created a debugger object, but here we start
debugging in earnest. We can also turn off debugging (but have
the hooks suspended or not) using 'stop'.
'opts' is a hash of every known value you might want to set when
starting the debug... |
def is_stop_here(self, frame, event, arg):
""" Does the magic to determine if we stop here and run a
command processor or not. If so, return True and set
self.stop_reason; if not, return False.
Determining factors can be whether a breakpoint was
encountered, whether we are stepp... |
def set_next(self, frame, step_ignore=0, step_events=None):
"Sets to stop on the next event that happens in frame 'frame'."
self.step_events = None # Consider all events
self.stop_level = Mstack.count_frames(frame)
self.last_level = self.stop_level
self.last_fra... |
def trace_dispatch(self, frame, event, arg):
'''A trace event occurred. Filter or pass the information to a
specialized event processor. Note that there may be more filtering
that goes on in the command processor (e.g. to force a
different line). We could put that here, but since that se... |
def stack_trace(self, f):
"""A mini stack trace routine for threads."""
while f:
if (not self.core.ignore_filter.is_included(f)
or self.settings['dbg_trepan']):
s = Mstack.format_stack_entry(self, (f, f.f_lineno))
self.msg(" "*4 + s)
... |
def run(self, args):
"""Get file information"""
if len(args) == 0:
if not self.proc.curframe:
self.errmsg("No frame - no default file.")
return False
filename = self.proc.curframe.f_code.co_filename
else:
filename = args[0]
... |
def run(self, args):
"""**next**[**+**|**-**] [*count*]
Step one statement ignoring steps into function calls at this level.
With an integer argument, perform `next` that many times. However if
an exception occurs at this level, or we *return*, *yield* or the
thread changes, we stop regardless of count.
A su... |
def checkfuncname(b, frame):
"""Check whether we should break here because of `b.funcname`."""
if not b.funcname:
# Breakpoint was set via line number.
if b.line != frame.f_lineno:
# Breakpoint was set at a line with a def statement and the function
# defined is called: d... |
def delete_breakpoint(self, bp):
" remove breakpoint `bp'"
bpnum = bp.number
self.bpbynumber[bpnum] = None # No longer in list
index = (bp.filename, bp.line)
if index not in self.bplist: return False
self.bplist[index].remove(bp)
if not self.bplist[index]:
... |
def delete_breakpoint_by_number(self, bpnum):
"Remove a breakpoint given its breakpoint number."
success, msg, bp = self.get_breakpoint(bpnum)
if not success:
return False, msg
self.delete_breakpoint(bp)
return (True, '') |
def en_disable_all_breakpoints(self, do_enable=True):
"Enable or disable all breakpoints."
bp_list = [bp for bp in self.bpbynumber if bp]
bp_nums = []
if do_enable:
endis = 'en'
else:
endis = 'dis'
pass
if not bp_list:
retu... |
def en_disable_breakpoint_by_number(self, bpnum, do_enable=True):
"Enable or disable a breakpoint given its breakpoint number."
success, msg, bp = self.get_breakpoint(bpnum)
if not success:
return success, msg
if do_enable:
endis = 'en'
else:
e... |
def delete_breakpoints_by_lineno(self, filename, lineno):
"""Removes all breakpoints at a give filename and line number.
Returns a list of breakpoints numbers deleted.
"""
if (filename, lineno) not in self.bplist:
return []
breakpoints = self.bplist[(filename, lineno)... |
def find_bp(self, filename, lineno, frame):
"""Determine which breakpoint for this file:line is to be acted upon.
Called only if we know there is a bpt at this
location. Returns breakpoint that was triggered and a flag
that indicates if it is ok to delete a temporary breakpoint.
... |
def open(self, inp, opts=None):
"""Use this to set what file to read from. """
if isinstance(inp, io.TextIOWrapper):
self.input = inp
elif isinstance(inp, 'string'.__class__): # FIXME
self.name = inp
self.input = open(inp, 'r')
else:
rais... |
def readline(self, prompt='', use_raw=None):
"""Read a line of input. Prompt and use_raw exist to be
compatible with other input routines and are ignored.
EOFError will be raised on EOF.
"""
line = self.input.readline()
if not line: raise EOFError
return line.rstr... |
def confirm(self, prompt, default):
""" Called when a dangerous action is about to be done to make sure
it's okay. `prompt' is printed; user response is returned."""
while True:
try:
self.write_confirm(prompt, default)
reply = self.readline('').strip()... |
def t_whitespace(self, s):
r'\s+'
self.add_token('SPACE', s)
self.pos += len(s)
pass |
def t_single_quote_file(self, s):
r"'[^'].+'"
# Pick out text inside of singe-quoted string
base = s[1:-1]
self.add_token('FILENAME', base)
self.pos += len(s) |
def t_double_quote_file(self, s):
r'"[^"]+"'
# Pick out text inside of singe-quoted string
base = s[1:-1]
self.add_token('FILENAME', base)
self.pos += len(s) |
def t_colon(self, s):
r':'
# Used to separate a filename from a line number
self.add_token('COLON', s)
self.pos += len(s) |
def t_comma(self, s):
r','
# Used in "list" to separate first from last
self.add_token('COMMA', s)
self.pos += len(s) |
def t_direction(self, s):
r'^[+-]$'
# Used in the "list" command
self.add_token('DIRECTION', s)
self.pos += len(s) |
def t_number(self, s):
r'\d+'
pos = self.pos
self.add_token('NUMBER', int(s))
self.pos = pos + len(s) |
def t_offset(self, s):
r'[+]\d+'
pos = self.pos
self.add_token('OFFSET', s)
self.pos = pos + len(s) |
def t_address(self, s):
r'[*]\d+'
pos = self.pos
self.add_token('ADDRESS', s)
self.pos = pos + len(s) |
def extract_concepts(self, sentences=None, ids=None,
composite_phrase=4, filename=None,
file_format='sldi', allow_acronym_variants=False,
word_sense_disambiguation=False, allow_large_n=False,
strict_model=False, relaxed_... |
def extract_concepts(self, sentences=None, ids=None, filename=None,
restrict_to_sts=None, restrict_to_sources=None):
""" extract_concepts takes a list of sentences and ids(optional)
then returns a list of Concept objects extracted via
MetaMapLite.
Su... |
def as_future(self, query):
"""Wrap a `sqlalchemy.orm.query.Query` object into a
`concurrent.futures.Future` so that it can be yielded.
Parameters
----------
query : sqlalchemy.orm.query.Query
SQLAlchemy query object to execute
Returns
-------
... |
def login_as(user, request, store_original_user=True):
"""
Utility function for forcing a login as specific user -- be careful about
calling this carelessly :)
"""
# Save the original user pk before it is replaced in the login method
original_user_pk = request.user.pk
# Find a suitable bac... |
def restore_original_login(request):
"""
Restore an original login session, checking the signed session
"""
original_session = request.session.get(la_settings.USER_SESSION_FLAG)
logout(request)
if not original_session:
return
try:
original_user_pk = signer.unsign(
... |
def _load_module(path):
"""Code to load create user module. Copied off django-browserid."""
i = path.rfind(".")
module, attr = path[:i], path[i + 1 :]
try:
mod = import_module(module)
except ImportError:
raise ImproperlyConfigured("Error importing CAN_LOGIN_AS function: {}".format(... |
def iterate_docs(client, expanded=False, progress=False):
"""
Yield each document in a Luminoso project in turn. Requires a client whose
URL points to a project.
If expanded=True, it will include additional fields that Luminoso added in
its analysis, such as 'terms' and 'vector'.
Otherwise, it... |
def download_docs(client, output_filename=None, expanded=False):
"""
Given a LuminosoClient pointing to a project and a filename to write to,
retrieve all its documents in batches, and write them to a JSON lines
(.jsons) file with one document per line.
"""
if output_filename is None:
# ... |
def _main(argv):
"""
Handle arguments for the 'lumi-download' command.
"""
parser = argparse.ArgumentParser(
description=DESCRIPTION,
formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_argument(
'-b',
'--base-url',
default=URL_BASE,
... |
def transcode(input_filename, output_filename=None, date_format=None):
"""
Convert a JSON or CSV file of input to a JSON stream (.jsons). This
kind of file can be easily uploaded using `luminoso_api.upload`.
"""
if output_filename is None:
# transcode to standard output
output = sys.... |
def transcode_to_stream(input_filename, date_format=None):
"""
Read a JSON or CSV file and convert it into a JSON stream, which will
be saved in an anonymous temp file.
"""
tmp = tempfile.TemporaryFile()
for entry in open_json_or_csv_somehow(input_filename,
... |
def open_json_or_csv_somehow(filename, date_format=None):
"""
Deduce the format of a file, within reason.
- If the filename ends with .csv or .txt, it's csv.
- If the filename ends with .jsons, it's a JSON stream (conveniently the
format we want to output).
- If the filename ends with .json, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.