partition stringclasses 3 values | func_name stringlengths 1 134 | docstring stringlengths 1 46.9k | path stringlengths 4 223 | original_string stringlengths 75 104k | code stringlengths 75 104k | docstring_tokens listlengths 1 1.97k | repo stringlengths 7 55 | language stringclasses 1 value | url stringlengths 87 315 | code_tokens listlengths 19 28.4k | sha stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|
test | ListTB._format_exception_only | Format the exception part of a traceback.
The arguments are the exception type and value such as given by
sys.exc_info()[:2]. The return value is a list of strings, each ending
in a newline. Normally, the list contains a single string; however,
for SyntaxError exceptions, it contains several lines that (when
printed) display detailed information about where the syntax error
occurred. The message indicating which exception occurred is the
always last string in the list.
Also lifted nearly verbatim from traceback.py | environment/lib/python2.7/site-packages/IPython/core/ultratb.py | def _format_exception_only(self, etype, value):
"""Format the exception part of a traceback.
The arguments are the exception type and value such as given by
sys.exc_info()[:2]. The return value is a list of strings, each ending
in a newline. Normally, the list contains a single string; however,
for SyntaxError exceptions, it contains several lines that (when
printed) display detailed information about where the syntax error
occurred. The message indicating which exception occurred is the
always last string in the list.
Also lifted nearly verbatim from traceback.py
"""
have_filedata = False
Colors = self.Colors
list = []
stype = Colors.excName + etype.__name__ + Colors.Normal
if value is None:
# Not sure if this can still happen in Python 2.6 and above
list.append( str(stype) + '\n')
else:
if etype is SyntaxError:
have_filedata = True
#print 'filename is',filename # dbg
if not value.filename: value.filename = "<string>"
list.append('%s File %s"%s"%s, line %s%d%s\n' % \
(Colors.normalEm,
Colors.filenameEm, value.filename, Colors.normalEm,
Colors.linenoEm, value.lineno, Colors.Normal ))
if value.text is not None:
i = 0
while i < len(value.text) and value.text[i].isspace():
i += 1
list.append('%s %s%s\n' % (Colors.line,
value.text.strip(),
Colors.Normal))
if value.offset is not None:
s = ' '
for c in value.text[i:value.offset-1]:
if c.isspace():
s += c
else:
s += ' '
list.append('%s%s^%s\n' % (Colors.caret, s,
Colors.Normal) )
try:
s = value.msg
except Exception:
s = self._some_str(value)
if s:
list.append('%s%s:%s %s\n' % (str(stype), Colors.excName,
Colors.Normal, s))
else:
list.append('%s\n' % str(stype))
# sync with user hooks
if have_filedata:
ipinst = ipapi.get()
if ipinst is not None:
ipinst.hooks.synchronize_with_editor(value.filename, value.lineno, 0)
return list | def _format_exception_only(self, etype, value):
"""Format the exception part of a traceback.
The arguments are the exception type and value such as given by
sys.exc_info()[:2]. The return value is a list of strings, each ending
in a newline. Normally, the list contains a single string; however,
for SyntaxError exceptions, it contains several lines that (when
printed) display detailed information about where the syntax error
occurred. The message indicating which exception occurred is the
always last string in the list.
Also lifted nearly verbatim from traceback.py
"""
have_filedata = False
Colors = self.Colors
list = []
stype = Colors.excName + etype.__name__ + Colors.Normal
if value is None:
# Not sure if this can still happen in Python 2.6 and above
list.append( str(stype) + '\n')
else:
if etype is SyntaxError:
have_filedata = True
#print 'filename is',filename # dbg
if not value.filename: value.filename = "<string>"
list.append('%s File %s"%s"%s, line %s%d%s\n' % \
(Colors.normalEm,
Colors.filenameEm, value.filename, Colors.normalEm,
Colors.linenoEm, value.lineno, Colors.Normal ))
if value.text is not None:
i = 0
while i < len(value.text) and value.text[i].isspace():
i += 1
list.append('%s %s%s\n' % (Colors.line,
value.text.strip(),
Colors.Normal))
if value.offset is not None:
s = ' '
for c in value.text[i:value.offset-1]:
if c.isspace():
s += c
else:
s += ' '
list.append('%s%s^%s\n' % (Colors.caret, s,
Colors.Normal) )
try:
s = value.msg
except Exception:
s = self._some_str(value)
if s:
list.append('%s%s:%s %s\n' % (str(stype), Colors.excName,
Colors.Normal, s))
else:
list.append('%s\n' % str(stype))
# sync with user hooks
if have_filedata:
ipinst = ipapi.get()
if ipinst is not None:
ipinst.hooks.synchronize_with_editor(value.filename, value.lineno, 0)
return list | [
"Format",
"the",
"exception",
"part",
"of",
"a",
"traceback",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/ultratb.py#L544-L607 | [
"def",
"_format_exception_only",
"(",
"self",
",",
"etype",
",",
"value",
")",
":",
"have_filedata",
"=",
"False",
"Colors",
"=",
"self",
".",
"Colors",
"list",
"=",
"[",
"]",
"stype",
"=",
"Colors",
".",
"excName",
"+",
"etype",
".",
"__name__",
"+",
"Colors",
".",
"Normal",
"if",
"value",
"is",
"None",
":",
"# Not sure if this can still happen in Python 2.6 and above",
"list",
".",
"append",
"(",
"str",
"(",
"stype",
")",
"+",
"'\\n'",
")",
"else",
":",
"if",
"etype",
"is",
"SyntaxError",
":",
"have_filedata",
"=",
"True",
"#print 'filename is',filename # dbg",
"if",
"not",
"value",
".",
"filename",
":",
"value",
".",
"filename",
"=",
"\"<string>\"",
"list",
".",
"append",
"(",
"'%s File %s\"%s\"%s, line %s%d%s\\n'",
"%",
"(",
"Colors",
".",
"normalEm",
",",
"Colors",
".",
"filenameEm",
",",
"value",
".",
"filename",
",",
"Colors",
".",
"normalEm",
",",
"Colors",
".",
"linenoEm",
",",
"value",
".",
"lineno",
",",
"Colors",
".",
"Normal",
")",
")",
"if",
"value",
".",
"text",
"is",
"not",
"None",
":",
"i",
"=",
"0",
"while",
"i",
"<",
"len",
"(",
"value",
".",
"text",
")",
"and",
"value",
".",
"text",
"[",
"i",
"]",
".",
"isspace",
"(",
")",
":",
"i",
"+=",
"1",
"list",
".",
"append",
"(",
"'%s %s%s\\n'",
"%",
"(",
"Colors",
".",
"line",
",",
"value",
".",
"text",
".",
"strip",
"(",
")",
",",
"Colors",
".",
"Normal",
")",
")",
"if",
"value",
".",
"offset",
"is",
"not",
"None",
":",
"s",
"=",
"' '",
"for",
"c",
"in",
"value",
".",
"text",
"[",
"i",
":",
"value",
".",
"offset",
"-",
"1",
"]",
":",
"if",
"c",
".",
"isspace",
"(",
")",
":",
"s",
"+=",
"c",
"else",
":",
"s",
"+=",
"' '",
"list",
".",
"append",
"(",
"'%s%s^%s\\n'",
"%",
"(",
"Colors",
".",
"caret",
",",
"s",
",",
"Colors",
".",
"Normal",
")",
")",
"try",
":",
"s",
"=",
"value",
".",
"msg",
"except",
"Exception",
":",
"s",
"=",
"self",
".",
"_some_str",
"(",
"value",
")",
"if",
"s",
":",
"list",
".",
"append",
"(",
"'%s%s:%s %s\\n'",
"%",
"(",
"str",
"(",
"stype",
")",
",",
"Colors",
".",
"excName",
",",
"Colors",
".",
"Normal",
",",
"s",
")",
")",
"else",
":",
"list",
".",
"append",
"(",
"'%s\\n'",
"%",
"str",
"(",
"stype",
")",
")",
"# sync with user hooks",
"if",
"have_filedata",
":",
"ipinst",
"=",
"ipapi",
".",
"get",
"(",
")",
"if",
"ipinst",
"is",
"not",
"None",
":",
"ipinst",
".",
"hooks",
".",
"synchronize_with_editor",
"(",
"value",
".",
"filename",
",",
"value",
".",
"lineno",
",",
"0",
")",
"return",
"list"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | ListTB.show_exception_only | Only print the exception type and message, without a traceback.
Parameters
----------
etype : exception type
value : exception value | environment/lib/python2.7/site-packages/IPython/core/ultratb.py | def show_exception_only(self, etype, evalue):
"""Only print the exception type and message, without a traceback.
Parameters
----------
etype : exception type
value : exception value
"""
# This method needs to use __call__ from *this* class, not the one from
# a subclass whose signature or behavior may be different
ostream = self.ostream
ostream.flush()
ostream.write('\n'.join(self.get_exception_only(etype, evalue)))
ostream.flush() | def show_exception_only(self, etype, evalue):
"""Only print the exception type and message, without a traceback.
Parameters
----------
etype : exception type
value : exception value
"""
# This method needs to use __call__ from *this* class, not the one from
# a subclass whose signature or behavior may be different
ostream = self.ostream
ostream.flush()
ostream.write('\n'.join(self.get_exception_only(etype, evalue)))
ostream.flush() | [
"Only",
"print",
"the",
"exception",
"type",
"and",
"message",
"without",
"a",
"traceback",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/ultratb.py#L620-L633 | [
"def",
"show_exception_only",
"(",
"self",
",",
"etype",
",",
"evalue",
")",
":",
"# This method needs to use __call__ from *this* class, not the one from",
"# a subclass whose signature or behavior may be different",
"ostream",
"=",
"self",
".",
"ostream",
"ostream",
".",
"flush",
"(",
")",
"ostream",
".",
"write",
"(",
"'\\n'",
".",
"join",
"(",
"self",
".",
"get_exception_only",
"(",
"etype",
",",
"evalue",
")",
")",
")",
"ostream",
".",
"flush",
"(",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | VerboseTB.structured_traceback | Return a nice text document describing the traceback. | environment/lib/python2.7/site-packages/IPython/core/ultratb.py | def structured_traceback(self, etype, evalue, etb, tb_offset=None,
context=5):
"""Return a nice text document describing the traceback."""
tb_offset = self.tb_offset if tb_offset is None else tb_offset
# some locals
try:
etype = etype.__name__
except AttributeError:
pass
Colors = self.Colors # just a shorthand + quicker name lookup
ColorsNormal = Colors.Normal # used a lot
col_scheme = self.color_scheme_table.active_scheme_name
indent = ' '*INDENT_SIZE
em_normal = '%s\n%s%s' % (Colors.valEm, indent,ColorsNormal)
undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
exc = '%s%s%s' % (Colors.excName,etype,ColorsNormal)
# some internal-use functions
def text_repr(value):
"""Hopefully pretty robust repr equivalent."""
# this is pretty horrible but should always return *something*
try:
return pydoc.text.repr(value)
except KeyboardInterrupt:
raise
except:
try:
return repr(value)
except KeyboardInterrupt:
raise
except:
try:
# all still in an except block so we catch
# getattr raising
name = getattr(value, '__name__', None)
if name:
# ick, recursion
return text_repr(name)
klass = getattr(value, '__class__', None)
if klass:
return '%s instance' % text_repr(klass)
except KeyboardInterrupt:
raise
except:
return 'UNRECOVERABLE REPR FAILURE'
def eqrepr(value, repr=text_repr): return '=%s' % repr(value)
def nullrepr(value, repr=text_repr): return ''
# meat of the code begins
try:
etype = etype.__name__
except AttributeError:
pass
if self.long_header:
# Header with the exception type, python version, and date
pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
date = time.ctime(time.time())
head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-'*75, ColorsNormal,
exc, ' '*(75-len(str(etype))-len(pyver)),
pyver, date.rjust(75) )
head += "\nA problem occured executing Python code. Here is the sequence of function"\
"\ncalls leading up to the error, with the most recent (innermost) call last."
else:
# Simplified header
head = '%s%s%s\n%s%s' % (Colors.topline, '-'*75, ColorsNormal,exc,
'Traceback (most recent call last)'.\
rjust(75 - len(str(etype)) ) )
frames = []
# Flush cache before calling inspect. This helps alleviate some of the
# problems with python 2.3's inspect.py.
##self.check_cache()
# Drop topmost frames if requested
try:
# Try the default getinnerframes and Alex's: Alex's fixes some
# problems, but it generates empty tracebacks for console errors
# (5 blanks lines) where none should be returned.
#records = inspect.getinnerframes(etb, context)[tb_offset:]
#print 'python records:', records # dbg
records = _fixed_getinnerframes(etb, context, tb_offset)
#print 'alex records:', records # dbg
except:
# FIXME: I've been getting many crash reports from python 2.3
# users, traceable to inspect.py. If I can find a small test-case
# to reproduce this, I should either write a better workaround or
# file a bug report against inspect (if that's the real problem).
# So far, I haven't been able to find an isolated example to
# reproduce the problem.
inspect_error()
traceback.print_exc(file=self.ostream)
info('\nUnfortunately, your original traceback can not be constructed.\n')
return ''
# build some color string templates outside these nested loops
tpl_link = '%s%%s%s' % (Colors.filenameEm,ColorsNormal)
tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
ColorsNormal)
tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
(Colors.vName, Colors.valEm, ColorsNormal)
tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
Colors.vName, ColorsNormal)
tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal)
tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm,Colors.line,
ColorsNormal)
# now, loop over all records printing context and info
abspath = os.path.abspath
for frame, file, lnum, func, lines, index in records:
#print '*** record:',file,lnum,func,lines,index # dbg
if not file:
file = '?'
elif not(file.startswith("<") and file.endswith(">")):
# Guess that filenames like <string> aren't real filenames, so
# don't call abspath on them.
try:
file = abspath(file)
except OSError:
# Not sure if this can still happen: abspath now works with
# file names like <string>
pass
link = tpl_link % file
args, varargs, varkw, locals = inspect.getargvalues(frame)
if func == '?':
call = ''
else:
# Decide whether to include variable details or not
var_repr = self.include_vars and eqrepr or nullrepr
try:
call = tpl_call % (func,inspect.formatargvalues(args,
varargs, varkw,
locals,formatvalue=var_repr))
except KeyError:
# This happens in situations like errors inside generator
# expressions, where local variables are listed in the
# line, but can't be extracted from the frame. I'm not
# 100% sure this isn't actually a bug in inspect itself,
# but since there's no info for us to compute with, the
# best we can do is report the failure and move on. Here
# we must *not* call any traceback construction again,
# because that would mess up use of %debug later on. So we
# simply report the failure and move on. The only
# limitation will be that this frame won't have locals
# listed in the call signature. Quite subtle problem...
# I can't think of a good way to validate this in a unit
# test, but running a script consisting of:
# dict( (k,v.strip()) for (k,v) in range(10) )
# will illustrate the error, if this exception catch is
# disabled.
call = tpl_call_fail % func
# Don't attempt to tokenize binary files.
if file.endswith(('.so', '.pyd', '.dll')):
frames.append('%s %s\n' % (link,call))
continue
elif file.endswith(('.pyc','.pyo')):
# Look up the corresponding source file.
file = pyfile.source_from_cache(file)
def linereader(file=file, lnum=[lnum], getline=linecache.getline):
line = getline(file, lnum[0])
lnum[0] += 1
return line
# Build the list of names on this line of code where the exception
# occurred.
try:
names = []
name_cont = False
for token_type, token, start, end, line in generate_tokens(linereader):
# build composite names
if token_type == tokenize.NAME and token not in keyword.kwlist:
if name_cont:
# Continuation of a dotted name
try:
names[-1].append(token)
except IndexError:
names.append([token])
name_cont = False
else:
# Regular new names. We append everything, the caller
# will be responsible for pruning the list later. It's
# very tricky to try to prune as we go, b/c composite
# names can fool us. The pruning at the end is easy
# to do (or the caller can print a list with repeated
# names if so desired.
names.append([token])
elif token == '.':
name_cont = True
elif token_type == tokenize.NEWLINE:
break
except (IndexError, UnicodeDecodeError):
# signals exit of tokenizer
pass
except tokenize.TokenError,msg:
_m = ("An unexpected error occurred while tokenizing input\n"
"The following traceback may be corrupted or invalid\n"
"The error message is: %s\n" % msg)
error(_m)
# Join composite names (e.g. "dict.fromkeys")
names = ['.'.join(n) for n in names]
# prune names list of duplicates, but keep the right order
unique_names = uniq_stable(names)
# Start loop over vars
lvals = []
if self.include_vars:
for name_full in unique_names:
name_base = name_full.split('.',1)[0]
if name_base in frame.f_code.co_varnames:
if locals.has_key(name_base):
try:
value = repr(eval(name_full,locals))
except:
value = undefined
else:
value = undefined
name = tpl_local_var % name_full
else:
if frame.f_globals.has_key(name_base):
try:
value = repr(eval(name_full,frame.f_globals))
except:
value = undefined
else:
value = undefined
name = tpl_global_var % name_full
lvals.append(tpl_name_val % (name,value))
if lvals:
lvals = '%s%s' % (indent,em_normal.join(lvals))
else:
lvals = ''
level = '%s %s\n' % (link,call)
if index is None:
frames.append(level)
else:
frames.append('%s%s' % (level,''.join(
_format_traceback_lines(lnum,index,lines,Colors,lvals,
col_scheme))))
# Get (safely) a string form of the exception info
try:
etype_str,evalue_str = map(str,(etype,evalue))
except:
# User exception is improperly defined.
etype,evalue = str,sys.exc_info()[:2]
etype_str,evalue_str = map(str,(etype,evalue))
# ... and format it
exception = ['%s%s%s: %s' % (Colors.excName, etype_str,
ColorsNormal, evalue_str)]
if (not py3compat.PY3) and type(evalue) is types.InstanceType:
try:
names = [w for w in dir(evalue) if isinstance(w, basestring)]
except:
# Every now and then, an object with funny inernals blows up
# when dir() is called on it. We do the best we can to report
# the problem and continue
_m = '%sException reporting error (object with broken dir())%s:'
exception.append(_m % (Colors.excName,ColorsNormal))
etype_str,evalue_str = map(str,sys.exc_info()[:2])
exception.append('%s%s%s: %s' % (Colors.excName,etype_str,
ColorsNormal, evalue_str))
names = []
for name in names:
value = text_repr(getattr(evalue, name))
exception.append('\n%s%s = %s' % (indent, name, value))
# vds: >>
if records:
filepath, lnum = records[-1][1:3]
#print "file:", str(file), "linenb", str(lnum) # dbg
filepath = os.path.abspath(filepath)
ipinst = ipapi.get()
if ipinst is not None:
ipinst.hooks.synchronize_with_editor(filepath, lnum, 0)
# vds: <<
# return all our info assembled as a single string
# return '%s\n\n%s\n%s' % (head,'\n'.join(frames),''.join(exception[0]) )
return [head] + frames + [''.join(exception[0])] | def structured_traceback(self, etype, evalue, etb, tb_offset=None,
context=5):
"""Return a nice text document describing the traceback."""
tb_offset = self.tb_offset if tb_offset is None else tb_offset
# some locals
try:
etype = etype.__name__
except AttributeError:
pass
Colors = self.Colors # just a shorthand + quicker name lookup
ColorsNormal = Colors.Normal # used a lot
col_scheme = self.color_scheme_table.active_scheme_name
indent = ' '*INDENT_SIZE
em_normal = '%s\n%s%s' % (Colors.valEm, indent,ColorsNormal)
undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
exc = '%s%s%s' % (Colors.excName,etype,ColorsNormal)
# some internal-use functions
def text_repr(value):
"""Hopefully pretty robust repr equivalent."""
# this is pretty horrible but should always return *something*
try:
return pydoc.text.repr(value)
except KeyboardInterrupt:
raise
except:
try:
return repr(value)
except KeyboardInterrupt:
raise
except:
try:
# all still in an except block so we catch
# getattr raising
name = getattr(value, '__name__', None)
if name:
# ick, recursion
return text_repr(name)
klass = getattr(value, '__class__', None)
if klass:
return '%s instance' % text_repr(klass)
except KeyboardInterrupt:
raise
except:
return 'UNRECOVERABLE REPR FAILURE'
def eqrepr(value, repr=text_repr): return '=%s' % repr(value)
def nullrepr(value, repr=text_repr): return ''
# meat of the code begins
try:
etype = etype.__name__
except AttributeError:
pass
if self.long_header:
# Header with the exception type, python version, and date
pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
date = time.ctime(time.time())
head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-'*75, ColorsNormal,
exc, ' '*(75-len(str(etype))-len(pyver)),
pyver, date.rjust(75) )
head += "\nA problem occured executing Python code. Here is the sequence of function"\
"\ncalls leading up to the error, with the most recent (innermost) call last."
else:
# Simplified header
head = '%s%s%s\n%s%s' % (Colors.topline, '-'*75, ColorsNormal,exc,
'Traceback (most recent call last)'.\
rjust(75 - len(str(etype)) ) )
frames = []
# Flush cache before calling inspect. This helps alleviate some of the
# problems with python 2.3's inspect.py.
##self.check_cache()
# Drop topmost frames if requested
try:
# Try the default getinnerframes and Alex's: Alex's fixes some
# problems, but it generates empty tracebacks for console errors
# (5 blanks lines) where none should be returned.
#records = inspect.getinnerframes(etb, context)[tb_offset:]
#print 'python records:', records # dbg
records = _fixed_getinnerframes(etb, context, tb_offset)
#print 'alex records:', records # dbg
except:
# FIXME: I've been getting many crash reports from python 2.3
# users, traceable to inspect.py. If I can find a small test-case
# to reproduce this, I should either write a better workaround or
# file a bug report against inspect (if that's the real problem).
# So far, I haven't been able to find an isolated example to
# reproduce the problem.
inspect_error()
traceback.print_exc(file=self.ostream)
info('\nUnfortunately, your original traceback can not be constructed.\n')
return ''
# build some color string templates outside these nested loops
tpl_link = '%s%%s%s' % (Colors.filenameEm,ColorsNormal)
tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
ColorsNormal)
tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
(Colors.vName, Colors.valEm, ColorsNormal)
tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
Colors.vName, ColorsNormal)
tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal)
tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm,Colors.line,
ColorsNormal)
# now, loop over all records printing context and info
abspath = os.path.abspath
for frame, file, lnum, func, lines, index in records:
#print '*** record:',file,lnum,func,lines,index # dbg
if not file:
file = '?'
elif not(file.startswith("<") and file.endswith(">")):
# Guess that filenames like <string> aren't real filenames, so
# don't call abspath on them.
try:
file = abspath(file)
except OSError:
# Not sure if this can still happen: abspath now works with
# file names like <string>
pass
link = tpl_link % file
args, varargs, varkw, locals = inspect.getargvalues(frame)
if func == '?':
call = ''
else:
# Decide whether to include variable details or not
var_repr = self.include_vars and eqrepr or nullrepr
try:
call = tpl_call % (func,inspect.formatargvalues(args,
varargs, varkw,
locals,formatvalue=var_repr))
except KeyError:
# This happens in situations like errors inside generator
# expressions, where local variables are listed in the
# line, but can't be extracted from the frame. I'm not
# 100% sure this isn't actually a bug in inspect itself,
# but since there's no info for us to compute with, the
# best we can do is report the failure and move on. Here
# we must *not* call any traceback construction again,
# because that would mess up use of %debug later on. So we
# simply report the failure and move on. The only
# limitation will be that this frame won't have locals
# listed in the call signature. Quite subtle problem...
# I can't think of a good way to validate this in a unit
# test, but running a script consisting of:
# dict( (k,v.strip()) for (k,v) in range(10) )
# will illustrate the error, if this exception catch is
# disabled.
call = tpl_call_fail % func
# Don't attempt to tokenize binary files.
if file.endswith(('.so', '.pyd', '.dll')):
frames.append('%s %s\n' % (link,call))
continue
elif file.endswith(('.pyc','.pyo')):
# Look up the corresponding source file.
file = pyfile.source_from_cache(file)
def linereader(file=file, lnum=[lnum], getline=linecache.getline):
line = getline(file, lnum[0])
lnum[0] += 1
return line
# Build the list of names on this line of code where the exception
# occurred.
try:
names = []
name_cont = False
for token_type, token, start, end, line in generate_tokens(linereader):
# build composite names
if token_type == tokenize.NAME and token not in keyword.kwlist:
if name_cont:
# Continuation of a dotted name
try:
names[-1].append(token)
except IndexError:
names.append([token])
name_cont = False
else:
# Regular new names. We append everything, the caller
# will be responsible for pruning the list later. It's
# very tricky to try to prune as we go, b/c composite
# names can fool us. The pruning at the end is easy
# to do (or the caller can print a list with repeated
# names if so desired.
names.append([token])
elif token == '.':
name_cont = True
elif token_type == tokenize.NEWLINE:
break
except (IndexError, UnicodeDecodeError):
# signals exit of tokenizer
pass
except tokenize.TokenError,msg:
_m = ("An unexpected error occurred while tokenizing input\n"
"The following traceback may be corrupted or invalid\n"
"The error message is: %s\n" % msg)
error(_m)
# Join composite names (e.g. "dict.fromkeys")
names = ['.'.join(n) for n in names]
# prune names list of duplicates, but keep the right order
unique_names = uniq_stable(names)
# Start loop over vars
lvals = []
if self.include_vars:
for name_full in unique_names:
name_base = name_full.split('.',1)[0]
if name_base in frame.f_code.co_varnames:
if locals.has_key(name_base):
try:
value = repr(eval(name_full,locals))
except:
value = undefined
else:
value = undefined
name = tpl_local_var % name_full
else:
if frame.f_globals.has_key(name_base):
try:
value = repr(eval(name_full,frame.f_globals))
except:
value = undefined
else:
value = undefined
name = tpl_global_var % name_full
lvals.append(tpl_name_val % (name,value))
if lvals:
lvals = '%s%s' % (indent,em_normal.join(lvals))
else:
lvals = ''
level = '%s %s\n' % (link,call)
if index is None:
frames.append(level)
else:
frames.append('%s%s' % (level,''.join(
_format_traceback_lines(lnum,index,lines,Colors,lvals,
col_scheme))))
# Get (safely) a string form of the exception info
try:
etype_str,evalue_str = map(str,(etype,evalue))
except:
# User exception is improperly defined.
etype,evalue = str,sys.exc_info()[:2]
etype_str,evalue_str = map(str,(etype,evalue))
# ... and format it
exception = ['%s%s%s: %s' % (Colors.excName, etype_str,
ColorsNormal, evalue_str)]
if (not py3compat.PY3) and type(evalue) is types.InstanceType:
try:
names = [w for w in dir(evalue) if isinstance(w, basestring)]
except:
# Every now and then, an object with funny inernals blows up
# when dir() is called on it. We do the best we can to report
# the problem and continue
_m = '%sException reporting error (object with broken dir())%s:'
exception.append(_m % (Colors.excName,ColorsNormal))
etype_str,evalue_str = map(str,sys.exc_info()[:2])
exception.append('%s%s%s: %s' % (Colors.excName,etype_str,
ColorsNormal, evalue_str))
names = []
for name in names:
value = text_repr(getattr(evalue, name))
exception.append('\n%s%s = %s' % (indent, name, value))
# vds: >>
if records:
filepath, lnum = records[-1][1:3]
#print "file:", str(file), "linenb", str(lnum) # dbg
filepath = os.path.abspath(filepath)
ipinst = ipapi.get()
if ipinst is not None:
ipinst.hooks.synchronize_with_editor(filepath, lnum, 0)
# vds: <<
# return all our info assembled as a single string
# return '%s\n\n%s\n%s' % (head,'\n'.join(frames),''.join(exception[0]) )
return [head] + frames + [''.join(exception[0])] | [
"Return",
"a",
"nice",
"text",
"document",
"describing",
"the",
"traceback",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/ultratb.py#L674-L966 | [
"def",
"structured_traceback",
"(",
"self",
",",
"etype",
",",
"evalue",
",",
"etb",
",",
"tb_offset",
"=",
"None",
",",
"context",
"=",
"5",
")",
":",
"tb_offset",
"=",
"self",
".",
"tb_offset",
"if",
"tb_offset",
"is",
"None",
"else",
"tb_offset",
"# some locals",
"try",
":",
"etype",
"=",
"etype",
".",
"__name__",
"except",
"AttributeError",
":",
"pass",
"Colors",
"=",
"self",
".",
"Colors",
"# just a shorthand + quicker name lookup",
"ColorsNormal",
"=",
"Colors",
".",
"Normal",
"# used a lot",
"col_scheme",
"=",
"self",
".",
"color_scheme_table",
".",
"active_scheme_name",
"indent",
"=",
"' '",
"*",
"INDENT_SIZE",
"em_normal",
"=",
"'%s\\n%s%s'",
"%",
"(",
"Colors",
".",
"valEm",
",",
"indent",
",",
"ColorsNormal",
")",
"undefined",
"=",
"'%sundefined%s'",
"%",
"(",
"Colors",
".",
"em",
",",
"ColorsNormal",
")",
"exc",
"=",
"'%s%s%s'",
"%",
"(",
"Colors",
".",
"excName",
",",
"etype",
",",
"ColorsNormal",
")",
"# some internal-use functions",
"def",
"text_repr",
"(",
"value",
")",
":",
"\"\"\"Hopefully pretty robust repr equivalent.\"\"\"",
"# this is pretty horrible but should always return *something*",
"try",
":",
"return",
"pydoc",
".",
"text",
".",
"repr",
"(",
"value",
")",
"except",
"KeyboardInterrupt",
":",
"raise",
"except",
":",
"try",
":",
"return",
"repr",
"(",
"value",
")",
"except",
"KeyboardInterrupt",
":",
"raise",
"except",
":",
"try",
":",
"# all still in an except block so we catch",
"# getattr raising",
"name",
"=",
"getattr",
"(",
"value",
",",
"'__name__'",
",",
"None",
")",
"if",
"name",
":",
"# ick, recursion",
"return",
"text_repr",
"(",
"name",
")",
"klass",
"=",
"getattr",
"(",
"value",
",",
"'__class__'",
",",
"None",
")",
"if",
"klass",
":",
"return",
"'%s instance'",
"%",
"text_repr",
"(",
"klass",
")",
"except",
"KeyboardInterrupt",
":",
"raise",
"except",
":",
"return",
"'UNRECOVERABLE REPR FAILURE'",
"def",
"eqrepr",
"(",
"value",
",",
"repr",
"=",
"text_repr",
")",
":",
"return",
"'=%s'",
"%",
"repr",
"(",
"value",
")",
"def",
"nullrepr",
"(",
"value",
",",
"repr",
"=",
"text_repr",
")",
":",
"return",
"''",
"# meat of the code begins",
"try",
":",
"etype",
"=",
"etype",
".",
"__name__",
"except",
"AttributeError",
":",
"pass",
"if",
"self",
".",
"long_header",
":",
"# Header with the exception type, python version, and date",
"pyver",
"=",
"'Python '",
"+",
"sys",
".",
"version",
".",
"split",
"(",
")",
"[",
"0",
"]",
"+",
"': '",
"+",
"sys",
".",
"executable",
"date",
"=",
"time",
".",
"ctime",
"(",
"time",
".",
"time",
"(",
")",
")",
"head",
"=",
"'%s%s%s\\n%s%s%s\\n%s'",
"%",
"(",
"Colors",
".",
"topline",
",",
"'-'",
"*",
"75",
",",
"ColorsNormal",
",",
"exc",
",",
"' '",
"*",
"(",
"75",
"-",
"len",
"(",
"str",
"(",
"etype",
")",
")",
"-",
"len",
"(",
"pyver",
")",
")",
",",
"pyver",
",",
"date",
".",
"rjust",
"(",
"75",
")",
")",
"head",
"+=",
"\"\\nA problem occured executing Python code. Here is the sequence of function\"",
"\"\\ncalls leading up to the error, with the most recent (innermost) call last.\"",
"else",
":",
"# Simplified header",
"head",
"=",
"'%s%s%s\\n%s%s'",
"%",
"(",
"Colors",
".",
"topline",
",",
"'-'",
"*",
"75",
",",
"ColorsNormal",
",",
"exc",
",",
"'Traceback (most recent call last)'",
".",
"rjust",
"(",
"75",
"-",
"len",
"(",
"str",
"(",
"etype",
")",
")",
")",
")",
"frames",
"=",
"[",
"]",
"# Flush cache before calling inspect. This helps alleviate some of the",
"# problems with python 2.3's inspect.py.",
"##self.check_cache()",
"# Drop topmost frames if requested",
"try",
":",
"# Try the default getinnerframes and Alex's: Alex's fixes some",
"# problems, but it generates empty tracebacks for console errors",
"# (5 blanks lines) where none should be returned.",
"#records = inspect.getinnerframes(etb, context)[tb_offset:]",
"#print 'python records:', records # dbg",
"records",
"=",
"_fixed_getinnerframes",
"(",
"etb",
",",
"context",
",",
"tb_offset",
")",
"#print 'alex records:', records # dbg",
"except",
":",
"# FIXME: I've been getting many crash reports from python 2.3",
"# users, traceable to inspect.py. If I can find a small test-case",
"# to reproduce this, I should either write a better workaround or",
"# file a bug report against inspect (if that's the real problem).",
"# So far, I haven't been able to find an isolated example to",
"# reproduce the problem.",
"inspect_error",
"(",
")",
"traceback",
".",
"print_exc",
"(",
"file",
"=",
"self",
".",
"ostream",
")",
"info",
"(",
"'\\nUnfortunately, your original traceback can not be constructed.\\n'",
")",
"return",
"''",
"# build some color string templates outside these nested loops",
"tpl_link",
"=",
"'%s%%s%s'",
"%",
"(",
"Colors",
".",
"filenameEm",
",",
"ColorsNormal",
")",
"tpl_call",
"=",
"'in %s%%s%s%%s%s'",
"%",
"(",
"Colors",
".",
"vName",
",",
"Colors",
".",
"valEm",
",",
"ColorsNormal",
")",
"tpl_call_fail",
"=",
"'in %s%%s%s(***failed resolving arguments***)%s'",
"%",
"(",
"Colors",
".",
"vName",
",",
"Colors",
".",
"valEm",
",",
"ColorsNormal",
")",
"tpl_local_var",
"=",
"'%s%%s%s'",
"%",
"(",
"Colors",
".",
"vName",
",",
"ColorsNormal",
")",
"tpl_global_var",
"=",
"'%sglobal%s %s%%s%s'",
"%",
"(",
"Colors",
".",
"em",
",",
"ColorsNormal",
",",
"Colors",
".",
"vName",
",",
"ColorsNormal",
")",
"tpl_name_val",
"=",
"'%%s %s= %%s%s'",
"%",
"(",
"Colors",
".",
"valEm",
",",
"ColorsNormal",
")",
"tpl_line",
"=",
"'%s%%s%s %%s'",
"%",
"(",
"Colors",
".",
"lineno",
",",
"ColorsNormal",
")",
"tpl_line_em",
"=",
"'%s%%s%s %%s%s'",
"%",
"(",
"Colors",
".",
"linenoEm",
",",
"Colors",
".",
"line",
",",
"ColorsNormal",
")",
"# now, loop over all records printing context and info",
"abspath",
"=",
"os",
".",
"path",
".",
"abspath",
"for",
"frame",
",",
"file",
",",
"lnum",
",",
"func",
",",
"lines",
",",
"index",
"in",
"records",
":",
"#print '*** record:',file,lnum,func,lines,index # dbg",
"if",
"not",
"file",
":",
"file",
"=",
"'?'",
"elif",
"not",
"(",
"file",
".",
"startswith",
"(",
"\"<\"",
")",
"and",
"file",
".",
"endswith",
"(",
"\">\"",
")",
")",
":",
"# Guess that filenames like <string> aren't real filenames, so",
"# don't call abspath on them. ",
"try",
":",
"file",
"=",
"abspath",
"(",
"file",
")",
"except",
"OSError",
":",
"# Not sure if this can still happen: abspath now works with",
"# file names like <string>",
"pass",
"link",
"=",
"tpl_link",
"%",
"file",
"args",
",",
"varargs",
",",
"varkw",
",",
"locals",
"=",
"inspect",
".",
"getargvalues",
"(",
"frame",
")",
"if",
"func",
"==",
"'?'",
":",
"call",
"=",
"''",
"else",
":",
"# Decide whether to include variable details or not",
"var_repr",
"=",
"self",
".",
"include_vars",
"and",
"eqrepr",
"or",
"nullrepr",
"try",
":",
"call",
"=",
"tpl_call",
"%",
"(",
"func",
",",
"inspect",
".",
"formatargvalues",
"(",
"args",
",",
"varargs",
",",
"varkw",
",",
"locals",
",",
"formatvalue",
"=",
"var_repr",
")",
")",
"except",
"KeyError",
":",
"# This happens in situations like errors inside generator",
"# expressions, where local variables are listed in the",
"# line, but can't be extracted from the frame. I'm not",
"# 100% sure this isn't actually a bug in inspect itself,",
"# but since there's no info for us to compute with, the",
"# best we can do is report the failure and move on. Here",
"# we must *not* call any traceback construction again,",
"# because that would mess up use of %debug later on. So we",
"# simply report the failure and move on. The only",
"# limitation will be that this frame won't have locals",
"# listed in the call signature. Quite subtle problem...",
"# I can't think of a good way to validate this in a unit",
"# test, but running a script consisting of:",
"# dict( (k,v.strip()) for (k,v) in range(10) )",
"# will illustrate the error, if this exception catch is",
"# disabled.",
"call",
"=",
"tpl_call_fail",
"%",
"func",
"# Don't attempt to tokenize binary files.",
"if",
"file",
".",
"endswith",
"(",
"(",
"'.so'",
",",
"'.pyd'",
",",
"'.dll'",
")",
")",
":",
"frames",
".",
"append",
"(",
"'%s %s\\n'",
"%",
"(",
"link",
",",
"call",
")",
")",
"continue",
"elif",
"file",
".",
"endswith",
"(",
"(",
"'.pyc'",
",",
"'.pyo'",
")",
")",
":",
"# Look up the corresponding source file.",
"file",
"=",
"pyfile",
".",
"source_from_cache",
"(",
"file",
")",
"def",
"linereader",
"(",
"file",
"=",
"file",
",",
"lnum",
"=",
"[",
"lnum",
"]",
",",
"getline",
"=",
"linecache",
".",
"getline",
")",
":",
"line",
"=",
"getline",
"(",
"file",
",",
"lnum",
"[",
"0",
"]",
")",
"lnum",
"[",
"0",
"]",
"+=",
"1",
"return",
"line",
"# Build the list of names on this line of code where the exception",
"# occurred.",
"try",
":",
"names",
"=",
"[",
"]",
"name_cont",
"=",
"False",
"for",
"token_type",
",",
"token",
",",
"start",
",",
"end",
",",
"line",
"in",
"generate_tokens",
"(",
"linereader",
")",
":",
"# build composite names",
"if",
"token_type",
"==",
"tokenize",
".",
"NAME",
"and",
"token",
"not",
"in",
"keyword",
".",
"kwlist",
":",
"if",
"name_cont",
":",
"# Continuation of a dotted name",
"try",
":",
"names",
"[",
"-",
"1",
"]",
".",
"append",
"(",
"token",
")",
"except",
"IndexError",
":",
"names",
".",
"append",
"(",
"[",
"token",
"]",
")",
"name_cont",
"=",
"False",
"else",
":",
"# Regular new names. We append everything, the caller",
"# will be responsible for pruning the list later. It's",
"# very tricky to try to prune as we go, b/c composite",
"# names can fool us. The pruning at the end is easy",
"# to do (or the caller can print a list with repeated",
"# names if so desired.",
"names",
".",
"append",
"(",
"[",
"token",
"]",
")",
"elif",
"token",
"==",
"'.'",
":",
"name_cont",
"=",
"True",
"elif",
"token_type",
"==",
"tokenize",
".",
"NEWLINE",
":",
"break",
"except",
"(",
"IndexError",
",",
"UnicodeDecodeError",
")",
":",
"# signals exit of tokenizer",
"pass",
"except",
"tokenize",
".",
"TokenError",
",",
"msg",
":",
"_m",
"=",
"(",
"\"An unexpected error occurred while tokenizing input\\n\"",
"\"The following traceback may be corrupted or invalid\\n\"",
"\"The error message is: %s\\n\"",
"%",
"msg",
")",
"error",
"(",
"_m",
")",
"# Join composite names (e.g. \"dict.fromkeys\")",
"names",
"=",
"[",
"'.'",
".",
"join",
"(",
"n",
")",
"for",
"n",
"in",
"names",
"]",
"# prune names list of duplicates, but keep the right order",
"unique_names",
"=",
"uniq_stable",
"(",
"names",
")",
"# Start loop over vars",
"lvals",
"=",
"[",
"]",
"if",
"self",
".",
"include_vars",
":",
"for",
"name_full",
"in",
"unique_names",
":",
"name_base",
"=",
"name_full",
".",
"split",
"(",
"'.'",
",",
"1",
")",
"[",
"0",
"]",
"if",
"name_base",
"in",
"frame",
".",
"f_code",
".",
"co_varnames",
":",
"if",
"locals",
".",
"has_key",
"(",
"name_base",
")",
":",
"try",
":",
"value",
"=",
"repr",
"(",
"eval",
"(",
"name_full",
",",
"locals",
")",
")",
"except",
":",
"value",
"=",
"undefined",
"else",
":",
"value",
"=",
"undefined",
"name",
"=",
"tpl_local_var",
"%",
"name_full",
"else",
":",
"if",
"frame",
".",
"f_globals",
".",
"has_key",
"(",
"name_base",
")",
":",
"try",
":",
"value",
"=",
"repr",
"(",
"eval",
"(",
"name_full",
",",
"frame",
".",
"f_globals",
")",
")",
"except",
":",
"value",
"=",
"undefined",
"else",
":",
"value",
"=",
"undefined",
"name",
"=",
"tpl_global_var",
"%",
"name_full",
"lvals",
".",
"append",
"(",
"tpl_name_val",
"%",
"(",
"name",
",",
"value",
")",
")",
"if",
"lvals",
":",
"lvals",
"=",
"'%s%s'",
"%",
"(",
"indent",
",",
"em_normal",
".",
"join",
"(",
"lvals",
")",
")",
"else",
":",
"lvals",
"=",
"''",
"level",
"=",
"'%s %s\\n'",
"%",
"(",
"link",
",",
"call",
")",
"if",
"index",
"is",
"None",
":",
"frames",
".",
"append",
"(",
"level",
")",
"else",
":",
"frames",
".",
"append",
"(",
"'%s%s'",
"%",
"(",
"level",
",",
"''",
".",
"join",
"(",
"_format_traceback_lines",
"(",
"lnum",
",",
"index",
",",
"lines",
",",
"Colors",
",",
"lvals",
",",
"col_scheme",
")",
")",
")",
")",
"# Get (safely) a string form of the exception info",
"try",
":",
"etype_str",
",",
"evalue_str",
"=",
"map",
"(",
"str",
",",
"(",
"etype",
",",
"evalue",
")",
")",
"except",
":",
"# User exception is improperly defined.",
"etype",
",",
"evalue",
"=",
"str",
",",
"sys",
".",
"exc_info",
"(",
")",
"[",
":",
"2",
"]",
"etype_str",
",",
"evalue_str",
"=",
"map",
"(",
"str",
",",
"(",
"etype",
",",
"evalue",
")",
")",
"# ... and format it",
"exception",
"=",
"[",
"'%s%s%s: %s'",
"%",
"(",
"Colors",
".",
"excName",
",",
"etype_str",
",",
"ColorsNormal",
",",
"evalue_str",
")",
"]",
"if",
"(",
"not",
"py3compat",
".",
"PY3",
")",
"and",
"type",
"(",
"evalue",
")",
"is",
"types",
".",
"InstanceType",
":",
"try",
":",
"names",
"=",
"[",
"w",
"for",
"w",
"in",
"dir",
"(",
"evalue",
")",
"if",
"isinstance",
"(",
"w",
",",
"basestring",
")",
"]",
"except",
":",
"# Every now and then, an object with funny inernals blows up",
"# when dir() is called on it. We do the best we can to report",
"# the problem and continue",
"_m",
"=",
"'%sException reporting error (object with broken dir())%s:'",
"exception",
".",
"append",
"(",
"_m",
"%",
"(",
"Colors",
".",
"excName",
",",
"ColorsNormal",
")",
")",
"etype_str",
",",
"evalue_str",
"=",
"map",
"(",
"str",
",",
"sys",
".",
"exc_info",
"(",
")",
"[",
":",
"2",
"]",
")",
"exception",
".",
"append",
"(",
"'%s%s%s: %s'",
"%",
"(",
"Colors",
".",
"excName",
",",
"etype_str",
",",
"ColorsNormal",
",",
"evalue_str",
")",
")",
"names",
"=",
"[",
"]",
"for",
"name",
"in",
"names",
":",
"value",
"=",
"text_repr",
"(",
"getattr",
"(",
"evalue",
",",
"name",
")",
")",
"exception",
".",
"append",
"(",
"'\\n%s%s = %s'",
"%",
"(",
"indent",
",",
"name",
",",
"value",
")",
")",
"# vds: >>",
"if",
"records",
":",
"filepath",
",",
"lnum",
"=",
"records",
"[",
"-",
"1",
"]",
"[",
"1",
":",
"3",
"]",
"#print \"file:\", str(file), \"linenb\", str(lnum) # dbg",
"filepath",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"filepath",
")",
"ipinst",
"=",
"ipapi",
".",
"get",
"(",
")",
"if",
"ipinst",
"is",
"not",
"None",
":",
"ipinst",
".",
"hooks",
".",
"synchronize_with_editor",
"(",
"filepath",
",",
"lnum",
",",
"0",
")",
"# vds: <<",
"# return all our info assembled as a single string",
"# return '%s\\n\\n%s\\n%s' % (head,'\\n'.join(frames),''.join(exception[0]) )",
"return",
"[",
"head",
"]",
"+",
"frames",
"+",
"[",
"''",
".",
"join",
"(",
"exception",
"[",
"0",
"]",
")",
"]"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | VerboseTB.debugger | Call up the pdb debugger if desired, always clean up the tb
reference.
Keywords:
- force(False): by default, this routine checks the instance call_pdb
flag and does not actually invoke the debugger if the flag is false.
The 'force' option forces the debugger to activate even if the flag
is false.
If the call_pdb flag is set, the pdb interactive debugger is
invoked. In all cases, the self.tb reference to the current traceback
is deleted to prevent lingering references which hamper memory
management.
Note that each call to pdb() does an 'import readline', so if your app
requires a special setup for the readline completers, you'll have to
fix that by hand after invoking the exception handler. | environment/lib/python2.7/site-packages/IPython/core/ultratb.py | def debugger(self,force=False):
"""Call up the pdb debugger if desired, always clean up the tb
reference.
Keywords:
- force(False): by default, this routine checks the instance call_pdb
flag and does not actually invoke the debugger if the flag is false.
The 'force' option forces the debugger to activate even if the flag
is false.
If the call_pdb flag is set, the pdb interactive debugger is
invoked. In all cases, the self.tb reference to the current traceback
is deleted to prevent lingering references which hamper memory
management.
Note that each call to pdb() does an 'import readline', so if your app
requires a special setup for the readline completers, you'll have to
fix that by hand after invoking the exception handler."""
if force or self.call_pdb:
if self.pdb is None:
self.pdb = debugger.Pdb(
self.color_scheme_table.active_scheme_name)
# the system displayhook may have changed, restore the original
# for pdb
display_trap = DisplayTrap(hook=sys.__displayhook__)
with display_trap:
self.pdb.reset()
# Find the right frame so we don't pop up inside ipython itself
if hasattr(self,'tb') and self.tb is not None:
etb = self.tb
else:
etb = self.tb = sys.last_traceback
while self.tb is not None and self.tb.tb_next is not None:
self.tb = self.tb.tb_next
if etb and etb.tb_next:
etb = etb.tb_next
self.pdb.botframe = etb.tb_frame
self.pdb.interaction(self.tb.tb_frame, self.tb)
if hasattr(self,'tb'):
del self.tb | def debugger(self,force=False):
"""Call up the pdb debugger if desired, always clean up the tb
reference.
Keywords:
- force(False): by default, this routine checks the instance call_pdb
flag and does not actually invoke the debugger if the flag is false.
The 'force' option forces the debugger to activate even if the flag
is false.
If the call_pdb flag is set, the pdb interactive debugger is
invoked. In all cases, the self.tb reference to the current traceback
is deleted to prevent lingering references which hamper memory
management.
Note that each call to pdb() does an 'import readline', so if your app
requires a special setup for the readline completers, you'll have to
fix that by hand after invoking the exception handler."""
if force or self.call_pdb:
if self.pdb is None:
self.pdb = debugger.Pdb(
self.color_scheme_table.active_scheme_name)
# the system displayhook may have changed, restore the original
# for pdb
display_trap = DisplayTrap(hook=sys.__displayhook__)
with display_trap:
self.pdb.reset()
# Find the right frame so we don't pop up inside ipython itself
if hasattr(self,'tb') and self.tb is not None:
etb = self.tb
else:
etb = self.tb = sys.last_traceback
while self.tb is not None and self.tb.tb_next is not None:
self.tb = self.tb.tb_next
if etb and etb.tb_next:
etb = etb.tb_next
self.pdb.botframe = etb.tb_frame
self.pdb.interaction(self.tb.tb_frame, self.tb)
if hasattr(self,'tb'):
del self.tb | [
"Call",
"up",
"the",
"pdb",
"debugger",
"if",
"desired",
"always",
"clean",
"up",
"the",
"tb",
"reference",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/ultratb.py#L968-L1010 | [
"def",
"debugger",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"if",
"force",
"or",
"self",
".",
"call_pdb",
":",
"if",
"self",
".",
"pdb",
"is",
"None",
":",
"self",
".",
"pdb",
"=",
"debugger",
".",
"Pdb",
"(",
"self",
".",
"color_scheme_table",
".",
"active_scheme_name",
")",
"# the system displayhook may have changed, restore the original",
"# for pdb",
"display_trap",
"=",
"DisplayTrap",
"(",
"hook",
"=",
"sys",
".",
"__displayhook__",
")",
"with",
"display_trap",
":",
"self",
".",
"pdb",
".",
"reset",
"(",
")",
"# Find the right frame so we don't pop up inside ipython itself",
"if",
"hasattr",
"(",
"self",
",",
"'tb'",
")",
"and",
"self",
".",
"tb",
"is",
"not",
"None",
":",
"etb",
"=",
"self",
".",
"tb",
"else",
":",
"etb",
"=",
"self",
".",
"tb",
"=",
"sys",
".",
"last_traceback",
"while",
"self",
".",
"tb",
"is",
"not",
"None",
"and",
"self",
".",
"tb",
".",
"tb_next",
"is",
"not",
"None",
":",
"self",
".",
"tb",
"=",
"self",
".",
"tb",
".",
"tb_next",
"if",
"etb",
"and",
"etb",
".",
"tb_next",
":",
"etb",
"=",
"etb",
".",
"tb_next",
"self",
".",
"pdb",
".",
"botframe",
"=",
"etb",
".",
"tb_frame",
"self",
".",
"pdb",
".",
"interaction",
"(",
"self",
".",
"tb",
".",
"tb_frame",
",",
"self",
".",
"tb",
")",
"if",
"hasattr",
"(",
"self",
",",
"'tb'",
")",
":",
"del",
"self",
".",
"tb"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | FormattedTB.set_mode | Switch to the desired mode.
If mode is not specified, cycles through the available modes. | environment/lib/python2.7/site-packages/IPython/core/ultratb.py | def set_mode(self,mode=None):
"""Switch to the desired mode.
If mode is not specified, cycles through the available modes."""
if not mode:
new_idx = ( self.valid_modes.index(self.mode) + 1 ) % \
len(self.valid_modes)
self.mode = self.valid_modes[new_idx]
elif mode not in self.valid_modes:
raise ValueError, 'Unrecognized mode in FormattedTB: <'+mode+'>\n'\
'Valid modes: '+str(self.valid_modes)
else:
self.mode = mode
# include variable details only in 'Verbose' mode
self.include_vars = (self.mode == self.valid_modes[2])
# Set the join character for generating text tracebacks
self.tb_join_char = self._join_chars[self.mode] | def set_mode(self,mode=None):
"""Switch to the desired mode.
If mode is not specified, cycles through the available modes."""
if not mode:
new_idx = ( self.valid_modes.index(self.mode) + 1 ) % \
len(self.valid_modes)
self.mode = self.valid_modes[new_idx]
elif mode not in self.valid_modes:
raise ValueError, 'Unrecognized mode in FormattedTB: <'+mode+'>\n'\
'Valid modes: '+str(self.valid_modes)
else:
self.mode = mode
# include variable details only in 'Verbose' mode
self.include_vars = (self.mode == self.valid_modes[2])
# Set the join character for generating text tracebacks
self.tb_join_char = self._join_chars[self.mode] | [
"Switch",
"to",
"the",
"desired",
"mode",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/ultratb.py#L1096-L1113 | [
"def",
"set_mode",
"(",
"self",
",",
"mode",
"=",
"None",
")",
":",
"if",
"not",
"mode",
":",
"new_idx",
"=",
"(",
"self",
".",
"valid_modes",
".",
"index",
"(",
"self",
".",
"mode",
")",
"+",
"1",
")",
"%",
"len",
"(",
"self",
".",
"valid_modes",
")",
"self",
".",
"mode",
"=",
"self",
".",
"valid_modes",
"[",
"new_idx",
"]",
"elif",
"mode",
"not",
"in",
"self",
".",
"valid_modes",
":",
"raise",
"ValueError",
",",
"'Unrecognized mode in FormattedTB: <'",
"+",
"mode",
"+",
"'>\\n'",
"'Valid modes: '",
"+",
"str",
"(",
"self",
".",
"valid_modes",
")",
"else",
":",
"self",
".",
"mode",
"=",
"mode",
"# include variable details only in 'Verbose' mode",
"self",
".",
"include_vars",
"=",
"(",
"self",
".",
"mode",
"==",
"self",
".",
"valid_modes",
"[",
"2",
"]",
")",
"# Set the join character for generating text tracebacks",
"self",
".",
"tb_join_char",
"=",
"self",
".",
"_join_chars",
"[",
"self",
".",
"mode",
"]"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | group_required | View decorator for requiring a user group. | django_baseline/decorators.py | def group_required(group,
login_url=None,
redirect_field_name=REDIRECT_FIELD_NAME,
skip_superuser=True):
"""
View decorator for requiring a user group.
"""
def decorator(view_func):
@login_required(redirect_field_name=redirect_field_name,
login_url=login_url)
def _wrapped_view(request, *args, **kwargs):
if not (request.user.is_superuser and skip_superuser):
if request.user.groups.filter(name=group).count() == 0:
raise PermissionDenied
return view_func(request, *args, **kwargs)
return _wrapped_view
return decorator | def group_required(group,
login_url=None,
redirect_field_name=REDIRECT_FIELD_NAME,
skip_superuser=True):
"""
View decorator for requiring a user group.
"""
def decorator(view_func):
@login_required(redirect_field_name=redirect_field_name,
login_url=login_url)
def _wrapped_view(request, *args, **kwargs):
if not (request.user.is_superuser and skip_superuser):
if request.user.groups.filter(name=group).count() == 0:
raise PermissionDenied
return view_func(request, *args, **kwargs)
return _wrapped_view
return decorator | [
"View",
"decorator",
"for",
"requiring",
"a",
"user",
"group",
"."
] | theduke/django-baseline | python | https://github.com/theduke/django-baseline/blob/7be8b956e53c70b35f34e1783a8fe8f716955afb/django_baseline/decorators.py#L7-L26 | [
"def",
"group_required",
"(",
"group",
",",
"login_url",
"=",
"None",
",",
"redirect_field_name",
"=",
"REDIRECT_FIELD_NAME",
",",
"skip_superuser",
"=",
"True",
")",
":",
"def",
"decorator",
"(",
"view_func",
")",
":",
"@",
"login_required",
"(",
"redirect_field_name",
"=",
"redirect_field_name",
",",
"login_url",
"=",
"login_url",
")",
"def",
"_wrapped_view",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"(",
"request",
".",
"user",
".",
"is_superuser",
"and",
"skip_superuser",
")",
":",
"if",
"request",
".",
"user",
".",
"groups",
".",
"filter",
"(",
"name",
"=",
"group",
")",
".",
"count",
"(",
")",
"==",
"0",
":",
"raise",
"PermissionDenied",
"return",
"view_func",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"_wrapped_view",
"return",
"decorator"
] | 7be8b956e53c70b35f34e1783a8fe8f716955afb |
test | get_parent | parent, name = get_parent(globals, level)
Return the package that an import is being performed in. If globals comes
from the module foo.bar.bat (not itself a package), this returns the
sys.modules entry for foo.bar. If globals is from a package's __init__.py,
the package's entry in sys.modules is returned.
If globals doesn't come from a package or a module in a package, or a
corresponding entry is not found in sys.modules, None is returned. | environment/lib/python2.7/site-packages/IPython/lib/deepreload.py | def get_parent(globals, level):
"""
parent, name = get_parent(globals, level)
Return the package that an import is being performed in. If globals comes
from the module foo.bar.bat (not itself a package), this returns the
sys.modules entry for foo.bar. If globals is from a package's __init__.py,
the package's entry in sys.modules is returned.
If globals doesn't come from a package or a module in a package, or a
corresponding entry is not found in sys.modules, None is returned.
"""
orig_level = level
if not level or not isinstance(globals, dict):
return None, ''
pkgname = globals.get('__package__', None)
if pkgname is not None:
# __package__ is set, so use it
if not hasattr(pkgname, 'rindex'):
raise ValueError('__package__ set to non-string')
if len(pkgname) == 0:
if level > 0:
raise ValueError('Attempted relative import in non-package')
return None, ''
name = pkgname
else:
# __package__ not set, so figure it out and set it
if '__name__' not in globals:
return None, ''
modname = globals['__name__']
if '__path__' in globals:
# __path__ is set, so modname is already the package name
globals['__package__'] = name = modname
else:
# Normal module, so work out the package name if any
lastdot = modname.rfind('.')
if lastdot < 0 and level > 0:
raise ValueError("Attempted relative import in non-package")
if lastdot < 0:
globals['__package__'] = None
return None, ''
globals['__package__'] = name = modname[:lastdot]
dot = len(name)
for x in xrange(level, 1, -1):
try:
dot = name.rindex('.', 0, dot)
except ValueError:
raise ValueError("attempted relative import beyond top-level "
"package")
name = name[:dot]
try:
parent = sys.modules[name]
except:
if orig_level < 1:
warn("Parent module '%.200s' not found while handling absolute "
"import" % name)
parent = None
else:
raise SystemError("Parent module '%.200s' not loaded, cannot "
"perform relative import" % name)
# We expect, but can't guarantee, if parent != None, that:
# - parent.__name__ == name
# - parent.__dict__ is globals
# If this is violated... Who cares?
return parent, name | def get_parent(globals, level):
"""
parent, name = get_parent(globals, level)
Return the package that an import is being performed in. If globals comes
from the module foo.bar.bat (not itself a package), this returns the
sys.modules entry for foo.bar. If globals is from a package's __init__.py,
the package's entry in sys.modules is returned.
If globals doesn't come from a package or a module in a package, or a
corresponding entry is not found in sys.modules, None is returned.
"""
orig_level = level
if not level or not isinstance(globals, dict):
return None, ''
pkgname = globals.get('__package__', None)
if pkgname is not None:
# __package__ is set, so use it
if not hasattr(pkgname, 'rindex'):
raise ValueError('__package__ set to non-string')
if len(pkgname) == 0:
if level > 0:
raise ValueError('Attempted relative import in non-package')
return None, ''
name = pkgname
else:
# __package__ not set, so figure it out and set it
if '__name__' not in globals:
return None, ''
modname = globals['__name__']
if '__path__' in globals:
# __path__ is set, so modname is already the package name
globals['__package__'] = name = modname
else:
# Normal module, so work out the package name if any
lastdot = modname.rfind('.')
if lastdot < 0 and level > 0:
raise ValueError("Attempted relative import in non-package")
if lastdot < 0:
globals['__package__'] = None
return None, ''
globals['__package__'] = name = modname[:lastdot]
dot = len(name)
for x in xrange(level, 1, -1):
try:
dot = name.rindex('.', 0, dot)
except ValueError:
raise ValueError("attempted relative import beyond top-level "
"package")
name = name[:dot]
try:
parent = sys.modules[name]
except:
if orig_level < 1:
warn("Parent module '%.200s' not found while handling absolute "
"import" % name)
parent = None
else:
raise SystemError("Parent module '%.200s' not loaded, cannot "
"perform relative import" % name)
# We expect, but can't guarantee, if parent != None, that:
# - parent.__name__ == name
# - parent.__dict__ is globals
# If this is violated... Who cares?
return parent, name | [
"parent",
"name",
"=",
"get_parent",
"(",
"globals",
"level",
")"
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/lib/deepreload.py#L46-L117 | [
"def",
"get_parent",
"(",
"globals",
",",
"level",
")",
":",
"orig_level",
"=",
"level",
"if",
"not",
"level",
"or",
"not",
"isinstance",
"(",
"globals",
",",
"dict",
")",
":",
"return",
"None",
",",
"''",
"pkgname",
"=",
"globals",
".",
"get",
"(",
"'__package__'",
",",
"None",
")",
"if",
"pkgname",
"is",
"not",
"None",
":",
"# __package__ is set, so use it",
"if",
"not",
"hasattr",
"(",
"pkgname",
",",
"'rindex'",
")",
":",
"raise",
"ValueError",
"(",
"'__package__ set to non-string'",
")",
"if",
"len",
"(",
"pkgname",
")",
"==",
"0",
":",
"if",
"level",
">",
"0",
":",
"raise",
"ValueError",
"(",
"'Attempted relative import in non-package'",
")",
"return",
"None",
",",
"''",
"name",
"=",
"pkgname",
"else",
":",
"# __package__ not set, so figure it out and set it",
"if",
"'__name__'",
"not",
"in",
"globals",
":",
"return",
"None",
",",
"''",
"modname",
"=",
"globals",
"[",
"'__name__'",
"]",
"if",
"'__path__'",
"in",
"globals",
":",
"# __path__ is set, so modname is already the package name",
"globals",
"[",
"'__package__'",
"]",
"=",
"name",
"=",
"modname",
"else",
":",
"# Normal module, so work out the package name if any",
"lastdot",
"=",
"modname",
".",
"rfind",
"(",
"'.'",
")",
"if",
"lastdot",
"<",
"0",
"and",
"level",
">",
"0",
":",
"raise",
"ValueError",
"(",
"\"Attempted relative import in non-package\"",
")",
"if",
"lastdot",
"<",
"0",
":",
"globals",
"[",
"'__package__'",
"]",
"=",
"None",
"return",
"None",
",",
"''",
"globals",
"[",
"'__package__'",
"]",
"=",
"name",
"=",
"modname",
"[",
":",
"lastdot",
"]",
"dot",
"=",
"len",
"(",
"name",
")",
"for",
"x",
"in",
"xrange",
"(",
"level",
",",
"1",
",",
"-",
"1",
")",
":",
"try",
":",
"dot",
"=",
"name",
".",
"rindex",
"(",
"'.'",
",",
"0",
",",
"dot",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"\"attempted relative import beyond top-level \"",
"\"package\"",
")",
"name",
"=",
"name",
"[",
":",
"dot",
"]",
"try",
":",
"parent",
"=",
"sys",
".",
"modules",
"[",
"name",
"]",
"except",
":",
"if",
"orig_level",
"<",
"1",
":",
"warn",
"(",
"\"Parent module '%.200s' not found while handling absolute \"",
"\"import\"",
"%",
"name",
")",
"parent",
"=",
"None",
"else",
":",
"raise",
"SystemError",
"(",
"\"Parent module '%.200s' not loaded, cannot \"",
"\"perform relative import\"",
"%",
"name",
")",
"# We expect, but can't guarantee, if parent != None, that:",
"# - parent.__name__ == name",
"# - parent.__dict__ is globals",
"# If this is violated... Who cares?",
"return",
"parent",
",",
"name"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | load_next | mod, name, buf = load_next(mod, altmod, name, buf)
altmod is either None or same as mod | environment/lib/python2.7/site-packages/IPython/lib/deepreload.py | def load_next(mod, altmod, name, buf):
"""
mod, name, buf = load_next(mod, altmod, name, buf)
altmod is either None or same as mod
"""
if len(name) == 0:
# completely empty module name should only happen in
# 'from . import' (or '__import__("")')
return mod, None, buf
dot = name.find('.')
if dot == 0:
raise ValueError('Empty module name')
if dot < 0:
subname = name
next = None
else:
subname = name[:dot]
next = name[dot+1:]
if buf != '':
buf += '.'
buf += subname
result = import_submodule(mod, subname, buf)
if result is None and mod != altmod:
result = import_submodule(altmod, subname, subname)
if result is not None:
buf = subname
if result is None:
raise ImportError("No module named %.200s" % name)
return result, next, buf | def load_next(mod, altmod, name, buf):
"""
mod, name, buf = load_next(mod, altmod, name, buf)
altmod is either None or same as mod
"""
if len(name) == 0:
# completely empty module name should only happen in
# 'from . import' (or '__import__("")')
return mod, None, buf
dot = name.find('.')
if dot == 0:
raise ValueError('Empty module name')
if dot < 0:
subname = name
next = None
else:
subname = name[:dot]
next = name[dot+1:]
if buf != '':
buf += '.'
buf += subname
result = import_submodule(mod, subname, buf)
if result is None and mod != altmod:
result = import_submodule(altmod, subname, subname)
if result is not None:
buf = subname
if result is None:
raise ImportError("No module named %.200s" % name)
return result, next, buf | [
"mod",
"name",
"buf",
"=",
"load_next",
"(",
"mod",
"altmod",
"name",
"buf",
")"
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/lib/deepreload.py#L119-L155 | [
"def",
"load_next",
"(",
"mod",
",",
"altmod",
",",
"name",
",",
"buf",
")",
":",
"if",
"len",
"(",
"name",
")",
"==",
"0",
":",
"# completely empty module name should only happen in",
"# 'from . import' (or '__import__(\"\")')",
"return",
"mod",
",",
"None",
",",
"buf",
"dot",
"=",
"name",
".",
"find",
"(",
"'.'",
")",
"if",
"dot",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"'Empty module name'",
")",
"if",
"dot",
"<",
"0",
":",
"subname",
"=",
"name",
"next",
"=",
"None",
"else",
":",
"subname",
"=",
"name",
"[",
":",
"dot",
"]",
"next",
"=",
"name",
"[",
"dot",
"+",
"1",
":",
"]",
"if",
"buf",
"!=",
"''",
":",
"buf",
"+=",
"'.'",
"buf",
"+=",
"subname",
"result",
"=",
"import_submodule",
"(",
"mod",
",",
"subname",
",",
"buf",
")",
"if",
"result",
"is",
"None",
"and",
"mod",
"!=",
"altmod",
":",
"result",
"=",
"import_submodule",
"(",
"altmod",
",",
"subname",
",",
"subname",
")",
"if",
"result",
"is",
"not",
"None",
":",
"buf",
"=",
"subname",
"if",
"result",
"is",
"None",
":",
"raise",
"ImportError",
"(",
"\"No module named %.200s\"",
"%",
"name",
")",
"return",
"result",
",",
"next",
",",
"buf"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | import_submodule | m = import_submodule(mod, subname, fullname) | environment/lib/python2.7/site-packages/IPython/lib/deepreload.py | def import_submodule(mod, subname, fullname):
"""m = import_submodule(mod, subname, fullname)"""
# Require:
# if mod == None: subname == fullname
# else: mod.__name__ + "." + subname == fullname
global found_now
if fullname in found_now and fullname in sys.modules:
m = sys.modules[fullname]
else:
print 'Reloading', fullname
found_now[fullname] = 1
oldm = sys.modules.get(fullname, None)
if mod is None:
path = None
elif hasattr(mod, '__path__'):
path = mod.__path__
else:
return None
try:
# This appears to be necessary on Python 3, because imp.find_module()
# tries to import standard libraries (like io) itself, and we don't
# want them to be processed by our deep_import_hook.
with replace_import_hook(original_import):
fp, filename, stuff = imp.find_module(subname, path)
except ImportError:
return None
try:
m = imp.load_module(fullname, fp, filename, stuff)
except:
# load_module probably removed name from modules because of
# the error. Put back the original module object.
if oldm:
sys.modules[fullname] = oldm
raise
finally:
if fp: fp.close()
add_submodule(mod, m, fullname, subname)
return m | def import_submodule(mod, subname, fullname):
"""m = import_submodule(mod, subname, fullname)"""
# Require:
# if mod == None: subname == fullname
# else: mod.__name__ + "." + subname == fullname
global found_now
if fullname in found_now and fullname in sys.modules:
m = sys.modules[fullname]
else:
print 'Reloading', fullname
found_now[fullname] = 1
oldm = sys.modules.get(fullname, None)
if mod is None:
path = None
elif hasattr(mod, '__path__'):
path = mod.__path__
else:
return None
try:
# This appears to be necessary on Python 3, because imp.find_module()
# tries to import standard libraries (like io) itself, and we don't
# want them to be processed by our deep_import_hook.
with replace_import_hook(original_import):
fp, filename, stuff = imp.find_module(subname, path)
except ImportError:
return None
try:
m = imp.load_module(fullname, fp, filename, stuff)
except:
# load_module probably removed name from modules because of
# the error. Put back the original module object.
if oldm:
sys.modules[fullname] = oldm
raise
finally:
if fp: fp.close()
add_submodule(mod, m, fullname, subname)
return m | [
"m",
"=",
"import_submodule",
"(",
"mod",
"subname",
"fullname",
")"
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/lib/deepreload.py#L160-L203 | [
"def",
"import_submodule",
"(",
"mod",
",",
"subname",
",",
"fullname",
")",
":",
"# Require:",
"# if mod == None: subname == fullname",
"# else: mod.__name__ + \".\" + subname == fullname",
"global",
"found_now",
"if",
"fullname",
"in",
"found_now",
"and",
"fullname",
"in",
"sys",
".",
"modules",
":",
"m",
"=",
"sys",
".",
"modules",
"[",
"fullname",
"]",
"else",
":",
"print",
"'Reloading'",
",",
"fullname",
"found_now",
"[",
"fullname",
"]",
"=",
"1",
"oldm",
"=",
"sys",
".",
"modules",
".",
"get",
"(",
"fullname",
",",
"None",
")",
"if",
"mod",
"is",
"None",
":",
"path",
"=",
"None",
"elif",
"hasattr",
"(",
"mod",
",",
"'__path__'",
")",
":",
"path",
"=",
"mod",
".",
"__path__",
"else",
":",
"return",
"None",
"try",
":",
"# This appears to be necessary on Python 3, because imp.find_module()",
"# tries to import standard libraries (like io) itself, and we don't",
"# want them to be processed by our deep_import_hook.",
"with",
"replace_import_hook",
"(",
"original_import",
")",
":",
"fp",
",",
"filename",
",",
"stuff",
"=",
"imp",
".",
"find_module",
"(",
"subname",
",",
"path",
")",
"except",
"ImportError",
":",
"return",
"None",
"try",
":",
"m",
"=",
"imp",
".",
"load_module",
"(",
"fullname",
",",
"fp",
",",
"filename",
",",
"stuff",
")",
"except",
":",
"# load_module probably removed name from modules because of",
"# the error. Put back the original module object.",
"if",
"oldm",
":",
"sys",
".",
"modules",
"[",
"fullname",
"]",
"=",
"oldm",
"raise",
"finally",
":",
"if",
"fp",
":",
"fp",
".",
"close",
"(",
")",
"add_submodule",
"(",
"mod",
",",
"m",
",",
"fullname",
",",
"subname",
")",
"return",
"m"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | add_submodule | mod.{subname} = submod | environment/lib/python2.7/site-packages/IPython/lib/deepreload.py | def add_submodule(mod, submod, fullname, subname):
"""mod.{subname} = submod"""
if mod is None:
return #Nothing to do here.
if submod is None:
submod = sys.modules[fullname]
setattr(mod, subname, submod)
return | def add_submodule(mod, submod, fullname, subname):
"""mod.{subname} = submod"""
if mod is None:
return #Nothing to do here.
if submod is None:
submod = sys.modules[fullname]
setattr(mod, subname, submod)
return | [
"mod",
".",
"{",
"subname",
"}",
"=",
"submod"
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/lib/deepreload.py#L205-L215 | [
"def",
"add_submodule",
"(",
"mod",
",",
"submod",
",",
"fullname",
",",
"subname",
")",
":",
"if",
"mod",
"is",
"None",
":",
"return",
"#Nothing to do here.",
"if",
"submod",
"is",
"None",
":",
"submod",
"=",
"sys",
".",
"modules",
"[",
"fullname",
"]",
"setattr",
"(",
"mod",
",",
"subname",
",",
"submod",
")",
"return"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | ensure_fromlist | Handle 'from module import a, b, c' imports. | environment/lib/python2.7/site-packages/IPython/lib/deepreload.py | def ensure_fromlist(mod, fromlist, buf, recursive):
"""Handle 'from module import a, b, c' imports."""
if not hasattr(mod, '__path__'):
return
for item in fromlist:
if not hasattr(item, 'rindex'):
raise TypeError("Item in ``from list'' not a string")
if item == '*':
if recursive:
continue # avoid endless recursion
try:
all = mod.__all__
except AttributeError:
pass
else:
ret = ensure_fromlist(mod, all, buf, 1)
if not ret:
return 0
elif not hasattr(mod, item):
import_submodule(mod, item, buf + '.' + item) | def ensure_fromlist(mod, fromlist, buf, recursive):
"""Handle 'from module import a, b, c' imports."""
if not hasattr(mod, '__path__'):
return
for item in fromlist:
if not hasattr(item, 'rindex'):
raise TypeError("Item in ``from list'' not a string")
if item == '*':
if recursive:
continue # avoid endless recursion
try:
all = mod.__all__
except AttributeError:
pass
else:
ret = ensure_fromlist(mod, all, buf, 1)
if not ret:
return 0
elif not hasattr(mod, item):
import_submodule(mod, item, buf + '.' + item) | [
"Handle",
"from",
"module",
"import",
"a",
"b",
"c",
"imports",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/lib/deepreload.py#L217-L236 | [
"def",
"ensure_fromlist",
"(",
"mod",
",",
"fromlist",
",",
"buf",
",",
"recursive",
")",
":",
"if",
"not",
"hasattr",
"(",
"mod",
",",
"'__path__'",
")",
":",
"return",
"for",
"item",
"in",
"fromlist",
":",
"if",
"not",
"hasattr",
"(",
"item",
",",
"'rindex'",
")",
":",
"raise",
"TypeError",
"(",
"\"Item in ``from list'' not a string\"",
")",
"if",
"item",
"==",
"'*'",
":",
"if",
"recursive",
":",
"continue",
"# avoid endless recursion",
"try",
":",
"all",
"=",
"mod",
".",
"__all__",
"except",
"AttributeError",
":",
"pass",
"else",
":",
"ret",
"=",
"ensure_fromlist",
"(",
"mod",
",",
"all",
",",
"buf",
",",
"1",
")",
"if",
"not",
"ret",
":",
"return",
"0",
"elif",
"not",
"hasattr",
"(",
"mod",
",",
"item",
")",
":",
"import_submodule",
"(",
"mod",
",",
"item",
",",
"buf",
"+",
"'.'",
"+",
"item",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | deep_import_hook | Replacement for __import__() | environment/lib/python2.7/site-packages/IPython/lib/deepreload.py | def deep_import_hook(name, globals=None, locals=None, fromlist=None, level=-1):
"""Replacement for __import__()"""
parent, buf = get_parent(globals, level)
head, name, buf = load_next(parent, None if level < 0 else parent, name, buf)
tail = head
while name:
tail, name, buf = load_next(tail, tail, name, buf)
# If tail is None, both get_parent and load_next found
# an empty module name: someone called __import__("") or
# doctored faulty bytecode
if tail is None:
raise ValueError('Empty module name')
if not fromlist:
return head
ensure_fromlist(tail, fromlist, buf, 0)
return tail | def deep_import_hook(name, globals=None, locals=None, fromlist=None, level=-1):
"""Replacement for __import__()"""
parent, buf = get_parent(globals, level)
head, name, buf = load_next(parent, None if level < 0 else parent, name, buf)
tail = head
while name:
tail, name, buf = load_next(tail, tail, name, buf)
# If tail is None, both get_parent and load_next found
# an empty module name: someone called __import__("") or
# doctored faulty bytecode
if tail is None:
raise ValueError('Empty module name')
if not fromlist:
return head
ensure_fromlist(tail, fromlist, buf, 0)
return tail | [
"Replacement",
"for",
"__import__",
"()"
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/lib/deepreload.py#L238-L258 | [
"def",
"deep_import_hook",
"(",
"name",
",",
"globals",
"=",
"None",
",",
"locals",
"=",
"None",
",",
"fromlist",
"=",
"None",
",",
"level",
"=",
"-",
"1",
")",
":",
"parent",
",",
"buf",
"=",
"get_parent",
"(",
"globals",
",",
"level",
")",
"head",
",",
"name",
",",
"buf",
"=",
"load_next",
"(",
"parent",
",",
"None",
"if",
"level",
"<",
"0",
"else",
"parent",
",",
"name",
",",
"buf",
")",
"tail",
"=",
"head",
"while",
"name",
":",
"tail",
",",
"name",
",",
"buf",
"=",
"load_next",
"(",
"tail",
",",
"tail",
",",
"name",
",",
"buf",
")",
"# If tail is None, both get_parent and load_next found",
"# an empty module name: someone called __import__(\"\") or",
"# doctored faulty bytecode",
"if",
"tail",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'Empty module name'",
")",
"if",
"not",
"fromlist",
":",
"return",
"head",
"ensure_fromlist",
"(",
"tail",
",",
"fromlist",
",",
"buf",
",",
"0",
")",
"return",
"tail"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | deep_reload_hook | Replacement for reload(). | environment/lib/python2.7/site-packages/IPython/lib/deepreload.py | def deep_reload_hook(m):
"""Replacement for reload()."""
if not isinstance(m, ModuleType):
raise TypeError("reload() argument must be module")
name = m.__name__
if name not in sys.modules:
raise ImportError("reload(): module %.200s not in sys.modules" % name)
global modules_reloading
try:
return modules_reloading[name]
except:
modules_reloading[name] = m
dot = name.rfind('.')
if dot < 0:
subname = name
path = None
else:
try:
parent = sys.modules[name[:dot]]
except KeyError:
modules_reloading.clear()
raise ImportError("reload(): parent %.200s not in sys.modules" % name[:dot])
subname = name[dot+1:]
path = getattr(parent, "__path__", None)
try:
# This appears to be necessary on Python 3, because imp.find_module()
# tries to import standard libraries (like io) itself, and we don't
# want them to be processed by our deep_import_hook.
with replace_import_hook(original_import):
fp, filename, stuff = imp.find_module(subname, path)
finally:
modules_reloading.clear()
try:
newm = imp.load_module(name, fp, filename, stuff)
except:
# load_module probably removed name from modules because of
# the error. Put back the original module object.
sys.modules[name] = m
raise
finally:
if fp: fp.close()
modules_reloading.clear()
return newm | def deep_reload_hook(m):
"""Replacement for reload()."""
if not isinstance(m, ModuleType):
raise TypeError("reload() argument must be module")
name = m.__name__
if name not in sys.modules:
raise ImportError("reload(): module %.200s not in sys.modules" % name)
global modules_reloading
try:
return modules_reloading[name]
except:
modules_reloading[name] = m
dot = name.rfind('.')
if dot < 0:
subname = name
path = None
else:
try:
parent = sys.modules[name[:dot]]
except KeyError:
modules_reloading.clear()
raise ImportError("reload(): parent %.200s not in sys.modules" % name[:dot])
subname = name[dot+1:]
path = getattr(parent, "__path__", None)
try:
# This appears to be necessary on Python 3, because imp.find_module()
# tries to import standard libraries (like io) itself, and we don't
# want them to be processed by our deep_import_hook.
with replace_import_hook(original_import):
fp, filename, stuff = imp.find_module(subname, path)
finally:
modules_reloading.clear()
try:
newm = imp.load_module(name, fp, filename, stuff)
except:
# load_module probably removed name from modules because of
# the error. Put back the original module object.
sys.modules[name] = m
raise
finally:
if fp: fp.close()
modules_reloading.clear()
return newm | [
"Replacement",
"for",
"reload",
"()",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/lib/deepreload.py#L262-L311 | [
"def",
"deep_reload_hook",
"(",
"m",
")",
":",
"if",
"not",
"isinstance",
"(",
"m",
",",
"ModuleType",
")",
":",
"raise",
"TypeError",
"(",
"\"reload() argument must be module\"",
")",
"name",
"=",
"m",
".",
"__name__",
"if",
"name",
"not",
"in",
"sys",
".",
"modules",
":",
"raise",
"ImportError",
"(",
"\"reload(): module %.200s not in sys.modules\"",
"%",
"name",
")",
"global",
"modules_reloading",
"try",
":",
"return",
"modules_reloading",
"[",
"name",
"]",
"except",
":",
"modules_reloading",
"[",
"name",
"]",
"=",
"m",
"dot",
"=",
"name",
".",
"rfind",
"(",
"'.'",
")",
"if",
"dot",
"<",
"0",
":",
"subname",
"=",
"name",
"path",
"=",
"None",
"else",
":",
"try",
":",
"parent",
"=",
"sys",
".",
"modules",
"[",
"name",
"[",
":",
"dot",
"]",
"]",
"except",
"KeyError",
":",
"modules_reloading",
".",
"clear",
"(",
")",
"raise",
"ImportError",
"(",
"\"reload(): parent %.200s not in sys.modules\"",
"%",
"name",
"[",
":",
"dot",
"]",
")",
"subname",
"=",
"name",
"[",
"dot",
"+",
"1",
":",
"]",
"path",
"=",
"getattr",
"(",
"parent",
",",
"\"__path__\"",
",",
"None",
")",
"try",
":",
"# This appears to be necessary on Python 3, because imp.find_module()",
"# tries to import standard libraries (like io) itself, and we don't",
"# want them to be processed by our deep_import_hook.",
"with",
"replace_import_hook",
"(",
"original_import",
")",
":",
"fp",
",",
"filename",
",",
"stuff",
"=",
"imp",
".",
"find_module",
"(",
"subname",
",",
"path",
")",
"finally",
":",
"modules_reloading",
".",
"clear",
"(",
")",
"try",
":",
"newm",
"=",
"imp",
".",
"load_module",
"(",
"name",
",",
"fp",
",",
"filename",
",",
"stuff",
")",
"except",
":",
"# load_module probably removed name from modules because of",
"# the error. Put back the original module object.",
"sys",
".",
"modules",
"[",
"name",
"]",
"=",
"m",
"raise",
"finally",
":",
"if",
"fp",
":",
"fp",
".",
"close",
"(",
")",
"modules_reloading",
".",
"clear",
"(",
")",
"return",
"newm"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | reload | Recursively reload all modules used in the given module. Optionally
takes a list of modules to exclude from reloading. The default exclude
list contains sys, __main__, and __builtin__, to prevent, e.g., resetting
display, exception, and io hooks. | environment/lib/python2.7/site-packages/IPython/lib/deepreload.py | def reload(module, exclude=['sys', 'os.path', '__builtin__', '__main__']):
"""Recursively reload all modules used in the given module. Optionally
takes a list of modules to exclude from reloading. The default exclude
list contains sys, __main__, and __builtin__, to prevent, e.g., resetting
display, exception, and io hooks.
"""
global found_now
for i in exclude:
found_now[i] = 1
try:
with replace_import_hook(deep_import_hook):
ret = deep_reload_hook(module)
finally:
found_now = {}
return ret | def reload(module, exclude=['sys', 'os.path', '__builtin__', '__main__']):
"""Recursively reload all modules used in the given module. Optionally
takes a list of modules to exclude from reloading. The default exclude
list contains sys, __main__, and __builtin__, to prevent, e.g., resetting
display, exception, and io hooks.
"""
global found_now
for i in exclude:
found_now[i] = 1
try:
with replace_import_hook(deep_import_hook):
ret = deep_reload_hook(module)
finally:
found_now = {}
return ret | [
"Recursively",
"reload",
"all",
"modules",
"used",
"in",
"the",
"given",
"module",
".",
"Optionally",
"takes",
"a",
"list",
"of",
"modules",
"to",
"exclude",
"from",
"reloading",
".",
"The",
"default",
"exclude",
"list",
"contains",
"sys",
"__main__",
"and",
"__builtin__",
"to",
"prevent",
"e",
".",
"g",
".",
"resetting",
"display",
"exception",
"and",
"io",
"hooks",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/lib/deepreload.py#L320-L334 | [
"def",
"reload",
"(",
"module",
",",
"exclude",
"=",
"[",
"'sys'",
",",
"'os.path'",
",",
"'__builtin__'",
",",
"'__main__'",
"]",
")",
":",
"global",
"found_now",
"for",
"i",
"in",
"exclude",
":",
"found_now",
"[",
"i",
"]",
"=",
"1",
"try",
":",
"with",
"replace_import_hook",
"(",
"deep_import_hook",
")",
":",
"ret",
"=",
"deep_reload_hook",
"(",
"module",
")",
"finally",
":",
"found_now",
"=",
"{",
"}",
"return",
"ret"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | code_name | Compute a (probably) unique name for code for caching.
This now expects code to be unicode. | environment/lib/python2.7/site-packages/IPython/core/compilerop.py | def code_name(code, number=0):
""" Compute a (probably) unique name for code for caching.
This now expects code to be unicode.
"""
hash_digest = hashlib.md5(code.encode("utf-8")).hexdigest()
# Include the number and 12 characters of the hash in the name. It's
# pretty much impossible that in a single session we'll have collisions
# even with truncated hashes, and the full one makes tracebacks too long
return '<ipython-input-{0}-{1}>'.format(number, hash_digest[:12]) | def code_name(code, number=0):
""" Compute a (probably) unique name for code for caching.
This now expects code to be unicode.
"""
hash_digest = hashlib.md5(code.encode("utf-8")).hexdigest()
# Include the number and 12 characters of the hash in the name. It's
# pretty much impossible that in a single session we'll have collisions
# even with truncated hashes, and the full one makes tracebacks too long
return '<ipython-input-{0}-{1}>'.format(number, hash_digest[:12]) | [
"Compute",
"a",
"(",
"probably",
")",
"unique",
"name",
"for",
"code",
"for",
"caching",
".",
"This",
"now",
"expects",
"code",
"to",
"be",
"unicode",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/compilerop.py#L41-L50 | [
"def",
"code_name",
"(",
"code",
",",
"number",
"=",
"0",
")",
":",
"hash_digest",
"=",
"hashlib",
".",
"md5",
"(",
"code",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
".",
"hexdigest",
"(",
")",
"# Include the number and 12 characters of the hash in the name. It's",
"# pretty much impossible that in a single session we'll have collisions",
"# even with truncated hashes, and the full one makes tracebacks too long",
"return",
"'<ipython-input-{0}-{1}>'",
".",
"format",
"(",
"number",
",",
"hash_digest",
"[",
":",
"12",
"]",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | CachingCompiler.ast_parse | Parse code to an AST with the current compiler flags active.
Arguments are exactly the same as ast.parse (in the standard library),
and are passed to the built-in compile function. | environment/lib/python2.7/site-packages/IPython/core/compilerop.py | def ast_parse(self, source, filename='<unknown>', symbol='exec'):
"""Parse code to an AST with the current compiler flags active.
Arguments are exactly the same as ast.parse (in the standard library),
and are passed to the built-in compile function."""
return compile(source, filename, symbol, self.flags | PyCF_ONLY_AST, 1) | def ast_parse(self, source, filename='<unknown>', symbol='exec'):
"""Parse code to an AST with the current compiler flags active.
Arguments are exactly the same as ast.parse (in the standard library),
and are passed to the built-in compile function."""
return compile(source, filename, symbol, self.flags | PyCF_ONLY_AST, 1) | [
"Parse",
"code",
"to",
"an",
"AST",
"with",
"the",
"current",
"compiler",
"flags",
"active",
".",
"Arguments",
"are",
"exactly",
"the",
"same",
"as",
"ast",
".",
"parse",
"(",
"in",
"the",
"standard",
"library",
")",
"and",
"are",
"passed",
"to",
"the",
"built",
"-",
"in",
"compile",
"function",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/compilerop.py#L82-L87 | [
"def",
"ast_parse",
"(",
"self",
",",
"source",
",",
"filename",
"=",
"'<unknown>'",
",",
"symbol",
"=",
"'exec'",
")",
":",
"return",
"compile",
"(",
"source",
",",
"filename",
",",
"symbol",
",",
"self",
".",
"flags",
"|",
"PyCF_ONLY_AST",
",",
"1",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | CachingCompiler.cache | Make a name for a block of code, and cache the code.
Parameters
----------
code : str
The Python source code to cache.
number : int
A number which forms part of the code's name. Used for the execution
counter.
Returns
-------
The name of the cached code (as a string). Pass this as the filename
argument to compilation, so that tracebacks are correctly hooked up. | environment/lib/python2.7/site-packages/IPython/core/compilerop.py | def cache(self, code, number=0):
"""Make a name for a block of code, and cache the code.
Parameters
----------
code : str
The Python source code to cache.
number : int
A number which forms part of the code's name. Used for the execution
counter.
Returns
-------
The name of the cached code (as a string). Pass this as the filename
argument to compilation, so that tracebacks are correctly hooked up.
"""
name = code_name(code, number)
entry = (len(code), time.time(),
[line+'\n' for line in code.splitlines()], name)
linecache.cache[name] = entry
linecache._ipython_cache[name] = entry
return name | def cache(self, code, number=0):
"""Make a name for a block of code, and cache the code.
Parameters
----------
code : str
The Python source code to cache.
number : int
A number which forms part of the code's name. Used for the execution
counter.
Returns
-------
The name of the cached code (as a string). Pass this as the filename
argument to compilation, so that tracebacks are correctly hooked up.
"""
name = code_name(code, number)
entry = (len(code), time.time(),
[line+'\n' for line in code.splitlines()], name)
linecache.cache[name] = entry
linecache._ipython_cache[name] = entry
return name | [
"Make",
"a",
"name",
"for",
"a",
"block",
"of",
"code",
"and",
"cache",
"the",
"code",
".",
"Parameters",
"----------",
"code",
":",
"str",
"The",
"Python",
"source",
"code",
"to",
"cache",
".",
"number",
":",
"int",
"A",
"number",
"which",
"forms",
"part",
"of",
"the",
"code",
"s",
"name",
".",
"Used",
"for",
"the",
"execution",
"counter",
".",
"Returns",
"-------",
"The",
"name",
"of",
"the",
"cached",
"code",
"(",
"as",
"a",
"string",
")",
".",
"Pass",
"this",
"as",
"the",
"filename",
"argument",
"to",
"compilation",
"so",
"that",
"tracebacks",
"are",
"correctly",
"hooked",
"up",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/compilerop.py#L101-L122 | [
"def",
"cache",
"(",
"self",
",",
"code",
",",
"number",
"=",
"0",
")",
":",
"name",
"=",
"code_name",
"(",
"code",
",",
"number",
")",
"entry",
"=",
"(",
"len",
"(",
"code",
")",
",",
"time",
".",
"time",
"(",
")",
",",
"[",
"line",
"+",
"'\\n'",
"for",
"line",
"in",
"code",
".",
"splitlines",
"(",
")",
"]",
",",
"name",
")",
"linecache",
".",
"cache",
"[",
"name",
"]",
"=",
"entry",
"linecache",
".",
"_ipython_cache",
"[",
"name",
"]",
"=",
"entry",
"return",
"name"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | CachingCompiler.check_cache | Call linecache.checkcache() safely protecting our cached values. | environment/lib/python2.7/site-packages/IPython/core/compilerop.py | def check_cache(self, *args):
"""Call linecache.checkcache() safely protecting our cached values.
"""
# First call the orignal checkcache as intended
linecache._checkcache_ori(*args)
# Then, update back the cache with our data, so that tracebacks related
# to our compiled codes can be produced.
linecache.cache.update(linecache._ipython_cache) | def check_cache(self, *args):
"""Call linecache.checkcache() safely protecting our cached values.
"""
# First call the orignal checkcache as intended
linecache._checkcache_ori(*args)
# Then, update back the cache with our data, so that tracebacks related
# to our compiled codes can be produced.
linecache.cache.update(linecache._ipython_cache) | [
"Call",
"linecache",
".",
"checkcache",
"()",
"safely",
"protecting",
"our",
"cached",
"values",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/compilerop.py#L124-L131 | [
"def",
"check_cache",
"(",
"self",
",",
"*",
"args",
")",
":",
"# First call the orignal checkcache as intended",
"linecache",
".",
"_checkcache_ori",
"(",
"*",
"args",
")",
"# Then, update back the cache with our data, so that tracebacks related",
"# to our compiled codes can be produced.",
"linecache",
".",
"cache",
".",
"update",
"(",
"linecache",
".",
"_ipython_cache",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | CodeBuilder.add_line | Add a line of source to the code.
Don't include indentations or newlines. | virtualEnvironment/lib/python2.7/site-packages/coverage/templite.py | def add_line(self, line):
"""Add a line of source to the code.
Don't include indentations or newlines.
"""
self.code.append(" " * self.indent_amount)
self.code.append(line)
self.code.append("\n") | def add_line(self, line):
"""Add a line of source to the code.
Don't include indentations or newlines.
"""
self.code.append(" " * self.indent_amount)
self.code.append(line)
self.code.append("\n") | [
"Add",
"a",
"line",
"of",
"source",
"to",
"the",
"code",
"."
] | tnkteja/myhelp | python | https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/templite.py#L17-L25 | [
"def",
"add_line",
"(",
"self",
",",
"line",
")",
":",
"self",
".",
"code",
".",
"append",
"(",
"\" \"",
"*",
"self",
".",
"indent_amount",
")",
"self",
".",
"code",
".",
"append",
"(",
"line",
")",
"self",
".",
"code",
".",
"append",
"(",
"\"\\n\"",
")"
] | fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb |
test | CodeBuilder.add_section | Add a section, a sub-CodeBuilder. | virtualEnvironment/lib/python2.7/site-packages/coverage/templite.py | def add_section(self):
"""Add a section, a sub-CodeBuilder."""
sect = CodeBuilder(self.indent_amount)
self.code.append(sect)
return sect | def add_section(self):
"""Add a section, a sub-CodeBuilder."""
sect = CodeBuilder(self.indent_amount)
self.code.append(sect)
return sect | [
"Add",
"a",
"section",
"a",
"sub",
"-",
"CodeBuilder",
"."
] | tnkteja/myhelp | python | https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/templite.py#L27-L31 | [
"def",
"add_section",
"(",
"self",
")",
":",
"sect",
"=",
"CodeBuilder",
"(",
"self",
".",
"indent_amount",
")",
"self",
".",
"code",
".",
"append",
"(",
"sect",
")",
"return",
"sect"
] | fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb |
test | CodeBuilder.get_function | Compile the code, and return the function `fn_name`. | virtualEnvironment/lib/python2.7/site-packages/coverage/templite.py | def get_function(self, fn_name):
"""Compile the code, and return the function `fn_name`."""
assert self.indent_amount == 0
g = {}
code_text = str(self)
exec(code_text, g)
return g[fn_name] | def get_function(self, fn_name):
"""Compile the code, and return the function `fn_name`."""
assert self.indent_amount == 0
g = {}
code_text = str(self)
exec(code_text, g)
return g[fn_name] | [
"Compile",
"the",
"code",
"and",
"return",
"the",
"function",
"fn_name",
"."
] | tnkteja/myhelp | python | https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/templite.py#L44-L50 | [
"def",
"get_function",
"(",
"self",
",",
"fn_name",
")",
":",
"assert",
"self",
".",
"indent_amount",
"==",
"0",
"g",
"=",
"{",
"}",
"code_text",
"=",
"str",
"(",
"self",
")",
"exec",
"(",
"code_text",
",",
"g",
")",
"return",
"g",
"[",
"fn_name",
"]"
] | fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb |
test | Templite.expr_code | Generate a Python expression for `expr`. | virtualEnvironment/lib/python2.7/site-packages/coverage/templite.py | def expr_code(self, expr):
"""Generate a Python expression for `expr`."""
if "|" in expr:
pipes = expr.split("|")
code = self.expr_code(pipes[0])
for func in pipes[1:]:
self.all_vars.add(func)
code = "c_%s(%s)" % (func, code)
elif "." in expr:
dots = expr.split(".")
code = self.expr_code(dots[0])
args = [repr(d) for d in dots[1:]]
code = "dot(%s, %s)" % (code, ", ".join(args))
else:
self.all_vars.add(expr)
code = "c_%s" % expr
return code | def expr_code(self, expr):
"""Generate a Python expression for `expr`."""
if "|" in expr:
pipes = expr.split("|")
code = self.expr_code(pipes[0])
for func in pipes[1:]:
self.all_vars.add(func)
code = "c_%s(%s)" % (func, code)
elif "." in expr:
dots = expr.split(".")
code = self.expr_code(dots[0])
args = [repr(d) for d in dots[1:]]
code = "dot(%s, %s)" % (code, ", ".join(args))
else:
self.all_vars.add(expr)
code = "c_%s" % expr
return code | [
"Generate",
"a",
"Python",
"expression",
"for",
"expr",
"."
] | tnkteja/myhelp | python | https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/templite.py#L169-L185 | [
"def",
"expr_code",
"(",
"self",
",",
"expr",
")",
":",
"if",
"\"|\"",
"in",
"expr",
":",
"pipes",
"=",
"expr",
".",
"split",
"(",
"\"|\"",
")",
"code",
"=",
"self",
".",
"expr_code",
"(",
"pipes",
"[",
"0",
"]",
")",
"for",
"func",
"in",
"pipes",
"[",
"1",
":",
"]",
":",
"self",
".",
"all_vars",
".",
"add",
"(",
"func",
")",
"code",
"=",
"\"c_%s(%s)\"",
"%",
"(",
"func",
",",
"code",
")",
"elif",
"\".\"",
"in",
"expr",
":",
"dots",
"=",
"expr",
".",
"split",
"(",
"\".\"",
")",
"code",
"=",
"self",
".",
"expr_code",
"(",
"dots",
"[",
"0",
"]",
")",
"args",
"=",
"[",
"repr",
"(",
"d",
")",
"for",
"d",
"in",
"dots",
"[",
"1",
":",
"]",
"]",
"code",
"=",
"\"dot(%s, %s)\"",
"%",
"(",
"code",
",",
"\", \"",
".",
"join",
"(",
"args",
")",
")",
"else",
":",
"self",
".",
"all_vars",
".",
"add",
"(",
"expr",
")",
"code",
"=",
"\"c_%s\"",
"%",
"expr",
"return",
"code"
] | fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb |
test | Templite.render | Render this template by applying it to `context`.
`context` is a dictionary of values to use in this rendering. | virtualEnvironment/lib/python2.7/site-packages/coverage/templite.py | def render(self, context=None):
"""Render this template by applying it to `context`.
`context` is a dictionary of values to use in this rendering.
"""
# Make the complete context we'll use.
ctx = dict(self.context)
if context:
ctx.update(context)
return self.render_function(ctx, self.do_dots) | def render(self, context=None):
"""Render this template by applying it to `context`.
`context` is a dictionary of values to use in this rendering.
"""
# Make the complete context we'll use.
ctx = dict(self.context)
if context:
ctx.update(context)
return self.render_function(ctx, self.do_dots) | [
"Render",
"this",
"template",
"by",
"applying",
"it",
"to",
"context",
"."
] | tnkteja/myhelp | python | https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/templite.py#L187-L197 | [
"def",
"render",
"(",
"self",
",",
"context",
"=",
"None",
")",
":",
"# Make the complete context we'll use.",
"ctx",
"=",
"dict",
"(",
"self",
".",
"context",
")",
"if",
"context",
":",
"ctx",
".",
"update",
"(",
"context",
")",
"return",
"self",
".",
"render_function",
"(",
"ctx",
",",
"self",
".",
"do_dots",
")"
] | fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb |
test | Templite.do_dots | Evaluate dotted expressions at runtime. | virtualEnvironment/lib/python2.7/site-packages/coverage/templite.py | def do_dots(self, value, *dots):
"""Evaluate dotted expressions at runtime."""
for dot in dots:
try:
value = getattr(value, dot)
except AttributeError:
value = value[dot]
if hasattr(value, '__call__'):
value = value()
return value | def do_dots(self, value, *dots):
"""Evaluate dotted expressions at runtime."""
for dot in dots:
try:
value = getattr(value, dot)
except AttributeError:
value = value[dot]
if hasattr(value, '__call__'):
value = value()
return value | [
"Evaluate",
"dotted",
"expressions",
"at",
"runtime",
"."
] | tnkteja/myhelp | python | https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/templite.py#L199-L208 | [
"def",
"do_dots",
"(",
"self",
",",
"value",
",",
"*",
"dots",
")",
":",
"for",
"dot",
"in",
"dots",
":",
"try",
":",
"value",
"=",
"getattr",
"(",
"value",
",",
"dot",
")",
"except",
"AttributeError",
":",
"value",
"=",
"value",
"[",
"dot",
"]",
"if",
"hasattr",
"(",
"value",
",",
"'__call__'",
")",
":",
"value",
"=",
"value",
"(",
")",
"return",
"value"
] | fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb |
test | render_template | A shortcut function to render a partial template with context and return
the output. | django_baseline/template.py | def render_template(tpl, context):
'''
A shortcut function to render a partial template with context and return
the output.
'''
templates = [tpl] if type(tpl) != list else tpl
tpl_instance = None
for tpl in templates:
try:
tpl_instance = template.loader.get_template(tpl)
break
except template.TemplateDoesNotExist:
pass
if not tpl_instance:
raise Exception('Template does not exist: ' + templates[-1])
return tpl_instance.render(template.Context(context)) | def render_template(tpl, context):
'''
A shortcut function to render a partial template with context and return
the output.
'''
templates = [tpl] if type(tpl) != list else tpl
tpl_instance = None
for tpl in templates:
try:
tpl_instance = template.loader.get_template(tpl)
break
except template.TemplateDoesNotExist:
pass
if not tpl_instance:
raise Exception('Template does not exist: ' + templates[-1])
return tpl_instance.render(template.Context(context)) | [
"A",
"shortcut",
"function",
"to",
"render",
"a",
"partial",
"template",
"with",
"context",
"and",
"return",
"the",
"output",
"."
] | theduke/django-baseline | python | https://github.com/theduke/django-baseline/blob/7be8b956e53c70b35f34e1783a8fe8f716955afb/django_baseline/template.py#L5-L24 | [
"def",
"render_template",
"(",
"tpl",
",",
"context",
")",
":",
"templates",
"=",
"[",
"tpl",
"]",
"if",
"type",
"(",
"tpl",
")",
"!=",
"list",
"else",
"tpl",
"tpl_instance",
"=",
"None",
"for",
"tpl",
"in",
"templates",
":",
"try",
":",
"tpl_instance",
"=",
"template",
".",
"loader",
".",
"get_template",
"(",
"tpl",
")",
"break",
"except",
"template",
".",
"TemplateDoesNotExist",
":",
"pass",
"if",
"not",
"tpl_instance",
":",
"raise",
"Exception",
"(",
"'Template does not exist: '",
"+",
"templates",
"[",
"-",
"1",
"]",
")",
"return",
"tpl_instance",
".",
"render",
"(",
"template",
".",
"Context",
"(",
"context",
")",
")"
] | 7be8b956e53c70b35f34e1783a8fe8f716955afb |
test | format_display_data | Return a format data dict for an object.
By default all format types will be computed.
The following MIME types are currently implemented:
* text/plain
* text/html
* text/latex
* application/json
* application/javascript
* image/png
* image/jpeg
* image/svg+xml
Parameters
----------
obj : object
The Python object whose format data will be computed.
Returns
-------
format_dict : dict
A dictionary of key/value pairs, one or each format that was
generated for the object. The keys are the format types, which
will usually be MIME type strings and the values and JSON'able
data structure containing the raw data for the representation in
that format.
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. | environment/lib/python2.7/site-packages/IPython/core/formatters.py | def format_display_data(obj, include=None, exclude=None):
"""Return a format data dict for an object.
By default all format types will be computed.
The following MIME types are currently implemented:
* text/plain
* text/html
* text/latex
* application/json
* application/javascript
* image/png
* image/jpeg
* image/svg+xml
Parameters
----------
obj : object
The Python object whose format data will be computed.
Returns
-------
format_dict : dict
A dictionary of key/value pairs, one or each format that was
generated for the object. The keys are the format types, which
will usually be MIME type strings and the values and JSON'able
data structure containing the raw data for the representation in
that format.
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.
"""
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.instance().display_formatter.format(
obj,
include,
exclude
) | def format_display_data(obj, include=None, exclude=None):
"""Return a format data dict for an object.
By default all format types will be computed.
The following MIME types are currently implemented:
* text/plain
* text/html
* text/latex
* application/json
* application/javascript
* image/png
* image/jpeg
* image/svg+xml
Parameters
----------
obj : object
The Python object whose format data will be computed.
Returns
-------
format_dict : dict
A dictionary of key/value pairs, one or each format that was
generated for the object. The keys are the format types, which
will usually be MIME type strings and the values and JSON'able
data structure containing the raw data for the representation in
that format.
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.
"""
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.instance().display_formatter.format(
obj,
include,
exclude
) | [
"Return",
"a",
"format",
"data",
"dict",
"for",
"an",
"object",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/formatters.py#L576-L620 | [
"def",
"format_display_data",
"(",
"obj",
",",
"include",
"=",
"None",
",",
"exclude",
"=",
"None",
")",
":",
"from",
"IPython",
".",
"core",
".",
"interactiveshell",
"import",
"InteractiveShell",
"InteractiveShell",
".",
"instance",
"(",
")",
".",
"display_formatter",
".",
"format",
"(",
"obj",
",",
"include",
",",
"exclude",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | DisplayFormatter._formatters_default | Activate the default formatters. | environment/lib/python2.7/site-packages/IPython/core/formatters.py | def _formatters_default(self):
"""Activate the default formatters."""
formatter_classes = [
PlainTextFormatter,
HTMLFormatter,
SVGFormatter,
PNGFormatter,
JPEGFormatter,
LatexFormatter,
JSONFormatter,
JavascriptFormatter
]
d = {}
for cls in formatter_classes:
f = cls(config=self.config)
d[f.format_type] = f
return d | def _formatters_default(self):
"""Activate the default formatters."""
formatter_classes = [
PlainTextFormatter,
HTMLFormatter,
SVGFormatter,
PNGFormatter,
JPEGFormatter,
LatexFormatter,
JSONFormatter,
JavascriptFormatter
]
d = {}
for cls in formatter_classes:
f = cls(config=self.config)
d[f.format_type] = f
return d | [
"Activate",
"the",
"default",
"formatters",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/formatters.py#L48-L64 | [
"def",
"_formatters_default",
"(",
"self",
")",
":",
"formatter_classes",
"=",
"[",
"PlainTextFormatter",
",",
"HTMLFormatter",
",",
"SVGFormatter",
",",
"PNGFormatter",
",",
"JPEGFormatter",
",",
"LatexFormatter",
",",
"JSONFormatter",
",",
"JavascriptFormatter",
"]",
"d",
"=",
"{",
"}",
"for",
"cls",
"in",
"formatter_classes",
":",
"f",
"=",
"cls",
"(",
"config",
"=",
"self",
".",
"config",
")",
"d",
"[",
"f",
".",
"format_type",
"]",
"=",
"f",
"return",
"d"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | DisplayFormatter.format | Return a format data dict for an object.
By default all format types will be computed.
The following MIME types are currently implemented:
* text/plain
* text/html
* text/latex
* application/json
* application/javascript
* image/png
* image/jpeg
* image/svg+xml
Parameters
----------
obj : object
The Python object whose format data will be computed.
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.
Returns
-------
format_dict : dict
A dictionary of key/value pairs, one or each format that was
generated for the object. The keys are the format types, which
will usually be MIME type strings and the values and JSON'able
data structure containing the raw data for the representation in
that format. | environment/lib/python2.7/site-packages/IPython/core/formatters.py | def format(self, obj, include=None, exclude=None):
"""Return a format data dict for an object.
By default all format types will be computed.
The following MIME types are currently implemented:
* text/plain
* text/html
* text/latex
* application/json
* application/javascript
* image/png
* image/jpeg
* image/svg+xml
Parameters
----------
obj : object
The Python object whose format data will be computed.
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.
Returns
-------
format_dict : dict
A dictionary of key/value pairs, one or each format that was
generated for the object. The keys are the format types, which
will usually be MIME type strings and the values and JSON'able
data structure containing the raw data for the representation in
that format.
"""
format_dict = {}
# If plain text only is active
if self.plain_text_only:
formatter = self.formatters['text/plain']
try:
data = formatter(obj)
except:
# FIXME: log the exception
raise
if data is not None:
format_dict['text/plain'] = data
return format_dict
for format_type, formatter in self.formatters.items():
if include is not None:
if format_type not in include:
continue
if exclude is not None:
if format_type in exclude:
continue
try:
data = formatter(obj)
except:
# FIXME: log the exception
raise
if data is not None:
format_dict[format_type] = data
return format_dict | def format(self, obj, include=None, exclude=None):
"""Return a format data dict for an object.
By default all format types will be computed.
The following MIME types are currently implemented:
* text/plain
* text/html
* text/latex
* application/json
* application/javascript
* image/png
* image/jpeg
* image/svg+xml
Parameters
----------
obj : object
The Python object whose format data will be computed.
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.
Returns
-------
format_dict : dict
A dictionary of key/value pairs, one or each format that was
generated for the object. The keys are the format types, which
will usually be MIME type strings and the values and JSON'able
data structure containing the raw data for the representation in
that format.
"""
format_dict = {}
# If plain text only is active
if self.plain_text_only:
formatter = self.formatters['text/plain']
try:
data = formatter(obj)
except:
# FIXME: log the exception
raise
if data is not None:
format_dict['text/plain'] = data
return format_dict
for format_type, formatter in self.formatters.items():
if include is not None:
if format_type not in include:
continue
if exclude is not None:
if format_type in exclude:
continue
try:
data = formatter(obj)
except:
# FIXME: log the exception
raise
if data is not None:
format_dict[format_type] = data
return format_dict | [
"Return",
"a",
"format",
"data",
"dict",
"for",
"an",
"object",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/formatters.py#L66-L132 | [
"def",
"format",
"(",
"self",
",",
"obj",
",",
"include",
"=",
"None",
",",
"exclude",
"=",
"None",
")",
":",
"format_dict",
"=",
"{",
"}",
"# If plain text only is active",
"if",
"self",
".",
"plain_text_only",
":",
"formatter",
"=",
"self",
".",
"formatters",
"[",
"'text/plain'",
"]",
"try",
":",
"data",
"=",
"formatter",
"(",
"obj",
")",
"except",
":",
"# FIXME: log the exception",
"raise",
"if",
"data",
"is",
"not",
"None",
":",
"format_dict",
"[",
"'text/plain'",
"]",
"=",
"data",
"return",
"format_dict",
"for",
"format_type",
",",
"formatter",
"in",
"self",
".",
"formatters",
".",
"items",
"(",
")",
":",
"if",
"include",
"is",
"not",
"None",
":",
"if",
"format_type",
"not",
"in",
"include",
":",
"continue",
"if",
"exclude",
"is",
"not",
"None",
":",
"if",
"format_type",
"in",
"exclude",
":",
"continue",
"try",
":",
"data",
"=",
"formatter",
"(",
"obj",
")",
"except",
":",
"# FIXME: log the exception",
"raise",
"if",
"data",
"is",
"not",
"None",
":",
"format_dict",
"[",
"format_type",
"]",
"=",
"data",
"return",
"format_dict"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | BaseFormatter.for_type | Add a format function for a given type.
Parameters
-----------
typ : class
The class of the object that will be formatted using `func`.
func : callable
The callable that will be called to compute the format data. The
call signature of this function is simple, it must take the
object to be formatted and return the raw data for the given
format. Subclasses may use a different call signature for the
`func` argument. | environment/lib/python2.7/site-packages/IPython/core/formatters.py | def for_type(self, typ, func):
"""Add a format function for a given type.
Parameters
-----------
typ : class
The class of the object that will be formatted using `func`.
func : callable
The callable that will be called to compute the format data. The
call signature of this function is simple, it must take the
object to be formatted and return the raw data for the given
format. Subclasses may use a different call signature for the
`func` argument.
"""
oldfunc = self.type_printers.get(typ, None)
if func is not None:
# To support easy restoration of old printers, we need to ignore
# Nones.
self.type_printers[typ] = func
return oldfunc | def for_type(self, typ, func):
"""Add a format function for a given type.
Parameters
-----------
typ : class
The class of the object that will be formatted using `func`.
func : callable
The callable that will be called to compute the format data. The
call signature of this function is simple, it must take the
object to be formatted and return the raw data for the given
format. Subclasses may use a different call signature for the
`func` argument.
"""
oldfunc = self.type_printers.get(typ, None)
if func is not None:
# To support easy restoration of old printers, we need to ignore
# Nones.
self.type_printers[typ] = func
return oldfunc | [
"Add",
"a",
"format",
"function",
"for",
"a",
"given",
"type",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/formatters.py#L253-L272 | [
"def",
"for_type",
"(",
"self",
",",
"typ",
",",
"func",
")",
":",
"oldfunc",
"=",
"self",
".",
"type_printers",
".",
"get",
"(",
"typ",
",",
"None",
")",
"if",
"func",
"is",
"not",
"None",
":",
"# To support easy restoration of old printers, we need to ignore",
"# Nones.",
"self",
".",
"type_printers",
"[",
"typ",
"]",
"=",
"func",
"return",
"oldfunc"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | BaseFormatter.for_type_by_name | Add a format function for a type specified by the full dotted
module and name of the type, rather than the type of the object.
Parameters
----------
type_module : str
The full dotted name of the module the type is defined in, like
``numpy``.
type_name : str
The name of the type (the class name), like ``dtype``
func : callable
The callable that will be called to compute the format data. The
call signature of this function is simple, it must take the
object to be formatted and return the raw data for the given
format. Subclasses may use a different call signature for the
`func` argument. | environment/lib/python2.7/site-packages/IPython/core/formatters.py | def for_type_by_name(self, type_module, type_name, func):
"""Add a format function for a type specified by the full dotted
module and name of the type, rather than the type of the object.
Parameters
----------
type_module : str
The full dotted name of the module the type is defined in, like
``numpy``.
type_name : str
The name of the type (the class name), like ``dtype``
func : callable
The callable that will be called to compute the format data. The
call signature of this function is simple, it must take the
object to be formatted and return the raw data for the given
format. Subclasses may use a different call signature for the
`func` argument.
"""
key = (type_module, type_name)
oldfunc = self.deferred_printers.get(key, None)
if func is not None:
# To support easy restoration of old printers, we need to ignore
# Nones.
self.deferred_printers[key] = func
return oldfunc | def for_type_by_name(self, type_module, type_name, func):
"""Add a format function for a type specified by the full dotted
module and name of the type, rather than the type of the object.
Parameters
----------
type_module : str
The full dotted name of the module the type is defined in, like
``numpy``.
type_name : str
The name of the type (the class name), like ``dtype``
func : callable
The callable that will be called to compute the format data. The
call signature of this function is simple, it must take the
object to be formatted and return the raw data for the given
format. Subclasses may use a different call signature for the
`func` argument.
"""
key = (type_module, type_name)
oldfunc = self.deferred_printers.get(key, None)
if func is not None:
# To support easy restoration of old printers, we need to ignore
# Nones.
self.deferred_printers[key] = func
return oldfunc | [
"Add",
"a",
"format",
"function",
"for",
"a",
"type",
"specified",
"by",
"the",
"full",
"dotted",
"module",
"and",
"name",
"of",
"the",
"type",
"rather",
"than",
"the",
"type",
"of",
"the",
"object",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/formatters.py#L274-L298 | [
"def",
"for_type_by_name",
"(",
"self",
",",
"type_module",
",",
"type_name",
",",
"func",
")",
":",
"key",
"=",
"(",
"type_module",
",",
"type_name",
")",
"oldfunc",
"=",
"self",
".",
"deferred_printers",
".",
"get",
"(",
"key",
",",
"None",
")",
"if",
"func",
"is",
"not",
"None",
":",
"# To support easy restoration of old printers, we need to ignore",
"# Nones.",
"self",
".",
"deferred_printers",
"[",
"key",
"]",
"=",
"func",
"return",
"oldfunc"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | BaseFormatter._in_deferred_types | Check if the given class is specified in the deferred type registry.
Returns the printer from the registry if it exists, and None if the
class is not in the registry. Successful matches will be moved to the
regular type registry for future use. | environment/lib/python2.7/site-packages/IPython/core/formatters.py | def _in_deferred_types(self, cls):
"""
Check if the given class is specified in the deferred type registry.
Returns the printer from the registry if it exists, and None if the
class is not in the registry. Successful matches will be moved to the
regular type registry for future use.
"""
mod = getattr(cls, '__module__', None)
name = getattr(cls, '__name__', None)
key = (mod, name)
printer = None
if key in self.deferred_printers:
# Move the printer over to the regular registry.
printer = self.deferred_printers.pop(key)
self.type_printers[cls] = printer
return printer | def _in_deferred_types(self, cls):
"""
Check if the given class is specified in the deferred type registry.
Returns the printer from the registry if it exists, and None if the
class is not in the registry. Successful matches will be moved to the
regular type registry for future use.
"""
mod = getattr(cls, '__module__', None)
name = getattr(cls, '__name__', None)
key = (mod, name)
printer = None
if key in self.deferred_printers:
# Move the printer over to the regular registry.
printer = self.deferred_printers.pop(key)
self.type_printers[cls] = printer
return printer | [
"Check",
"if",
"the",
"given",
"class",
"is",
"specified",
"in",
"the",
"deferred",
"type",
"registry",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/formatters.py#L300-L316 | [
"def",
"_in_deferred_types",
"(",
"self",
",",
"cls",
")",
":",
"mod",
"=",
"getattr",
"(",
"cls",
",",
"'__module__'",
",",
"None",
")",
"name",
"=",
"getattr",
"(",
"cls",
",",
"'__name__'",
",",
"None",
")",
"key",
"=",
"(",
"mod",
",",
"name",
")",
"printer",
"=",
"None",
"if",
"key",
"in",
"self",
".",
"deferred_printers",
":",
"# Move the printer over to the regular registry.",
"printer",
"=",
"self",
".",
"deferred_printers",
".",
"pop",
"(",
"key",
")",
"self",
".",
"type_printers",
"[",
"cls",
"]",
"=",
"printer",
"return",
"printer"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | PlainTextFormatter._float_precision_changed | float_precision changed, set float_format accordingly.
float_precision can be set by int or str.
This will set float_format, after interpreting input.
If numpy has been imported, numpy print precision will also be set.
integer `n` sets format to '%.nf', otherwise, format set directly.
An empty string returns to defaults (repr for float, 8 for numpy).
This parameter can be set via the '%precision' magic. | environment/lib/python2.7/site-packages/IPython/core/formatters.py | def _float_precision_changed(self, name, old, new):
"""float_precision changed, set float_format accordingly.
float_precision can be set by int or str.
This will set float_format, after interpreting input.
If numpy has been imported, numpy print precision will also be set.
integer `n` sets format to '%.nf', otherwise, format set directly.
An empty string returns to defaults (repr for float, 8 for numpy).
This parameter can be set via the '%precision' magic.
"""
if '%' in new:
# got explicit format string
fmt = new
try:
fmt%3.14159
except Exception:
raise ValueError("Precision must be int or format string, not %r"%new)
elif new:
# otherwise, should be an int
try:
i = int(new)
assert i >= 0
except ValueError:
raise ValueError("Precision must be int or format string, not %r"%new)
except AssertionError:
raise ValueError("int precision must be non-negative, not %r"%i)
fmt = '%%.%if'%i
if 'numpy' in sys.modules:
# set numpy precision if it has been imported
import numpy
numpy.set_printoptions(precision=i)
else:
# default back to repr
fmt = '%r'
if 'numpy' in sys.modules:
import numpy
# numpy default is 8
numpy.set_printoptions(precision=8)
self.float_format = fmt | def _float_precision_changed(self, name, old, new):
"""float_precision changed, set float_format accordingly.
float_precision can be set by int or str.
This will set float_format, after interpreting input.
If numpy has been imported, numpy print precision will also be set.
integer `n` sets format to '%.nf', otherwise, format set directly.
An empty string returns to defaults (repr for float, 8 for numpy).
This parameter can be set via the '%precision' magic.
"""
if '%' in new:
# got explicit format string
fmt = new
try:
fmt%3.14159
except Exception:
raise ValueError("Precision must be int or format string, not %r"%new)
elif new:
# otherwise, should be an int
try:
i = int(new)
assert i >= 0
except ValueError:
raise ValueError("Precision must be int or format string, not %r"%new)
except AssertionError:
raise ValueError("int precision must be non-negative, not %r"%i)
fmt = '%%.%if'%i
if 'numpy' in sys.modules:
# set numpy precision if it has been imported
import numpy
numpy.set_printoptions(precision=i)
else:
# default back to repr
fmt = '%r'
if 'numpy' in sys.modules:
import numpy
# numpy default is 8
numpy.set_printoptions(precision=8)
self.float_format = fmt | [
"float_precision",
"changed",
"set",
"float_format",
"accordingly",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/formatters.py#L370-L413 | [
"def",
"_float_precision_changed",
"(",
"self",
",",
"name",
",",
"old",
",",
"new",
")",
":",
"if",
"'%'",
"in",
"new",
":",
"# got explicit format string",
"fmt",
"=",
"new",
"try",
":",
"fmt",
"%",
"3.14159",
"except",
"Exception",
":",
"raise",
"ValueError",
"(",
"\"Precision must be int or format string, not %r\"",
"%",
"new",
")",
"elif",
"new",
":",
"# otherwise, should be an int",
"try",
":",
"i",
"=",
"int",
"(",
"new",
")",
"assert",
"i",
">=",
"0",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"\"Precision must be int or format string, not %r\"",
"%",
"new",
")",
"except",
"AssertionError",
":",
"raise",
"ValueError",
"(",
"\"int precision must be non-negative, not %r\"",
"%",
"i",
")",
"fmt",
"=",
"'%%.%if'",
"%",
"i",
"if",
"'numpy'",
"in",
"sys",
".",
"modules",
":",
"# set numpy precision if it has been imported",
"import",
"numpy",
"numpy",
".",
"set_printoptions",
"(",
"precision",
"=",
"i",
")",
"else",
":",
"# default back to repr",
"fmt",
"=",
"'%r'",
"if",
"'numpy'",
"in",
"sys",
".",
"modules",
":",
"import",
"numpy",
"# numpy default is 8",
"numpy",
".",
"set_printoptions",
"(",
"precision",
"=",
"8",
")",
"self",
".",
"float_format",
"=",
"fmt"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | user_config_files | Return path to any existing user config files | environment/lib/python2.7/site-packages/nose/config.py | def user_config_files():
"""Return path to any existing user config files
"""
return filter(os.path.exists,
map(os.path.expanduser, config_files)) | def user_config_files():
"""Return path to any existing user config files
"""
return filter(os.path.exists,
map(os.path.expanduser, config_files)) | [
"Return",
"path",
"to",
"any",
"existing",
"user",
"config",
"files"
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/config.py#L607-L611 | [
"def",
"user_config_files",
"(",
")",
":",
"return",
"filter",
"(",
"os",
".",
"path",
".",
"exists",
",",
"map",
"(",
"os",
".",
"path",
".",
"expanduser",
",",
"config_files",
")",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | flag | Does the value look like an on/off flag? | environment/lib/python2.7/site-packages/nose/config.py | def flag(val):
"""Does the value look like an on/off flag?"""
if val == 1:
return True
elif val == 0:
return False
val = str(val)
if len(val) > 5:
return False
return val.upper() in ('1', '0', 'F', 'T', 'TRUE', 'FALSE', 'ON', 'OFF') | def flag(val):
"""Does the value look like an on/off flag?"""
if val == 1:
return True
elif val == 0:
return False
val = str(val)
if len(val) > 5:
return False
return val.upper() in ('1', '0', 'F', 'T', 'TRUE', 'FALSE', 'ON', 'OFF') | [
"Does",
"the",
"value",
"look",
"like",
"an",
"on",
"/",
"off",
"flag?"
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/config.py#L625-L634 | [
"def",
"flag",
"(",
"val",
")",
":",
"if",
"val",
"==",
"1",
":",
"return",
"True",
"elif",
"val",
"==",
"0",
":",
"return",
"False",
"val",
"=",
"str",
"(",
"val",
")",
"if",
"len",
"(",
"val",
")",
">",
"5",
":",
"return",
"False",
"return",
"val",
".",
"upper",
"(",
")",
"in",
"(",
"'1'",
",",
"'0'",
",",
"'F'",
",",
"'T'",
",",
"'TRUE'",
",",
"'FALSE'",
",",
"'ON'",
",",
"'OFF'",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | Config.configure | Configure the nose running environment. Execute configure before
collecting tests with nose.TestCollector to enable output capture and
other features. | environment/lib/python2.7/site-packages/nose/config.py | def configure(self, argv=None, doc=None):
"""Configure the nose running environment. Execute configure before
collecting tests with nose.TestCollector to enable output capture and
other features.
"""
env = self.env
if argv is None:
argv = sys.argv
cfg_files = getattr(self, 'files', [])
options, args = self._parseArgs(argv, cfg_files)
# If -c --config has been specified on command line,
# load those config files and reparse
if getattr(options, 'files', []):
options, args = self._parseArgs(argv, options.files)
self.options = options
if args:
self.testNames = args
if options.testNames is not None:
self.testNames.extend(tolist(options.testNames))
if options.py3where is not None:
if sys.version_info >= (3,):
options.where = options.py3where
# `where` is an append action, so it can't have a default value
# in the parser, or that default will always be in the list
if not options.where:
options.where = env.get('NOSE_WHERE', None)
# include and exclude also
if not options.ignoreFiles:
options.ignoreFiles = env.get('NOSE_IGNORE_FILES', [])
if not options.include:
options.include = env.get('NOSE_INCLUDE', [])
if not options.exclude:
options.exclude = env.get('NOSE_EXCLUDE', [])
self.addPaths = options.addPaths
self.stopOnError = options.stopOnError
self.verbosity = options.verbosity
self.includeExe = options.includeExe
self.traverseNamespace = options.traverseNamespace
self.debug = options.debug
self.debugLog = options.debugLog
self.loggingConfig = options.loggingConfig
self.firstPackageWins = options.firstPackageWins
self.configureLogging()
if options.where is not None:
self.configureWhere(options.where)
if options.testMatch:
self.testMatch = re.compile(options.testMatch)
if options.ignoreFiles:
self.ignoreFiles = map(re.compile, tolist(options.ignoreFiles))
log.info("Ignoring files matching %s", options.ignoreFiles)
else:
log.info("Ignoring files matching %s", self.ignoreFilesDefaultStrings)
if options.include:
self.include = map(re.compile, tolist(options.include))
log.info("Including tests matching %s", options.include)
if options.exclude:
self.exclude = map(re.compile, tolist(options.exclude))
log.info("Excluding tests matching %s", options.exclude)
# When listing plugins we don't want to run them
if not options.showPlugins:
self.plugins.configure(options, self)
self.plugins.begin() | def configure(self, argv=None, doc=None):
"""Configure the nose running environment. Execute configure before
collecting tests with nose.TestCollector to enable output capture and
other features.
"""
env = self.env
if argv is None:
argv = sys.argv
cfg_files = getattr(self, 'files', [])
options, args = self._parseArgs(argv, cfg_files)
# If -c --config has been specified on command line,
# load those config files and reparse
if getattr(options, 'files', []):
options, args = self._parseArgs(argv, options.files)
self.options = options
if args:
self.testNames = args
if options.testNames is not None:
self.testNames.extend(tolist(options.testNames))
if options.py3where is not None:
if sys.version_info >= (3,):
options.where = options.py3where
# `where` is an append action, so it can't have a default value
# in the parser, or that default will always be in the list
if not options.where:
options.where = env.get('NOSE_WHERE', None)
# include and exclude also
if not options.ignoreFiles:
options.ignoreFiles = env.get('NOSE_IGNORE_FILES', [])
if not options.include:
options.include = env.get('NOSE_INCLUDE', [])
if not options.exclude:
options.exclude = env.get('NOSE_EXCLUDE', [])
self.addPaths = options.addPaths
self.stopOnError = options.stopOnError
self.verbosity = options.verbosity
self.includeExe = options.includeExe
self.traverseNamespace = options.traverseNamespace
self.debug = options.debug
self.debugLog = options.debugLog
self.loggingConfig = options.loggingConfig
self.firstPackageWins = options.firstPackageWins
self.configureLogging()
if options.where is not None:
self.configureWhere(options.where)
if options.testMatch:
self.testMatch = re.compile(options.testMatch)
if options.ignoreFiles:
self.ignoreFiles = map(re.compile, tolist(options.ignoreFiles))
log.info("Ignoring files matching %s", options.ignoreFiles)
else:
log.info("Ignoring files matching %s", self.ignoreFilesDefaultStrings)
if options.include:
self.include = map(re.compile, tolist(options.include))
log.info("Including tests matching %s", options.include)
if options.exclude:
self.exclude = map(re.compile, tolist(options.exclude))
log.info("Excluding tests matching %s", options.exclude)
# When listing plugins we don't want to run them
if not options.showPlugins:
self.plugins.configure(options, self)
self.plugins.begin() | [
"Configure",
"the",
"nose",
"running",
"environment",
".",
"Execute",
"configure",
"before",
"collecting",
"tests",
"with",
"nose",
".",
"TestCollector",
"to",
"enable",
"output",
"capture",
"and",
"other",
"features",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/config.py#L266-L339 | [
"def",
"configure",
"(",
"self",
",",
"argv",
"=",
"None",
",",
"doc",
"=",
"None",
")",
":",
"env",
"=",
"self",
".",
"env",
"if",
"argv",
"is",
"None",
":",
"argv",
"=",
"sys",
".",
"argv",
"cfg_files",
"=",
"getattr",
"(",
"self",
",",
"'files'",
",",
"[",
"]",
")",
"options",
",",
"args",
"=",
"self",
".",
"_parseArgs",
"(",
"argv",
",",
"cfg_files",
")",
"# If -c --config has been specified on command line,",
"# load those config files and reparse",
"if",
"getattr",
"(",
"options",
",",
"'files'",
",",
"[",
"]",
")",
":",
"options",
",",
"args",
"=",
"self",
".",
"_parseArgs",
"(",
"argv",
",",
"options",
".",
"files",
")",
"self",
".",
"options",
"=",
"options",
"if",
"args",
":",
"self",
".",
"testNames",
"=",
"args",
"if",
"options",
".",
"testNames",
"is",
"not",
"None",
":",
"self",
".",
"testNames",
".",
"extend",
"(",
"tolist",
"(",
"options",
".",
"testNames",
")",
")",
"if",
"options",
".",
"py3where",
"is",
"not",
"None",
":",
"if",
"sys",
".",
"version_info",
">=",
"(",
"3",
",",
")",
":",
"options",
".",
"where",
"=",
"options",
".",
"py3where",
"# `where` is an append action, so it can't have a default value",
"# in the parser, or that default will always be in the list",
"if",
"not",
"options",
".",
"where",
":",
"options",
".",
"where",
"=",
"env",
".",
"get",
"(",
"'NOSE_WHERE'",
",",
"None",
")",
"# include and exclude also",
"if",
"not",
"options",
".",
"ignoreFiles",
":",
"options",
".",
"ignoreFiles",
"=",
"env",
".",
"get",
"(",
"'NOSE_IGNORE_FILES'",
",",
"[",
"]",
")",
"if",
"not",
"options",
".",
"include",
":",
"options",
".",
"include",
"=",
"env",
".",
"get",
"(",
"'NOSE_INCLUDE'",
",",
"[",
"]",
")",
"if",
"not",
"options",
".",
"exclude",
":",
"options",
".",
"exclude",
"=",
"env",
".",
"get",
"(",
"'NOSE_EXCLUDE'",
",",
"[",
"]",
")",
"self",
".",
"addPaths",
"=",
"options",
".",
"addPaths",
"self",
".",
"stopOnError",
"=",
"options",
".",
"stopOnError",
"self",
".",
"verbosity",
"=",
"options",
".",
"verbosity",
"self",
".",
"includeExe",
"=",
"options",
".",
"includeExe",
"self",
".",
"traverseNamespace",
"=",
"options",
".",
"traverseNamespace",
"self",
".",
"debug",
"=",
"options",
".",
"debug",
"self",
".",
"debugLog",
"=",
"options",
".",
"debugLog",
"self",
".",
"loggingConfig",
"=",
"options",
".",
"loggingConfig",
"self",
".",
"firstPackageWins",
"=",
"options",
".",
"firstPackageWins",
"self",
".",
"configureLogging",
"(",
")",
"if",
"options",
".",
"where",
"is",
"not",
"None",
":",
"self",
".",
"configureWhere",
"(",
"options",
".",
"where",
")",
"if",
"options",
".",
"testMatch",
":",
"self",
".",
"testMatch",
"=",
"re",
".",
"compile",
"(",
"options",
".",
"testMatch",
")",
"if",
"options",
".",
"ignoreFiles",
":",
"self",
".",
"ignoreFiles",
"=",
"map",
"(",
"re",
".",
"compile",
",",
"tolist",
"(",
"options",
".",
"ignoreFiles",
")",
")",
"log",
".",
"info",
"(",
"\"Ignoring files matching %s\"",
",",
"options",
".",
"ignoreFiles",
")",
"else",
":",
"log",
".",
"info",
"(",
"\"Ignoring files matching %s\"",
",",
"self",
".",
"ignoreFilesDefaultStrings",
")",
"if",
"options",
".",
"include",
":",
"self",
".",
"include",
"=",
"map",
"(",
"re",
".",
"compile",
",",
"tolist",
"(",
"options",
".",
"include",
")",
")",
"log",
".",
"info",
"(",
"\"Including tests matching %s\"",
",",
"options",
".",
"include",
")",
"if",
"options",
".",
"exclude",
":",
"self",
".",
"exclude",
"=",
"map",
"(",
"re",
".",
"compile",
",",
"tolist",
"(",
"options",
".",
"exclude",
")",
")",
"log",
".",
"info",
"(",
"\"Excluding tests matching %s\"",
",",
"options",
".",
"exclude",
")",
"# When listing plugins we don't want to run them",
"if",
"not",
"options",
".",
"showPlugins",
":",
"self",
".",
"plugins",
".",
"configure",
"(",
"options",
",",
"self",
")",
"self",
".",
"plugins",
".",
"begin",
"(",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | Config.configureLogging | Configure logging for nose, or optionally other packages. Any logger
name may be set with the debug option, and that logger will be set to
debug level and be assigned the same handler as the nose loggers, unless
it already has a handler. | environment/lib/python2.7/site-packages/nose/config.py | def configureLogging(self):
"""Configure logging for nose, or optionally other packages. Any logger
name may be set with the debug option, and that logger will be set to
debug level and be assigned the same handler as the nose loggers, unless
it already has a handler.
"""
if self.loggingConfig:
from logging.config import fileConfig
fileConfig(self.loggingConfig)
return
format = logging.Formatter('%(name)s: %(levelname)s: %(message)s')
if self.debugLog:
handler = logging.FileHandler(self.debugLog)
else:
handler = logging.StreamHandler(self.logStream)
handler.setFormatter(format)
logger = logging.getLogger('nose')
logger.propagate = 0
# only add our default handler if there isn't already one there
# this avoids annoying duplicate log messages.
if handler not in logger.handlers:
logger.addHandler(handler)
# default level
lvl = logging.WARNING
if self.verbosity >= 5:
lvl = 0
elif self.verbosity >= 4:
lvl = logging.DEBUG
elif self.verbosity >= 3:
lvl = logging.INFO
logger.setLevel(lvl)
# individual overrides
if self.debug:
# no blanks
debug_loggers = [ name for name in self.debug.split(',')
if name ]
for logger_name in debug_loggers:
l = logging.getLogger(logger_name)
l.setLevel(logging.DEBUG)
if not l.handlers and not logger_name.startswith('nose'):
l.addHandler(handler) | def configureLogging(self):
"""Configure logging for nose, or optionally other packages. Any logger
name may be set with the debug option, and that logger will be set to
debug level and be assigned the same handler as the nose loggers, unless
it already has a handler.
"""
if self.loggingConfig:
from logging.config import fileConfig
fileConfig(self.loggingConfig)
return
format = logging.Formatter('%(name)s: %(levelname)s: %(message)s')
if self.debugLog:
handler = logging.FileHandler(self.debugLog)
else:
handler = logging.StreamHandler(self.logStream)
handler.setFormatter(format)
logger = logging.getLogger('nose')
logger.propagate = 0
# only add our default handler if there isn't already one there
# this avoids annoying duplicate log messages.
if handler not in logger.handlers:
logger.addHandler(handler)
# default level
lvl = logging.WARNING
if self.verbosity >= 5:
lvl = 0
elif self.verbosity >= 4:
lvl = logging.DEBUG
elif self.verbosity >= 3:
lvl = logging.INFO
logger.setLevel(lvl)
# individual overrides
if self.debug:
# no blanks
debug_loggers = [ name for name in self.debug.split(',')
if name ]
for logger_name in debug_loggers:
l = logging.getLogger(logger_name)
l.setLevel(logging.DEBUG)
if not l.handlers and not logger_name.startswith('nose'):
l.addHandler(handler) | [
"Configure",
"logging",
"for",
"nose",
"or",
"optionally",
"other",
"packages",
".",
"Any",
"logger",
"name",
"may",
"be",
"set",
"with",
"the",
"debug",
"option",
"and",
"that",
"logger",
"will",
"be",
"set",
"to",
"debug",
"level",
"and",
"be",
"assigned",
"the",
"same",
"handler",
"as",
"the",
"nose",
"loggers",
"unless",
"it",
"already",
"has",
"a",
"handler",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/config.py#L341-L386 | [
"def",
"configureLogging",
"(",
"self",
")",
":",
"if",
"self",
".",
"loggingConfig",
":",
"from",
"logging",
".",
"config",
"import",
"fileConfig",
"fileConfig",
"(",
"self",
".",
"loggingConfig",
")",
"return",
"format",
"=",
"logging",
".",
"Formatter",
"(",
"'%(name)s: %(levelname)s: %(message)s'",
")",
"if",
"self",
".",
"debugLog",
":",
"handler",
"=",
"logging",
".",
"FileHandler",
"(",
"self",
".",
"debugLog",
")",
"else",
":",
"handler",
"=",
"logging",
".",
"StreamHandler",
"(",
"self",
".",
"logStream",
")",
"handler",
".",
"setFormatter",
"(",
"format",
")",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"'nose'",
")",
"logger",
".",
"propagate",
"=",
"0",
"# only add our default handler if there isn't already one there",
"# this avoids annoying duplicate log messages.",
"if",
"handler",
"not",
"in",
"logger",
".",
"handlers",
":",
"logger",
".",
"addHandler",
"(",
"handler",
")",
"# default level",
"lvl",
"=",
"logging",
".",
"WARNING",
"if",
"self",
".",
"verbosity",
">=",
"5",
":",
"lvl",
"=",
"0",
"elif",
"self",
".",
"verbosity",
">=",
"4",
":",
"lvl",
"=",
"logging",
".",
"DEBUG",
"elif",
"self",
".",
"verbosity",
">=",
"3",
":",
"lvl",
"=",
"logging",
".",
"INFO",
"logger",
".",
"setLevel",
"(",
"lvl",
")",
"# individual overrides",
"if",
"self",
".",
"debug",
":",
"# no blanks",
"debug_loggers",
"=",
"[",
"name",
"for",
"name",
"in",
"self",
".",
"debug",
".",
"split",
"(",
"','",
")",
"if",
"name",
"]",
"for",
"logger_name",
"in",
"debug_loggers",
":",
"l",
"=",
"logging",
".",
"getLogger",
"(",
"logger_name",
")",
"l",
".",
"setLevel",
"(",
"logging",
".",
"DEBUG",
")",
"if",
"not",
"l",
".",
"handlers",
"and",
"not",
"logger_name",
".",
"startswith",
"(",
"'nose'",
")",
":",
"l",
".",
"addHandler",
"(",
"handler",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | Config.configureWhere | Configure the working directory or directories for the test run. | environment/lib/python2.7/site-packages/nose/config.py | def configureWhere(self, where):
"""Configure the working directory or directories for the test run.
"""
from nose.importer import add_path
self.workingDir = None
where = tolist(where)
warned = False
for path in where:
if not self.workingDir:
abs_path = absdir(path)
if abs_path is None:
raise ValueError("Working directory %s not found, or "
"not a directory" % path)
log.info("Set working dir to %s", abs_path)
self.workingDir = abs_path
if self.addPaths and \
os.path.exists(os.path.join(abs_path, '__init__.py')):
log.info("Working directory %s is a package; "
"adding to sys.path" % abs_path)
add_path(abs_path)
continue
if not warned:
warn("Use of multiple -w arguments is deprecated and "
"support may be removed in a future release. You can "
"get the same behavior by passing directories without "
"the -w argument on the command line, or by using the "
"--tests argument in a configuration file.",
DeprecationWarning)
self.testNames.append(path) | def configureWhere(self, where):
"""Configure the working directory or directories for the test run.
"""
from nose.importer import add_path
self.workingDir = None
where = tolist(where)
warned = False
for path in where:
if not self.workingDir:
abs_path = absdir(path)
if abs_path is None:
raise ValueError("Working directory %s not found, or "
"not a directory" % path)
log.info("Set working dir to %s", abs_path)
self.workingDir = abs_path
if self.addPaths and \
os.path.exists(os.path.join(abs_path, '__init__.py')):
log.info("Working directory %s is a package; "
"adding to sys.path" % abs_path)
add_path(abs_path)
continue
if not warned:
warn("Use of multiple -w arguments is deprecated and "
"support may be removed in a future release. You can "
"get the same behavior by passing directories without "
"the -w argument on the command line, or by using the "
"--tests argument in a configuration file.",
DeprecationWarning)
self.testNames.append(path) | [
"Configure",
"the",
"working",
"directory",
"or",
"directories",
"for",
"the",
"test",
"run",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/config.py#L388-L416 | [
"def",
"configureWhere",
"(",
"self",
",",
"where",
")",
":",
"from",
"nose",
".",
"importer",
"import",
"add_path",
"self",
".",
"workingDir",
"=",
"None",
"where",
"=",
"tolist",
"(",
"where",
")",
"warned",
"=",
"False",
"for",
"path",
"in",
"where",
":",
"if",
"not",
"self",
".",
"workingDir",
":",
"abs_path",
"=",
"absdir",
"(",
"path",
")",
"if",
"abs_path",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Working directory %s not found, or \"",
"\"not a directory\"",
"%",
"path",
")",
"log",
".",
"info",
"(",
"\"Set working dir to %s\"",
",",
"abs_path",
")",
"self",
".",
"workingDir",
"=",
"abs_path",
"if",
"self",
".",
"addPaths",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"abs_path",
",",
"'__init__.py'",
")",
")",
":",
"log",
".",
"info",
"(",
"\"Working directory %s is a package; \"",
"\"adding to sys.path\"",
"%",
"abs_path",
")",
"add_path",
"(",
"abs_path",
")",
"continue",
"if",
"not",
"warned",
":",
"warn",
"(",
"\"Use of multiple -w arguments is deprecated and \"",
"\"support may be removed in a future release. You can \"",
"\"get the same behavior by passing directories without \"",
"\"the -w argument on the command line, or by using the \"",
"\"--tests argument in a configuration file.\"",
",",
"DeprecationWarning",
")",
"self",
".",
"testNames",
".",
"append",
"(",
"path",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | Config.getParser | Get the command line option parser. | environment/lib/python2.7/site-packages/nose/config.py | def getParser(self, doc=None):
"""Get the command line option parser.
"""
if self.parser:
return self.parser
env = self.env
parser = self.parserClass(doc)
parser.add_option(
"-V","--version", action="store_true",
dest="version", default=False,
help="Output nose version and exit")
parser.add_option(
"-p", "--plugins", action="store_true",
dest="showPlugins", default=False,
help="Output list of available plugins and exit. Combine with "
"higher verbosity for greater detail")
parser.add_option(
"-v", "--verbose",
action="count", dest="verbosity",
default=self.verbosity,
help="Be more verbose. [NOSE_VERBOSE]")
parser.add_option(
"--verbosity", action="store", dest="verbosity",
metavar='VERBOSITY',
type="int", help="Set verbosity; --verbosity=2 is "
"the same as -v")
parser.add_option(
"-q", "--quiet", action="store_const", const=0, dest="verbosity",
help="Be less verbose")
parser.add_option(
"-c", "--config", action="append", dest="files",
metavar="FILES",
help="Load configuration from config file(s). May be specified "
"multiple times; in that case, all config files will be "
"loaded and combined")
parser.add_option(
"-w", "--where", action="append", dest="where",
metavar="WHERE",
help="Look for tests in this directory. "
"May be specified multiple times. The first directory passed "
"will be used as the working directory, in place of the current "
"working directory, which is the default. Others will be added "
"to the list of tests to execute. [NOSE_WHERE]"
)
parser.add_option(
"--py3where", action="append", dest="py3where",
metavar="PY3WHERE",
help="Look for tests in this directory under Python 3.x. "
"Functions the same as 'where', but only applies if running under "
"Python 3.x or above. Note that, if present under 3.x, this "
"option completely replaces any directories specified with "
"'where', so the 'where' option becomes ineffective. "
"[NOSE_PY3WHERE]"
)
parser.add_option(
"-m", "--match", "--testmatch", action="store",
dest="testMatch", metavar="REGEX",
help="Files, directories, function names, and class names "
"that match this regular expression are considered tests. "
"Default: %s [NOSE_TESTMATCH]" % self.testMatchPat,
default=self.testMatchPat)
parser.add_option(
"--tests", action="store", dest="testNames", default=None,
metavar='NAMES',
help="Run these tests (comma-separated list). This argument is "
"useful mainly from configuration files; on the command line, "
"just pass the tests to run as additional arguments with no "
"switch.")
parser.add_option(
"-l", "--debug", action="store",
dest="debug", default=self.debug,
help="Activate debug logging for one or more systems. "
"Available debug loggers: nose, nose.importer, "
"nose.inspector, nose.plugins, nose.result and "
"nose.selector. Separate multiple names with a comma.")
parser.add_option(
"--debug-log", dest="debugLog", action="store",
default=self.debugLog, metavar="FILE",
help="Log debug messages to this file "
"(default: sys.stderr)")
parser.add_option(
"--logging-config", "--log-config",
dest="loggingConfig", action="store",
default=self.loggingConfig, metavar="FILE",
help="Load logging config from this file -- bypasses all other"
" logging config settings.")
parser.add_option(
"-I", "--ignore-files", action="append", dest="ignoreFiles",
metavar="REGEX",
help="Completely ignore any file that matches this regular "
"expression. Takes precedence over any other settings or "
"plugins. "
"Specifying this option will replace the default setting. "
"Specify this option multiple times "
"to add more regular expressions [NOSE_IGNORE_FILES]")
parser.add_option(
"-e", "--exclude", action="append", dest="exclude",
metavar="REGEX",
help="Don't run tests that match regular "
"expression [NOSE_EXCLUDE]")
parser.add_option(
"-i", "--include", action="append", dest="include",
metavar="REGEX",
help="This regular expression will be applied to files, "
"directories, function names, and class names for a chance "
"to include additional tests that do not match TESTMATCH. "
"Specify this option multiple times "
"to add more regular expressions [NOSE_INCLUDE]")
parser.add_option(
"-x", "--stop", action="store_true", dest="stopOnError",
default=self.stopOnError,
help="Stop running tests after the first error or failure")
parser.add_option(
"-P", "--no-path-adjustment", action="store_false",
dest="addPaths",
default=self.addPaths,
help="Don't make any changes to sys.path when "
"loading tests [NOSE_NOPATH]")
parser.add_option(
"--exe", action="store_true", dest="includeExe",
default=self.includeExe,
help="Look for tests in python modules that are "
"executable. Normal behavior is to exclude executable "
"modules, since they may not be import-safe "
"[NOSE_INCLUDE_EXE]")
parser.add_option(
"--noexe", action="store_false", dest="includeExe",
help="DO NOT look for tests in python modules that are "
"executable. (The default on the windows platform is to "
"do so.)")
parser.add_option(
"--traverse-namespace", action="store_true",
default=self.traverseNamespace, dest="traverseNamespace",
help="Traverse through all path entries of a namespace package")
parser.add_option(
"--first-package-wins", "--first-pkg-wins", "--1st-pkg-wins",
action="store_true", default=False, dest="firstPackageWins",
help="nose's importer will normally evict a package from sys."
"modules if it sees a package with the same name in a different "
"location. Set this option to disable that behavior.")
self.plugins.loadPlugins()
self.pluginOpts(parser)
self.parser = parser
return parser | def getParser(self, doc=None):
"""Get the command line option parser.
"""
if self.parser:
return self.parser
env = self.env
parser = self.parserClass(doc)
parser.add_option(
"-V","--version", action="store_true",
dest="version", default=False,
help="Output nose version and exit")
parser.add_option(
"-p", "--plugins", action="store_true",
dest="showPlugins", default=False,
help="Output list of available plugins and exit. Combine with "
"higher verbosity for greater detail")
parser.add_option(
"-v", "--verbose",
action="count", dest="verbosity",
default=self.verbosity,
help="Be more verbose. [NOSE_VERBOSE]")
parser.add_option(
"--verbosity", action="store", dest="verbosity",
metavar='VERBOSITY',
type="int", help="Set verbosity; --verbosity=2 is "
"the same as -v")
parser.add_option(
"-q", "--quiet", action="store_const", const=0, dest="verbosity",
help="Be less verbose")
parser.add_option(
"-c", "--config", action="append", dest="files",
metavar="FILES",
help="Load configuration from config file(s). May be specified "
"multiple times; in that case, all config files will be "
"loaded and combined")
parser.add_option(
"-w", "--where", action="append", dest="where",
metavar="WHERE",
help="Look for tests in this directory. "
"May be specified multiple times. The first directory passed "
"will be used as the working directory, in place of the current "
"working directory, which is the default. Others will be added "
"to the list of tests to execute. [NOSE_WHERE]"
)
parser.add_option(
"--py3where", action="append", dest="py3where",
metavar="PY3WHERE",
help="Look for tests in this directory under Python 3.x. "
"Functions the same as 'where', but only applies if running under "
"Python 3.x or above. Note that, if present under 3.x, this "
"option completely replaces any directories specified with "
"'where', so the 'where' option becomes ineffective. "
"[NOSE_PY3WHERE]"
)
parser.add_option(
"-m", "--match", "--testmatch", action="store",
dest="testMatch", metavar="REGEX",
help="Files, directories, function names, and class names "
"that match this regular expression are considered tests. "
"Default: %s [NOSE_TESTMATCH]" % self.testMatchPat,
default=self.testMatchPat)
parser.add_option(
"--tests", action="store", dest="testNames", default=None,
metavar='NAMES',
help="Run these tests (comma-separated list). This argument is "
"useful mainly from configuration files; on the command line, "
"just pass the tests to run as additional arguments with no "
"switch.")
parser.add_option(
"-l", "--debug", action="store",
dest="debug", default=self.debug,
help="Activate debug logging for one or more systems. "
"Available debug loggers: nose, nose.importer, "
"nose.inspector, nose.plugins, nose.result and "
"nose.selector. Separate multiple names with a comma.")
parser.add_option(
"--debug-log", dest="debugLog", action="store",
default=self.debugLog, metavar="FILE",
help="Log debug messages to this file "
"(default: sys.stderr)")
parser.add_option(
"--logging-config", "--log-config",
dest="loggingConfig", action="store",
default=self.loggingConfig, metavar="FILE",
help="Load logging config from this file -- bypasses all other"
" logging config settings.")
parser.add_option(
"-I", "--ignore-files", action="append", dest="ignoreFiles",
metavar="REGEX",
help="Completely ignore any file that matches this regular "
"expression. Takes precedence over any other settings or "
"plugins. "
"Specifying this option will replace the default setting. "
"Specify this option multiple times "
"to add more regular expressions [NOSE_IGNORE_FILES]")
parser.add_option(
"-e", "--exclude", action="append", dest="exclude",
metavar="REGEX",
help="Don't run tests that match regular "
"expression [NOSE_EXCLUDE]")
parser.add_option(
"-i", "--include", action="append", dest="include",
metavar="REGEX",
help="This regular expression will be applied to files, "
"directories, function names, and class names for a chance "
"to include additional tests that do not match TESTMATCH. "
"Specify this option multiple times "
"to add more regular expressions [NOSE_INCLUDE]")
parser.add_option(
"-x", "--stop", action="store_true", dest="stopOnError",
default=self.stopOnError,
help="Stop running tests after the first error or failure")
parser.add_option(
"-P", "--no-path-adjustment", action="store_false",
dest="addPaths",
default=self.addPaths,
help="Don't make any changes to sys.path when "
"loading tests [NOSE_NOPATH]")
parser.add_option(
"--exe", action="store_true", dest="includeExe",
default=self.includeExe,
help="Look for tests in python modules that are "
"executable. Normal behavior is to exclude executable "
"modules, since they may not be import-safe "
"[NOSE_INCLUDE_EXE]")
parser.add_option(
"--noexe", action="store_false", dest="includeExe",
help="DO NOT look for tests in python modules that are "
"executable. (The default on the windows platform is to "
"do so.)")
parser.add_option(
"--traverse-namespace", action="store_true",
default=self.traverseNamespace, dest="traverseNamespace",
help="Traverse through all path entries of a namespace package")
parser.add_option(
"--first-package-wins", "--first-pkg-wins", "--1st-pkg-wins",
action="store_true", default=False, dest="firstPackageWins",
help="nose's importer will normally evict a package from sys."
"modules if it sees a package with the same name in a different "
"location. Set this option to disable that behavior.")
self.plugins.loadPlugins()
self.pluginOpts(parser)
self.parser = parser
return parser | [
"Get",
"the",
"command",
"line",
"option",
"parser",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/config.py#L423-L568 | [
"def",
"getParser",
"(",
"self",
",",
"doc",
"=",
"None",
")",
":",
"if",
"self",
".",
"parser",
":",
"return",
"self",
".",
"parser",
"env",
"=",
"self",
".",
"env",
"parser",
"=",
"self",
".",
"parserClass",
"(",
"doc",
")",
"parser",
".",
"add_option",
"(",
"\"-V\"",
",",
"\"--version\"",
",",
"action",
"=",
"\"store_true\"",
",",
"dest",
"=",
"\"version\"",
",",
"default",
"=",
"False",
",",
"help",
"=",
"\"Output nose version and exit\"",
")",
"parser",
".",
"add_option",
"(",
"\"-p\"",
",",
"\"--plugins\"",
",",
"action",
"=",
"\"store_true\"",
",",
"dest",
"=",
"\"showPlugins\"",
",",
"default",
"=",
"False",
",",
"help",
"=",
"\"Output list of available plugins and exit. Combine with \"",
"\"higher verbosity for greater detail\"",
")",
"parser",
".",
"add_option",
"(",
"\"-v\"",
",",
"\"--verbose\"",
",",
"action",
"=",
"\"count\"",
",",
"dest",
"=",
"\"verbosity\"",
",",
"default",
"=",
"self",
".",
"verbosity",
",",
"help",
"=",
"\"Be more verbose. [NOSE_VERBOSE]\"",
")",
"parser",
".",
"add_option",
"(",
"\"--verbosity\"",
",",
"action",
"=",
"\"store\"",
",",
"dest",
"=",
"\"verbosity\"",
",",
"metavar",
"=",
"'VERBOSITY'",
",",
"type",
"=",
"\"int\"",
",",
"help",
"=",
"\"Set verbosity; --verbosity=2 is \"",
"\"the same as -v\"",
")",
"parser",
".",
"add_option",
"(",
"\"-q\"",
",",
"\"--quiet\"",
",",
"action",
"=",
"\"store_const\"",
",",
"const",
"=",
"0",
",",
"dest",
"=",
"\"verbosity\"",
",",
"help",
"=",
"\"Be less verbose\"",
")",
"parser",
".",
"add_option",
"(",
"\"-c\"",
",",
"\"--config\"",
",",
"action",
"=",
"\"append\"",
",",
"dest",
"=",
"\"files\"",
",",
"metavar",
"=",
"\"FILES\"",
",",
"help",
"=",
"\"Load configuration from config file(s). May be specified \"",
"\"multiple times; in that case, all config files will be \"",
"\"loaded and combined\"",
")",
"parser",
".",
"add_option",
"(",
"\"-w\"",
",",
"\"--where\"",
",",
"action",
"=",
"\"append\"",
",",
"dest",
"=",
"\"where\"",
",",
"metavar",
"=",
"\"WHERE\"",
",",
"help",
"=",
"\"Look for tests in this directory. \"",
"\"May be specified multiple times. The first directory passed \"",
"\"will be used as the working directory, in place of the current \"",
"\"working directory, which is the default. Others will be added \"",
"\"to the list of tests to execute. [NOSE_WHERE]\"",
")",
"parser",
".",
"add_option",
"(",
"\"--py3where\"",
",",
"action",
"=",
"\"append\"",
",",
"dest",
"=",
"\"py3where\"",
",",
"metavar",
"=",
"\"PY3WHERE\"",
",",
"help",
"=",
"\"Look for tests in this directory under Python 3.x. \"",
"\"Functions the same as 'where', but only applies if running under \"",
"\"Python 3.x or above. Note that, if present under 3.x, this \"",
"\"option completely replaces any directories specified with \"",
"\"'where', so the 'where' option becomes ineffective. \"",
"\"[NOSE_PY3WHERE]\"",
")",
"parser",
".",
"add_option",
"(",
"\"-m\"",
",",
"\"--match\"",
",",
"\"--testmatch\"",
",",
"action",
"=",
"\"store\"",
",",
"dest",
"=",
"\"testMatch\"",
",",
"metavar",
"=",
"\"REGEX\"",
",",
"help",
"=",
"\"Files, directories, function names, and class names \"",
"\"that match this regular expression are considered tests. \"",
"\"Default: %s [NOSE_TESTMATCH]\"",
"%",
"self",
".",
"testMatchPat",
",",
"default",
"=",
"self",
".",
"testMatchPat",
")",
"parser",
".",
"add_option",
"(",
"\"--tests\"",
",",
"action",
"=",
"\"store\"",
",",
"dest",
"=",
"\"testNames\"",
",",
"default",
"=",
"None",
",",
"metavar",
"=",
"'NAMES'",
",",
"help",
"=",
"\"Run these tests (comma-separated list). This argument is \"",
"\"useful mainly from configuration files; on the command line, \"",
"\"just pass the tests to run as additional arguments with no \"",
"\"switch.\"",
")",
"parser",
".",
"add_option",
"(",
"\"-l\"",
",",
"\"--debug\"",
",",
"action",
"=",
"\"store\"",
",",
"dest",
"=",
"\"debug\"",
",",
"default",
"=",
"self",
".",
"debug",
",",
"help",
"=",
"\"Activate debug logging for one or more systems. \"",
"\"Available debug loggers: nose, nose.importer, \"",
"\"nose.inspector, nose.plugins, nose.result and \"",
"\"nose.selector. Separate multiple names with a comma.\"",
")",
"parser",
".",
"add_option",
"(",
"\"--debug-log\"",
",",
"dest",
"=",
"\"debugLog\"",
",",
"action",
"=",
"\"store\"",
",",
"default",
"=",
"self",
".",
"debugLog",
",",
"metavar",
"=",
"\"FILE\"",
",",
"help",
"=",
"\"Log debug messages to this file \"",
"\"(default: sys.stderr)\"",
")",
"parser",
".",
"add_option",
"(",
"\"--logging-config\"",
",",
"\"--log-config\"",
",",
"dest",
"=",
"\"loggingConfig\"",
",",
"action",
"=",
"\"store\"",
",",
"default",
"=",
"self",
".",
"loggingConfig",
",",
"metavar",
"=",
"\"FILE\"",
",",
"help",
"=",
"\"Load logging config from this file -- bypasses all other\"",
"\" logging config settings.\"",
")",
"parser",
".",
"add_option",
"(",
"\"-I\"",
",",
"\"--ignore-files\"",
",",
"action",
"=",
"\"append\"",
",",
"dest",
"=",
"\"ignoreFiles\"",
",",
"metavar",
"=",
"\"REGEX\"",
",",
"help",
"=",
"\"Completely ignore any file that matches this regular \"",
"\"expression. Takes precedence over any other settings or \"",
"\"plugins. \"",
"\"Specifying this option will replace the default setting. \"",
"\"Specify this option multiple times \"",
"\"to add more regular expressions [NOSE_IGNORE_FILES]\"",
")",
"parser",
".",
"add_option",
"(",
"\"-e\"",
",",
"\"--exclude\"",
",",
"action",
"=",
"\"append\"",
",",
"dest",
"=",
"\"exclude\"",
",",
"metavar",
"=",
"\"REGEX\"",
",",
"help",
"=",
"\"Don't run tests that match regular \"",
"\"expression [NOSE_EXCLUDE]\"",
")",
"parser",
".",
"add_option",
"(",
"\"-i\"",
",",
"\"--include\"",
",",
"action",
"=",
"\"append\"",
",",
"dest",
"=",
"\"include\"",
",",
"metavar",
"=",
"\"REGEX\"",
",",
"help",
"=",
"\"This regular expression will be applied to files, \"",
"\"directories, function names, and class names for a chance \"",
"\"to include additional tests that do not match TESTMATCH. \"",
"\"Specify this option multiple times \"",
"\"to add more regular expressions [NOSE_INCLUDE]\"",
")",
"parser",
".",
"add_option",
"(",
"\"-x\"",
",",
"\"--stop\"",
",",
"action",
"=",
"\"store_true\"",
",",
"dest",
"=",
"\"stopOnError\"",
",",
"default",
"=",
"self",
".",
"stopOnError",
",",
"help",
"=",
"\"Stop running tests after the first error or failure\"",
")",
"parser",
".",
"add_option",
"(",
"\"-P\"",
",",
"\"--no-path-adjustment\"",
",",
"action",
"=",
"\"store_false\"",
",",
"dest",
"=",
"\"addPaths\"",
",",
"default",
"=",
"self",
".",
"addPaths",
",",
"help",
"=",
"\"Don't make any changes to sys.path when \"",
"\"loading tests [NOSE_NOPATH]\"",
")",
"parser",
".",
"add_option",
"(",
"\"--exe\"",
",",
"action",
"=",
"\"store_true\"",
",",
"dest",
"=",
"\"includeExe\"",
",",
"default",
"=",
"self",
".",
"includeExe",
",",
"help",
"=",
"\"Look for tests in python modules that are \"",
"\"executable. Normal behavior is to exclude executable \"",
"\"modules, since they may not be import-safe \"",
"\"[NOSE_INCLUDE_EXE]\"",
")",
"parser",
".",
"add_option",
"(",
"\"--noexe\"",
",",
"action",
"=",
"\"store_false\"",
",",
"dest",
"=",
"\"includeExe\"",
",",
"help",
"=",
"\"DO NOT look for tests in python modules that are \"",
"\"executable. (The default on the windows platform is to \"",
"\"do so.)\"",
")",
"parser",
".",
"add_option",
"(",
"\"--traverse-namespace\"",
",",
"action",
"=",
"\"store_true\"",
",",
"default",
"=",
"self",
".",
"traverseNamespace",
",",
"dest",
"=",
"\"traverseNamespace\"",
",",
"help",
"=",
"\"Traverse through all path entries of a namespace package\"",
")",
"parser",
".",
"add_option",
"(",
"\"--first-package-wins\"",
",",
"\"--first-pkg-wins\"",
",",
"\"--1st-pkg-wins\"",
",",
"action",
"=",
"\"store_true\"",
",",
"default",
"=",
"False",
",",
"dest",
"=",
"\"firstPackageWins\"",
",",
"help",
"=",
"\"nose's importer will normally evict a package from sys.\"",
"\"modules if it sees a package with the same name in a different \"",
"\"location. Set this option to disable that behavior.\"",
")",
"self",
".",
"plugins",
".",
"loadPlugins",
"(",
")",
"self",
".",
"pluginOpts",
"(",
"parser",
")",
"self",
".",
"parser",
"=",
"parser",
"return",
"parser"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | page_dumb | Very dumb 'pager' in Python, for when nothing else works.
Only moves forward, same interface as page(), except for pager_cmd and
mode. | environment/lib/python2.7/site-packages/IPython/core/page.py | def page_dumb(strng, start=0, screen_lines=25):
"""Very dumb 'pager' in Python, for when nothing else works.
Only moves forward, same interface as page(), except for pager_cmd and
mode."""
out_ln = strng.splitlines()[start:]
screens = chop(out_ln,screen_lines-1)
if len(screens) == 1:
print >>io.stdout, os.linesep.join(screens[0])
else:
last_escape = ""
for scr in screens[0:-1]:
hunk = os.linesep.join(scr)
print >>io.stdout, last_escape + hunk
if not page_more():
return
esc_list = esc_re.findall(hunk)
if len(esc_list) > 0:
last_escape = esc_list[-1]
print >>io.stdout, last_escape + os.linesep.join(screens[-1]) | def page_dumb(strng, start=0, screen_lines=25):
"""Very dumb 'pager' in Python, for when nothing else works.
Only moves forward, same interface as page(), except for pager_cmd and
mode."""
out_ln = strng.splitlines()[start:]
screens = chop(out_ln,screen_lines-1)
if len(screens) == 1:
print >>io.stdout, os.linesep.join(screens[0])
else:
last_escape = ""
for scr in screens[0:-1]:
hunk = os.linesep.join(scr)
print >>io.stdout, last_escape + hunk
if not page_more():
return
esc_list = esc_re.findall(hunk)
if len(esc_list) > 0:
last_escape = esc_list[-1]
print >>io.stdout, last_escape + os.linesep.join(screens[-1]) | [
"Very",
"dumb",
"pager",
"in",
"Python",
"for",
"when",
"nothing",
"else",
"works",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/page.py#L51-L71 | [
"def",
"page_dumb",
"(",
"strng",
",",
"start",
"=",
"0",
",",
"screen_lines",
"=",
"25",
")",
":",
"out_ln",
"=",
"strng",
".",
"splitlines",
"(",
")",
"[",
"start",
":",
"]",
"screens",
"=",
"chop",
"(",
"out_ln",
",",
"screen_lines",
"-",
"1",
")",
"if",
"len",
"(",
"screens",
")",
"==",
"1",
":",
"print",
">>",
"io",
".",
"stdout",
",",
"os",
".",
"linesep",
".",
"join",
"(",
"screens",
"[",
"0",
"]",
")",
"else",
":",
"last_escape",
"=",
"\"\"",
"for",
"scr",
"in",
"screens",
"[",
"0",
":",
"-",
"1",
"]",
":",
"hunk",
"=",
"os",
".",
"linesep",
".",
"join",
"(",
"scr",
")",
"print",
">>",
"io",
".",
"stdout",
",",
"last_escape",
"+",
"hunk",
"if",
"not",
"page_more",
"(",
")",
":",
"return",
"esc_list",
"=",
"esc_re",
".",
"findall",
"(",
"hunk",
")",
"if",
"len",
"(",
"esc_list",
")",
">",
"0",
":",
"last_escape",
"=",
"esc_list",
"[",
"-",
"1",
"]",
"print",
">>",
"io",
".",
"stdout",
",",
"last_escape",
"+",
"os",
".",
"linesep",
".",
"join",
"(",
"screens",
"[",
"-",
"1",
"]",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | _detect_screen_size | Attempt to work out the number of lines on the screen.
This is called by page(). It can raise an error (e.g. when run in the
test suite), so it's separated out so it can easily be called in a try block. | environment/lib/python2.7/site-packages/IPython/core/page.py | def _detect_screen_size(use_curses, screen_lines_def):
"""Attempt to work out the number of lines on the screen.
This is called by page(). It can raise an error (e.g. when run in the
test suite), so it's separated out so it can easily be called in a try block.
"""
TERM = os.environ.get('TERM',None)
if (TERM=='xterm' or TERM=='xterm-color') and sys.platform != 'sunos5':
local_use_curses = use_curses
else:
# curses causes problems on many terminals other than xterm, and
# some termios calls lock up on Sun OS5.
local_use_curses = False
if local_use_curses:
import termios
import curses
# There is a bug in curses, where *sometimes* it fails to properly
# initialize, and then after the endwin() call is made, the
# terminal is left in an unusable state. Rather than trying to
# check everytime for this (by requesting and comparing termios
# flags each time), we just save the initial terminal state and
# unconditionally reset it every time. It's cheaper than making
# the checks.
term_flags = termios.tcgetattr(sys.stdout)
# Curses modifies the stdout buffer size by default, which messes
# up Python's normal stdout buffering. This would manifest itself
# to IPython users as delayed printing on stdout after having used
# the pager.
#
# We can prevent this by manually setting the NCURSES_NO_SETBUF
# environment variable. For more details, see:
# http://bugs.python.org/issue10144
NCURSES_NO_SETBUF = os.environ.get('NCURSES_NO_SETBUF', None)
os.environ['NCURSES_NO_SETBUF'] = ''
# Proceed with curses initialization
scr = curses.initscr()
screen_lines_real,screen_cols = scr.getmaxyx()
curses.endwin()
# Restore environment
if NCURSES_NO_SETBUF is None:
del os.environ['NCURSES_NO_SETBUF']
else:
os.environ['NCURSES_NO_SETBUF'] = NCURSES_NO_SETBUF
# Restore terminal state in case endwin() didn't.
termios.tcsetattr(sys.stdout,termios.TCSANOW,term_flags)
# Now we have what we needed: the screen size in rows/columns
return screen_lines_real
#print '***Screen size:',screen_lines_real,'lines x',\
#screen_cols,'columns.' # dbg
else:
return screen_lines_def | def _detect_screen_size(use_curses, screen_lines_def):
"""Attempt to work out the number of lines on the screen.
This is called by page(). It can raise an error (e.g. when run in the
test suite), so it's separated out so it can easily be called in a try block.
"""
TERM = os.environ.get('TERM',None)
if (TERM=='xterm' or TERM=='xterm-color') and sys.platform != 'sunos5':
local_use_curses = use_curses
else:
# curses causes problems on many terminals other than xterm, and
# some termios calls lock up on Sun OS5.
local_use_curses = False
if local_use_curses:
import termios
import curses
# There is a bug in curses, where *sometimes* it fails to properly
# initialize, and then after the endwin() call is made, the
# terminal is left in an unusable state. Rather than trying to
# check everytime for this (by requesting and comparing termios
# flags each time), we just save the initial terminal state and
# unconditionally reset it every time. It's cheaper than making
# the checks.
term_flags = termios.tcgetattr(sys.stdout)
# Curses modifies the stdout buffer size by default, which messes
# up Python's normal stdout buffering. This would manifest itself
# to IPython users as delayed printing on stdout after having used
# the pager.
#
# We can prevent this by manually setting the NCURSES_NO_SETBUF
# environment variable. For more details, see:
# http://bugs.python.org/issue10144
NCURSES_NO_SETBUF = os.environ.get('NCURSES_NO_SETBUF', None)
os.environ['NCURSES_NO_SETBUF'] = ''
# Proceed with curses initialization
scr = curses.initscr()
screen_lines_real,screen_cols = scr.getmaxyx()
curses.endwin()
# Restore environment
if NCURSES_NO_SETBUF is None:
del os.environ['NCURSES_NO_SETBUF']
else:
os.environ['NCURSES_NO_SETBUF'] = NCURSES_NO_SETBUF
# Restore terminal state in case endwin() didn't.
termios.tcsetattr(sys.stdout,termios.TCSANOW,term_flags)
# Now we have what we needed: the screen size in rows/columns
return screen_lines_real
#print '***Screen size:',screen_lines_real,'lines x',\
#screen_cols,'columns.' # dbg
else:
return screen_lines_def | [
"Attempt",
"to",
"work",
"out",
"the",
"number",
"of",
"lines",
"on",
"the",
"screen",
".",
"This",
"is",
"called",
"by",
"page",
"()",
".",
"It",
"can",
"raise",
"an",
"error",
"(",
"e",
".",
"g",
".",
"when",
"run",
"in",
"the",
"test",
"suite",
")",
"so",
"it",
"s",
"separated",
"out",
"so",
"it",
"can",
"easily",
"be",
"called",
"in",
"a",
"try",
"block",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/page.py#L73-L127 | [
"def",
"_detect_screen_size",
"(",
"use_curses",
",",
"screen_lines_def",
")",
":",
"TERM",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'TERM'",
",",
"None",
")",
"if",
"(",
"TERM",
"==",
"'xterm'",
"or",
"TERM",
"==",
"'xterm-color'",
")",
"and",
"sys",
".",
"platform",
"!=",
"'sunos5'",
":",
"local_use_curses",
"=",
"use_curses",
"else",
":",
"# curses causes problems on many terminals other than xterm, and",
"# some termios calls lock up on Sun OS5.",
"local_use_curses",
"=",
"False",
"if",
"local_use_curses",
":",
"import",
"termios",
"import",
"curses",
"# There is a bug in curses, where *sometimes* it fails to properly",
"# initialize, and then after the endwin() call is made, the",
"# terminal is left in an unusable state. Rather than trying to",
"# check everytime for this (by requesting and comparing termios",
"# flags each time), we just save the initial terminal state and",
"# unconditionally reset it every time. It's cheaper than making",
"# the checks.",
"term_flags",
"=",
"termios",
".",
"tcgetattr",
"(",
"sys",
".",
"stdout",
")",
"# Curses modifies the stdout buffer size by default, which messes",
"# up Python's normal stdout buffering. This would manifest itself",
"# to IPython users as delayed printing on stdout after having used",
"# the pager.",
"#",
"# We can prevent this by manually setting the NCURSES_NO_SETBUF",
"# environment variable. For more details, see:",
"# http://bugs.python.org/issue10144",
"NCURSES_NO_SETBUF",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'NCURSES_NO_SETBUF'",
",",
"None",
")",
"os",
".",
"environ",
"[",
"'NCURSES_NO_SETBUF'",
"]",
"=",
"''",
"# Proceed with curses initialization",
"scr",
"=",
"curses",
".",
"initscr",
"(",
")",
"screen_lines_real",
",",
"screen_cols",
"=",
"scr",
".",
"getmaxyx",
"(",
")",
"curses",
".",
"endwin",
"(",
")",
"# Restore environment",
"if",
"NCURSES_NO_SETBUF",
"is",
"None",
":",
"del",
"os",
".",
"environ",
"[",
"'NCURSES_NO_SETBUF'",
"]",
"else",
":",
"os",
".",
"environ",
"[",
"'NCURSES_NO_SETBUF'",
"]",
"=",
"NCURSES_NO_SETBUF",
"# Restore terminal state in case endwin() didn't.",
"termios",
".",
"tcsetattr",
"(",
"sys",
".",
"stdout",
",",
"termios",
".",
"TCSANOW",
",",
"term_flags",
")",
"# Now we have what we needed: the screen size in rows/columns",
"return",
"screen_lines_real",
"#print '***Screen size:',screen_lines_real,'lines x',\\",
"#screen_cols,'columns.' # dbg",
"else",
":",
"return",
"screen_lines_def"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | page | Print a string, piping through a pager after a certain length.
The screen_lines parameter specifies the number of *usable* lines of your
terminal screen (total lines minus lines you need to reserve to show other
information).
If you set screen_lines to a number <=0, page() will try to auto-determine
your screen size and will only use up to (screen_size+screen_lines) for
printing, paging after that. That is, if you want auto-detection but need
to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
auto-detection without any lines reserved simply use screen_lines = 0.
If a string won't fit in the allowed lines, it is sent through the
specified pager command. If none given, look for PAGER in the environment,
and ultimately default to less.
If no system pager works, the string is sent through a 'dumb pager'
written in python, very simplistic. | environment/lib/python2.7/site-packages/IPython/core/page.py | def page(strng, start=0, screen_lines=0, pager_cmd=None):
"""Print a string, piping through a pager after a certain length.
The screen_lines parameter specifies the number of *usable* lines of your
terminal screen (total lines minus lines you need to reserve to show other
information).
If you set screen_lines to a number <=0, page() will try to auto-determine
your screen size and will only use up to (screen_size+screen_lines) for
printing, paging after that. That is, if you want auto-detection but need
to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
auto-detection without any lines reserved simply use screen_lines = 0.
If a string won't fit in the allowed lines, it is sent through the
specified pager command. If none given, look for PAGER in the environment,
and ultimately default to less.
If no system pager works, the string is sent through a 'dumb pager'
written in python, very simplistic.
"""
# Some routines may auto-compute start offsets incorrectly and pass a
# negative value. Offset to 0 for robustness.
start = max(0, start)
# first, try the hook
ip = ipapi.get()
if ip:
try:
ip.hooks.show_in_pager(strng)
return
except TryNext:
pass
# Ugly kludge, but calling curses.initscr() flat out crashes in emacs
TERM = os.environ.get('TERM','dumb')
if TERM in ['dumb','emacs'] and os.name != 'nt':
print strng
return
# chop off the topmost part of the string we don't want to see
str_lines = strng.splitlines()[start:]
str_toprint = os.linesep.join(str_lines)
num_newlines = len(str_lines)
len_str = len(str_toprint)
# Dumb heuristics to guesstimate number of on-screen lines the string
# takes. Very basic, but good enough for docstrings in reasonable
# terminals. If someone later feels like refining it, it's not hard.
numlines = max(num_newlines,int(len_str/80)+1)
screen_lines_def = get_terminal_size()[1]
# auto-determine screen size
if screen_lines <= 0:
try:
screen_lines += _detect_screen_size(use_curses, screen_lines_def)
except (TypeError, UnsupportedOperation):
print >>io.stdout, str_toprint
return
#print 'numlines',numlines,'screenlines',screen_lines # dbg
if numlines <= screen_lines :
#print '*** normal print' # dbg
print >>io.stdout, str_toprint
else:
# Try to open pager and default to internal one if that fails.
# All failure modes are tagged as 'retval=1', to match the return
# value of a failed system command. If any intermediate attempt
# sets retval to 1, at the end we resort to our own page_dumb() pager.
pager_cmd = get_pager_cmd(pager_cmd)
pager_cmd += ' ' + get_pager_start(pager_cmd,start)
if os.name == 'nt':
if pager_cmd.startswith('type'):
# The default WinXP 'type' command is failing on complex strings.
retval = 1
else:
tmpname = tempfile.mktemp('.txt')
tmpfile = open(tmpname,'wt')
tmpfile.write(strng)
tmpfile.close()
cmd = "%s < %s" % (pager_cmd,tmpname)
if os.system(cmd):
retval = 1
else:
retval = None
os.remove(tmpname)
else:
try:
retval = None
# if I use popen4, things hang. No idea why.
#pager,shell_out = os.popen4(pager_cmd)
pager = os.popen(pager_cmd,'w')
pager.write(strng)
pager.close()
retval = pager.close() # success returns None
except IOError,msg: # broken pipe when user quits
if msg.args == (32,'Broken pipe'):
retval = None
else:
retval = 1
except OSError:
# Other strange problems, sometimes seen in Win2k/cygwin
retval = 1
if retval is not None:
page_dumb(strng,screen_lines=screen_lines) | def page(strng, start=0, screen_lines=0, pager_cmd=None):
"""Print a string, piping through a pager after a certain length.
The screen_lines parameter specifies the number of *usable* lines of your
terminal screen (total lines minus lines you need to reserve to show other
information).
If you set screen_lines to a number <=0, page() will try to auto-determine
your screen size and will only use up to (screen_size+screen_lines) for
printing, paging after that. That is, if you want auto-detection but need
to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
auto-detection without any lines reserved simply use screen_lines = 0.
If a string won't fit in the allowed lines, it is sent through the
specified pager command. If none given, look for PAGER in the environment,
and ultimately default to less.
If no system pager works, the string is sent through a 'dumb pager'
written in python, very simplistic.
"""
# Some routines may auto-compute start offsets incorrectly and pass a
# negative value. Offset to 0 for robustness.
start = max(0, start)
# first, try the hook
ip = ipapi.get()
if ip:
try:
ip.hooks.show_in_pager(strng)
return
except TryNext:
pass
# Ugly kludge, but calling curses.initscr() flat out crashes in emacs
TERM = os.environ.get('TERM','dumb')
if TERM in ['dumb','emacs'] and os.name != 'nt':
print strng
return
# chop off the topmost part of the string we don't want to see
str_lines = strng.splitlines()[start:]
str_toprint = os.linesep.join(str_lines)
num_newlines = len(str_lines)
len_str = len(str_toprint)
# Dumb heuristics to guesstimate number of on-screen lines the string
# takes. Very basic, but good enough for docstrings in reasonable
# terminals. If someone later feels like refining it, it's not hard.
numlines = max(num_newlines,int(len_str/80)+1)
screen_lines_def = get_terminal_size()[1]
# auto-determine screen size
if screen_lines <= 0:
try:
screen_lines += _detect_screen_size(use_curses, screen_lines_def)
except (TypeError, UnsupportedOperation):
print >>io.stdout, str_toprint
return
#print 'numlines',numlines,'screenlines',screen_lines # dbg
if numlines <= screen_lines :
#print '*** normal print' # dbg
print >>io.stdout, str_toprint
else:
# Try to open pager and default to internal one if that fails.
# All failure modes are tagged as 'retval=1', to match the return
# value of a failed system command. If any intermediate attempt
# sets retval to 1, at the end we resort to our own page_dumb() pager.
pager_cmd = get_pager_cmd(pager_cmd)
pager_cmd += ' ' + get_pager_start(pager_cmd,start)
if os.name == 'nt':
if pager_cmd.startswith('type'):
# The default WinXP 'type' command is failing on complex strings.
retval = 1
else:
tmpname = tempfile.mktemp('.txt')
tmpfile = open(tmpname,'wt')
tmpfile.write(strng)
tmpfile.close()
cmd = "%s < %s" % (pager_cmd,tmpname)
if os.system(cmd):
retval = 1
else:
retval = None
os.remove(tmpname)
else:
try:
retval = None
# if I use popen4, things hang. No idea why.
#pager,shell_out = os.popen4(pager_cmd)
pager = os.popen(pager_cmd,'w')
pager.write(strng)
pager.close()
retval = pager.close() # success returns None
except IOError,msg: # broken pipe when user quits
if msg.args == (32,'Broken pipe'):
retval = None
else:
retval = 1
except OSError:
# Other strange problems, sometimes seen in Win2k/cygwin
retval = 1
if retval is not None:
page_dumb(strng,screen_lines=screen_lines) | [
"Print",
"a",
"string",
"piping",
"through",
"a",
"pager",
"after",
"a",
"certain",
"length",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/page.py#L129-L233 | [
"def",
"page",
"(",
"strng",
",",
"start",
"=",
"0",
",",
"screen_lines",
"=",
"0",
",",
"pager_cmd",
"=",
"None",
")",
":",
"# Some routines may auto-compute start offsets incorrectly and pass a",
"# negative value. Offset to 0 for robustness.",
"start",
"=",
"max",
"(",
"0",
",",
"start",
")",
"# first, try the hook",
"ip",
"=",
"ipapi",
".",
"get",
"(",
")",
"if",
"ip",
":",
"try",
":",
"ip",
".",
"hooks",
".",
"show_in_pager",
"(",
"strng",
")",
"return",
"except",
"TryNext",
":",
"pass",
"# Ugly kludge, but calling curses.initscr() flat out crashes in emacs",
"TERM",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'TERM'",
",",
"'dumb'",
")",
"if",
"TERM",
"in",
"[",
"'dumb'",
",",
"'emacs'",
"]",
"and",
"os",
".",
"name",
"!=",
"'nt'",
":",
"print",
"strng",
"return",
"# chop off the topmost part of the string we don't want to see",
"str_lines",
"=",
"strng",
".",
"splitlines",
"(",
")",
"[",
"start",
":",
"]",
"str_toprint",
"=",
"os",
".",
"linesep",
".",
"join",
"(",
"str_lines",
")",
"num_newlines",
"=",
"len",
"(",
"str_lines",
")",
"len_str",
"=",
"len",
"(",
"str_toprint",
")",
"# Dumb heuristics to guesstimate number of on-screen lines the string",
"# takes. Very basic, but good enough for docstrings in reasonable",
"# terminals. If someone later feels like refining it, it's not hard.",
"numlines",
"=",
"max",
"(",
"num_newlines",
",",
"int",
"(",
"len_str",
"/",
"80",
")",
"+",
"1",
")",
"screen_lines_def",
"=",
"get_terminal_size",
"(",
")",
"[",
"1",
"]",
"# auto-determine screen size",
"if",
"screen_lines",
"<=",
"0",
":",
"try",
":",
"screen_lines",
"+=",
"_detect_screen_size",
"(",
"use_curses",
",",
"screen_lines_def",
")",
"except",
"(",
"TypeError",
",",
"UnsupportedOperation",
")",
":",
"print",
">>",
"io",
".",
"stdout",
",",
"str_toprint",
"return",
"#print 'numlines',numlines,'screenlines',screen_lines # dbg",
"if",
"numlines",
"<=",
"screen_lines",
":",
"#print '*** normal print' # dbg",
"print",
">>",
"io",
".",
"stdout",
",",
"str_toprint",
"else",
":",
"# Try to open pager and default to internal one if that fails.",
"# All failure modes are tagged as 'retval=1', to match the return",
"# value of a failed system command. If any intermediate attempt",
"# sets retval to 1, at the end we resort to our own page_dumb() pager.",
"pager_cmd",
"=",
"get_pager_cmd",
"(",
"pager_cmd",
")",
"pager_cmd",
"+=",
"' '",
"+",
"get_pager_start",
"(",
"pager_cmd",
",",
"start",
")",
"if",
"os",
".",
"name",
"==",
"'nt'",
":",
"if",
"pager_cmd",
".",
"startswith",
"(",
"'type'",
")",
":",
"# The default WinXP 'type' command is failing on complex strings.",
"retval",
"=",
"1",
"else",
":",
"tmpname",
"=",
"tempfile",
".",
"mktemp",
"(",
"'.txt'",
")",
"tmpfile",
"=",
"open",
"(",
"tmpname",
",",
"'wt'",
")",
"tmpfile",
".",
"write",
"(",
"strng",
")",
"tmpfile",
".",
"close",
"(",
")",
"cmd",
"=",
"\"%s < %s\"",
"%",
"(",
"pager_cmd",
",",
"tmpname",
")",
"if",
"os",
".",
"system",
"(",
"cmd",
")",
":",
"retval",
"=",
"1",
"else",
":",
"retval",
"=",
"None",
"os",
".",
"remove",
"(",
"tmpname",
")",
"else",
":",
"try",
":",
"retval",
"=",
"None",
"# if I use popen4, things hang. No idea why.",
"#pager,shell_out = os.popen4(pager_cmd)",
"pager",
"=",
"os",
".",
"popen",
"(",
"pager_cmd",
",",
"'w'",
")",
"pager",
".",
"write",
"(",
"strng",
")",
"pager",
".",
"close",
"(",
")",
"retval",
"=",
"pager",
".",
"close",
"(",
")",
"# success returns None",
"except",
"IOError",
",",
"msg",
":",
"# broken pipe when user quits",
"if",
"msg",
".",
"args",
"==",
"(",
"32",
",",
"'Broken pipe'",
")",
":",
"retval",
"=",
"None",
"else",
":",
"retval",
"=",
"1",
"except",
"OSError",
":",
"# Other strange problems, sometimes seen in Win2k/cygwin",
"retval",
"=",
"1",
"if",
"retval",
"is",
"not",
"None",
":",
"page_dumb",
"(",
"strng",
",",
"screen_lines",
"=",
"screen_lines",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | page_file | Page a file, using an optional pager command and starting line. | environment/lib/python2.7/site-packages/IPython/core/page.py | def page_file(fname, start=0, pager_cmd=None):
"""Page a file, using an optional pager command and starting line.
"""
pager_cmd = get_pager_cmd(pager_cmd)
pager_cmd += ' ' + get_pager_start(pager_cmd,start)
try:
if os.environ['TERM'] in ['emacs','dumb']:
raise EnvironmentError
system(pager_cmd + ' ' + fname)
except:
try:
if start > 0:
start -= 1
page(open(fname).read(),start)
except:
print 'Unable to show file',`fname` | def page_file(fname, start=0, pager_cmd=None):
"""Page a file, using an optional pager command and starting line.
"""
pager_cmd = get_pager_cmd(pager_cmd)
pager_cmd += ' ' + get_pager_start(pager_cmd,start)
try:
if os.environ['TERM'] in ['emacs','dumb']:
raise EnvironmentError
system(pager_cmd + ' ' + fname)
except:
try:
if start > 0:
start -= 1
page(open(fname).read(),start)
except:
print 'Unable to show file',`fname` | [
"Page",
"a",
"file",
"using",
"an",
"optional",
"pager",
"command",
"and",
"starting",
"line",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/page.py#L236-L253 | [
"def",
"page_file",
"(",
"fname",
",",
"start",
"=",
"0",
",",
"pager_cmd",
"=",
"None",
")",
":",
"pager_cmd",
"=",
"get_pager_cmd",
"(",
"pager_cmd",
")",
"pager_cmd",
"+=",
"' '",
"+",
"get_pager_start",
"(",
"pager_cmd",
",",
"start",
")",
"try",
":",
"if",
"os",
".",
"environ",
"[",
"'TERM'",
"]",
"in",
"[",
"'emacs'",
",",
"'dumb'",
"]",
":",
"raise",
"EnvironmentError",
"system",
"(",
"pager_cmd",
"+",
"' '",
"+",
"fname",
")",
"except",
":",
"try",
":",
"if",
"start",
">",
"0",
":",
"start",
"-=",
"1",
"page",
"(",
"open",
"(",
"fname",
")",
".",
"read",
"(",
")",
",",
"start",
")",
"except",
":",
"print",
"'Unable to show file'",
",",
"`fname`"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | get_pager_cmd | Return a pager command.
Makes some attempts at finding an OS-correct one. | environment/lib/python2.7/site-packages/IPython/core/page.py | def get_pager_cmd(pager_cmd=None):
"""Return a pager command.
Makes some attempts at finding an OS-correct one.
"""
if os.name == 'posix':
default_pager_cmd = 'less -r' # -r for color control sequences
elif os.name in ['nt','dos']:
default_pager_cmd = 'type'
if pager_cmd is None:
try:
pager_cmd = os.environ['PAGER']
except:
pager_cmd = default_pager_cmd
return pager_cmd | def get_pager_cmd(pager_cmd=None):
"""Return a pager command.
Makes some attempts at finding an OS-correct one.
"""
if os.name == 'posix':
default_pager_cmd = 'less -r' # -r for color control sequences
elif os.name in ['nt','dos']:
default_pager_cmd = 'type'
if pager_cmd is None:
try:
pager_cmd = os.environ['PAGER']
except:
pager_cmd = default_pager_cmd
return pager_cmd | [
"Return",
"a",
"pager",
"command",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/page.py#L256-L271 | [
"def",
"get_pager_cmd",
"(",
"pager_cmd",
"=",
"None",
")",
":",
"if",
"os",
".",
"name",
"==",
"'posix'",
":",
"default_pager_cmd",
"=",
"'less -r'",
"# -r for color control sequences",
"elif",
"os",
".",
"name",
"in",
"[",
"'nt'",
",",
"'dos'",
"]",
":",
"default_pager_cmd",
"=",
"'type'",
"if",
"pager_cmd",
"is",
"None",
":",
"try",
":",
"pager_cmd",
"=",
"os",
".",
"environ",
"[",
"'PAGER'",
"]",
"except",
":",
"pager_cmd",
"=",
"default_pager_cmd",
"return",
"pager_cmd"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | get_pager_start | Return the string for paging files with an offset.
This is the '+N' argument which less and more (under Unix) accept. | environment/lib/python2.7/site-packages/IPython/core/page.py | def get_pager_start(pager, start):
"""Return the string for paging files with an offset.
This is the '+N' argument which less and more (under Unix) accept.
"""
if pager in ['less','more']:
if start:
start_string = '+' + str(start)
else:
start_string = ''
else:
start_string = ''
return start_string | def get_pager_start(pager, start):
"""Return the string for paging files with an offset.
This is the '+N' argument which less and more (under Unix) accept.
"""
if pager in ['less','more']:
if start:
start_string = '+' + str(start)
else:
start_string = ''
else:
start_string = ''
return start_string | [
"Return",
"the",
"string",
"for",
"paging",
"files",
"with",
"an",
"offset",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/page.py#L274-L287 | [
"def",
"get_pager_start",
"(",
"pager",
",",
"start",
")",
":",
"if",
"pager",
"in",
"[",
"'less'",
",",
"'more'",
"]",
":",
"if",
"start",
":",
"start_string",
"=",
"'+'",
"+",
"str",
"(",
"start",
")",
"else",
":",
"start_string",
"=",
"''",
"else",
":",
"start_string",
"=",
"''",
"return",
"start_string"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | snip_print | Print a string snipping the midsection to fit in width.
print_full: mode control:
- 0: only snip long strings
- 1: send to page() directly.
- 2: snip long strings and ask for full length viewing with page()
Return 1 if snipping was necessary, 0 otherwise. | environment/lib/python2.7/site-packages/IPython/core/page.py | def snip_print(str,width = 75,print_full = 0,header = ''):
"""Print a string snipping the midsection to fit in width.
print_full: mode control:
- 0: only snip long strings
- 1: send to page() directly.
- 2: snip long strings and ask for full length viewing with page()
Return 1 if snipping was necessary, 0 otherwise."""
if print_full == 1:
page(header+str)
return 0
print header,
if len(str) < width:
print str
snip = 0
else:
whalf = int((width -5)/2)
print str[:whalf] + ' <...> ' + str[-whalf:]
snip = 1
if snip and print_full == 2:
if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
page(str)
return snip | def snip_print(str,width = 75,print_full = 0,header = ''):
"""Print a string snipping the midsection to fit in width.
print_full: mode control:
- 0: only snip long strings
- 1: send to page() directly.
- 2: snip long strings and ask for full length viewing with page()
Return 1 if snipping was necessary, 0 otherwise."""
if print_full == 1:
page(header+str)
return 0
print header,
if len(str) < width:
print str
snip = 0
else:
whalf = int((width -5)/2)
print str[:whalf] + ' <...> ' + str[-whalf:]
snip = 1
if snip and print_full == 2:
if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
page(str)
return snip | [
"Print",
"a",
"string",
"snipping",
"the",
"midsection",
"to",
"fit",
"in",
"width",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/page.py#L315-L339 | [
"def",
"snip_print",
"(",
"str",
",",
"width",
"=",
"75",
",",
"print_full",
"=",
"0",
",",
"header",
"=",
"''",
")",
":",
"if",
"print_full",
"==",
"1",
":",
"page",
"(",
"header",
"+",
"str",
")",
"return",
"0",
"print",
"header",
",",
"if",
"len",
"(",
"str",
")",
"<",
"width",
":",
"print",
"str",
"snip",
"=",
"0",
"else",
":",
"whalf",
"=",
"int",
"(",
"(",
"width",
"-",
"5",
")",
"/",
"2",
")",
"print",
"str",
"[",
":",
"whalf",
"]",
"+",
"' <...> '",
"+",
"str",
"[",
"-",
"whalf",
":",
"]",
"snip",
"=",
"1",
"if",
"snip",
"and",
"print_full",
"==",
"2",
":",
"if",
"raw_input",
"(",
"header",
"+",
"' Snipped. View (y/n)? [N]'",
")",
".",
"lower",
"(",
")",
"==",
"'y'",
":",
"page",
"(",
"str",
")",
"return",
"snip"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | timings_out | timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output)
Execute a function reps times, return a tuple with the elapsed total
CPU time in seconds, the time per call and the function's output.
Under Unix, the return value is the sum of user+system time consumed by
the process, computed via the resource module. This prevents problems
related to the wraparound effect which the time.clock() function has.
Under Windows the return value is in wall clock seconds. See the
documentation for the time module for more details. | environment/lib/python2.7/site-packages/IPython/utils/timing.py | def timings_out(reps,func,*args,**kw):
"""timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output)
Execute a function reps times, return a tuple with the elapsed total
CPU time in seconds, the time per call and the function's output.
Under Unix, the return value is the sum of user+system time consumed by
the process, computed via the resource module. This prevents problems
related to the wraparound effect which the time.clock() function has.
Under Windows the return value is in wall clock seconds. See the
documentation for the time module for more details."""
reps = int(reps)
assert reps >=1, 'reps must be >= 1'
if reps==1:
start = clock()
out = func(*args,**kw)
tot_time = clock()-start
else:
rng = xrange(reps-1) # the last time is executed separately to store output
start = clock()
for dummy in rng: func(*args,**kw)
out = func(*args,**kw) # one last time
tot_time = clock()-start
av_time = tot_time / reps
return tot_time,av_time,out | def timings_out(reps,func,*args,**kw):
"""timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output)
Execute a function reps times, return a tuple with the elapsed total
CPU time in seconds, the time per call and the function's output.
Under Unix, the return value is the sum of user+system time consumed by
the process, computed via the resource module. This prevents problems
related to the wraparound effect which the time.clock() function has.
Under Windows the return value is in wall clock seconds. See the
documentation for the time module for more details."""
reps = int(reps)
assert reps >=1, 'reps must be >= 1'
if reps==1:
start = clock()
out = func(*args,**kw)
tot_time = clock()-start
else:
rng = xrange(reps-1) # the last time is executed separately to store output
start = clock()
for dummy in rng: func(*args,**kw)
out = func(*args,**kw) # one last time
tot_time = clock()-start
av_time = tot_time / reps
return tot_time,av_time,out | [
"timings_out",
"(",
"reps",
"func",
"*",
"args",
"**",
"kw",
")",
"-",
">",
"(",
"t_total",
"t_per_call",
"output",
")"
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/timing.py#L70-L96 | [
"def",
"timings_out",
"(",
"reps",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"reps",
"=",
"int",
"(",
"reps",
")",
"assert",
"reps",
">=",
"1",
",",
"'reps must be >= 1'",
"if",
"reps",
"==",
"1",
":",
"start",
"=",
"clock",
"(",
")",
"out",
"=",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
"tot_time",
"=",
"clock",
"(",
")",
"-",
"start",
"else",
":",
"rng",
"=",
"xrange",
"(",
"reps",
"-",
"1",
")",
"# the last time is executed separately to store output",
"start",
"=",
"clock",
"(",
")",
"for",
"dummy",
"in",
"rng",
":",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
"out",
"=",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
"# one last time",
"tot_time",
"=",
"clock",
"(",
")",
"-",
"start",
"av_time",
"=",
"tot_time",
"/",
"reps",
"return",
"tot_time",
",",
"av_time",
",",
"out"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | timings | timings(reps,func,*args,**kw) -> (t_total,t_per_call)
Execute a function reps times, return a tuple with the elapsed total CPU
time in seconds and the time per call. These are just the first two values
in timings_out(). | environment/lib/python2.7/site-packages/IPython/utils/timing.py | def timings(reps,func,*args,**kw):
"""timings(reps,func,*args,**kw) -> (t_total,t_per_call)
Execute a function reps times, return a tuple with the elapsed total CPU
time in seconds and the time per call. These are just the first two values
in timings_out()."""
return timings_out(reps,func,*args,**kw)[0:2] | def timings(reps,func,*args,**kw):
"""timings(reps,func,*args,**kw) -> (t_total,t_per_call)
Execute a function reps times, return a tuple with the elapsed total CPU
time in seconds and the time per call. These are just the first two values
in timings_out()."""
return timings_out(reps,func,*args,**kw)[0:2] | [
"timings",
"(",
"reps",
"func",
"*",
"args",
"**",
"kw",
")",
"-",
">",
"(",
"t_total",
"t_per_call",
")"
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/timing.py#L99-L106 | [
"def",
"timings",
"(",
"reps",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"return",
"timings_out",
"(",
"reps",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
"[",
"0",
":",
"2",
"]"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | print_basic_unicode | A function to pretty print sympy Basic objects. | environment/lib/python2.7/site-packages/IPython/extensions/sympyprinting.py | def print_basic_unicode(o, p, cycle):
"""A function to pretty print sympy Basic objects."""
if cycle:
return p.text('Basic(...)')
out = pretty(o, use_unicode=True)
if '\n' in out:
p.text(u'\n')
p.text(out) | def print_basic_unicode(o, p, cycle):
"""A function to pretty print sympy Basic objects."""
if cycle:
return p.text('Basic(...)')
out = pretty(o, use_unicode=True)
if '\n' in out:
p.text(u'\n')
p.text(out) | [
"A",
"function",
"to",
"pretty",
"print",
"sympy",
"Basic",
"objects",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/extensions/sympyprinting.py#L44-L51 | [
"def",
"print_basic_unicode",
"(",
"o",
",",
"p",
",",
"cycle",
")",
":",
"if",
"cycle",
":",
"return",
"p",
".",
"text",
"(",
"'Basic(...)'",
")",
"out",
"=",
"pretty",
"(",
"o",
",",
"use_unicode",
"=",
"True",
")",
"if",
"'\\n'",
"in",
"out",
":",
"p",
".",
"text",
"(",
"u'\\n'",
")",
"p",
".",
"text",
"(",
"out",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | print_png | A function to display sympy expression using inline style LaTeX in PNG. | environment/lib/python2.7/site-packages/IPython/extensions/sympyprinting.py | def print_png(o):
"""
A function to display sympy expression using inline style LaTeX in PNG.
"""
s = latex(o, mode='inline')
# mathtext does not understand certain latex flags, so we try to replace
# them with suitable subs.
s = s.replace('\\operatorname','')
s = s.replace('\\overline', '\\bar')
png = latex_to_png(s)
return png | def print_png(o):
"""
A function to display sympy expression using inline style LaTeX in PNG.
"""
s = latex(o, mode='inline')
# mathtext does not understand certain latex flags, so we try to replace
# them with suitable subs.
s = s.replace('\\operatorname','')
s = s.replace('\\overline', '\\bar')
png = latex_to_png(s)
return png | [
"A",
"function",
"to",
"display",
"sympy",
"expression",
"using",
"inline",
"style",
"LaTeX",
"in",
"PNG",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/extensions/sympyprinting.py#L54-L64 | [
"def",
"print_png",
"(",
"o",
")",
":",
"s",
"=",
"latex",
"(",
"o",
",",
"mode",
"=",
"'inline'",
")",
"# mathtext does not understand certain latex flags, so we try to replace",
"# them with suitable subs.",
"s",
"=",
"s",
".",
"replace",
"(",
"'\\\\operatorname'",
",",
"''",
")",
"s",
"=",
"s",
".",
"replace",
"(",
"'\\\\overline'",
",",
"'\\\\bar'",
")",
"png",
"=",
"latex_to_png",
"(",
"s",
")",
"return",
"png"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | print_display_png | A function to display sympy expression using display style LaTeX in PNG. | environment/lib/python2.7/site-packages/IPython/extensions/sympyprinting.py | def print_display_png(o):
"""
A function to display sympy expression using display style LaTeX in PNG.
"""
s = latex(o, mode='plain')
s = s.strip('$')
# As matplotlib does not support display style, dvipng backend is
# used here.
png = latex_to_png('$$%s$$' % s, backend='dvipng')
return png | def print_display_png(o):
"""
A function to display sympy expression using display style LaTeX in PNG.
"""
s = latex(o, mode='plain')
s = s.strip('$')
# As matplotlib does not support display style, dvipng backend is
# used here.
png = latex_to_png('$$%s$$' % s, backend='dvipng')
return png | [
"A",
"function",
"to",
"display",
"sympy",
"expression",
"using",
"display",
"style",
"LaTeX",
"in",
"PNG",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/extensions/sympyprinting.py#L67-L76 | [
"def",
"print_display_png",
"(",
"o",
")",
":",
"s",
"=",
"latex",
"(",
"o",
",",
"mode",
"=",
"'plain'",
")",
"s",
"=",
"s",
".",
"strip",
"(",
"'$'",
")",
"# As matplotlib does not support display style, dvipng backend is",
"# used here.",
"png",
"=",
"latex_to_png",
"(",
"'$$%s$$'",
"%",
"s",
",",
"backend",
"=",
"'dvipng'",
")",
"return",
"png"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | can_print_latex | Return True if type o can be printed with LaTeX.
If o is a container type, this is True if and only if every element of o
can be printed with LaTeX. | environment/lib/python2.7/site-packages/IPython/extensions/sympyprinting.py | def can_print_latex(o):
"""
Return True if type o can be printed with LaTeX.
If o is a container type, this is True if and only if every element of o
can be printed with LaTeX.
"""
import sympy
if isinstance(o, (list, tuple, set, frozenset)):
return all(can_print_latex(i) for i in o)
elif isinstance(o, dict):
return all((isinstance(i, basestring) or can_print_latex(i)) and can_print_latex(o[i]) for i in o)
elif isinstance(o,(sympy.Basic, sympy.matrices.Matrix, int, long, float)):
return True
return False | def can_print_latex(o):
"""
Return True if type o can be printed with LaTeX.
If o is a container type, this is True if and only if every element of o
can be printed with LaTeX.
"""
import sympy
if isinstance(o, (list, tuple, set, frozenset)):
return all(can_print_latex(i) for i in o)
elif isinstance(o, dict):
return all((isinstance(i, basestring) or can_print_latex(i)) and can_print_latex(o[i]) for i in o)
elif isinstance(o,(sympy.Basic, sympy.matrices.Matrix, int, long, float)):
return True
return False | [
"Return",
"True",
"if",
"type",
"o",
"can",
"be",
"printed",
"with",
"LaTeX",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/extensions/sympyprinting.py#L79-L93 | [
"def",
"can_print_latex",
"(",
"o",
")",
":",
"import",
"sympy",
"if",
"isinstance",
"(",
"o",
",",
"(",
"list",
",",
"tuple",
",",
"set",
",",
"frozenset",
")",
")",
":",
"return",
"all",
"(",
"can_print_latex",
"(",
"i",
")",
"for",
"i",
"in",
"o",
")",
"elif",
"isinstance",
"(",
"o",
",",
"dict",
")",
":",
"return",
"all",
"(",
"(",
"isinstance",
"(",
"i",
",",
"basestring",
")",
"or",
"can_print_latex",
"(",
"i",
")",
")",
"and",
"can_print_latex",
"(",
"o",
"[",
"i",
"]",
")",
"for",
"i",
"in",
"o",
")",
"elif",
"isinstance",
"(",
"o",
",",
"(",
"sympy",
".",
"Basic",
",",
"sympy",
".",
"matrices",
".",
"Matrix",
",",
"int",
",",
"long",
",",
"float",
")",
")",
":",
"return",
"True",
"return",
"False"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | print_latex | A function to generate the latex representation of sympy
expressions. | environment/lib/python2.7/site-packages/IPython/extensions/sympyprinting.py | def print_latex(o):
"""A function to generate the latex representation of sympy
expressions."""
if can_print_latex(o):
s = latex(o, mode='plain')
s = s.replace('\\dag','\\dagger')
s = s.strip('$')
return '$$%s$$' % s
# Fallback to the string printer
return None | def print_latex(o):
"""A function to generate the latex representation of sympy
expressions."""
if can_print_latex(o):
s = latex(o, mode='plain')
s = s.replace('\\dag','\\dagger')
s = s.strip('$')
return '$$%s$$' % s
# Fallback to the string printer
return None | [
"A",
"function",
"to",
"generate",
"the",
"latex",
"representation",
"of",
"sympy",
"expressions",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/extensions/sympyprinting.py#L95-L104 | [
"def",
"print_latex",
"(",
"o",
")",
":",
"if",
"can_print_latex",
"(",
"o",
")",
":",
"s",
"=",
"latex",
"(",
"o",
",",
"mode",
"=",
"'plain'",
")",
"s",
"=",
"s",
".",
"replace",
"(",
"'\\\\dag'",
",",
"'\\\\dagger'",
")",
"s",
"=",
"s",
".",
"strip",
"(",
"'$'",
")",
"return",
"'$$%s$$'",
"%",
"s",
"# Fallback to the string printer",
"return",
"None"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | load_ipython_extension | Load the extension in IPython. | environment/lib/python2.7/site-packages/IPython/extensions/sympyprinting.py | def load_ipython_extension(ip):
"""Load the extension in IPython."""
import sympy
# sympyprinting extension has been moved to SymPy as of 0.7.2, if it
# exists there, warn the user and import it
try:
import sympy.interactive.ipythonprinting
except ImportError:
pass
else:
warnings.warn("The sympyprinting extension in IPython is deprecated, "
"use sympy.interactive.ipythonprinting")
ip.extension_manager.load_extension('sympy.interactive.ipythonprinting')
return
global _loaded
if not _loaded:
plaintext_formatter = ip.display_formatter.formatters['text/plain']
for cls in (object, str):
plaintext_formatter.for_type(cls, print_basic_unicode)
printable_containers = [list, tuple]
# set and frozen set were broken with SymPy's latex() function, but
# was fixed in the 0.7.1-git development version. See
# http://code.google.com/p/sympy/issues/detail?id=3062.
if sympy.__version__ > '0.7.1':
printable_containers += [set, frozenset]
else:
plaintext_formatter.for_type(cls, print_basic_unicode)
plaintext_formatter.for_type_by_name(
'sympy.core.basic', 'Basic', print_basic_unicode
)
plaintext_formatter.for_type_by_name(
'sympy.matrices.matrices', 'Matrix', print_basic_unicode
)
png_formatter = ip.display_formatter.formatters['image/png']
png_formatter.for_type_by_name(
'sympy.core.basic', 'Basic', print_png
)
png_formatter.for_type_by_name(
'sympy.matrices.matrices', 'Matrix', print_display_png
)
for cls in [dict, int, long, float] + printable_containers:
png_formatter.for_type(cls, print_png)
latex_formatter = ip.display_formatter.formatters['text/latex']
latex_formatter.for_type_by_name(
'sympy.core.basic', 'Basic', print_latex
)
latex_formatter.for_type_by_name(
'sympy.matrices.matrices', 'Matrix', print_latex
)
for cls in printable_containers:
# Use LaTeX only if every element is printable by latex
latex_formatter.for_type(cls, print_latex)
_loaded = True | def load_ipython_extension(ip):
"""Load the extension in IPython."""
import sympy
# sympyprinting extension has been moved to SymPy as of 0.7.2, if it
# exists there, warn the user and import it
try:
import sympy.interactive.ipythonprinting
except ImportError:
pass
else:
warnings.warn("The sympyprinting extension in IPython is deprecated, "
"use sympy.interactive.ipythonprinting")
ip.extension_manager.load_extension('sympy.interactive.ipythonprinting')
return
global _loaded
if not _loaded:
plaintext_formatter = ip.display_formatter.formatters['text/plain']
for cls in (object, str):
plaintext_formatter.for_type(cls, print_basic_unicode)
printable_containers = [list, tuple]
# set and frozen set were broken with SymPy's latex() function, but
# was fixed in the 0.7.1-git development version. See
# http://code.google.com/p/sympy/issues/detail?id=3062.
if sympy.__version__ > '0.7.1':
printable_containers += [set, frozenset]
else:
plaintext_formatter.for_type(cls, print_basic_unicode)
plaintext_formatter.for_type_by_name(
'sympy.core.basic', 'Basic', print_basic_unicode
)
plaintext_formatter.for_type_by_name(
'sympy.matrices.matrices', 'Matrix', print_basic_unicode
)
png_formatter = ip.display_formatter.formatters['image/png']
png_formatter.for_type_by_name(
'sympy.core.basic', 'Basic', print_png
)
png_formatter.for_type_by_name(
'sympy.matrices.matrices', 'Matrix', print_display_png
)
for cls in [dict, int, long, float] + printable_containers:
png_formatter.for_type(cls, print_png)
latex_formatter = ip.display_formatter.formatters['text/latex']
latex_formatter.for_type_by_name(
'sympy.core.basic', 'Basic', print_latex
)
latex_formatter.for_type_by_name(
'sympy.matrices.matrices', 'Matrix', print_latex
)
for cls in printable_containers:
# Use LaTeX only if every element is printable by latex
latex_formatter.for_type(cls, print_latex)
_loaded = True | [
"Load",
"the",
"extension",
"in",
"IPython",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/extensions/sympyprinting.py#L108-L171 | [
"def",
"load_ipython_extension",
"(",
"ip",
")",
":",
"import",
"sympy",
"# sympyprinting extension has been moved to SymPy as of 0.7.2, if it",
"# exists there, warn the user and import it",
"try",
":",
"import",
"sympy",
".",
"interactive",
".",
"ipythonprinting",
"except",
"ImportError",
":",
"pass",
"else",
":",
"warnings",
".",
"warn",
"(",
"\"The sympyprinting extension in IPython is deprecated, \"",
"\"use sympy.interactive.ipythonprinting\"",
")",
"ip",
".",
"extension_manager",
".",
"load_extension",
"(",
"'sympy.interactive.ipythonprinting'",
")",
"return",
"global",
"_loaded",
"if",
"not",
"_loaded",
":",
"plaintext_formatter",
"=",
"ip",
".",
"display_formatter",
".",
"formatters",
"[",
"'text/plain'",
"]",
"for",
"cls",
"in",
"(",
"object",
",",
"str",
")",
":",
"plaintext_formatter",
".",
"for_type",
"(",
"cls",
",",
"print_basic_unicode",
")",
"printable_containers",
"=",
"[",
"list",
",",
"tuple",
"]",
"# set and frozen set were broken with SymPy's latex() function, but",
"# was fixed in the 0.7.1-git development version. See",
"# http://code.google.com/p/sympy/issues/detail?id=3062.",
"if",
"sympy",
".",
"__version__",
">",
"'0.7.1'",
":",
"printable_containers",
"+=",
"[",
"set",
",",
"frozenset",
"]",
"else",
":",
"plaintext_formatter",
".",
"for_type",
"(",
"cls",
",",
"print_basic_unicode",
")",
"plaintext_formatter",
".",
"for_type_by_name",
"(",
"'sympy.core.basic'",
",",
"'Basic'",
",",
"print_basic_unicode",
")",
"plaintext_formatter",
".",
"for_type_by_name",
"(",
"'sympy.matrices.matrices'",
",",
"'Matrix'",
",",
"print_basic_unicode",
")",
"png_formatter",
"=",
"ip",
".",
"display_formatter",
".",
"formatters",
"[",
"'image/png'",
"]",
"png_formatter",
".",
"for_type_by_name",
"(",
"'sympy.core.basic'",
",",
"'Basic'",
",",
"print_png",
")",
"png_formatter",
".",
"for_type_by_name",
"(",
"'sympy.matrices.matrices'",
",",
"'Matrix'",
",",
"print_display_png",
")",
"for",
"cls",
"in",
"[",
"dict",
",",
"int",
",",
"long",
",",
"float",
"]",
"+",
"printable_containers",
":",
"png_formatter",
".",
"for_type",
"(",
"cls",
",",
"print_png",
")",
"latex_formatter",
"=",
"ip",
".",
"display_formatter",
".",
"formatters",
"[",
"'text/latex'",
"]",
"latex_formatter",
".",
"for_type_by_name",
"(",
"'sympy.core.basic'",
",",
"'Basic'",
",",
"print_latex",
")",
"latex_formatter",
".",
"for_type_by_name",
"(",
"'sympy.matrices.matrices'",
",",
"'Matrix'",
",",
"print_latex",
")",
"for",
"cls",
"in",
"printable_containers",
":",
"# Use LaTeX only if every element is printable by latex",
"latex_formatter",
".",
"for_type",
"(",
"cls",
",",
"print_latex",
")",
"_loaded",
"=",
"True"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | str2tokens | Usage:
{% with 'this, is a, string'|str2tokens:',' as token_list %}do something{% endwith %} | toolware/templatetags/strings.py | def str2tokens(string, delimiter):
"""
Usage:
{% with 'this, is a, string'|str2tokens:',' as token_list %}do something{% endwith %}
"""
token_list = [token.strip() for token in string.split(delimiter)]
return token_list | def str2tokens(string, delimiter):
"""
Usage:
{% with 'this, is a, string'|str2tokens:',' as token_list %}do something{% endwith %}
"""
token_list = [token.strip() for token in string.split(delimiter)]
return token_list | [
"Usage",
":",
"{",
"%",
"with",
"this",
"is",
"a",
"string",
"|str2tokens",
":",
"as",
"token_list",
"%",
"}",
"do",
"something",
"{",
"%",
"endwith",
"%",
"}"
] | un33k/django-toolware | python | https://github.com/un33k/django-toolware/blob/973f3e003dc38b812897dab88455bee37dcaf931/toolware/templatetags/strings.py#L22-L29 | [
"def",
"str2tokens",
"(",
"string",
",",
"delimiter",
")",
":",
"token_list",
"=",
"[",
"token",
".",
"strip",
"(",
")",
"for",
"token",
"in",
"string",
".",
"split",
"(",
"delimiter",
")",
"]",
"return",
"token_list"
] | 973f3e003dc38b812897dab88455bee37dcaf931 |
test | str2tokenstags | Usage:
{% str2tokens 'a/b/c/d' '/' as token_list %} | toolware/templatetags/strings.py | def str2tokenstags(string, delimiter):
"""
Usage:
{% str2tokens 'a/b/c/d' '/' as token_list %}
"""
token_list = [token.strip() for token in string.split(delimiter)]
return token_list | def str2tokenstags(string, delimiter):
"""
Usage:
{% str2tokens 'a/b/c/d' '/' as token_list %}
"""
token_list = [token.strip() for token in string.split(delimiter)]
return token_list | [
"Usage",
":",
"{",
"%",
"str2tokens",
"a",
"/",
"b",
"/",
"c",
"/",
"d",
"/",
"as",
"token_list",
"%",
"}"
] | un33k/django-toolware | python | https://github.com/un33k/django-toolware/blob/973f3e003dc38b812897dab88455bee37dcaf931/toolware/templatetags/strings.py#L33-L40 | [
"def",
"str2tokenstags",
"(",
"string",
",",
"delimiter",
")",
":",
"token_list",
"=",
"[",
"token",
".",
"strip",
"(",
")",
"for",
"token",
"in",
"string",
".",
"split",
"(",
"delimiter",
")",
"]",
"return",
"token_list"
] | 973f3e003dc38b812897dab88455bee37dcaf931 |
test | Plugin.add_options | Non-camel-case version of func name for backwards compatibility.
.. warning ::
DEPRECATED: Do not use this method,
use :meth:`options <nose.plugins.base.IPluginInterface.options>`
instead. | environment/lib/python2.7/site-packages/nose/plugins/base.py | def add_options(self, parser, env=None):
"""Non-camel-case version of func name for backwards compatibility.
.. warning ::
DEPRECATED: Do not use this method,
use :meth:`options <nose.plugins.base.IPluginInterface.options>`
instead.
"""
# FIXME raise deprecation warning if wasn't called by wrapper
if env is None:
env = os.environ
try:
self.options(parser, env)
self.can_configure = True
except OptionConflictError, e:
warn("Plugin %s has conflicting option string: %s and will "
"be disabled" % (self, e), RuntimeWarning)
self.enabled = False
self.can_configure = False | def add_options(self, parser, env=None):
"""Non-camel-case version of func name for backwards compatibility.
.. warning ::
DEPRECATED: Do not use this method,
use :meth:`options <nose.plugins.base.IPluginInterface.options>`
instead.
"""
# FIXME raise deprecation warning if wasn't called by wrapper
if env is None:
env = os.environ
try:
self.options(parser, env)
self.can_configure = True
except OptionConflictError, e:
warn("Plugin %s has conflicting option string: %s and will "
"be disabled" % (self, e), RuntimeWarning)
self.enabled = False
self.can_configure = False | [
"Non",
"-",
"camel",
"-",
"case",
"version",
"of",
"func",
"name",
"for",
"backwards",
"compatibility",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/plugins/base.py#L54-L74 | [
"def",
"add_options",
"(",
"self",
",",
"parser",
",",
"env",
"=",
"None",
")",
":",
"# FIXME raise deprecation warning if wasn't called by wrapper",
"if",
"env",
"is",
"None",
":",
"env",
"=",
"os",
".",
"environ",
"try",
":",
"self",
".",
"options",
"(",
"parser",
",",
"env",
")",
"self",
".",
"can_configure",
"=",
"True",
"except",
"OptionConflictError",
",",
"e",
":",
"warn",
"(",
"\"Plugin %s has conflicting option string: %s and will \"",
"\"be disabled\"",
"%",
"(",
"self",
",",
"e",
")",
",",
"RuntimeWarning",
")",
"self",
".",
"enabled",
"=",
"False",
"self",
".",
"can_configure",
"=",
"False"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | Plugin.options | Register commandline options.
Implement this method for normal options behavior with protection from
OptionConflictErrors. If you override this method and want the default
--with-$name option to be registered, be sure to call super(). | environment/lib/python2.7/site-packages/nose/plugins/base.py | def options(self, parser, env):
"""Register commandline options.
Implement this method for normal options behavior with protection from
OptionConflictErrors. If you override this method and want the default
--with-$name option to be registered, be sure to call super().
"""
env_opt = 'NOSE_WITH_%s' % self.name.upper()
env_opt = env_opt.replace('-', '_')
parser.add_option("--with-%s" % self.name,
action="store_true",
dest=self.enableOpt,
default=env.get(env_opt),
help="Enable plugin %s: %s [%s]" %
(self.__class__.__name__, self.help(), env_opt)) | def options(self, parser, env):
"""Register commandline options.
Implement this method for normal options behavior with protection from
OptionConflictErrors. If you override this method and want the default
--with-$name option to be registered, be sure to call super().
"""
env_opt = 'NOSE_WITH_%s' % self.name.upper()
env_opt = env_opt.replace('-', '_')
parser.add_option("--with-%s" % self.name,
action="store_true",
dest=self.enableOpt,
default=env.get(env_opt),
help="Enable plugin %s: %s [%s]" %
(self.__class__.__name__, self.help(), env_opt)) | [
"Register",
"commandline",
"options",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/plugins/base.py#L76-L90 | [
"def",
"options",
"(",
"self",
",",
"parser",
",",
"env",
")",
":",
"env_opt",
"=",
"'NOSE_WITH_%s'",
"%",
"self",
".",
"name",
".",
"upper",
"(",
")",
"env_opt",
"=",
"env_opt",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
"parser",
".",
"add_option",
"(",
"\"--with-%s\"",
"%",
"self",
".",
"name",
",",
"action",
"=",
"\"store_true\"",
",",
"dest",
"=",
"self",
".",
"enableOpt",
",",
"default",
"=",
"env",
".",
"get",
"(",
"env_opt",
")",
",",
"help",
"=",
"\"Enable plugin %s: %s [%s]\"",
"%",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"self",
".",
"help",
"(",
")",
",",
"env_opt",
")",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | Plugin.configure | Configure the plugin and system, based on selected options.
The base plugin class sets the plugin to enabled if the enable option
for the plugin (self.enableOpt) is true. | environment/lib/python2.7/site-packages/nose/plugins/base.py | def configure(self, options, conf):
"""Configure the plugin and system, based on selected options.
The base plugin class sets the plugin to enabled if the enable option
for the plugin (self.enableOpt) is true.
"""
if not self.can_configure:
return
self.conf = conf
if hasattr(options, self.enableOpt):
self.enabled = getattr(options, self.enableOpt) | def configure(self, options, conf):
"""Configure the plugin and system, based on selected options.
The base plugin class sets the plugin to enabled if the enable option
for the plugin (self.enableOpt) is true.
"""
if not self.can_configure:
return
self.conf = conf
if hasattr(options, self.enableOpt):
self.enabled = getattr(options, self.enableOpt) | [
"Configure",
"the",
"plugin",
"and",
"system",
"based",
"on",
"selected",
"options",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/plugins/base.py#L92-L102 | [
"def",
"configure",
"(",
"self",
",",
"options",
",",
"conf",
")",
":",
"if",
"not",
"self",
".",
"can_configure",
":",
"return",
"self",
".",
"conf",
"=",
"conf",
"if",
"hasattr",
"(",
"options",
",",
"self",
".",
"enableOpt",
")",
":",
"self",
".",
"enabled",
"=",
"getattr",
"(",
"options",
",",
"self",
".",
"enableOpt",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | validate_string_list | Validate that the input is a list of strings.
Raises ValueError if not. | environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py | def validate_string_list(lst):
"""Validate that the input is a list of strings.
Raises ValueError if not."""
if not isinstance(lst, list):
raise ValueError('input %r must be a list' % lst)
for x in lst:
if not isinstance(x, basestring):
raise ValueError('element %r in list must be a string' % x) | def validate_string_list(lst):
"""Validate that the input is a list of strings.
Raises ValueError if not."""
if not isinstance(lst, list):
raise ValueError('input %r must be a list' % lst)
for x in lst:
if not isinstance(x, basestring):
raise ValueError('element %r in list must be a string' % x) | [
"Validate",
"that",
"the",
"input",
"is",
"a",
"list",
"of",
"strings",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py#L60-L68 | [
"def",
"validate_string_list",
"(",
"lst",
")",
":",
"if",
"not",
"isinstance",
"(",
"lst",
",",
"list",
")",
":",
"raise",
"ValueError",
"(",
"'input %r must be a list'",
"%",
"lst",
")",
"for",
"x",
"in",
"lst",
":",
"if",
"not",
"isinstance",
"(",
"x",
",",
"basestring",
")",
":",
"raise",
"ValueError",
"(",
"'element %r in list must be a string'",
"%",
"x",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | validate_string_dict | Validate that the input is a dict with string keys and values.
Raises ValueError if not. | environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py | def validate_string_dict(dct):
"""Validate that the input is a dict with string keys and values.
Raises ValueError if not."""
for k,v in dct.iteritems():
if not isinstance(k, basestring):
raise ValueError('key %r in dict must be a string' % k)
if not isinstance(v, basestring):
raise ValueError('value %r in dict must be a string' % v) | def validate_string_dict(dct):
"""Validate that the input is a dict with string keys and values.
Raises ValueError if not."""
for k,v in dct.iteritems():
if not isinstance(k, basestring):
raise ValueError('key %r in dict must be a string' % k)
if not isinstance(v, basestring):
raise ValueError('value %r in dict must be a string' % v) | [
"Validate",
"that",
"the",
"input",
"is",
"a",
"dict",
"with",
"string",
"keys",
"and",
"values",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py#L71-L79 | [
"def",
"validate_string_dict",
"(",
"dct",
")",
":",
"for",
"k",
",",
"v",
"in",
"dct",
".",
"iteritems",
"(",
")",
":",
"if",
"not",
"isinstance",
"(",
"k",
",",
"basestring",
")",
":",
"raise",
"ValueError",
"(",
"'key %r in dict must be a string'",
"%",
"k",
")",
"if",
"not",
"isinstance",
"(",
"v",
",",
"basestring",
")",
":",
"raise",
"ValueError",
"(",
"'value %r in dict must be a string'",
"%",
"v",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | ZMQSocketChannel._run_loop | Run my loop, ignoring EINTR events in the poller | environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py | def _run_loop(self):
"""Run my loop, ignoring EINTR events in the poller"""
while True:
try:
self.ioloop.start()
except ZMQError as e:
if e.errno == errno.EINTR:
continue
else:
raise
except Exception:
if self._exiting:
break
else:
raise
else:
break | def _run_loop(self):
"""Run my loop, ignoring EINTR events in the poller"""
while True:
try:
self.ioloop.start()
except ZMQError as e:
if e.errno == errno.EINTR:
continue
else:
raise
except Exception:
if self._exiting:
break
else:
raise
else:
break | [
"Run",
"my",
"loop",
"ignoring",
"EINTR",
"events",
"in",
"the",
"poller"
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py#L123-L139 | [
"def",
"_run_loop",
"(",
"self",
")",
":",
"while",
"True",
":",
"try",
":",
"self",
".",
"ioloop",
".",
"start",
"(",
")",
"except",
"ZMQError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"==",
"errno",
".",
"EINTR",
":",
"continue",
"else",
":",
"raise",
"except",
"Exception",
":",
"if",
"self",
".",
"_exiting",
":",
"break",
"else",
":",
"raise",
"else",
":",
"break"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | ZMQSocketChannel._queue_send | Queue a message to be sent from the IOLoop's thread.
Parameters
----------
msg : message to send
This is threadsafe, as it uses IOLoop.add_callback to give the loop's
thread control of the action. | environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py | def _queue_send(self, msg):
"""Queue a message to be sent from the IOLoop's thread.
Parameters
----------
msg : message to send
This is threadsafe, as it uses IOLoop.add_callback to give the loop's
thread control of the action.
"""
def thread_send():
self.session.send(self.stream, msg)
self.ioloop.add_callback(thread_send) | def _queue_send(self, msg):
"""Queue a message to be sent from the IOLoop's thread.
Parameters
----------
msg : message to send
This is threadsafe, as it uses IOLoop.add_callback to give the loop's
thread control of the action.
"""
def thread_send():
self.session.send(self.stream, msg)
self.ioloop.add_callback(thread_send) | [
"Queue",
"a",
"message",
"to",
"be",
"sent",
"from",
"the",
"IOLoop",
"s",
"thread",
".",
"Parameters",
"----------",
"msg",
":",
"message",
"to",
"send",
"This",
"is",
"threadsafe",
"as",
"it",
"uses",
"IOLoop",
".",
"add_callback",
"to",
"give",
"the",
"loop",
"s",
"thread",
"control",
"of",
"the",
"action",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py#L159-L171 | [
"def",
"_queue_send",
"(",
"self",
",",
"msg",
")",
":",
"def",
"thread_send",
"(",
")",
":",
"self",
".",
"session",
".",
"send",
"(",
"self",
".",
"stream",
",",
"msg",
")",
"self",
".",
"ioloop",
".",
"add_callback",
"(",
"thread_send",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | ZMQSocketChannel._handle_recv | callback for stream.on_recv
unpacks message, and calls handlers with it. | environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py | def _handle_recv(self, msg):
"""callback for stream.on_recv
unpacks message, and calls handlers with it.
"""
ident,smsg = self.session.feed_identities(msg)
self.call_handlers(self.session.unserialize(smsg)) | def _handle_recv(self, msg):
"""callback for stream.on_recv
unpacks message, and calls handlers with it.
"""
ident,smsg = self.session.feed_identities(msg)
self.call_handlers(self.session.unserialize(smsg)) | [
"callback",
"for",
"stream",
".",
"on_recv",
"unpacks",
"message",
"and",
"calls",
"handlers",
"with",
"it",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py#L173-L179 | [
"def",
"_handle_recv",
"(",
"self",
",",
"msg",
")",
":",
"ident",
",",
"smsg",
"=",
"self",
".",
"session",
".",
"feed_identities",
"(",
"msg",
")",
"self",
".",
"call_handlers",
"(",
"self",
".",
"session",
".",
"unserialize",
"(",
"smsg",
")",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | ShellSocketChannel.run | The thread's main activity. Call start() instead. | environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py | def run(self):
"""The thread's main activity. Call start() instead."""
self.socket = self.context.socket(zmq.DEALER)
self.socket.setsockopt(zmq.IDENTITY, self.session.bsession)
self.socket.connect('tcp://%s:%i' % self.address)
self.stream = zmqstream.ZMQStream(self.socket, self.ioloop)
self.stream.on_recv(self._handle_recv)
self._run_loop()
try:
self.socket.close()
except:
pass | def run(self):
"""The thread's main activity. Call start() instead."""
self.socket = self.context.socket(zmq.DEALER)
self.socket.setsockopt(zmq.IDENTITY, self.session.bsession)
self.socket.connect('tcp://%s:%i' % self.address)
self.stream = zmqstream.ZMQStream(self.socket, self.ioloop)
self.stream.on_recv(self._handle_recv)
self._run_loop()
try:
self.socket.close()
except:
pass | [
"The",
"thread",
"s",
"main",
"activity",
".",
"Call",
"start",
"()",
"instead",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py#L195-L206 | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"socket",
"=",
"self",
".",
"context",
".",
"socket",
"(",
"zmq",
".",
"DEALER",
")",
"self",
".",
"socket",
".",
"setsockopt",
"(",
"zmq",
".",
"IDENTITY",
",",
"self",
".",
"session",
".",
"bsession",
")",
"self",
".",
"socket",
".",
"connect",
"(",
"'tcp://%s:%i'",
"%",
"self",
".",
"address",
")",
"self",
".",
"stream",
"=",
"zmqstream",
".",
"ZMQStream",
"(",
"self",
".",
"socket",
",",
"self",
".",
"ioloop",
")",
"self",
".",
"stream",
".",
"on_recv",
"(",
"self",
".",
"_handle_recv",
")",
"self",
".",
"_run_loop",
"(",
")",
"try",
":",
"self",
".",
"socket",
".",
"close",
"(",
")",
"except",
":",
"pass"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | ShellSocketChannel.execute | Execute code in the kernel.
Parameters
----------
code : str
A string of Python code.
silent : bool, optional (default False)
If set, the kernel will execute the code as quietly possible.
user_variables : list, optional
A list of variable names to pull from the user's namespace. They
will come back as a dict with these names as keys and their
:func:`repr` as values.
user_expressions : dict, optional
A dict with string keys and to pull from the user's
namespace. They will come back as a dict with these names as keys
and their :func:`repr` as values.
allow_stdin : bool, optional
Flag for
A dict with string keys and to pull from the user's
namespace. They will come back as a dict with these names as keys
and their :func:`repr` as values.
Returns
-------
The msg_id of the message sent. | environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py | def execute(self, code, silent=False,
user_variables=None, user_expressions=None, allow_stdin=None):
"""Execute code in the kernel.
Parameters
----------
code : str
A string of Python code.
silent : bool, optional (default False)
If set, the kernel will execute the code as quietly possible.
user_variables : list, optional
A list of variable names to pull from the user's namespace. They
will come back as a dict with these names as keys and their
:func:`repr` as values.
user_expressions : dict, optional
A dict with string keys and to pull from the user's
namespace. They will come back as a dict with these names as keys
and their :func:`repr` as values.
allow_stdin : bool, optional
Flag for
A dict with string keys and to pull from the user's
namespace. They will come back as a dict with these names as keys
and their :func:`repr` as values.
Returns
-------
The msg_id of the message sent.
"""
if user_variables is None:
user_variables = []
if user_expressions is None:
user_expressions = {}
if allow_stdin is None:
allow_stdin = self.allow_stdin
# Don't waste network traffic if inputs are invalid
if not isinstance(code, basestring):
raise ValueError('code %r must be a string' % code)
validate_string_list(user_variables)
validate_string_dict(user_expressions)
# Create class for content/msg creation. Related to, but possibly
# not in Session.
content = dict(code=code, silent=silent,
user_variables=user_variables,
user_expressions=user_expressions,
allow_stdin=allow_stdin,
)
msg = self.session.msg('execute_request', content)
self._queue_send(msg)
return msg['header']['msg_id'] | def execute(self, code, silent=False,
user_variables=None, user_expressions=None, allow_stdin=None):
"""Execute code in the kernel.
Parameters
----------
code : str
A string of Python code.
silent : bool, optional (default False)
If set, the kernel will execute the code as quietly possible.
user_variables : list, optional
A list of variable names to pull from the user's namespace. They
will come back as a dict with these names as keys and their
:func:`repr` as values.
user_expressions : dict, optional
A dict with string keys and to pull from the user's
namespace. They will come back as a dict with these names as keys
and their :func:`repr` as values.
allow_stdin : bool, optional
Flag for
A dict with string keys and to pull from the user's
namespace. They will come back as a dict with these names as keys
and their :func:`repr` as values.
Returns
-------
The msg_id of the message sent.
"""
if user_variables is None:
user_variables = []
if user_expressions is None:
user_expressions = {}
if allow_stdin is None:
allow_stdin = self.allow_stdin
# Don't waste network traffic if inputs are invalid
if not isinstance(code, basestring):
raise ValueError('code %r must be a string' % code)
validate_string_list(user_variables)
validate_string_dict(user_expressions)
# Create class for content/msg creation. Related to, but possibly
# not in Session.
content = dict(code=code, silent=silent,
user_variables=user_variables,
user_expressions=user_expressions,
allow_stdin=allow_stdin,
)
msg = self.session.msg('execute_request', content)
self._queue_send(msg)
return msg['header']['msg_id'] | [
"Execute",
"code",
"in",
"the",
"kernel",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py#L222-L277 | [
"def",
"execute",
"(",
"self",
",",
"code",
",",
"silent",
"=",
"False",
",",
"user_variables",
"=",
"None",
",",
"user_expressions",
"=",
"None",
",",
"allow_stdin",
"=",
"None",
")",
":",
"if",
"user_variables",
"is",
"None",
":",
"user_variables",
"=",
"[",
"]",
"if",
"user_expressions",
"is",
"None",
":",
"user_expressions",
"=",
"{",
"}",
"if",
"allow_stdin",
"is",
"None",
":",
"allow_stdin",
"=",
"self",
".",
"allow_stdin",
"# Don't waste network traffic if inputs are invalid",
"if",
"not",
"isinstance",
"(",
"code",
",",
"basestring",
")",
":",
"raise",
"ValueError",
"(",
"'code %r must be a string'",
"%",
"code",
")",
"validate_string_list",
"(",
"user_variables",
")",
"validate_string_dict",
"(",
"user_expressions",
")",
"# Create class for content/msg creation. Related to, but possibly",
"# not in Session.",
"content",
"=",
"dict",
"(",
"code",
"=",
"code",
",",
"silent",
"=",
"silent",
",",
"user_variables",
"=",
"user_variables",
",",
"user_expressions",
"=",
"user_expressions",
",",
"allow_stdin",
"=",
"allow_stdin",
",",
")",
"msg",
"=",
"self",
".",
"session",
".",
"msg",
"(",
"'execute_request'",
",",
"content",
")",
"self",
".",
"_queue_send",
"(",
"msg",
")",
"return",
"msg",
"[",
"'header'",
"]",
"[",
"'msg_id'",
"]"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | ShellSocketChannel.complete | Tab complete text in the kernel's namespace.
Parameters
----------
text : str
The text to complete.
line : str
The full line of text that is the surrounding context for the
text to complete.
cursor_pos : int
The position of the cursor in the line where the completion was
requested.
block : str, optional
The full block of code in which the completion is being requested.
Returns
-------
The msg_id of the message sent. | environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py | def complete(self, text, line, cursor_pos, block=None):
"""Tab complete text in the kernel's namespace.
Parameters
----------
text : str
The text to complete.
line : str
The full line of text that is the surrounding context for the
text to complete.
cursor_pos : int
The position of the cursor in the line where the completion was
requested.
block : str, optional
The full block of code in which the completion is being requested.
Returns
-------
The msg_id of the message sent.
"""
content = dict(text=text, line=line, block=block, cursor_pos=cursor_pos)
msg = self.session.msg('complete_request', content)
self._queue_send(msg)
return msg['header']['msg_id'] | def complete(self, text, line, cursor_pos, block=None):
"""Tab complete text in the kernel's namespace.
Parameters
----------
text : str
The text to complete.
line : str
The full line of text that is the surrounding context for the
text to complete.
cursor_pos : int
The position of the cursor in the line where the completion was
requested.
block : str, optional
The full block of code in which the completion is being requested.
Returns
-------
The msg_id of the message sent.
"""
content = dict(text=text, line=line, block=block, cursor_pos=cursor_pos)
msg = self.session.msg('complete_request', content)
self._queue_send(msg)
return msg['header']['msg_id'] | [
"Tab",
"complete",
"text",
"in",
"the",
"kernel",
"s",
"namespace",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py#L279-L302 | [
"def",
"complete",
"(",
"self",
",",
"text",
",",
"line",
",",
"cursor_pos",
",",
"block",
"=",
"None",
")",
":",
"content",
"=",
"dict",
"(",
"text",
"=",
"text",
",",
"line",
"=",
"line",
",",
"block",
"=",
"block",
",",
"cursor_pos",
"=",
"cursor_pos",
")",
"msg",
"=",
"self",
".",
"session",
".",
"msg",
"(",
"'complete_request'",
",",
"content",
")",
"self",
".",
"_queue_send",
"(",
"msg",
")",
"return",
"msg",
"[",
"'header'",
"]",
"[",
"'msg_id'",
"]"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | ShellSocketChannel.object_info | Get metadata information about an object.
Parameters
----------
oname : str
A string specifying the object name.
detail_level : int, optional
The level of detail for the introspection (0-2)
Returns
-------
The msg_id of the message sent. | environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py | def object_info(self, oname, detail_level=0):
"""Get metadata information about an object.
Parameters
----------
oname : str
A string specifying the object name.
detail_level : int, optional
The level of detail for the introspection (0-2)
Returns
-------
The msg_id of the message sent.
"""
content = dict(oname=oname, detail_level=detail_level)
msg = self.session.msg('object_info_request', content)
self._queue_send(msg)
return msg['header']['msg_id'] | def object_info(self, oname, detail_level=0):
"""Get metadata information about an object.
Parameters
----------
oname : str
A string specifying the object name.
detail_level : int, optional
The level of detail for the introspection (0-2)
Returns
-------
The msg_id of the message sent.
"""
content = dict(oname=oname, detail_level=detail_level)
msg = self.session.msg('object_info_request', content)
self._queue_send(msg)
return msg['header']['msg_id'] | [
"Get",
"metadata",
"information",
"about",
"an",
"object",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py#L304-L321 | [
"def",
"object_info",
"(",
"self",
",",
"oname",
",",
"detail_level",
"=",
"0",
")",
":",
"content",
"=",
"dict",
"(",
"oname",
"=",
"oname",
",",
"detail_level",
"=",
"detail_level",
")",
"msg",
"=",
"self",
".",
"session",
".",
"msg",
"(",
"'object_info_request'",
",",
"content",
")",
"self",
".",
"_queue_send",
"(",
"msg",
")",
"return",
"msg",
"[",
"'header'",
"]",
"[",
"'msg_id'",
"]"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | ShellSocketChannel.history | Get entries from the history list.
Parameters
----------
raw : bool
If True, return the raw input.
output : bool
If True, then return the output as well.
hist_access_type : str
'range' (fill in session, start and stop params), 'tail' (fill in n)
or 'search' (fill in pattern param).
session : int
For a range request, the session from which to get lines. Session
numbers are positive integers; negative ones count back from the
current session.
start : int
The first line number of a history range.
stop : int
The final (excluded) line number of a history range.
n : int
The number of lines of history to get for a tail request.
pattern : str
The glob-syntax pattern for a search request.
Returns
-------
The msg_id of the message sent. | environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py | def history(self, raw=True, output=False, hist_access_type='range', **kwargs):
"""Get entries from the history list.
Parameters
----------
raw : bool
If True, return the raw input.
output : bool
If True, then return the output as well.
hist_access_type : str
'range' (fill in session, start and stop params), 'tail' (fill in n)
or 'search' (fill in pattern param).
session : int
For a range request, the session from which to get lines. Session
numbers are positive integers; negative ones count back from the
current session.
start : int
The first line number of a history range.
stop : int
The final (excluded) line number of a history range.
n : int
The number of lines of history to get for a tail request.
pattern : str
The glob-syntax pattern for a search request.
Returns
-------
The msg_id of the message sent.
"""
content = dict(raw=raw, output=output, hist_access_type=hist_access_type,
**kwargs)
msg = self.session.msg('history_request', content)
self._queue_send(msg)
return msg['header']['msg_id'] | def history(self, raw=True, output=False, hist_access_type='range', **kwargs):
"""Get entries from the history list.
Parameters
----------
raw : bool
If True, return the raw input.
output : bool
If True, then return the output as well.
hist_access_type : str
'range' (fill in session, start and stop params), 'tail' (fill in n)
or 'search' (fill in pattern param).
session : int
For a range request, the session from which to get lines. Session
numbers are positive integers; negative ones count back from the
current session.
start : int
The first line number of a history range.
stop : int
The final (excluded) line number of a history range.
n : int
The number of lines of history to get for a tail request.
pattern : str
The glob-syntax pattern for a search request.
Returns
-------
The msg_id of the message sent.
"""
content = dict(raw=raw, output=output, hist_access_type=hist_access_type,
**kwargs)
msg = self.session.msg('history_request', content)
self._queue_send(msg)
return msg['header']['msg_id'] | [
"Get",
"entries",
"from",
"the",
"history",
"list",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py#L323-L359 | [
"def",
"history",
"(",
"self",
",",
"raw",
"=",
"True",
",",
"output",
"=",
"False",
",",
"hist_access_type",
"=",
"'range'",
",",
"*",
"*",
"kwargs",
")",
":",
"content",
"=",
"dict",
"(",
"raw",
"=",
"raw",
",",
"output",
"=",
"output",
",",
"hist_access_type",
"=",
"hist_access_type",
",",
"*",
"*",
"kwargs",
")",
"msg",
"=",
"self",
".",
"session",
".",
"msg",
"(",
"'history_request'",
",",
"content",
")",
"self",
".",
"_queue_send",
"(",
"msg",
")",
"return",
"msg",
"[",
"'header'",
"]",
"[",
"'msg_id'",
"]"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | ShellSocketChannel.shutdown | Request an immediate kernel shutdown.
Upon receipt of the (empty) reply, client code can safely assume that
the kernel has shut down and it's safe to forcefully terminate it if
it's still alive.
The kernel will send the reply via a function registered with Python's
atexit module, ensuring it's truly done as the kernel is done with all
normal operation. | environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py | def shutdown(self, restart=False):
"""Request an immediate kernel shutdown.
Upon receipt of the (empty) reply, client code can safely assume that
the kernel has shut down and it's safe to forcefully terminate it if
it's still alive.
The kernel will send the reply via a function registered with Python's
atexit module, ensuring it's truly done as the kernel is done with all
normal operation.
"""
# Send quit message to kernel. Once we implement kernel-side setattr,
# this should probably be done that way, but for now this will do.
msg = self.session.msg('shutdown_request', {'restart':restart})
self._queue_send(msg)
return msg['header']['msg_id'] | def shutdown(self, restart=False):
"""Request an immediate kernel shutdown.
Upon receipt of the (empty) reply, client code can safely assume that
the kernel has shut down and it's safe to forcefully terminate it if
it's still alive.
The kernel will send the reply via a function registered with Python's
atexit module, ensuring it's truly done as the kernel is done with all
normal operation.
"""
# Send quit message to kernel. Once we implement kernel-side setattr,
# this should probably be done that way, but for now this will do.
msg = self.session.msg('shutdown_request', {'restart':restart})
self._queue_send(msg)
return msg['header']['msg_id'] | [
"Request",
"an",
"immediate",
"kernel",
"shutdown",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py#L361-L376 | [
"def",
"shutdown",
"(",
"self",
",",
"restart",
"=",
"False",
")",
":",
"# Send quit message to kernel. Once we implement kernel-side setattr,",
"# this should probably be done that way, but for now this will do.",
"msg",
"=",
"self",
".",
"session",
".",
"msg",
"(",
"'shutdown_request'",
",",
"{",
"'restart'",
":",
"restart",
"}",
")",
"self",
".",
"_queue_send",
"(",
"msg",
")",
"return",
"msg",
"[",
"'header'",
"]",
"[",
"'msg_id'",
"]"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | SubSocketChannel.flush | Immediately processes all pending messages on the SUB channel.
Callers should use this method to ensure that :method:`call_handlers`
has been called for all messages that have been received on the
0MQ SUB socket of this channel.
This method is thread safe.
Parameters
----------
timeout : float, optional
The maximum amount of time to spend flushing, in seconds. The
default is one second. | environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py | def flush(self, timeout=1.0):
"""Immediately processes all pending messages on the SUB channel.
Callers should use this method to ensure that :method:`call_handlers`
has been called for all messages that have been received on the
0MQ SUB socket of this channel.
This method is thread safe.
Parameters
----------
timeout : float, optional
The maximum amount of time to spend flushing, in seconds. The
default is one second.
"""
# We do the IOLoop callback process twice to ensure that the IOLoop
# gets to perform at least one full poll.
stop_time = time.time() + timeout
for i in xrange(2):
self._flushed = False
self.ioloop.add_callback(self._flush)
while not self._flushed and time.time() < stop_time:
time.sleep(0.01) | def flush(self, timeout=1.0):
"""Immediately processes all pending messages on the SUB channel.
Callers should use this method to ensure that :method:`call_handlers`
has been called for all messages that have been received on the
0MQ SUB socket of this channel.
This method is thread safe.
Parameters
----------
timeout : float, optional
The maximum amount of time to spend flushing, in seconds. The
default is one second.
"""
# We do the IOLoop callback process twice to ensure that the IOLoop
# gets to perform at least one full poll.
stop_time = time.time() + timeout
for i in xrange(2):
self._flushed = False
self.ioloop.add_callback(self._flush)
while not self._flushed and time.time() < stop_time:
time.sleep(0.01) | [
"Immediately",
"processes",
"all",
"pending",
"messages",
"on",
"the",
"SUB",
"channel",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py#L416-L438 | [
"def",
"flush",
"(",
"self",
",",
"timeout",
"=",
"1.0",
")",
":",
"# We do the IOLoop callback process twice to ensure that the IOLoop",
"# gets to perform at least one full poll.",
"stop_time",
"=",
"time",
".",
"time",
"(",
")",
"+",
"timeout",
"for",
"i",
"in",
"xrange",
"(",
"2",
")",
":",
"self",
".",
"_flushed",
"=",
"False",
"self",
".",
"ioloop",
".",
"add_callback",
"(",
"self",
".",
"_flush",
")",
"while",
"not",
"self",
".",
"_flushed",
"and",
"time",
".",
"time",
"(",
")",
"<",
"stop_time",
":",
"time",
".",
"sleep",
"(",
"0.01",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | StdInSocketChannel.input | Send a string of raw input to the kernel. | environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py | def input(self, string):
"""Send a string of raw input to the kernel."""
content = dict(value=string)
msg = self.session.msg('input_reply', content)
self._queue_send(msg) | def input(self, string):
"""Send a string of raw input to the kernel."""
content = dict(value=string)
msg = self.session.msg('input_reply', content)
self._queue_send(msg) | [
"Send",
"a",
"string",
"of",
"raw",
"input",
"to",
"the",
"kernel",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py#L483-L487 | [
"def",
"input",
"(",
"self",
",",
"string",
")",
":",
"content",
"=",
"dict",
"(",
"value",
"=",
"string",
")",
"msg",
"=",
"self",
".",
"session",
".",
"msg",
"(",
"'input_reply'",
",",
"content",
")",
"self",
".",
"_queue_send",
"(",
"msg",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | HBSocketChannel._poll | poll for heartbeat replies until we reach self.time_to_dead
Ignores interrupts, and returns the result of poll(), which
will be an empty list if no messages arrived before the timeout,
or the event tuple if there is a message to receive. | environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py | def _poll(self, start_time):
"""poll for heartbeat replies until we reach self.time_to_dead
Ignores interrupts, and returns the result of poll(), which
will be an empty list if no messages arrived before the timeout,
or the event tuple if there is a message to receive.
"""
until_dead = self.time_to_dead - (time.time() - start_time)
# ensure poll at least once
until_dead = max(until_dead, 1e-3)
events = []
while True:
try:
events = self.poller.poll(1000 * until_dead)
except ZMQError as e:
if e.errno == errno.EINTR:
# ignore interrupts during heartbeat
# this may never actually happen
until_dead = self.time_to_dead - (time.time() - start_time)
until_dead = max(until_dead, 1e-3)
pass
else:
raise
except Exception:
if self._exiting:
break
else:
raise
else:
break
return events | def _poll(self, start_time):
"""poll for heartbeat replies until we reach self.time_to_dead
Ignores interrupts, and returns the result of poll(), which
will be an empty list if no messages arrived before the timeout,
or the event tuple if there is a message to receive.
"""
until_dead = self.time_to_dead - (time.time() - start_time)
# ensure poll at least once
until_dead = max(until_dead, 1e-3)
events = []
while True:
try:
events = self.poller.poll(1000 * until_dead)
except ZMQError as e:
if e.errno == errno.EINTR:
# ignore interrupts during heartbeat
# this may never actually happen
until_dead = self.time_to_dead - (time.time() - start_time)
until_dead = max(until_dead, 1e-3)
pass
else:
raise
except Exception:
if self._exiting:
break
else:
raise
else:
break
return events | [
"poll",
"for",
"heartbeat",
"replies",
"until",
"we",
"reach",
"self",
".",
"time_to_dead",
"Ignores",
"interrupts",
"and",
"returns",
"the",
"result",
"of",
"poll",
"()",
"which",
"will",
"be",
"an",
"empty",
"list",
"if",
"no",
"messages",
"arrived",
"before",
"the",
"timeout",
"or",
"the",
"event",
"tuple",
"if",
"there",
"is",
"a",
"message",
"to",
"receive",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py#L522-L553 | [
"def",
"_poll",
"(",
"self",
",",
"start_time",
")",
":",
"until_dead",
"=",
"self",
".",
"time_to_dead",
"-",
"(",
"time",
".",
"time",
"(",
")",
"-",
"start_time",
")",
"# ensure poll at least once",
"until_dead",
"=",
"max",
"(",
"until_dead",
",",
"1e-3",
")",
"events",
"=",
"[",
"]",
"while",
"True",
":",
"try",
":",
"events",
"=",
"self",
".",
"poller",
".",
"poll",
"(",
"1000",
"*",
"until_dead",
")",
"except",
"ZMQError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"==",
"errno",
".",
"EINTR",
":",
"# ignore interrupts during heartbeat",
"# this may never actually happen",
"until_dead",
"=",
"self",
".",
"time_to_dead",
"-",
"(",
"time",
".",
"time",
"(",
")",
"-",
"start_time",
")",
"until_dead",
"=",
"max",
"(",
"until_dead",
",",
"1e-3",
")",
"pass",
"else",
":",
"raise",
"except",
"Exception",
":",
"if",
"self",
".",
"_exiting",
":",
"break",
"else",
":",
"raise",
"else",
":",
"break",
"return",
"events"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | HBSocketChannel.run | The thread's main activity. Call start() instead. | environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py | def run(self):
"""The thread's main activity. Call start() instead."""
self._create_socket()
self._running = True
self._beating = True
while self._running:
if self._pause:
# just sleep, and skip the rest of the loop
time.sleep(self.time_to_dead)
continue
since_last_heartbeat = 0.0
# io.rprint('Ping from HB channel') # dbg
# no need to catch EFSM here, because the previous event was
# either a recv or connect, which cannot be followed by EFSM
self.socket.send(b'ping')
request_time = time.time()
ready = self._poll(request_time)
if ready:
self._beating = True
# the poll above guarantees we have something to recv
self.socket.recv()
# sleep the remainder of the cycle
remainder = self.time_to_dead - (time.time() - request_time)
if remainder > 0:
time.sleep(remainder)
continue
else:
# nothing was received within the time limit, signal heart failure
self._beating = False
since_last_heartbeat = time.time() - request_time
self.call_handlers(since_last_heartbeat)
# and close/reopen the socket, because the REQ/REP cycle has been broken
self._create_socket()
continue
try:
self.socket.close()
except:
pass | def run(self):
"""The thread's main activity. Call start() instead."""
self._create_socket()
self._running = True
self._beating = True
while self._running:
if self._pause:
# just sleep, and skip the rest of the loop
time.sleep(self.time_to_dead)
continue
since_last_heartbeat = 0.0
# io.rprint('Ping from HB channel') # dbg
# no need to catch EFSM here, because the previous event was
# either a recv or connect, which cannot be followed by EFSM
self.socket.send(b'ping')
request_time = time.time()
ready = self._poll(request_time)
if ready:
self._beating = True
# the poll above guarantees we have something to recv
self.socket.recv()
# sleep the remainder of the cycle
remainder = self.time_to_dead - (time.time() - request_time)
if remainder > 0:
time.sleep(remainder)
continue
else:
# nothing was received within the time limit, signal heart failure
self._beating = False
since_last_heartbeat = time.time() - request_time
self.call_handlers(since_last_heartbeat)
# and close/reopen the socket, because the REQ/REP cycle has been broken
self._create_socket()
continue
try:
self.socket.close()
except:
pass | [
"The",
"thread",
"s",
"main",
"activity",
".",
"Call",
"start",
"()",
"instead",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py#L555-L594 | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"_create_socket",
"(",
")",
"self",
".",
"_running",
"=",
"True",
"self",
".",
"_beating",
"=",
"True",
"while",
"self",
".",
"_running",
":",
"if",
"self",
".",
"_pause",
":",
"# just sleep, and skip the rest of the loop",
"time",
".",
"sleep",
"(",
"self",
".",
"time_to_dead",
")",
"continue",
"since_last_heartbeat",
"=",
"0.0",
"# io.rprint('Ping from HB channel') # dbg",
"# no need to catch EFSM here, because the previous event was",
"# either a recv or connect, which cannot be followed by EFSM",
"self",
".",
"socket",
".",
"send",
"(",
"b'ping'",
")",
"request_time",
"=",
"time",
".",
"time",
"(",
")",
"ready",
"=",
"self",
".",
"_poll",
"(",
"request_time",
")",
"if",
"ready",
":",
"self",
".",
"_beating",
"=",
"True",
"# the poll above guarantees we have something to recv",
"self",
".",
"socket",
".",
"recv",
"(",
")",
"# sleep the remainder of the cycle",
"remainder",
"=",
"self",
".",
"time_to_dead",
"-",
"(",
"time",
".",
"time",
"(",
")",
"-",
"request_time",
")",
"if",
"remainder",
">",
"0",
":",
"time",
".",
"sleep",
"(",
"remainder",
")",
"continue",
"else",
":",
"# nothing was received within the time limit, signal heart failure",
"self",
".",
"_beating",
"=",
"False",
"since_last_heartbeat",
"=",
"time",
".",
"time",
"(",
")",
"-",
"request_time",
"self",
".",
"call_handlers",
"(",
"since_last_heartbeat",
")",
"# and close/reopen the socket, because the REQ/REP cycle has been broken",
"self",
".",
"_create_socket",
"(",
")",
"continue",
"try",
":",
"self",
".",
"socket",
".",
"close",
"(",
")",
"except",
":",
"pass"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | HBSocketChannel.is_beating | Is the heartbeat running and responsive (and not paused). | environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py | def is_beating(self):
"""Is the heartbeat running and responsive (and not paused)."""
if self.is_alive() and not self._pause and self._beating:
return True
else:
return False | def is_beating(self):
"""Is the heartbeat running and responsive (and not paused)."""
if self.is_alive() and not self._pause and self._beating:
return True
else:
return False | [
"Is",
"the",
"heartbeat",
"running",
"and",
"responsive",
"(",
"and",
"not",
"paused",
")",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py#L604-L609 | [
"def",
"is_beating",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_alive",
"(",
")",
"and",
"not",
"self",
".",
"_pause",
"and",
"self",
".",
"_beating",
":",
"return",
"True",
"else",
":",
"return",
"False"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | KernelManager.start_channels | Starts the channels for this kernel.
This will create the channels if they do not exist and then start
them. If port numbers of 0 are being used (random ports) then you
must first call :method:`start_kernel`. If the channels have been
stopped and you call this, :class:`RuntimeError` will be raised. | environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py | def start_channels(self, shell=True, sub=True, stdin=True, hb=True):
"""Starts the channels for this kernel.
This will create the channels if they do not exist and then start
them. If port numbers of 0 are being used (random ports) then you
must first call :method:`start_kernel`. If the channels have been
stopped and you call this, :class:`RuntimeError` will be raised.
"""
if shell:
self.shell_channel.start()
if sub:
self.sub_channel.start()
if stdin:
self.stdin_channel.start()
self.shell_channel.allow_stdin = True
else:
self.shell_channel.allow_stdin = False
if hb:
self.hb_channel.start() | def start_channels(self, shell=True, sub=True, stdin=True, hb=True):
"""Starts the channels for this kernel.
This will create the channels if they do not exist and then start
them. If port numbers of 0 are being used (random ports) then you
must first call :method:`start_kernel`. If the channels have been
stopped and you call this, :class:`RuntimeError` will be raised.
"""
if shell:
self.shell_channel.start()
if sub:
self.sub_channel.start()
if stdin:
self.stdin_channel.start()
self.shell_channel.allow_stdin = True
else:
self.shell_channel.allow_stdin = False
if hb:
self.hb_channel.start() | [
"Starts",
"the",
"channels",
"for",
"this",
"kernel",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py#L693-L711 | [
"def",
"start_channels",
"(",
"self",
",",
"shell",
"=",
"True",
",",
"sub",
"=",
"True",
",",
"stdin",
"=",
"True",
",",
"hb",
"=",
"True",
")",
":",
"if",
"shell",
":",
"self",
".",
"shell_channel",
".",
"start",
"(",
")",
"if",
"sub",
":",
"self",
".",
"sub_channel",
".",
"start",
"(",
")",
"if",
"stdin",
":",
"self",
".",
"stdin_channel",
".",
"start",
"(",
")",
"self",
".",
"shell_channel",
".",
"allow_stdin",
"=",
"True",
"else",
":",
"self",
".",
"shell_channel",
".",
"allow_stdin",
"=",
"False",
"if",
"hb",
":",
"self",
".",
"hb_channel",
".",
"start",
"(",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | KernelManager.stop_channels | Stops all the running channels for this kernel. | environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py | def stop_channels(self):
"""Stops all the running channels for this kernel.
"""
if self.shell_channel.is_alive():
self.shell_channel.stop()
if self.sub_channel.is_alive():
self.sub_channel.stop()
if self.stdin_channel.is_alive():
self.stdin_channel.stop()
if self.hb_channel.is_alive():
self.hb_channel.stop() | def stop_channels(self):
"""Stops all the running channels for this kernel.
"""
if self.shell_channel.is_alive():
self.shell_channel.stop()
if self.sub_channel.is_alive():
self.sub_channel.stop()
if self.stdin_channel.is_alive():
self.stdin_channel.stop()
if self.hb_channel.is_alive():
self.hb_channel.stop() | [
"Stops",
"all",
"the",
"running",
"channels",
"for",
"this",
"kernel",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py#L713-L723 | [
"def",
"stop_channels",
"(",
"self",
")",
":",
"if",
"self",
".",
"shell_channel",
".",
"is_alive",
"(",
")",
":",
"self",
".",
"shell_channel",
".",
"stop",
"(",
")",
"if",
"self",
".",
"sub_channel",
".",
"is_alive",
"(",
")",
":",
"self",
".",
"sub_channel",
".",
"stop",
"(",
")",
"if",
"self",
".",
"stdin_channel",
".",
"is_alive",
"(",
")",
":",
"self",
".",
"stdin_channel",
".",
"stop",
"(",
")",
"if",
"self",
".",
"hb_channel",
".",
"is_alive",
"(",
")",
":",
"self",
".",
"hb_channel",
".",
"stop",
"(",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | KernelManager.channels_running | Are any of the channels created and running? | environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py | def channels_running(self):
"""Are any of the channels created and running?"""
return (self.shell_channel.is_alive() or self.sub_channel.is_alive() or
self.stdin_channel.is_alive() or self.hb_channel.is_alive()) | def channels_running(self):
"""Are any of the channels created and running?"""
return (self.shell_channel.is_alive() or self.sub_channel.is_alive() or
self.stdin_channel.is_alive() or self.hb_channel.is_alive()) | [
"Are",
"any",
"of",
"the",
"channels",
"created",
"and",
"running?"
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py#L726-L729 | [
"def",
"channels_running",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"shell_channel",
".",
"is_alive",
"(",
")",
"or",
"self",
".",
"sub_channel",
".",
"is_alive",
"(",
")",
"or",
"self",
".",
"stdin_channel",
".",
"is_alive",
"(",
")",
"or",
"self",
".",
"hb_channel",
".",
"is_alive",
"(",
")",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | KernelManager.cleanup_connection_file | cleanup connection file *if we wrote it*
Will not raise if the connection file was already removed somehow. | environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py | def cleanup_connection_file(self):
"""cleanup connection file *if we wrote it*
Will not raise if the connection file was already removed somehow.
"""
if self._connection_file_written:
# cleanup connection files on full shutdown of kernel we started
self._connection_file_written = False
try:
os.remove(self.connection_file)
except OSError:
pass | def cleanup_connection_file(self):
"""cleanup connection file *if we wrote it*
Will not raise if the connection file was already removed somehow.
"""
if self._connection_file_written:
# cleanup connection files on full shutdown of kernel we started
self._connection_file_written = False
try:
os.remove(self.connection_file)
except OSError:
pass | [
"cleanup",
"connection",
"file",
"*",
"if",
"we",
"wrote",
"it",
"*",
"Will",
"not",
"raise",
"if",
"the",
"connection",
"file",
"was",
"already",
"removed",
"somehow",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py#L735-L746 | [
"def",
"cleanup_connection_file",
"(",
"self",
")",
":",
"if",
"self",
".",
"_connection_file_written",
":",
"# cleanup connection files on full shutdown of kernel we started",
"self",
".",
"_connection_file_written",
"=",
"False",
"try",
":",
"os",
".",
"remove",
"(",
"self",
".",
"connection_file",
")",
"except",
"OSError",
":",
"pass"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | KernelManager.load_connection_file | load connection info from JSON dict in self.connection_file | environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py | def load_connection_file(self):
"""load connection info from JSON dict in self.connection_file"""
with open(self.connection_file) as f:
cfg = json.loads(f.read())
self.ip = cfg['ip']
self.shell_port = cfg['shell_port']
self.stdin_port = cfg['stdin_port']
self.iopub_port = cfg['iopub_port']
self.hb_port = cfg['hb_port']
self.session.key = str_to_bytes(cfg['key']) | def load_connection_file(self):
"""load connection info from JSON dict in self.connection_file"""
with open(self.connection_file) as f:
cfg = json.loads(f.read())
self.ip = cfg['ip']
self.shell_port = cfg['shell_port']
self.stdin_port = cfg['stdin_port']
self.iopub_port = cfg['iopub_port']
self.hb_port = cfg['hb_port']
self.session.key = str_to_bytes(cfg['key']) | [
"load",
"connection",
"info",
"from",
"JSON",
"dict",
"in",
"self",
".",
"connection_file"
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py#L748-L758 | [
"def",
"load_connection_file",
"(",
"self",
")",
":",
"with",
"open",
"(",
"self",
".",
"connection_file",
")",
"as",
"f",
":",
"cfg",
"=",
"json",
".",
"loads",
"(",
"f",
".",
"read",
"(",
")",
")",
"self",
".",
"ip",
"=",
"cfg",
"[",
"'ip'",
"]",
"self",
".",
"shell_port",
"=",
"cfg",
"[",
"'shell_port'",
"]",
"self",
".",
"stdin_port",
"=",
"cfg",
"[",
"'stdin_port'",
"]",
"self",
".",
"iopub_port",
"=",
"cfg",
"[",
"'iopub_port'",
"]",
"self",
".",
"hb_port",
"=",
"cfg",
"[",
"'hb_port'",
"]",
"self",
".",
"session",
".",
"key",
"=",
"str_to_bytes",
"(",
"cfg",
"[",
"'key'",
"]",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | KernelManager.write_connection_file | write connection info to JSON dict in self.connection_file | environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py | def write_connection_file(self):
"""write connection info to JSON dict in self.connection_file"""
if self._connection_file_written:
return
self.connection_file,cfg = write_connection_file(self.connection_file,
ip=self.ip, key=self.session.key,
stdin_port=self.stdin_port, iopub_port=self.iopub_port,
shell_port=self.shell_port, hb_port=self.hb_port)
# write_connection_file also sets default ports:
self.shell_port = cfg['shell_port']
self.stdin_port = cfg['stdin_port']
self.iopub_port = cfg['iopub_port']
self.hb_port = cfg['hb_port']
self._connection_file_written = True | def write_connection_file(self):
"""write connection info to JSON dict in self.connection_file"""
if self._connection_file_written:
return
self.connection_file,cfg = write_connection_file(self.connection_file,
ip=self.ip, key=self.session.key,
stdin_port=self.stdin_port, iopub_port=self.iopub_port,
shell_port=self.shell_port, hb_port=self.hb_port)
# write_connection_file also sets default ports:
self.shell_port = cfg['shell_port']
self.stdin_port = cfg['stdin_port']
self.iopub_port = cfg['iopub_port']
self.hb_port = cfg['hb_port']
self._connection_file_written = True | [
"write",
"connection",
"info",
"to",
"JSON",
"dict",
"in",
"self",
".",
"connection_file"
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py#L760-L774 | [
"def",
"write_connection_file",
"(",
"self",
")",
":",
"if",
"self",
".",
"_connection_file_written",
":",
"return",
"self",
".",
"connection_file",
",",
"cfg",
"=",
"write_connection_file",
"(",
"self",
".",
"connection_file",
",",
"ip",
"=",
"self",
".",
"ip",
",",
"key",
"=",
"self",
".",
"session",
".",
"key",
",",
"stdin_port",
"=",
"self",
".",
"stdin_port",
",",
"iopub_port",
"=",
"self",
".",
"iopub_port",
",",
"shell_port",
"=",
"self",
".",
"shell_port",
",",
"hb_port",
"=",
"self",
".",
"hb_port",
")",
"# write_connection_file also sets default ports:",
"self",
".",
"shell_port",
"=",
"cfg",
"[",
"'shell_port'",
"]",
"self",
".",
"stdin_port",
"=",
"cfg",
"[",
"'stdin_port'",
"]",
"self",
".",
"iopub_port",
"=",
"cfg",
"[",
"'iopub_port'",
"]",
"self",
".",
"hb_port",
"=",
"cfg",
"[",
"'hb_port'",
"]",
"self",
".",
"_connection_file_written",
"=",
"True"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | KernelManager.start_kernel | Starts a kernel process and configures the manager to use it.
If random ports (port=0) are being used, this method must be called
before the channels are created.
Parameters:
-----------
launcher : callable, optional (default None)
A custom function for launching the kernel process (generally a
wrapper around ``entry_point.base_launch_kernel``). In most cases,
it should not be necessary to use this parameter.
**kw : optional
See respective options for IPython and Python kernels. | environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py | def start_kernel(self, **kw):
"""Starts a kernel process and configures the manager to use it.
If random ports (port=0) are being used, this method must be called
before the channels are created.
Parameters:
-----------
launcher : callable, optional (default None)
A custom function for launching the kernel process (generally a
wrapper around ``entry_point.base_launch_kernel``). In most cases,
it should not be necessary to use this parameter.
**kw : optional
See respective options for IPython and Python kernels.
"""
if self.ip not in LOCAL_IPS:
raise RuntimeError("Can only launch a kernel on a local interface. "
"Make sure that the '*_address' attributes are "
"configured properly. "
"Currently valid addresses are: %s"%LOCAL_IPS
)
# write connection file / get default ports
self.write_connection_file()
self._launch_args = kw.copy()
launch_kernel = kw.pop('launcher', None)
if launch_kernel is None:
from ipkernel import launch_kernel
self.kernel = launch_kernel(fname=self.connection_file, **kw) | def start_kernel(self, **kw):
"""Starts a kernel process and configures the manager to use it.
If random ports (port=0) are being used, this method must be called
before the channels are created.
Parameters:
-----------
launcher : callable, optional (default None)
A custom function for launching the kernel process (generally a
wrapper around ``entry_point.base_launch_kernel``). In most cases,
it should not be necessary to use this parameter.
**kw : optional
See respective options for IPython and Python kernels.
"""
if self.ip not in LOCAL_IPS:
raise RuntimeError("Can only launch a kernel on a local interface. "
"Make sure that the '*_address' attributes are "
"configured properly. "
"Currently valid addresses are: %s"%LOCAL_IPS
)
# write connection file / get default ports
self.write_connection_file()
self._launch_args = kw.copy()
launch_kernel = kw.pop('launcher', None)
if launch_kernel is None:
from ipkernel import launch_kernel
self.kernel = launch_kernel(fname=self.connection_file, **kw) | [
"Starts",
"a",
"kernel",
"process",
"and",
"configures",
"the",
"manager",
"to",
"use",
"it",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py#L776-L806 | [
"def",
"start_kernel",
"(",
"self",
",",
"*",
"*",
"kw",
")",
":",
"if",
"self",
".",
"ip",
"not",
"in",
"LOCAL_IPS",
":",
"raise",
"RuntimeError",
"(",
"\"Can only launch a kernel on a local interface. \"",
"\"Make sure that the '*_address' attributes are \"",
"\"configured properly. \"",
"\"Currently valid addresses are: %s\"",
"%",
"LOCAL_IPS",
")",
"# write connection file / get default ports",
"self",
".",
"write_connection_file",
"(",
")",
"self",
".",
"_launch_args",
"=",
"kw",
".",
"copy",
"(",
")",
"launch_kernel",
"=",
"kw",
".",
"pop",
"(",
"'launcher'",
",",
"None",
")",
"if",
"launch_kernel",
"is",
"None",
":",
"from",
"ipkernel",
"import",
"launch_kernel",
"self",
".",
"kernel",
"=",
"launch_kernel",
"(",
"fname",
"=",
"self",
".",
"connection_file",
",",
"*",
"*",
"kw",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | KernelManager.shutdown_kernel | Attempts to the stop the kernel process cleanly. If the kernel
cannot be stopped, it is killed, if possible. | environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py | def shutdown_kernel(self, restart=False):
""" Attempts to the stop the kernel process cleanly. If the kernel
cannot be stopped, it is killed, if possible.
"""
# FIXME: Shutdown does not work on Windows due to ZMQ errors!
if sys.platform == 'win32':
self.kill_kernel()
return
# Pause the heart beat channel if it exists.
if self._hb_channel is not None:
self._hb_channel.pause()
# Don't send any additional kernel kill messages immediately, to give
# the kernel a chance to properly execute shutdown actions. Wait for at
# most 1s, checking every 0.1s.
self.shell_channel.shutdown(restart=restart)
for i in range(10):
if self.is_alive:
time.sleep(0.1)
else:
break
else:
# OK, we've waited long enough.
if self.has_kernel:
self.kill_kernel()
if not restart and self._connection_file_written:
# cleanup connection files on full shutdown of kernel we started
self._connection_file_written = False
try:
os.remove(self.connection_file)
except IOError:
pass | def shutdown_kernel(self, restart=False):
""" Attempts to the stop the kernel process cleanly. If the kernel
cannot be stopped, it is killed, if possible.
"""
# FIXME: Shutdown does not work on Windows due to ZMQ errors!
if sys.platform == 'win32':
self.kill_kernel()
return
# Pause the heart beat channel if it exists.
if self._hb_channel is not None:
self._hb_channel.pause()
# Don't send any additional kernel kill messages immediately, to give
# the kernel a chance to properly execute shutdown actions. Wait for at
# most 1s, checking every 0.1s.
self.shell_channel.shutdown(restart=restart)
for i in range(10):
if self.is_alive:
time.sleep(0.1)
else:
break
else:
# OK, we've waited long enough.
if self.has_kernel:
self.kill_kernel()
if not restart and self._connection_file_written:
# cleanup connection files on full shutdown of kernel we started
self._connection_file_written = False
try:
os.remove(self.connection_file)
except IOError:
pass | [
"Attempts",
"to",
"the",
"stop",
"the",
"kernel",
"process",
"cleanly",
".",
"If",
"the",
"kernel",
"cannot",
"be",
"stopped",
"it",
"is",
"killed",
"if",
"possible",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py#L808-L841 | [
"def",
"shutdown_kernel",
"(",
"self",
",",
"restart",
"=",
"False",
")",
":",
"# FIXME: Shutdown does not work on Windows due to ZMQ errors!",
"if",
"sys",
".",
"platform",
"==",
"'win32'",
":",
"self",
".",
"kill_kernel",
"(",
")",
"return",
"# Pause the heart beat channel if it exists.",
"if",
"self",
".",
"_hb_channel",
"is",
"not",
"None",
":",
"self",
".",
"_hb_channel",
".",
"pause",
"(",
")",
"# Don't send any additional kernel kill messages immediately, to give",
"# the kernel a chance to properly execute shutdown actions. Wait for at",
"# most 1s, checking every 0.1s.",
"self",
".",
"shell_channel",
".",
"shutdown",
"(",
"restart",
"=",
"restart",
")",
"for",
"i",
"in",
"range",
"(",
"10",
")",
":",
"if",
"self",
".",
"is_alive",
":",
"time",
".",
"sleep",
"(",
"0.1",
")",
"else",
":",
"break",
"else",
":",
"# OK, we've waited long enough.",
"if",
"self",
".",
"has_kernel",
":",
"self",
".",
"kill_kernel",
"(",
")",
"if",
"not",
"restart",
"and",
"self",
".",
"_connection_file_written",
":",
"# cleanup connection files on full shutdown of kernel we started",
"self",
".",
"_connection_file_written",
"=",
"False",
"try",
":",
"os",
".",
"remove",
"(",
"self",
".",
"connection_file",
")",
"except",
"IOError",
":",
"pass"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | KernelManager.restart_kernel | Restarts a kernel with the arguments that were used to launch it.
If the old kernel was launched with random ports, the same ports will be
used for the new kernel.
Parameters
----------
now : bool, optional
If True, the kernel is forcefully restarted *immediately*, without
having a chance to do any cleanup action. Otherwise the kernel is
given 1s to clean up before a forceful restart is issued.
In all cases the kernel is restarted, the only difference is whether
it is given a chance to perform a clean shutdown or not.
**kw : optional
Any options specified here will replace those used to launch the
kernel. | environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py | def restart_kernel(self, now=False, **kw):
"""Restarts a kernel with the arguments that were used to launch it.
If the old kernel was launched with random ports, the same ports will be
used for the new kernel.
Parameters
----------
now : bool, optional
If True, the kernel is forcefully restarted *immediately*, without
having a chance to do any cleanup action. Otherwise the kernel is
given 1s to clean up before a forceful restart is issued.
In all cases the kernel is restarted, the only difference is whether
it is given a chance to perform a clean shutdown or not.
**kw : optional
Any options specified here will replace those used to launch the
kernel.
"""
if self._launch_args is None:
raise RuntimeError("Cannot restart the kernel. "
"No previous call to 'start_kernel'.")
else:
# Stop currently running kernel.
if self.has_kernel:
if now:
self.kill_kernel()
else:
self.shutdown_kernel(restart=True)
# Start new kernel.
self._launch_args.update(kw)
self.start_kernel(**self._launch_args)
# FIXME: Messages get dropped in Windows due to probable ZMQ bug
# unless there is some delay here.
if sys.platform == 'win32':
time.sleep(0.2) | def restart_kernel(self, now=False, **kw):
"""Restarts a kernel with the arguments that were used to launch it.
If the old kernel was launched with random ports, the same ports will be
used for the new kernel.
Parameters
----------
now : bool, optional
If True, the kernel is forcefully restarted *immediately*, without
having a chance to do any cleanup action. Otherwise the kernel is
given 1s to clean up before a forceful restart is issued.
In all cases the kernel is restarted, the only difference is whether
it is given a chance to perform a clean shutdown or not.
**kw : optional
Any options specified here will replace those used to launch the
kernel.
"""
if self._launch_args is None:
raise RuntimeError("Cannot restart the kernel. "
"No previous call to 'start_kernel'.")
else:
# Stop currently running kernel.
if self.has_kernel:
if now:
self.kill_kernel()
else:
self.shutdown_kernel(restart=True)
# Start new kernel.
self._launch_args.update(kw)
self.start_kernel(**self._launch_args)
# FIXME: Messages get dropped in Windows due to probable ZMQ bug
# unless there is some delay here.
if sys.platform == 'win32':
time.sleep(0.2) | [
"Restarts",
"a",
"kernel",
"with",
"the",
"arguments",
"that",
"were",
"used",
"to",
"launch",
"it",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py#L843-L881 | [
"def",
"restart_kernel",
"(",
"self",
",",
"now",
"=",
"False",
",",
"*",
"*",
"kw",
")",
":",
"if",
"self",
".",
"_launch_args",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"\"Cannot restart the kernel. \"",
"\"No previous call to 'start_kernel'.\"",
")",
"else",
":",
"# Stop currently running kernel.",
"if",
"self",
".",
"has_kernel",
":",
"if",
"now",
":",
"self",
".",
"kill_kernel",
"(",
")",
"else",
":",
"self",
".",
"shutdown_kernel",
"(",
"restart",
"=",
"True",
")",
"# Start new kernel.",
"self",
".",
"_launch_args",
".",
"update",
"(",
"kw",
")",
"self",
".",
"start_kernel",
"(",
"*",
"*",
"self",
".",
"_launch_args",
")",
"# FIXME: Messages get dropped in Windows due to probable ZMQ bug",
"# unless there is some delay here.",
"if",
"sys",
".",
"platform",
"==",
"'win32'",
":",
"time",
".",
"sleep",
"(",
"0.2",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | KernelManager.kill_kernel | Kill the running kernel. | environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py | def kill_kernel(self):
""" Kill the running kernel. """
if self.has_kernel:
# Pause the heart beat channel if it exists.
if self._hb_channel is not None:
self._hb_channel.pause()
# Attempt to kill the kernel.
try:
self.kernel.kill()
except OSError, e:
# In Windows, we will get an Access Denied error if the process
# has already terminated. Ignore it.
if sys.platform == 'win32':
if e.winerror != 5:
raise
# On Unix, we may get an ESRCH error if the process has already
# terminated. Ignore it.
else:
from errno import ESRCH
if e.errno != ESRCH:
raise
self.kernel = None
else:
raise RuntimeError("Cannot kill kernel. No kernel is running!") | def kill_kernel(self):
""" Kill the running kernel. """
if self.has_kernel:
# Pause the heart beat channel if it exists.
if self._hb_channel is not None:
self._hb_channel.pause()
# Attempt to kill the kernel.
try:
self.kernel.kill()
except OSError, e:
# In Windows, we will get an Access Denied error if the process
# has already terminated. Ignore it.
if sys.platform == 'win32':
if e.winerror != 5:
raise
# On Unix, we may get an ESRCH error if the process has already
# terminated. Ignore it.
else:
from errno import ESRCH
if e.errno != ESRCH:
raise
self.kernel = None
else:
raise RuntimeError("Cannot kill kernel. No kernel is running!") | [
"Kill",
"the",
"running",
"kernel",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py#L890-L914 | [
"def",
"kill_kernel",
"(",
"self",
")",
":",
"if",
"self",
".",
"has_kernel",
":",
"# Pause the heart beat channel if it exists.",
"if",
"self",
".",
"_hb_channel",
"is",
"not",
"None",
":",
"self",
".",
"_hb_channel",
".",
"pause",
"(",
")",
"# Attempt to kill the kernel.",
"try",
":",
"self",
".",
"kernel",
".",
"kill",
"(",
")",
"except",
"OSError",
",",
"e",
":",
"# In Windows, we will get an Access Denied error if the process",
"# has already terminated. Ignore it.",
"if",
"sys",
".",
"platform",
"==",
"'win32'",
":",
"if",
"e",
".",
"winerror",
"!=",
"5",
":",
"raise",
"# On Unix, we may get an ESRCH error if the process has already",
"# terminated. Ignore it.",
"else",
":",
"from",
"errno",
"import",
"ESRCH",
"if",
"e",
".",
"errno",
"!=",
"ESRCH",
":",
"raise",
"self",
".",
"kernel",
"=",
"None",
"else",
":",
"raise",
"RuntimeError",
"(",
"\"Cannot kill kernel. No kernel is running!\"",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | KernelManager.interrupt_kernel | Interrupts the kernel. Unlike ``signal_kernel``, this operation is
well supported on all platforms. | environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py | def interrupt_kernel(self):
""" Interrupts the kernel. Unlike ``signal_kernel``, this operation is
well supported on all platforms.
"""
if self.has_kernel:
if sys.platform == 'win32':
from parentpoller import ParentPollerWindows as Poller
Poller.send_interrupt(self.kernel.win32_interrupt_event)
else:
self.kernel.send_signal(signal.SIGINT)
else:
raise RuntimeError("Cannot interrupt kernel. No kernel is running!") | def interrupt_kernel(self):
""" Interrupts the kernel. Unlike ``signal_kernel``, this operation is
well supported on all platforms.
"""
if self.has_kernel:
if sys.platform == 'win32':
from parentpoller import ParentPollerWindows as Poller
Poller.send_interrupt(self.kernel.win32_interrupt_event)
else:
self.kernel.send_signal(signal.SIGINT)
else:
raise RuntimeError("Cannot interrupt kernel. No kernel is running!") | [
"Interrupts",
"the",
"kernel",
".",
"Unlike",
"signal_kernel",
"this",
"operation",
"is",
"well",
"supported",
"on",
"all",
"platforms",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py#L916-L927 | [
"def",
"interrupt_kernel",
"(",
"self",
")",
":",
"if",
"self",
".",
"has_kernel",
":",
"if",
"sys",
".",
"platform",
"==",
"'win32'",
":",
"from",
"parentpoller",
"import",
"ParentPollerWindows",
"as",
"Poller",
"Poller",
".",
"send_interrupt",
"(",
"self",
".",
"kernel",
".",
"win32_interrupt_event",
")",
"else",
":",
"self",
".",
"kernel",
".",
"send_signal",
"(",
"signal",
".",
"SIGINT",
")",
"else",
":",
"raise",
"RuntimeError",
"(",
"\"Cannot interrupt kernel. No kernel is running!\"",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | KernelManager.signal_kernel | Sends a signal to the kernel. Note that since only SIGTERM is
supported on Windows, this function is only useful on Unix systems. | environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py | def signal_kernel(self, signum):
""" Sends a signal to the kernel. Note that since only SIGTERM is
supported on Windows, this function is only useful on Unix systems.
"""
if self.has_kernel:
self.kernel.send_signal(signum)
else:
raise RuntimeError("Cannot signal kernel. No kernel is running!") | def signal_kernel(self, signum):
""" Sends a signal to the kernel. Note that since only SIGTERM is
supported on Windows, this function is only useful on Unix systems.
"""
if self.has_kernel:
self.kernel.send_signal(signum)
else:
raise RuntimeError("Cannot signal kernel. No kernel is running!") | [
"Sends",
"a",
"signal",
"to",
"the",
"kernel",
".",
"Note",
"that",
"since",
"only",
"SIGTERM",
"is",
"supported",
"on",
"Windows",
"this",
"function",
"is",
"only",
"useful",
"on",
"Unix",
"systems",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py#L929-L936 | [
"def",
"signal_kernel",
"(",
"self",
",",
"signum",
")",
":",
"if",
"self",
".",
"has_kernel",
":",
"self",
".",
"kernel",
".",
"send_signal",
"(",
"signum",
")",
"else",
":",
"raise",
"RuntimeError",
"(",
"\"Cannot signal kernel. No kernel is running!\"",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | KernelManager.is_alive | Is the kernel process still running? | environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py | def is_alive(self):
"""Is the kernel process still running?"""
if self.has_kernel:
if self.kernel.poll() is None:
return True
else:
return False
elif self._hb_channel is not None:
# We didn't start the kernel with this KernelManager so we
# use the heartbeat.
return self._hb_channel.is_beating()
else:
# no heartbeat and not local, we can't tell if it's running,
# so naively return True
return True | def is_alive(self):
"""Is the kernel process still running?"""
if self.has_kernel:
if self.kernel.poll() is None:
return True
else:
return False
elif self._hb_channel is not None:
# We didn't start the kernel with this KernelManager so we
# use the heartbeat.
return self._hb_channel.is_beating()
else:
# no heartbeat and not local, we can't tell if it's running,
# so naively return True
return True | [
"Is",
"the",
"kernel",
"process",
"still",
"running?"
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py#L939-L953 | [
"def",
"is_alive",
"(",
"self",
")",
":",
"if",
"self",
".",
"has_kernel",
":",
"if",
"self",
".",
"kernel",
".",
"poll",
"(",
")",
"is",
"None",
":",
"return",
"True",
"else",
":",
"return",
"False",
"elif",
"self",
".",
"_hb_channel",
"is",
"not",
"None",
":",
"# We didn't start the kernel with this KernelManager so we",
"# use the heartbeat.",
"return",
"self",
".",
"_hb_channel",
".",
"is_beating",
"(",
")",
"else",
":",
"# no heartbeat and not local, we can't tell if it's running,",
"# so naively return True",
"return",
"True"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | KernelManager.shell_channel | Get the REQ socket channel object to make requests of the kernel. | environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py | def shell_channel(self):
"""Get the REQ socket channel object to make requests of the kernel."""
if self._shell_channel is None:
self._shell_channel = self.shell_channel_class(self.context,
self.session,
(self.ip, self.shell_port))
return self._shell_channel | def shell_channel(self):
"""Get the REQ socket channel object to make requests of the kernel."""
if self._shell_channel is None:
self._shell_channel = self.shell_channel_class(self.context,
self.session,
(self.ip, self.shell_port))
return self._shell_channel | [
"Get",
"the",
"REQ",
"socket",
"channel",
"object",
"to",
"make",
"requests",
"of",
"the",
"kernel",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py#L960-L966 | [
"def",
"shell_channel",
"(",
"self",
")",
":",
"if",
"self",
".",
"_shell_channel",
"is",
"None",
":",
"self",
".",
"_shell_channel",
"=",
"self",
".",
"shell_channel_class",
"(",
"self",
".",
"context",
",",
"self",
".",
"session",
",",
"(",
"self",
".",
"ip",
",",
"self",
".",
"shell_port",
")",
")",
"return",
"self",
".",
"_shell_channel"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | KernelManager.sub_channel | Get the SUB socket channel object. | environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py | def sub_channel(self):
"""Get the SUB socket channel object."""
if self._sub_channel is None:
self._sub_channel = self.sub_channel_class(self.context,
self.session,
(self.ip, self.iopub_port))
return self._sub_channel | def sub_channel(self):
"""Get the SUB socket channel object."""
if self._sub_channel is None:
self._sub_channel = self.sub_channel_class(self.context,
self.session,
(self.ip, self.iopub_port))
return self._sub_channel | [
"Get",
"the",
"SUB",
"socket",
"channel",
"object",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py#L969-L975 | [
"def",
"sub_channel",
"(",
"self",
")",
":",
"if",
"self",
".",
"_sub_channel",
"is",
"None",
":",
"self",
".",
"_sub_channel",
"=",
"self",
".",
"sub_channel_class",
"(",
"self",
".",
"context",
",",
"self",
".",
"session",
",",
"(",
"self",
".",
"ip",
",",
"self",
".",
"iopub_port",
")",
")",
"return",
"self",
".",
"_sub_channel"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | KernelManager.stdin_channel | Get the REP socket channel object to handle stdin (raw_input). | environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py | def stdin_channel(self):
"""Get the REP socket channel object to handle stdin (raw_input)."""
if self._stdin_channel is None:
self._stdin_channel = self.stdin_channel_class(self.context,
self.session,
(self.ip, self.stdin_port))
return self._stdin_channel | def stdin_channel(self):
"""Get the REP socket channel object to handle stdin (raw_input)."""
if self._stdin_channel is None:
self._stdin_channel = self.stdin_channel_class(self.context,
self.session,
(self.ip, self.stdin_port))
return self._stdin_channel | [
"Get",
"the",
"REP",
"socket",
"channel",
"object",
"to",
"handle",
"stdin",
"(",
"raw_input",
")",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py#L978-L984 | [
"def",
"stdin_channel",
"(",
"self",
")",
":",
"if",
"self",
".",
"_stdin_channel",
"is",
"None",
":",
"self",
".",
"_stdin_channel",
"=",
"self",
".",
"stdin_channel_class",
"(",
"self",
".",
"context",
",",
"self",
".",
"session",
",",
"(",
"self",
".",
"ip",
",",
"self",
".",
"stdin_port",
")",
")",
"return",
"self",
".",
"_stdin_channel"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | KernelManager.hb_channel | Get the heartbeat socket channel object to check that the
kernel is alive. | environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py | def hb_channel(self):
"""Get the heartbeat socket channel object to check that the
kernel is alive."""
if self._hb_channel is None:
self._hb_channel = self.hb_channel_class(self.context,
self.session,
(self.ip, self.hb_port))
return self._hb_channel | def hb_channel(self):
"""Get the heartbeat socket channel object to check that the
kernel is alive."""
if self._hb_channel is None:
self._hb_channel = self.hb_channel_class(self.context,
self.session,
(self.ip, self.hb_port))
return self._hb_channel | [
"Get",
"the",
"heartbeat",
"socket",
"channel",
"object",
"to",
"check",
"that",
"the",
"kernel",
"is",
"alive",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py#L987-L994 | [
"def",
"hb_channel",
"(",
"self",
")",
":",
"if",
"self",
".",
"_hb_channel",
"is",
"None",
":",
"self",
".",
"_hb_channel",
"=",
"self",
".",
"hb_channel_class",
"(",
"self",
".",
"context",
",",
"self",
".",
"session",
",",
"(",
"self",
".",
"ip",
",",
"self",
".",
"hb_port",
")",
")",
"return",
"self",
".",
"_hb_channel"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | bind_kernel | Bind an Engine's Kernel to be used as a full IPython kernel.
This allows a running Engine to be used simultaneously as a full IPython kernel
with the QtConsole or other frontends.
This function returns immediately. | environment/lib/python2.7/site-packages/IPython/parallel/__init__.py | def bind_kernel(**kwargs):
"""Bind an Engine's Kernel to be used as a full IPython kernel.
This allows a running Engine to be used simultaneously as a full IPython kernel
with the QtConsole or other frontends.
This function returns immediately.
"""
from IPython.zmq.ipkernel import IPKernelApp
from IPython.parallel.apps.ipengineapp import IPEngineApp
# first check for IPKernelApp, in which case this should be a no-op
# because there is already a bound kernel
if IPKernelApp.initialized() and isinstance(IPKernelApp._instance, IPKernelApp):
return
if IPEngineApp.initialized():
try:
app = IPEngineApp.instance()
except MultipleInstanceError:
pass
else:
return app.bind_kernel(**kwargs)
raise RuntimeError("bind_kernel be called from an IPEngineApp instance") | def bind_kernel(**kwargs):
"""Bind an Engine's Kernel to be used as a full IPython kernel.
This allows a running Engine to be used simultaneously as a full IPython kernel
with the QtConsole or other frontends.
This function returns immediately.
"""
from IPython.zmq.ipkernel import IPKernelApp
from IPython.parallel.apps.ipengineapp import IPEngineApp
# first check for IPKernelApp, in which case this should be a no-op
# because there is already a bound kernel
if IPKernelApp.initialized() and isinstance(IPKernelApp._instance, IPKernelApp):
return
if IPEngineApp.initialized():
try:
app = IPEngineApp.instance()
except MultipleInstanceError:
pass
else:
return app.bind_kernel(**kwargs)
raise RuntimeError("bind_kernel be called from an IPEngineApp instance") | [
"Bind",
"an",
"Engine",
"s",
"Kernel",
"to",
"be",
"used",
"as",
"a",
"full",
"IPython",
"kernel",
".",
"This",
"allows",
"a",
"running",
"Engine",
"to",
"be",
"used",
"simultaneously",
"as",
"a",
"full",
"IPython",
"kernel",
"with",
"the",
"QtConsole",
"or",
"other",
"frontends",
".",
"This",
"function",
"returns",
"immediately",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/__init__.py#L48-L72 | [
"def",
"bind_kernel",
"(",
"*",
"*",
"kwargs",
")",
":",
"from",
"IPython",
".",
"zmq",
".",
"ipkernel",
"import",
"IPKernelApp",
"from",
"IPython",
".",
"parallel",
".",
"apps",
".",
"ipengineapp",
"import",
"IPEngineApp",
"# first check for IPKernelApp, in which case this should be a no-op",
"# because there is already a bound kernel",
"if",
"IPKernelApp",
".",
"initialized",
"(",
")",
"and",
"isinstance",
"(",
"IPKernelApp",
".",
"_instance",
",",
"IPKernelApp",
")",
":",
"return",
"if",
"IPEngineApp",
".",
"initialized",
"(",
")",
":",
"try",
":",
"app",
"=",
"IPEngineApp",
".",
"instance",
"(",
")",
"except",
"MultipleInstanceError",
":",
"pass",
"else",
":",
"return",
"app",
".",
"bind_kernel",
"(",
"*",
"*",
"kwargs",
")",
"raise",
"RuntimeError",
"(",
"\"bind_kernel be called from an IPEngineApp instance\"",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | ExtensionDebugger.debug | Emit a debugging message depending on the debugging level.
:param level: The debugging level.
:param message: The message to emit. | timid/extensions.py | def debug(self, level, message):
"""
Emit a debugging message depending on the debugging level.
:param level: The debugging level.
:param message: The message to emit.
"""
if self._debug >= level:
print(message, file=sys.stderr) | def debug(self, level, message):
"""
Emit a debugging message depending on the debugging level.
:param level: The debugging level.
:param message: The message to emit.
"""
if self._debug >= level:
print(message, file=sys.stderr) | [
"Emit",
"a",
"debugging",
"message",
"depending",
"on",
"the",
"debugging",
"level",
"."
] | rackerlabs/timid | python | https://github.com/rackerlabs/timid/blob/b1c6aa159ab380a033740f4aa392cf0d125e0ac6/timid/extensions.py#L262-L271 | [
"def",
"debug",
"(",
"self",
",",
"level",
",",
"message",
")",
":",
"if",
"self",
".",
"_debug",
">=",
"level",
":",
"print",
"(",
"message",
",",
"file",
"=",
"sys",
".",
"stderr",
")"
] | b1c6aa159ab380a033740f4aa392cf0d125e0ac6 |
test | ExtensionSet._get_extension_classes | Retrieve the extension classes in priority order.
:returns: A list of extension classes, in proper priority
order. | timid/extensions.py | def _get_extension_classes(cls):
"""
Retrieve the extension classes in priority order.
:returns: A list of extension classes, in proper priority
order.
"""
if cls._extension_classes is None:
exts = {}
# Iterate over the entrypoints
for ext in entry.points[NAMESPACE_EXTENSIONS]:
exts.setdefault(ext.priority, [])
exts[ext.priority].append(ext)
# Save the list of extension classes
cls._extension_classes = list(utils.iter_prio_dict(exts))
return cls._extension_classes | def _get_extension_classes(cls):
"""
Retrieve the extension classes in priority order.
:returns: A list of extension classes, in proper priority
order.
"""
if cls._extension_classes is None:
exts = {}
# Iterate over the entrypoints
for ext in entry.points[NAMESPACE_EXTENSIONS]:
exts.setdefault(ext.priority, [])
exts[ext.priority].append(ext)
# Save the list of extension classes
cls._extension_classes = list(utils.iter_prio_dict(exts))
return cls._extension_classes | [
"Retrieve",
"the",
"extension",
"classes",
"in",
"priority",
"order",
"."
] | rackerlabs/timid | python | https://github.com/rackerlabs/timid/blob/b1c6aa159ab380a033740f4aa392cf0d125e0ac6/timid/extensions.py#L284-L303 | [
"def",
"_get_extension_classes",
"(",
"cls",
")",
":",
"if",
"cls",
".",
"_extension_classes",
"is",
"None",
":",
"exts",
"=",
"{",
"}",
"# Iterate over the entrypoints",
"for",
"ext",
"in",
"entry",
".",
"points",
"[",
"NAMESPACE_EXTENSIONS",
"]",
":",
"exts",
".",
"setdefault",
"(",
"ext",
".",
"priority",
",",
"[",
"]",
")",
"exts",
"[",
"ext",
".",
"priority",
"]",
".",
"append",
"(",
"ext",
")",
"# Save the list of extension classes",
"cls",
".",
"_extension_classes",
"=",
"list",
"(",
"utils",
".",
"iter_prio_dict",
"(",
"exts",
")",
")",
"return",
"cls",
".",
"_extension_classes"
] | b1c6aa159ab380a033740f4aa392cf0d125e0ac6 |
test | ExtensionSet.prepare | Prepare all the extensions. Extensions are prepared during
argument parser preparation. An extension implementing the
``prepare()`` method is able to add command line arguments
specific for that extension.
:param parser: The argument parser, an instance of
``argparse.ArgumentParser``. | timid/extensions.py | def prepare(cls, parser):
"""
Prepare all the extensions. Extensions are prepared during
argument parser preparation. An extension implementing the
``prepare()`` method is able to add command line arguments
specific for that extension.
:param parser: The argument parser, an instance of
``argparse.ArgumentParser``.
"""
debugger = ExtensionDebugger('prepare')
for ext in cls._get_extension_classes():
with debugger(ext):
ext.prepare(parser) | def prepare(cls, parser):
"""
Prepare all the extensions. Extensions are prepared during
argument parser preparation. An extension implementing the
``prepare()`` method is able to add command line arguments
specific for that extension.
:param parser: The argument parser, an instance of
``argparse.ArgumentParser``.
"""
debugger = ExtensionDebugger('prepare')
for ext in cls._get_extension_classes():
with debugger(ext):
ext.prepare(parser) | [
"Prepare",
"all",
"the",
"extensions",
".",
"Extensions",
"are",
"prepared",
"during",
"argument",
"parser",
"preparation",
".",
"An",
"extension",
"implementing",
"the",
"prepare",
"()",
"method",
"is",
"able",
"to",
"add",
"command",
"line",
"arguments",
"specific",
"for",
"that",
"extension",
"."
] | rackerlabs/timid | python | https://github.com/rackerlabs/timid/blob/b1c6aa159ab380a033740f4aa392cf0d125e0ac6/timid/extensions.py#L306-L321 | [
"def",
"prepare",
"(",
"cls",
",",
"parser",
")",
":",
"debugger",
"=",
"ExtensionDebugger",
"(",
"'prepare'",
")",
"for",
"ext",
"in",
"cls",
".",
"_get_extension_classes",
"(",
")",
":",
"with",
"debugger",
"(",
"ext",
")",
":",
"ext",
".",
"prepare",
"(",
"parser",
")"
] | b1c6aa159ab380a033740f4aa392cf0d125e0ac6 |
test | ExtensionSet.activate | Initialize the extensions. This loops over each extension
invoking its ``activate()`` method; those extensions that
return an object are considered "activated" and will be called
at later phases of extension processing.
:param ctxt: An instance of ``timid.context.Context``.
:param args: An instance of ``argparse.Namespace`` containing
the result of processing command line arguments.
:returns: An instance of ``ExtensionSet``. | timid/extensions.py | def activate(cls, ctxt, args):
"""
Initialize the extensions. This loops over each extension
invoking its ``activate()`` method; those extensions that
return an object are considered "activated" and will be called
at later phases of extension processing.
:param ctxt: An instance of ``timid.context.Context``.
:param args: An instance of ``argparse.Namespace`` containing
the result of processing command line arguments.
:returns: An instance of ``ExtensionSet``.
"""
debugger = ExtensionDebugger('activate')
exts = []
for ext in cls._get_extension_classes():
# Not using debugger as a context manager here, because we
# want to know about the exception even if we're ignoring
# it...but we need to notify which extension is being
# processed!
debugger(ext)
try:
# Check if the extension is being activated
obj = ext.activate(ctxt, args)
except Exception:
# Hmmm, failed to activate; handle the error
exc_info = sys.exc_info()
if not debugger.__exit__(*exc_info):
six.reraise(*exc_info)
else:
# OK, if the extension is activated, use it
if obj is not None:
exts.append(obj)
debugger.debug(2, 'Activating extension "%s.%s"' %
(ext.__module__, ext.__name__))
# Initialize and return the ExtensionSet
return cls(exts) | def activate(cls, ctxt, args):
"""
Initialize the extensions. This loops over each extension
invoking its ``activate()`` method; those extensions that
return an object are considered "activated" and will be called
at later phases of extension processing.
:param ctxt: An instance of ``timid.context.Context``.
:param args: An instance of ``argparse.Namespace`` containing
the result of processing command line arguments.
:returns: An instance of ``ExtensionSet``.
"""
debugger = ExtensionDebugger('activate')
exts = []
for ext in cls._get_extension_classes():
# Not using debugger as a context manager here, because we
# want to know about the exception even if we're ignoring
# it...but we need to notify which extension is being
# processed!
debugger(ext)
try:
# Check if the extension is being activated
obj = ext.activate(ctxt, args)
except Exception:
# Hmmm, failed to activate; handle the error
exc_info = sys.exc_info()
if not debugger.__exit__(*exc_info):
six.reraise(*exc_info)
else:
# OK, if the extension is activated, use it
if obj is not None:
exts.append(obj)
debugger.debug(2, 'Activating extension "%s.%s"' %
(ext.__module__, ext.__name__))
# Initialize and return the ExtensionSet
return cls(exts) | [
"Initialize",
"the",
"extensions",
".",
"This",
"loops",
"over",
"each",
"extension",
"invoking",
"its",
"activate",
"()",
"method",
";",
"those",
"extensions",
"that",
"return",
"an",
"object",
"are",
"considered",
"activated",
"and",
"will",
"be",
"called",
"at",
"later",
"phases",
"of",
"extension",
"processing",
"."
] | rackerlabs/timid | python | https://github.com/rackerlabs/timid/blob/b1c6aa159ab380a033740f4aa392cf0d125e0ac6/timid/extensions.py#L324-L364 | [
"def",
"activate",
"(",
"cls",
",",
"ctxt",
",",
"args",
")",
":",
"debugger",
"=",
"ExtensionDebugger",
"(",
"'activate'",
")",
"exts",
"=",
"[",
"]",
"for",
"ext",
"in",
"cls",
".",
"_get_extension_classes",
"(",
")",
":",
"# Not using debugger as a context manager here, because we",
"# want to know about the exception even if we're ignoring",
"# it...but we need to notify which extension is being",
"# processed!",
"debugger",
"(",
"ext",
")",
"try",
":",
"# Check if the extension is being activated",
"obj",
"=",
"ext",
".",
"activate",
"(",
"ctxt",
",",
"args",
")",
"except",
"Exception",
":",
"# Hmmm, failed to activate; handle the error",
"exc_info",
"=",
"sys",
".",
"exc_info",
"(",
")",
"if",
"not",
"debugger",
".",
"__exit__",
"(",
"*",
"exc_info",
")",
":",
"six",
".",
"reraise",
"(",
"*",
"exc_info",
")",
"else",
":",
"# OK, if the extension is activated, use it",
"if",
"obj",
"is",
"not",
"None",
":",
"exts",
".",
"append",
"(",
"obj",
")",
"debugger",
".",
"debug",
"(",
"2",
",",
"'Activating extension \"%s.%s\"'",
"%",
"(",
"ext",
".",
"__module__",
",",
"ext",
".",
"__name__",
")",
")",
"# Initialize and return the ExtensionSet",
"return",
"cls",
"(",
"exts",
")"
] | b1c6aa159ab380a033740f4aa392cf0d125e0ac6 |
test | ExtensionSet.read_steps | Called after reading steps, prior to adding them to the list of
test steps. Extensions are able to alter the list (in place).
:param ctxt: An instance of ``timid.context.Context``.
:param steps: A list of ``timid.steps.Step`` instances.
:returns: The ``steps`` parameter, for convenience. | timid/extensions.py | def read_steps(self, ctxt, steps):
"""
Called after reading steps, prior to adding them to the list of
test steps. Extensions are able to alter the list (in place).
:param ctxt: An instance of ``timid.context.Context``.
:param steps: A list of ``timid.steps.Step`` instances.
:returns: The ``steps`` parameter, for convenience.
"""
debugger = ExtensionDebugger('read_steps')
for ext in self.exts:
with debugger(ext):
ext.read_steps(ctxt, steps)
# Convenience return
return steps | def read_steps(self, ctxt, steps):
"""
Called after reading steps, prior to adding them to the list of
test steps. Extensions are able to alter the list (in place).
:param ctxt: An instance of ``timid.context.Context``.
:param steps: A list of ``timid.steps.Step`` instances.
:returns: The ``steps`` parameter, for convenience.
"""
debugger = ExtensionDebugger('read_steps')
for ext in self.exts:
with debugger(ext):
ext.read_steps(ctxt, steps)
# Convenience return
return steps | [
"Called",
"after",
"reading",
"steps",
"prior",
"to",
"adding",
"them",
"to",
"the",
"list",
"of",
"test",
"steps",
".",
"Extensions",
"are",
"able",
"to",
"alter",
"the",
"list",
"(",
"in",
"place",
")",
"."
] | rackerlabs/timid | python | https://github.com/rackerlabs/timid/blob/b1c6aa159ab380a033740f4aa392cf0d125e0ac6/timid/extensions.py#L375-L393 | [
"def",
"read_steps",
"(",
"self",
",",
"ctxt",
",",
"steps",
")",
":",
"debugger",
"=",
"ExtensionDebugger",
"(",
"'read_steps'",
")",
"for",
"ext",
"in",
"self",
".",
"exts",
":",
"with",
"debugger",
"(",
"ext",
")",
":",
"ext",
".",
"read_steps",
"(",
"ctxt",
",",
"steps",
")",
"# Convenience return",
"return",
"steps"
] | b1c6aa159ab380a033740f4aa392cf0d125e0ac6 |
test | ExtensionSet.pre_step | Called prior to executing a step.
:param ctxt: An instance of ``timid.context.Context``.
:param step: An instance of ``timid.steps.Step`` describing
the step to be executed.
:param idx: The index of the step in the list of steps.
:returns: A ``True`` value if the step is to be skipped,
``False`` otherwise. | timid/extensions.py | def pre_step(self, ctxt, step, idx):
"""
Called prior to executing a step.
:param ctxt: An instance of ``timid.context.Context``.
:param step: An instance of ``timid.steps.Step`` describing
the step to be executed.
:param idx: The index of the step in the list of steps.
:returns: A ``True`` value if the step is to be skipped,
``False`` otherwise.
"""
debugger = ExtensionDebugger('pre_step')
for ext in self.exts:
with debugger(ext):
if ext.pre_step(ctxt, step, idx):
# Step must be skipped
debugger.debug(3, 'Skipping step %d' % idx)
return True
return False | def pre_step(self, ctxt, step, idx):
"""
Called prior to executing a step.
:param ctxt: An instance of ``timid.context.Context``.
:param step: An instance of ``timid.steps.Step`` describing
the step to be executed.
:param idx: The index of the step in the list of steps.
:returns: A ``True`` value if the step is to be skipped,
``False`` otherwise.
"""
debugger = ExtensionDebugger('pre_step')
for ext in self.exts:
with debugger(ext):
if ext.pre_step(ctxt, step, idx):
# Step must be skipped
debugger.debug(3, 'Skipping step %d' % idx)
return True
return False | [
"Called",
"prior",
"to",
"executing",
"a",
"step",
"."
] | rackerlabs/timid | python | https://github.com/rackerlabs/timid/blob/b1c6aa159ab380a033740f4aa392cf0d125e0ac6/timid/extensions.py#L395-L417 | [
"def",
"pre_step",
"(",
"self",
",",
"ctxt",
",",
"step",
",",
"idx",
")",
":",
"debugger",
"=",
"ExtensionDebugger",
"(",
"'pre_step'",
")",
"for",
"ext",
"in",
"self",
".",
"exts",
":",
"with",
"debugger",
"(",
"ext",
")",
":",
"if",
"ext",
".",
"pre_step",
"(",
"ctxt",
",",
"step",
",",
"idx",
")",
":",
"# Step must be skipped",
"debugger",
".",
"debug",
"(",
"3",
",",
"'Skipping step %d'",
"%",
"idx",
")",
"return",
"True",
"return",
"False"
] | b1c6aa159ab380a033740f4aa392cf0d125e0ac6 |
test | ExtensionSet.post_step | Called after executing a step.
:param ctxt: An instance of ``timid.context.Context``.
:param step: An instance of ``timid.steps.Step`` describing
the step that was executed.
:param idx: The index of the step in the list of steps.
:param result: An instance of ``timid.steps.StepResult``
describing the result of executing the step.
May be altered by the extension, e.g., to set
the ``ignore`` attribute.
:returns: The ``result`` parameter, for convenience. | timid/extensions.py | def post_step(self, ctxt, step, idx, result):
"""
Called after executing a step.
:param ctxt: An instance of ``timid.context.Context``.
:param step: An instance of ``timid.steps.Step`` describing
the step that was executed.
:param idx: The index of the step in the list of steps.
:param result: An instance of ``timid.steps.StepResult``
describing the result of executing the step.
May be altered by the extension, e.g., to set
the ``ignore`` attribute.
:returns: The ``result`` parameter, for convenience.
"""
debugger = ExtensionDebugger('post_step')
for ext in self.exts:
with debugger(ext):
ext.post_step(ctxt, step, idx, result)
# Convenience return
return result | def post_step(self, ctxt, step, idx, result):
"""
Called after executing a step.
:param ctxt: An instance of ``timid.context.Context``.
:param step: An instance of ``timid.steps.Step`` describing
the step that was executed.
:param idx: The index of the step in the list of steps.
:param result: An instance of ``timid.steps.StepResult``
describing the result of executing the step.
May be altered by the extension, e.g., to set
the ``ignore`` attribute.
:returns: The ``result`` parameter, for convenience.
"""
debugger = ExtensionDebugger('post_step')
for ext in self.exts:
with debugger(ext):
ext.post_step(ctxt, step, idx, result)
# Convenience return
return result | [
"Called",
"after",
"executing",
"a",
"step",
"."
] | rackerlabs/timid | python | https://github.com/rackerlabs/timid/blob/b1c6aa159ab380a033740f4aa392cf0d125e0ac6/timid/extensions.py#L419-L442 | [
"def",
"post_step",
"(",
"self",
",",
"ctxt",
",",
"step",
",",
"idx",
",",
"result",
")",
":",
"debugger",
"=",
"ExtensionDebugger",
"(",
"'post_step'",
")",
"for",
"ext",
"in",
"self",
".",
"exts",
":",
"with",
"debugger",
"(",
"ext",
")",
":",
"ext",
".",
"post_step",
"(",
"ctxt",
",",
"step",
",",
"idx",
",",
"result",
")",
"# Convenience return",
"return",
"result"
] | b1c6aa159ab380a033740f4aa392cf0d125e0ac6 |
test | ExtensionSet.finalize | Called at the end of processing. This call allows extensions to
emit any additional data, such as timing information, prior to
``timid``'s exit. Extensions may also alter the return value.
:param ctxt: An instance of ``timid.context.Context``.
:param result: The return value of the basic ``timid`` call,
or an ``Exception`` instance if an exception
was raised. Without the extension, this would
be passed directly to ``sys.exit()``.
:returns: The final result. | timid/extensions.py | def finalize(self, ctxt, result):
"""
Called at the end of processing. This call allows extensions to
emit any additional data, such as timing information, prior to
``timid``'s exit. Extensions may also alter the return value.
:param ctxt: An instance of ``timid.context.Context``.
:param result: The return value of the basic ``timid`` call,
or an ``Exception`` instance if an exception
was raised. Without the extension, this would
be passed directly to ``sys.exit()``.
:returns: The final result.
"""
debugger = ExtensionDebugger('finalize')
for ext in self.exts:
with debugger(ext):
result = ext.finalize(ctxt, result)
return result | def finalize(self, ctxt, result):
"""
Called at the end of processing. This call allows extensions to
emit any additional data, such as timing information, prior to
``timid``'s exit. Extensions may also alter the return value.
:param ctxt: An instance of ``timid.context.Context``.
:param result: The return value of the basic ``timid`` call,
or an ``Exception`` instance if an exception
was raised. Without the extension, this would
be passed directly to ``sys.exit()``.
:returns: The final result.
"""
debugger = ExtensionDebugger('finalize')
for ext in self.exts:
with debugger(ext):
result = ext.finalize(ctxt, result)
return result | [
"Called",
"at",
"the",
"end",
"of",
"processing",
".",
"This",
"call",
"allows",
"extensions",
"to",
"emit",
"any",
"additional",
"data",
"such",
"as",
"timing",
"information",
"prior",
"to",
"timid",
"s",
"exit",
".",
"Extensions",
"may",
"also",
"alter",
"the",
"return",
"value",
"."
] | rackerlabs/timid | python | https://github.com/rackerlabs/timid/blob/b1c6aa159ab380a033740f4aa392cf0d125e0ac6/timid/extensions.py#L444-L465 | [
"def",
"finalize",
"(",
"self",
",",
"ctxt",
",",
"result",
")",
":",
"debugger",
"=",
"ExtensionDebugger",
"(",
"'finalize'",
")",
"for",
"ext",
"in",
"self",
".",
"exts",
":",
"with",
"debugger",
"(",
"ext",
")",
":",
"result",
"=",
"ext",
".",
"finalize",
"(",
"ctxt",
",",
"result",
")",
"return",
"result"
] | b1c6aa159ab380a033740f4aa392cf0d125e0ac6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.