rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
return
def _nt_quote_args (args): """Obscure quoting command line arguments on NT. Simply quote every argument which contains blanks.""" # XXX this doesn't seem very robust to me -- but if the Windows guys # say it'll work, I guess I'll have to accept it. (What if an arg # contains quotes? What other magic characters, othe...
for ordinal in (-100, 0x20000):
for ordinal in (-100, 0x200000):
def test_fixup(s): s2 = u'\ud800\udc01' test_lecmp(s, s2) s2 = u'\ud900\udc01' test_lecmp(s, s2) s2 = u'\uda00\udc01' test_lecmp(s, s2) s2 = u'\udb00\udc01' test_lecmp(s, s2) s2 = u'\ud800\udd01' test_lecmp(s, s2) s2 = u'\ud900\udd01' test_lecmp(s, s2) s2 = u'\uda00\udd01' test_lecmp(s, s2) s2 = u'\udb00\udd01' test_le...
print '*** formatting u"%%c" % %i should give a ValueError' % ordinal
print '*** formatting u"%%c" %% %i should give a ValueError' % ordinal
def test_fixup(s): s2 = u'\ud800\udc01' test_lecmp(s, s2) s2 = u'\ud900\udc01' test_lecmp(s, s2) s2 = u'\uda00\udc01' test_lecmp(s, s2) s2 = u'\udb00\udc01' test_lecmp(s, s2) s2 = u'\ud800\udd01' test_lecmp(s, s2) s2 = u'\ud900\udd01' test_lecmp(s, s2) s2 = u'\uda00\udd01' test_lecmp(s, s2) s2 = u'\udb00\udd01' test_le...
MethodNumber(1), CoerceNumber(2)]
MethodNumber(2), CoerceNumber(2)]
def __cmp__(self, other): return cmp(self.arg, other)
print '=', x
print '=', format_result(x)
def do_infix_binops(): for a in candidates: for b in candidates: for op in infix_binops: print '%s %s %s' % (a, op, b), try: x = eval('a %s b' % op) except: error = sys.exc_info()[:2] print '... %s' % error[0] else: print '=', x try: z = copy.copy(a) except copy.Error: z = a # assume it has no inplace ops print '%s %s=...
print '=>', z
print '=>', format_result(z)
def do_infix_binops(): for a in candidates: for b in candidates: for op in infix_binops: print '%s %s %s' % (a, op, b), try: x = eval('a %s b' % op) except: error = sys.exc_info()[:2] print '... %s' % error[0] else: print '=', x try: z = copy.copy(a) except copy.Error: z = a # assume it has no inplace ops print '%s %s=...
print '=', x
print '=', format_result(x)
def do_prefix_binops(): for a in candidates: for b in candidates: for op in prefix_binops: print '%s(%s, %s)' % (op, a, b), try: x = eval('%s(a, b)' % op) except: error = sys.exc_info()[:2] print '... %s' % error[0] else: print '=', x
if sys.platform == 'mac': _MWERKSDIR="Moes:Applications (Mac OS 9):Metrowerks CodeWarrior 7.0:Metrowerks CodeWarrior" else: _MWERKSDIR="/Volumes/Moes/Applications (Mac OS 9)/Metrowerks CodeWarrior 7.0/Metrowerks CodeWarrior/" INCLUDEDIR=os.path.join(_MWERKSDIR, "MacOS Support", "Universal", "Interfaces", "CIncludes")
INCLUDEDIR="/Users/jack/src/Universal/Interfaces/CIncludes"
def _pardir(p): return os.path.split(p)[0]
if sys.platform == 'mac': TOOLBOXDIR=os.path.join(sys.prefix, "Lib", "plat-mac", "Carbon") else: TOOLBOXDIR="/Users/jack/src/python/Lib/plat-mac/Carbon"
TOOLBOXDIR="/Users/jack/src/python/Lib/plat-mac/Carbon"
def _pardir(p): return os.path.split(p)[0]
res = [] for c in s: if c in safe: res.append(c) else: res.append('%%%02x' % ord(c))
res = list(s) for i in range(len(res)): c = res[i] if c not in safe: res[i] = '%%%02x' % ord(c)
def quote(s, safe = '/'): safe = always_safe + safe res = [] for c in s: if c in safe: res.append(c) else: res.append('%%%02x' % ord(c)) return string.joinfields(res, '')
s = string.join(string.split(s, ' '), '+') return quote(s, safe + '+')
l = string.split(s, ' ') for i in range(len(l)): l[i] = quote(l[i], safe) return string.join(l, '+')
def quote_plus(s, safe = '/'): if ' ' in s: # replace ' ' with '+' s = string.join(string.split(s, ' '), '+') return quote(s, safe + '+') else: return quote(s, safe)
dict = {}
def readmodule(module, path=[], inpackage=0): '''Read a module file and return a dictionary of classes. Search for MODULE in PATH and sys.path, read and parse the module and return a dictionary with one entry for each class found in the module.''' i = string.rfind(module, '.') if i >= 0: # Dotted module name package ...
dict = {'__path__': [file]}
dict['__path__'] = [file]
def readmodule(module, path=[], inpackage=0): '''Read a module file and return a dictionary of classes. Search for MODULE in PATH and sys.path, read and parse the module and return a dictionary with one entry for each class found in the module.''' i = string.rfind(module, '.') if i >= 0: # Dotted module name package ...
return dict
path = [file] + path f, file, (suff, mode, type) = \ imp.find_module('__init__', [file])
def readmodule(module, path=[], inpackage=0): '''Read a module file and return a dictionary of classes. Search for MODULE in PATH and sys.path, read and parse the module and return a dictionary with one entry for each class found in the module.''' i = string.rfind(module, '.') if i >= 0: # Dotted module name package ...
print repr(p)
def test_pickling(self): p = pickle.dumps(self.set) print repr(p) copy = pickle.loads(p) repr(copy) self.assertEqual(self.set, copy, "%s != %s" % (self.set, copy))
repr(copy)
def test_pickling(self): p = pickle.dumps(self.set) print repr(p) copy = pickle.loads(p) repr(copy) self.assertEqual(self.set, copy, "%s != %s" % (self.set, copy))
ZGUuDQ0KJAAAAAAAAADqs5WMrtL7367S+9+u0vvf1c7336/S+98tzvXfrNL731Hy/9+s0vvfzM3o 36bS+9+u0vrf89L7367S+9+j0vvfUfLx36PS+99p1P3fr9L731JpY2iu0vvfAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAUEUAAEwBAwD9e9Q5AAAAAAAAAADgAA8BCwEGAABAAAAAEAAAAJAAAADVAAAA
ZGUuDQ0KJAAAAAAAAABwj7aMNO7Y3zTu2N807tjfT/LU3zXu2N+38tbfNu7Y39zx3N827tjfVvHL 3zzu2N807tnfae7Y3zTu2N857tjf3PHS3znu2N+M6N7fNe7Y31JpY2g07tjfAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAUEUAAEwBAwAu6+E5AAAAAAAAAADgAA8BCwEGAABAAAAAEAAAAJAAAPDUAAAA
def get_exe_bytes (self): import base64 return base64.decodestring(EXEDATA)
bGwgUmlnaHRzIFJlc2VydmVkLiAkCgBVUFghDAkCCmbxMY8TFMU40bYAAPM0AAAAsAAAJgEABP+/
bGwgUmlnaHRzIFJlc2VydmVkLiAkCgBVUFghDAkCCl/uS+s25ddS0bYAAO40AAAAsAAAJgEAkP+/
def get_exe_bytes (self): import base64 return base64.decodestring(EXEDATA)
dZNqAVhfXr/7//9dW8NVi+yD7BCLRRRTVleLQBaLPXg0iUX4M/a79u7+d0PAOXUIdQfHRQgBDFZo gFYRY9/+9lZWUwUM/9eD+P8p/A+FiG182s23P/gDdRshGP91EOgV/wD2bffmcagPhApB67EfUHQJ UJn9sW176y9cGBjxUwxqAv9VGIW12bLxwC5nEGbW8GTsdSUuwmhUMOlTt/ue7wH0OwdZDvwkdAoT vb37yAONRfBQ3GaLSAoDQAxRYdj70Ht0Sn38GQNQ4XVvpqQ7+HUJC4idhy+U7psOVmoEVhCghIs9 iN/X4CKQhg9o...
dZNqAVhfXu/u/v9dW8NVi+yD7AxTVleLPXguM/a7OsA5dQjt7d39dQfHRQgBDFZogE0RVlZTBfsz 9v8M/9eD+P+JRfwPhYhkfPgDdRshb67dfCD/dRDoHv8AaJ8PhAO2Z992QeuxH1B0CVCQ6y9cIC3b H9sY6lMMagL/VSDowC7GXlibZxBmdSUuu/luDU9oVCfpUwHkOwePfLvvWQ7sJHQKEwONRfT3Wdhu bnUcAhg6dH38Et5Mw7ADQKQ0FHUJ3TfD6wuIlncOVmoEVhCgwUVoMBCIdIl2rW2+rw9hOII86yal K9u2NdsCUyqc...
def get_exe_bytes (self): import base64 return base64.decodestring(EXEDATA)
(pid, status) = os.waitpid(pid, 0)
try: (pid, status) = os.waitpid(pid, 0) except OSError, exc: import errno if exc.errno == errno.EINTR: continue raise DistutilsExecError, \ "command '%s' failed: %s" % (cmd[0], exc[-1])
def _spawn_posix (cmd, search_path=1, verbose=0, dry_run=0): log.info(string.join(cmd, ' ')) if dry_run: return exec_fn = search_path and os.execvp or os.execv pid = os.fork() if pid == 0: # in the child try: #print "cmd[0] =", cmd[0] #print "cmd =", cmd exec_fn(cmd[0], cmd) except OSError, e:...
while 1:
while True:
def _do_cmp(f1, f2): bufsize = BUFSIZE fp1 = open(f1, 'rb') fp2 = open(f2, 'rb') while 1: b1 = fp1.read(bufsize) b2 = fp2.read(bufsize) if b1 != b2: return 0 if not b1: return 1
return 0
return False
def _do_cmp(f1, f2): bufsize = BUFSIZE fp1 = open(f1, 'rb') fp2 = open(f2, 'rb') while 1: b1 = fp1.read(bufsize) b2 = fp2.read(bufsize) if b1 != b2: return 0 if not b1: return 1
return 1
return True
def _do_cmp(f1, f2): bufsize = BUFSIZE fp1 = open(f1, 'rb') fp2 = open(f2, 'rb') while 1: b1 = fp1.read(bufsize) b2 = fp2.read(bufsize) if b1 != b2: return 0 if not b1: return 1
__p4_attrs = ('subdirs',) __p3_attrs = ('same_files', 'diff_files', 'funny_files') __p2_attrs = ('common_dirs', 'common_files', 'common_funny') __p1_attrs = ('common', 'left_only', 'right_only') __p0_attrs = ('left_list', 'right_list') def __getattr__(self, attr): if attr in self.__p4_attrs: self.phase4() elif attr in...
def phase0(self): # Compare everything except common subdirectories self.left_list = _filter(os.listdir(self.left), self.hide+self.ignore) self.right_list = _filter(os.listdir(self.right), self.hide+self.ignore) self.left_list.sort() self.right_list.sort()
a_only, b_only = [], [] common = {} b = {} for fnm in self.right_list: b[fnm] = 1 for x in self.left_list: if b.get(x, 0): common[x] = 1 else: a_only.append(x) for x in self.right_list: if common.get(x, 0): pass else: b_only.append(x)
b = dict.fromkeys(self.right_list) common = dict.fromkeys(ifilter(b.has_key, self.left_list)) self.left_only = list(ifilterfalse(common.has_key, self.left_list)) self.right_only = list(ifilterfalse(common.has_key, self.right_list))
def phase1(self): # Compute common names a_only, b_only = [], [] common = {} b = {} for fnm in self.right_list: b[fnm] = 1 for x in self.left_list: if b.get(x, 0): common[x] = 1 else: a_only.append(x) for x in self.right_list: if common.get(x, 0): pass else: b_only.append(x) self.common = common.keys() self.left_only =...
self.left_only = a_only self.right_only = b_only
def phase1(self): # Compute common names a_only, b_only = [], [] common = {} b = {} for fnm in self.right_list: b[fnm] = 1 for x in self.left_list: if b.get(x, 0): common[x] = 1 else: a_only.append(x) for x in self.right_list: if common.get(x, 0): pass else: b_only.append(x) self.common = common.keys() self.left_only =...
def _cmp(a, b, sh):
def _cmp(a, b, sh, abs=abs, cmp=cmp):
def _cmp(a, b, sh): try: return not abs(cmp(a, b, sh)) except os.error: return 2
def _filter(list, skip): result = [] for item in list: if item not in skip: result.append(item) return result
def _filter(flist, skip): return list(ifilterfalse(skip.__contains__, flist))
def _filter(list, skip): result = [] for item in list: if item not in skip: result.append(item) return result
self.wfile.flush()
if not self.wfile.closed: self.wfile.flush()
def finish(self): self.wfile.flush() self.wfile.close() self.rfile.close()
13 0 LOAD_FAST 0 (a)
%-4d 0 LOAD_FAST 0 (a)
def _f(a): print a return 1
14 5 LOAD_CONST 1 (1)
%-4d 5 LOAD_CONST 1 (1)
def _f(a): print a return 1
"""
\ %-4d 0 SETUP_LOOP 23 (to 26) 3 LOAD_GLOBAL 0 (range) 6 LOAD_CONST 1 (1) %-4d 9 LOAD_CONST 2 (10) 12 CALL_FUNCTION 2 15 GET_ITER >> 16 FOR_ITER 6 (to 25) 19 STORE_FAST 0 (res) %-4d 22 JUMP_ABSOLUTE...
def _f(a): print a return 1
s = StringIO.StringIO() save_stdout = sys.stdout sys.stdout = s dis.dis(_f) sys.stdout = save_stdout got = s.getvalue() lines = got.split('\n') lines = [line.rstrip() for line in lines] got = '\n'.join(lines) self.assertEqual(dis_f, got)
self.do_disassembly_test(_f, dis_f) def test_bug_708901(self): self.do_disassembly_test(bug708901, dis_bug708901)
def test_dis(self): s = StringIO.StringIO() save_stdout = sys.stdout sys.stdout = s dis.dis(_f) sys.stdout = save_stdout got = s.getvalue() # Trim trailing blanks (if any). lines = got.split('\n') lines = [line.rstrip() for line in lines] got = '\n'.join(lines) self.assertEqual(dis_f, got)
self.__super_init(fp, hdrs, url)
def __init__(self, url, code, msg, hdrs, fp): self.__super_init(fp, hdrs, url) self.code = code self.msg = msg self.hdrs = hdrs self.fp = fp # XXX self.filename = url
timeaware = timetz(now.hour, now.minute, now.second, now.microsecond, tzinfo=tz55)
timeaware = now.timetz().replace(tzinfo=tz55)
def test_tz_aware_arithmetic(self): import random
nowawareplus = self.theclass.combine(nowawareplus.date(), timetz(nowawareplus.hour, nowawareplus.minute, nowawareplus.second, nowawareplus.microsecond, tzinfo=tzr))
nowawareplus = nowawareplus.replace(tzinfo=tzr)
def test_tz_aware_arithmetic(self): import random
def _encode_chunks(self): """MIME-encode a header with many different charsets and/or encodings. Given a list of pairs (string, charset), return a MIME-encoded string suitable for use in a header field. Each pair may have different charsets and/or encodings, and the resulting header will accurately reflect each setti...
def _encode_chunks(self, newchunks):
def _encode_chunks(self): """MIME-encode a header with many different charsets and/or encodings.
for header, charset in self._chunks:
for header, charset in newchunks:
def _encode_chunks(self): """MIME-encode a header with many different charsets and/or encodings.
self._chunks = newchunks return self._encode_chunks()
return self._encode_chunks(newchunks)
def encode(self): """Encode a message header into an RFC-compliant format.
if str[0] == '"' and str[-1:] == '"': return str[1:-1] if str[0] == '<' and str[-1:] == '>':
if str.startswith('"') and str.endswith('"'): return str[1:-1].replace('\\\\', '\\').replace('\\"', '"') if str.startswith('<') and str.endswith('>'):
def unquote(str): """Remove quotes from a string.""" if len(str) > 1: if str[0] == '"' and str[-1:] == '"': return str[1:-1] if str[0] == '<' and str[-1:] == '>': return str[1:-1] return str
self.assertEqual(len(Set(map(id, list(self.seq)))), len(self.seq))
self.assertEqual(len(Set(map(id, list(enumerate(self.seq))))), len(self.seq))
def test_tuple_reuse(self): # Tests an implementation detail where tuple is reused # whenever nothing else holds a reference to it self.assertEqual(len(Set(map(id, list(self.seq)))), len(self.seq)) self.assertEqual(len(Set(map(id, enumerate(self.seq)))), min(1,len(self.seq)))
def html(etype, evalue, etb, context=5): """Return a nice HTML document describing the traceback.""" import sys, os, types, time, traceback import keyword, tokenize, linecache, inspect, pydoc
__UNDEF__ = [] def small(text): return '<small>' + text + '</small>' def strong(text): return '<strong>' + text + '</strong>' def grey(text): return '<font color=" def lookup(name, frame, locals): """Find the value for a given name in the given environment.""" if name in locals: return 'local', locals[name] if name in...
def html(etype, evalue, etb, context=5): """Return a nice HTML document describing the traceback.""" import sys, os, types, time, traceback import keyword, tokenize, linecache, inspect, pydoc if type(etype) is types.ClassType: etype = etype.__name__ pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable da...
' <p>A problem occurred in a Python script. Here is the sequence of function calls leading up to the error, with the most recent (innermost) call last.''' indent = '<tt><small>' + '&nbsp;' * 5 + '</small>&nbsp;</tt>'
' <p>A problem occurred in a Python script. Here is the sequence of function calls leading up to the error, in the order they occurred.''' indent = '<tt>' + small('&nbsp;' * 5) + '&nbsp;</tt>'
def html(etype, evalue, etb, context=5): """Return a nice HTML document describing the traceback.""" import sys, os, types, time, traceback import keyword, tokenize, linecache, inspect, pydoc if type(etype) is types.ClassType: etype = etype.__name__ pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable da...
link = '<a href="file:%s">%s</a>' % (file, pydoc.html.escape(file))
link = '<a href="file://%s">%s</a>' % (file, pydoc.html.escape(file))
def html(etype, evalue, etb, context=5): """Return a nice HTML document describing the traceback.""" import sys, os, types, time, traceback import keyword, tokenize, linecache, inspect, pydoc if type(etype) is types.ClassType: etype = etype.__name__ pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable da...
if func == '?': call = '' else: def eqrepr(value): return '=' + pydoc.html.repr(value) call = 'in <strong>%s</strong>' % func + inspect.formatargvalues( args, varargs, varkw, locals, formatvalue=eqrepr) names = [] def tokeneater(type, token, start, end, line): if type == tokenize.NAME and token not in keyword.kwlist: ...
call = '' if func != '?': call = 'in ' + strong(func) + \ inspect.formatargvalues(args, varargs, varkw, locals, formatvalue=lambda value: '=' + pydoc.html.repr(value)) highlight = {} def reader(lnum=[lnum]): highlight[lnum[0]] = 1 try: return linecache.getline(file, lnum[0]) finally: lnum[0] += 1 vars = scanvars(reade...
def html(etype, evalue, etb, context=5): """Return a nice HTML document describing the traceback.""" import sys, os, types, time, traceback import keyword, tokenize, linecache, inspect, pydoc if type(etype) is types.ClassType: etype = etype.__name__ pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable da...
num = '<small><font color=" '&nbsp;' * (5-len(str(i))) + str(i)) line = '<tt>%s&nbsp;%s</tt>' % (num, pydoc.html.preformat(line)) if i == lnum: line = ''' <table width="100%%" bgcolor=" <tr><td>%s</td></tr></table>\n''' % line excerpt.append('\n' + line) if i == lnum: excerpt.append(lvals) i = i + 1 frames.append('<p>'...
num = small('&nbsp;' * (5-len(str(i))) + str(i)) + '&nbsp;' line = '<tt>%s%s</tt>' % (num, pydoc.html.preformat(line)) if i in highlight: rows.append('<tr><td bgcolor=" else: rows.append('<tr><td>%s</td></tr>' % grey(line)) i += 1 done, dump = {}, [] for name, where, value in vars: if name in done: continue done[name]...
def linereader(lnum=[lnum]): line = linecache.getline(file, lnum[0]) lnum[0] += 1 return line
plaintrace = ''.join(traceback.format_exception(etype, evalue, etb))
def linereader(lnum=[lnum]): line = linecache.getline(file, lnum[0]) lnum[0] += 1 return line
<!-- The above is a description of an error that occurred in a Python program. It is formatted for display in a Web browser because it appears that we are running in a CGI environment. In case you are viewing this message outside of a Web browser, here is the original error traceback:
<!-- The above is a description of an error in a Python program, formatted for a Web browser because the 'cgitb' module was enabled. In case you are not reading this in a Web browser, here is the original traceback:
def linereader(lnum=[lnum]): line = linecache.getline(file, lnum[0]) lnum[0] += 1 return line
''' % plaintrace
''' % ''.join(traceback.format_exception(etype, evalue, etb))
def linereader(lnum=[lnum]): line = linecache.getline(file, lnum[0]) lnum[0] += 1 return line
def __init__(self, display=1, logdir=None):
def __init__(self, display=1, logdir=None, context=5):
def __init__(self, display=1, logdir=None): self.display = display # send tracebacks to browser if true self.logdir = logdir # log tracebacks to files if not None
import sys, os
import sys
def handle(self, info=None): import sys, os info = info or sys.exc_info() text = 0 print reset()
text = 0
def handle(self, info=None): import sys, os info = info or sys.exc_info() text = 0 print reset()
doc = html(*info)
text, doc = 0, html(info, self.context)
def handle(self, info=None): import sys, os info = info or sys.exc_info() text = 0 print reset()
doc = ''.join(traceback.format_exception(*info)) text = 1
text, doc = 1, ''.join(traceback.format_exception(*info))
def handle(self, info=None): import sys, os info = info or sys.exc_info() text = 0 print reset()
print '<pre>', doc, '</pre>'
print '<pre>' + doc + '</pre>'
def handle(self, info=None): import sys, os info = info or sys.exc_info() text = 0 print reset()
import tempfile
import os, tempfile
def handle(self, info=None): import sys, os info = info or sys.exc_info() text = 0 print reset()
print '<p>Tried to write to %s, but failed.' % path
print '<p> Tried to save traceback to %s, but failed.' % path
def handle(self, info=None): import sys, os info = info or sys.exc_info() text = 0 print reset()
print '<dd>', escape(form[key])
print '<dd>', escape(`form[key]`)
def print_form( form ): skeys = form.keys() skeys.sort() print '<h3> The following name/value pairs ' \ 'were entered in the form: </h3>' print '<dl>' for key in skeys: print '<dt>', escape(key), ':', print '<i>', escape(`type(form[key])`), '</i>', print '<dd>', escape(form[key]) print '</dl>'
s = regsub.gsub('&', '&amp;') s = regsub.gsub('<', '&lt;') s = regsub.gsub('>', '&gt;')
s = regsub.gsub('&', '&amp;', s) s = regsub.gsub('<', '&lt;', s) s = regsub.gsub('>', '&gt;', s)
def escape( s ): s = regsub.gsub('&', '&amp;') # Must be done first s = regsub.gsub('<', '&lt;') s = regsub.gsub('>', '&gt;') return s
class SMTPRecipientsRefused(SMTPResponseException):
class SMTPRecipientsRefused(SMTPException):
def __init__(self, code, msg, sender): self.smtp_code = code self.smtp_error = msg self.sender = sender self.args = (code, msg, sender)
self.send(quotedata(msg)) self.send("%s.%s" % (CRLF, CRLF))
q = quotedata(msg) if q[-2:] != CRLF: q = q + CRLF q = q + "." + CRLF self.send(q)
def data(self,msg): """SMTP 'DATA' command -- sends message data to server.
def readline(self):
def readline(self, length=None):
def readline(self): if self.buflist: self.buf = self.buf + string.joinfields(self.buflist, '') self.buflist = [] i = string.find(self.buf, '\n', self.pos) if i < 0: newpos = self.len else: newpos = i+1 r = self.buf[self.pos:newpos] self.pos = newpos return r
src = sys.modules[key]
src = sys.modules[name]
def load_dynamic(self, name, filename, file):
print exc_type_name + ':', repr.repr(exc_value)
print exc_type_name + ':', _saferepr(exc_value)
def user_exception(self, frame, (exc_type, exc_value, exc_traceback)): """This function is called if an exception occurs, but only if we are to stop at or just below this level.""" frame.f_locals['__exception__'] = exc_type, exc_value if type(exc_type) == type(''): exc_type_name = exc_type else: exc_type_name = exc_typ...
zinfo.external_attr = st[0] << 16L
zinfo.external_attr = (st[0] & 0xFFFF) << 16L
def write(self, filename, arcname=None, compress_type=None): """Put the bytes from filename into the archive under the name arcname.""" st = os.stat(filename) mtime = time.localtime(st.st_mtime) date_time = mtime[0:6] # Create ZipInfo instance to store file information if arcname is None: zinfo = ZipInfo(filename, date...
SyntaxError: 'return' with argument inside generator (<doctest test.test_generators.__test__.syntax[0]>, line 2)
SyntaxError: 'return' with argument inside generator (<doctest test.test_generators.__test__.syntax[0]>, line 3)
>>> def f():
SyntaxError: 'return' with argument inside generator (<doctest test.test_generators.__test__.syntax[24]>, line 8)
SyntaxError: 'return' with argument inside generator (<doctest test.test_generators.__test__.syntax[24]>, line 10)
... def f(i):
/.
/\.
def test_getstatus(self): # This pattern should match 'ls -ld /.' on any posix # system, however perversely configured. pat = r'''d......... # It is a directory. \s+\d+ # It has some number of links. \s+\w+\s+\w+ # It has a user and group, which may # be named anything. \s+\d+ # It has a size. [^/]* ...
hdrfields = string.split(hdr)
hdrfields = hdr.split(" ", 2)
def decode(in_file, out_file=None, mode=None): """Decode uuencoded file""" # # Open the input file, if needed. # if in_file == '-': in_file = sys.stdin elif type(in_file) == type(''): in_file = open(in_file) # # Read until a begin is encountered or we've exhausted the file # while 1: hdr = in_file.readline() if not hdr...
string.atoi(hdrfields[1], 8)
int(hdrfields[1], 8)
def decode(in_file, out_file=None, mode=None): """Decode uuencoded file""" # # Open the input file, if needed. # if in_file == '-': in_file = sys.stdin elif type(in_file) == type(''): in_file = open(in_file) # # Read until a begin is encountered or we've exhausted the file # while 1: hdr = in_file.readline() if not hdr...
out_file = hdrfields[2]
out_file = hdrfields[2].rstrip()
def decode(in_file, out_file=None, mode=None): """Decode uuencoded file""" # # Open the input file, if needed. # if in_file == '-': in_file = sys.stdin elif type(in_file) == type(''): in_file = open(in_file) # # Read until a begin is encountered or we've exhausted the file # while 1: hdr = in_file.readline() if not hdr...
mode = string.atoi(hdrfields[1], 8)
mode = int(hdrfields[1], 8)
def decode(in_file, out_file=None, mode=None): """Decode uuencoded file""" # # Open the input file, if needed. # if in_file == '-': in_file = sys.stdin elif type(in_file) == type(''): in_file = open(in_file) # # Read until a begin is encountered or we've exhausted the file # while 1: hdr = in_file.readline() if not hdr...
print "Distribution.parse_config_files():"
if DEBUG: print "Distribution.parse_config_files():"
def parse_config_files (self, filenames=None):
print " reading", filename
if DEBUG: print " reading", filename
def parse_config_files (self, filenames=None):
print "showing 'global' help; commands=", self.commands
def parse_command_line (self, args): """Parse the setup script's command line. 'args' must be a list of command-line arguments, most likely 'sys.argv[1:]' (see the 'setup()' function). This list is first processed for "global options" -- options that set attributes of the Distribution instance. Then, it is alternate...
print "showing help for command", cmd_class
def _parse_command_opts (self, parser, args): """Parse the command-line options for a single command. 'parser' must be a FancyGetopt instance; 'args' must be the list of arguments, starting with the current command (whose options we are about to parse). Returns a new version of 'args' with the next command at the fron...
print "Distribution.get_command_obj(): " \ "creating '%s' command object" % command
if DEBUG: print "Distribution.get_command_obj(): " \ "creating '%s' command object" % command
def get_command_obj (self, command, create=1): """Return the command object for 'command'. Normally this object is cached on a previous call to 'get_command_obj()'; if no comand object for 'command' is in the cache, then we either create and return it (if 'create' is true) or return None. """ cmd_obj = self.command_ob...
('two', '(compound, (argument, list))',))
('two', '(compound, (argument, list))', 'compound', 'argument', 'list',))
def f5((compound, first), two): pass
def storbinary(self, cmd, fp, blocksize):
def storbinary(self, cmd, fp, blocksize=8192):
def storbinary(self, cmd, fp, blocksize): '''Store a file in binary mode.''' self.voidcmd('TYPE I') conn = self.transfercmd(cmd) while 1: buf = fp.read(blocksize) if not buf: break conn.send(buf) conn.close() return self.voidresp()
def resolve_dotted_attribute(obj, attr): """resolve_dotted_attribute(math, 'cos.__doc__') => math.cos.__doc__ Resolves a dotted attribute name to an object. Raises an AttributeError if any attribute in the chain starts with a '_'. """ for i in attr.split('.'): if i.startswith('_'): raise AttributeError( 'attempt to ac...
def resolve_dotted_attribute(obj, attr): """resolve_dotted_attribute(math, 'cos.__doc__') => math.cos.__doc__
return apply( getattr(self.server.instance,'_dispatch'), (method, params) )
return self.server.instance._dispatch(method, params)
def resolve_dotted_attribute(obj, attr): """resolve_dotted_attribute(math, 'cos.__doc__') => math.cos.__doc__
func = resolve_dotted_attribute(
func = _resolve_dotted_attribute(
def resolve_dotted_attribute(obj, attr): """resolve_dotted_attribute(math, 'cos.__doc__') => math.cos.__doc__
assert self.type is not None, self.__original
if self.type is None: raise ValueError, "unknown url type: %s" % self.__original
def get_type(self): if self.type is None: self.type, self.__r_type = splittype(self.__original) assert self.type is not None, self.__original return self.type
pos = pos + self.chunk_size
pos = pos + self.chunksize
def seek(self, pos, whence = 0): """Seek to specified position into the chunk. Default position is 0 (start of chunk). If the file is not seekable, this will result in an error. """
if do_copy: macostools.copy(os.path.join(sys.exec_prefix, src), dst) else: macostools.mkalias(os.path.join(sys.exec_prefix, src), dst)
try: if do_copy: macostools.copy(os.path.join(sys.exec_prefix, src), dst) else: macostools.mkalias(os.path.join(sys.exec_prefix, src), dst) except IOError: return 0
def mkcorealias(src, altsrc): import string import macostools version = string.split(sys.version)[0] dst = getextensiondirfile(src+ ' ' + version) if not dst: return 0 if not os.path.exists(os.path.join(sys.exec_prefix, src)): if not os.path.exists(os.path.join(sys.exec_prefix, altsrc)): return 0 src = altsrc try: os.u...
self.__testMethodName = methodName
self._testMethodName = methodName
def __init__(self, methodName='runTest'): """Create an instance of the class that will use the named test method when executed. Raises a ValueError if the instance does not have a method with the specified name. """ try: self.__testMethodName = methodName testMethod = getattr(self, methodName) self.__testMethodDoc = te...
self.__testMethodDoc = testMethod.__doc__
self._testMethodDoc = testMethod.__doc__
def __init__(self, methodName='runTest'): """Create an instance of the class that will use the named test method when executed. Raises a ValueError if the instance does not have a method with the specified name. """ try: self.__testMethodName = methodName testMethod = getattr(self, methodName) self.__testMethodDoc = te...
doc = self.__testMethodDoc
doc = self._testMethodDoc
def shortDescription(self): """Returns a one-line description of the test, or None if no description has been provided.
return "%s.%s" % (_strclass(self.__class__), self.__testMethodName)
return "%s.%s" % (_strclass(self.__class__), self._testMethodName)
def id(self): return "%s.%s" % (_strclass(self.__class__), self.__testMethodName)
return "%s (%s)" % (self.__testMethodName, _strclass(self.__class__))
return "%s (%s)" % (self._testMethodName, _strclass(self.__class__))
def __str__(self): return "%s (%s)" % (self.__testMethodName, _strclass(self.__class__))
(_strclass(self.__class__), self.__testMethodName)
(_strclass(self.__class__), self._testMethodName)
def __repr__(self): return "<%s testMethod=%s>" % \ (_strclass(self.__class__), self.__testMethodName)
testMethod = getattr(self, self.__testMethodName)
testMethod = getattr(self, self._testMethodName)
def run(self, result=None): if result is None: result = self.defaultTestResult() result.startTest(self) testMethod = getattr(self, self.__testMethodName) try: try: self.setUp() except KeyboardInterrupt: raise except: result.addError(self, self.__exc_info()) return
result.addError(self, self.__exc_info())
result.addError(self, self._exc_info())
def run(self, result=None): if result is None: result = self.defaultTestResult() result.startTest(self) testMethod = getattr(self, self.__testMethodName) try: try: self.setUp() except KeyboardInterrupt: raise except: result.addError(self, self.__exc_info()) return
result.addFailure(self, self.__exc_info())
result.addFailure(self, self._exc_info())
def run(self, result=None): if result is None: result = self.defaultTestResult() result.startTest(self) testMethod = getattr(self, self.__testMethodName) try: try: self.setUp() except KeyboardInterrupt: raise except: result.addError(self, self.__exc_info()) return
getattr(self, self.__testMethodName)()
getattr(self, self._testMethodName)()
def debug(self): """Run the test without collecting errors in a TestResult""" self.setUp() getattr(self, self.__testMethodName)() self.tearDown()
def __exc_info(self):
def _exc_info(self):
def __exc_info(self): """Return a version of sys.exc_info() with the traceback frame minimised; usually the top level of the traceback frame is not needed. """ exctype, excvalue, tb = sys.exc_info() if sys.platform[:4] == 'java': ## tracebacks look different in Jython return (exctype, excvalue, tb) return (exctype, exc...
raise ValueError, "CRC check failed"
raise IOError, "CRC check failed"
def _read_eof(self): # We've read to the end of the file, so we have to rewind in order # to reread the 8 bytes containing the CRC and the file size. # We check the that the computed CRC and size of the # uncompressed data matches the stored values. Note that the size # stored is the true file size mod 2**32. self.fil...
raise ValueError, "Incorrect length of data produced"
raise IOError, "Incorrect length of data produced"
def _read_eof(self): # We've read to the end of the file, so we have to rewind in order # to reread the 8 bytes containing the CRC and the file size. # We check the that the computed CRC and size of the # uncompressed data matches the stored values. Note that the size # stored is the true file size mod 2**32. self.fil...
state = ' '
self.state = ' '
def get_token(self): "Get a token from the input stream (or from stack if it's monempty)" if self.pushback: tok = self.pushback[0] self.pushback = self.pushback[1:] if (self.debug >= 1): print "Popping " + tok return tok tok = '' while 1: nextchar = self.instream.read(1); if nextchar == '\n': self.lineno = self.lineno ...
if 'Host' in (headers or [k for k in headers.iterkeys() if k.lower() == "host"]):
if 'host' in [k.lower() for k in headers]:
def _send_request(self, method, url, body, headers): # If headers already contains a host header, then define the # optional skip_host argument to putrequest(). The check is # harder because field names are case insensitive. if 'Host' in (headers or [k for k in headers.iterkeys() if k.lower() == "host"]): self.putrequ...