rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
class Comparable(AnotherDateTimeClass): def timetuple(self): return () their = Comparable() self.assertEqual(cmp(our, their), 0) self.assertEqual(cmp(their, our), 0) self.failUnless(our == their) self.failUnless(their == our)
self.assertRaises(TypeError, cmp, their, our) class LargerThanAnything: def __lt__(self, other): return False def __le__(self, other): return isinstance(other, LargerThanAnything) def __eq__(self, other): return isinstance(other, LargerThanAnything) def __ne__(self, other): return not isinstance(other, LargerThanAnything) def __gt__(self, other): return not isinstance(other, LargerThanAnything) def __ge__(self, other): return True their = LargerThanAnything() self.assertEqual(our == their, False) self.assertEqual(their == our, False) self.assertEqual(our != their, True) self.assertEqual(their != our, True) self.assertEqual(our < their, True) self.assertEqual(their < our, False) self.assertEqual(cmp(our, their), -1) self.assertEqual(cmp(their, our), 1)
def __cmp__(self, other): # Return "equal" so calling this can't be confused with # compare-by-address (which never says "equal" for distinct # objects). return 0
self.assert_(as_date.__eq__(as_datetime))
self.assertEqual(as_date.__eq__(as_datetime), True)
def test_bug_1028306(self): # Trying to compare a date to a datetime should act like a mixed- # type comparison, despite that datetime is a subclass of date. as_date = date.today() as_datetime = datetime.combine(as_date, time()) self.assert_(as_date != as_datetime) self.assert_(as_datetime != as_date) self.assert_(not as_date == as_datetime) self.assert_(not as_datetime == as_date) self.assertRaises(TypeError, lambda: as_date < as_datetime) self.assertRaises(TypeError, lambda: as_datetime < as_date) self.assertRaises(TypeError, lambda: as_date <= as_datetime) self.assertRaises(TypeError, lambda: as_datetime <= as_date) self.assertRaises(TypeError, lambda: as_date > as_datetime) self.assertRaises(TypeError, lambda: as_datetime > as_date) self.assertRaises(TypeError, lambda: as_date >= as_datetime) self.assertRaises(TypeError, lambda: as_datetime >= as_date)
self.assert_(not as_date.__eq__(as_datetime.replace(day= different_day)))
as_different = as_datetime.replace(day= different_day) self.assertEqual(as_date.__eq__(as_different), False)
def test_bug_1028306(self): # Trying to compare a date to a datetime should act like a mixed- # type comparison, despite that datetime is a subclass of date. as_date = date.today() as_datetime = datetime.combine(as_date, time()) self.assert_(as_date != as_datetime) self.assert_(as_datetime != as_date) self.assert_(not as_date == as_datetime) self.assert_(not as_datetime == as_date) self.assertRaises(TypeError, lambda: as_date < as_datetime) self.assertRaises(TypeError, lambda: as_datetime < as_date) self.assertRaises(TypeError, lambda: as_date <= as_datetime) self.assertRaises(TypeError, lambda: as_datetime <= as_date) self.assertRaises(TypeError, lambda: as_date > as_datetime) self.assertRaises(TypeError, lambda: as_datetime > as_date) self.assertRaises(TypeError, lambda: as_date >= as_datetime) self.assertRaises(TypeError, lambda: as_datetime >= as_date)
def test(openmethod, what):
def test(openmethod, what, ondisk=1):
def test(openmethod, what): if verbose: print '\nTesting: ', what fname = tempfile.mktemp() f = openmethod(fname, 'c') verify(f.keys() == []) if verbose: print 'creation...' f['0'] = '' f['a'] = 'Guido' f['b'] = 'van' f['c'] = 'Rossum' f['d'] = 'invented' f['f'] = 'Python' if verbose: print '%s %s %s' % (f['a'], f['b'], f['c']) if what == 'BTree' : if verbose: print 'key ordering...' f.set_location(f.first()[0]) while 1: try: rec = f.next() except KeyError: if rec != f.last(): print 'Error, last != last!' f.previous() break if verbose: print rec if not f.has_key('a'): print 'Error, missing key!' f.sync() f.close() if verbose: print 'modification...' f = openmethod(fname, 'w') f['d'] = 'discovered' if verbose: print 'access...' for key in f.keys(): word = f[key] if verbose: print word f.close() try: os.remove(fname) except os.error: pass
print '\nTesting: ', what
print '\nTesting: ', what, (ondisk and "on disk" or "in memory")
def test(openmethod, what): if verbose: print '\nTesting: ', what fname = tempfile.mktemp() f = openmethod(fname, 'c') verify(f.keys() == []) if verbose: print 'creation...' f['0'] = '' f['a'] = 'Guido' f['b'] = 'van' f['c'] = 'Rossum' f['d'] = 'invented' f['f'] = 'Python' if verbose: print '%s %s %s' % (f['a'], f['b'], f['c']) if what == 'BTree' : if verbose: print 'key ordering...' f.set_location(f.first()[0]) while 1: try: rec = f.next() except KeyError: if rec != f.last(): print 'Error, last != last!' f.previous() break if verbose: print rec if not f.has_key('a'): print 'Error, missing key!' f.sync() f.close() if verbose: print 'modification...' f = openmethod(fname, 'w') f['d'] = 'discovered' if verbose: print 'access...' for key in f.keys(): word = f[key] if verbose: print word f.close() try: os.remove(fname) except os.error: pass
fname = tempfile.mktemp()
if ondisk: fname = tempfile.mktemp() else: fname = None
def test(openmethod, what): if verbose: print '\nTesting: ', what fname = tempfile.mktemp() f = openmethod(fname, 'c') verify(f.keys() == []) if verbose: print 'creation...' f['0'] = '' f['a'] = 'Guido' f['b'] = 'van' f['c'] = 'Rossum' f['d'] = 'invented' f['f'] = 'Python' if verbose: print '%s %s %s' % (f['a'], f['b'], f['c']) if what == 'BTree' : if verbose: print 'key ordering...' f.set_location(f.first()[0]) while 1: try: rec = f.next() except KeyError: if rec != f.last(): print 'Error, last != last!' f.previous() break if verbose: print rec if not f.has_key('a'): print 'Error, missing key!' f.sync() f.close() if verbose: print 'modification...' f = openmethod(fname, 'w') f['d'] = 'discovered' if verbose: print 'access...' for key in f.keys(): word = f[key] if verbose: print word f.close() try: os.remove(fname) except os.error: pass
if verbose: print 'modification...' f = openmethod(fname, 'w') f['d'] = 'discovered'
if ondisk: if verbose: print 'modification...' f = openmethod(fname, 'w') f['d'] = 'discovered'
def test(openmethod, what): if verbose: print '\nTesting: ', what fname = tempfile.mktemp() f = openmethod(fname, 'c') verify(f.keys() == []) if verbose: print 'creation...' f['0'] = '' f['a'] = 'Guido' f['b'] = 'van' f['c'] = 'Rossum' f['d'] = 'invented' f['f'] = 'Python' if verbose: print '%s %s %s' % (f['a'], f['b'], f['c']) if what == 'BTree' : if verbose: print 'key ordering...' f.set_location(f.first()[0]) while 1: try: rec = f.next() except KeyError: if rec != f.last(): print 'Error, last != last!' f.previous() break if verbose: print rec if not f.has_key('a'): print 'Error, missing key!' f.sync() f.close() if verbose: print 'modification...' f = openmethod(fname, 'w') f['d'] = 'discovered' if verbose: print 'access...' for key in f.keys(): word = f[key] if verbose: print word f.close() try: os.remove(fname) except os.error: pass
if verbose: print 'access...' for key in f.keys(): word = f[key]
def test(openmethod, what): if verbose: print '\nTesting: ', what fname = tempfile.mktemp() f = openmethod(fname, 'c') verify(f.keys() == []) if verbose: print 'creation...' f['0'] = '' f['a'] = 'Guido' f['b'] = 'van' f['c'] = 'Rossum' f['d'] = 'invented' f['f'] = 'Python' if verbose: print '%s %s %s' % (f['a'], f['b'], f['c']) if what == 'BTree' : if verbose: print 'key ordering...' f.set_location(f.first()[0]) while 1: try: rec = f.next() except KeyError: if rec != f.last(): print 'Error, last != last!' f.previous() break if verbose: print rec if not f.has_key('a'): print 'Error, missing key!' f.sync() f.close() if verbose: print 'modification...' f = openmethod(fname, 'w') f['d'] = 'discovered' if verbose: print 'access...' for key in f.keys(): word = f[key] if verbose: print word f.close() try: os.remove(fname) except os.error: pass
print word
print 'access...' for key in f.keys(): word = f[key] if verbose: print word
def test(openmethod, what): if verbose: print '\nTesting: ', what fname = tempfile.mktemp() f = openmethod(fname, 'c') verify(f.keys() == []) if verbose: print 'creation...' f['0'] = '' f['a'] = 'Guido' f['b'] = 'van' f['c'] = 'Rossum' f['d'] = 'invented' f['f'] = 'Python' if verbose: print '%s %s %s' % (f['a'], f['b'], f['c']) if what == 'BTree' : if verbose: print 'key ordering...' f.set_location(f.first()[0]) while 1: try: rec = f.next() except KeyError: if rec != f.last(): print 'Error, last != last!' f.previous() break if verbose: print rec if not f.has_key('a'): print 'Error, missing key!' f.sync() f.close() if verbose: print 'modification...' f = openmethod(fname, 'w') f['d'] = 'discovered' if verbose: print 'access...' for key in f.keys(): word = f[key] if verbose: print word f.close() try: os.remove(fname) except os.error: pass
test(type[0], type[1])
test(*type)
def test(openmethod, what): if verbose: print '\nTesting: ', what fname = tempfile.mktemp() f = openmethod(fname, 'c') verify(f.keys() == []) if verbose: print 'creation...' f['0'] = '' f['a'] = 'Guido' f['b'] = 'van' f['c'] = 'Rossum' f['d'] = 'invented' f['f'] = 'Python' if verbose: print '%s %s %s' % (f['a'], f['b'], f['c']) if what == 'BTree' : if verbose: print 'key ordering...' f.set_location(f.first()[0]) while 1: try: rec = f.next() except KeyError: if rec != f.last(): print 'Error, last != last!' f.previous() break if verbose: print rec if not f.has_key('a'): print 'Error, missing key!' f.sync() f.close() if verbose: print 'modification...' f = openmethod(fname, 'w') f['d'] = 'discovered' if verbose: print 'access...' for key in f.keys(): word = f[key] if verbose: print word f.close() try: os.remove(fname) except os.error: pass
toaddrs = ','.split(prompt("To"))
toaddrs = prompt("To").split(',')
def prompt(prompt): sys.stdout.write(prompt + ": ") return sys.stdin.readline().strip()
SyntaxError: assignment to None (<doctest test.test_syntax[13]>, line 1)
SyntaxError: assignment to None (<doctest test.test_syntax[14]>, line 1)
>>> def f(None=1):
SyntaxError: non-default argument follows default argument (<doctest test.test_syntax[14]>, line 1)
SyntaxError: non-default argument follows default argument (<doctest test.test_syntax[15]>, line 1)
>>> def f(x, y=1, z):
SyntaxError: assignment to None (<doctest test.test_syntax[15]>, line 1)
SyntaxError: assignment to None (<doctest test.test_syntax[16]>, line 1)
>>> def f(x, None):
SyntaxError: assignment to None (<doctest test.test_syntax[16]>, line 1)
SyntaxError: assignment to None (<doctest test.test_syntax[17]>, line 1)
>>> def f(*None):
SyntaxError: assignment to None (<doctest test.test_syntax[17]>, line 1)
SyntaxError: assignment to None (<doctest test.test_syntax[18]>, line 1)
>>> def f(**None):
SyntaxError: assignment to None (<doctest test.test_syntax[18]>, line 1)
SyntaxError: assignment to None (<doctest test.test_syntax[19]>, line 1)
>>> def None(x):
SyntaxError: Generator expression must be parenthesized if not sole argument (<doctest test.test_syntax[22]>, line 1)
SyntaxError: Generator expression must be parenthesized if not sole argument (<doctest test.test_syntax[23]>, line 1)
>>> def f(it, *varargs):
SyntaxError: more than 255 arguments (<doctest test.test_syntax[24]>, line 1)
SyntaxError: more than 255 arguments (<doctest test.test_syntax[25]>, line 1)
>>> def f(it, *varargs):
SyntaxError: more than 255 arguments (<doctest test.test_syntax[25]>, line 1)
SyntaxError: more than 255 arguments (<doctest test.test_syntax[26]>, line 1)
>>> def f(it, *varargs):
SyntaxError: lambda cannot contain assignment (<doctest test.test_syntax[26]>, line 1)
SyntaxError: lambda cannot contain assignment (<doctest test.test_syntax[27]>, line 1)
>>> def f(it, *varargs):
SyntaxError: keyword can't be an expression (<doctest test.test_syntax[27]>, line 1)
SyntaxError: keyword can't be an expression (<doctest test.test_syntax[28]>, line 1)
>>> def f(it, *varargs):
SyntaxError: keyword can't be an expression (<doctest test.test_syntax[28]>, line 1)
SyntaxError: keyword can't be an expression (<doctest test.test_syntax[29]>, line 1)
>>> def f(it, *varargs):
SyntaxError: keyword can't be an expression (<doctest test.test_syntax[29]>, line 1)
SyntaxError: keyword can't be an expression (<doctest test.test_syntax[30]>, line 1)
>>> def f(it, *varargs):
SyntaxError: augmented assignment to generator expression not possible (<doctest test.test_syntax[30]>, line 1)
SyntaxError: augmented assignment to generator expression not possible (<doctest test.test_syntax[31]>, line 1)
>>> def f(it, *varargs):
SyntaxError: assignment to None (<doctest test.test_syntax[31]>, line 1)
SyntaxError: assignment to None (<doctest test.test_syntax[32]>, line 1)
>>> def f(it, *varargs):
SyntaxError: illegal expression for augmented assignment (<doctest test.test_syntax[32]>, line 1)
SyntaxError: illegal expression for augmented assignment (<doctest test.test_syntax[33]>, line 1)
>>> def f(it, *varargs):
import AppleScript_Suite import AppleScript_Suite
def select(self, _object, _attributes={}, **_arguments): """select: Select the specified object(s) Required argument: the object to select Keyword argument _attributes: AppleEvent attribute dictionary """ _code = 'misc' _subcode = 'slct'
self.doc.append(readme)
self.doc_files.append(readme)
def finalize_package_data (self): self.ensure_string('group', "Development/Libraries") self.ensure_string('vendor', "%s <%s>" % (self.distribution.get_contact(), self.distribution.get_contact_email())) self.ensure_string('packager') self.ensure_string_list('doc_files') if type(self.doc_files) is ListType: for readme in ('README', 'README.txt'): if os.path.exists(readme) and readme not in self.doc_files: self.doc.append(readme)
str = in_file.readline() while str and str != 'end\n': out_file.write(binascii.a2b_uu(str)) str = in_file.readline()
s = in_file.readline() while s and s != 'end\n': try: data = binascii.a2b_uu(s) except binascii.Error, v: nbytes = (((ord(s[0])-32) & 63) * 4 + 5) / 3 data = binascii.a2b_uu(s[:nbytes]) sys.stderr.write("Warning: %s\n" % str(v)) out_file.write(data) s = in_file.readline()
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: raise Error, 'No valid begin line found in input file' if hdr[:5] != 'begin': continue hdrfields = string.split(hdr) if len(hdrfields) == 3 and hdrfields[0] == 'begin': try: string.atoi(hdrfields[1], 8) break except ValueError: pass if out_file == None: out_file = hdrfields[2] if mode == None: mode = string.atoi(hdrfields[1], 8) # # Open the output file # if out_file == '-': out_file = sys.stdout elif type(out_file) == type(''): fp = open(out_file, 'wb') try: os.path.chmod(out_file, mode) except AttributeError: pass out_file = fp # # Main decoding loop # str = in_file.readline() while str and str != 'end\n': out_file.write(binascii.a2b_uu(str)) str = in_file.readline() if not str: raise Error, 'Truncated input file'
def translation(domain, localedir=None, languages=None, class_=None):
def translation(domain, localedir=None, languages=None, class_=None, fallback=0):
def translation(domain, localedir=None, languages=None, class_=None): if class_ is None: class_ = GNUTranslations mofile = find(domain, localedir, languages) if mofile is None: raise IOError(ENOENT, 'No translation file found for domain', domain) key = os.path.abspath(mofile) # TBD: do we need to worry about the file pointer getting collected? # Avoid opening, reading, and parsing the .mo file after it's been done # once. t = _translations.get(key) if t is None: t = _translations.setdefault(key, class_(open(mofile, 'rb'))) return t
translation(domain, localedir).install(unicode)
translation(domain, localedir, fallback=1).install(unicode)
def install(domain, localedir=None, unicode=0): translation(domain, localedir).install(unicode)
if sys.platform == 'aix4': python_lib = get_python_lib(standard_lib=1) ld_so_aix = os.path.join(python_lib, 'config', 'ld_so_aix') python_exp = os.path.join(python_lib, 'config', 'python.exp') g['LDSHARED'] = "%s %s -bI:%s" % (ld_so_aix, g['CC'], python_exp) elif sys.platform == 'beos': python_lib = get_python_lib(standard_lib=1) linkerscript_name = os.path.basename(string.split(g['LDSHARED'])[0]) linkerscript = os.path.join(python_lib, 'config', linkerscript_name) g['LDSHARED'] = ("%s -L%s/lib -lpython%s" % (linkerscript, PREFIX, sys.version[0:3]))
if python_build: g['LDSHARED'] = g['BLDSHARED']
def _init_posix(): """Initialize the module as appropriate for POSIX systems.""" g = {} # load the installed Makefile: try: filename = get_makefile_filename() parse_makefile(filename, g) except IOError, msg: my_msg = "invalid Python installation: unable to open %s" % filename if hasattr(msg, "strerror"): my_msg = my_msg + " (%s)" % msg.strerror raise DistutilsPlatformError, my_msg # On AIX, there are wrong paths to the linker scripts in the Makefile # -- these paths are relative to the Python source, but when installed # the scripts are in another directory. if sys.platform == 'aix4': # what about AIX 3.x ? # Linker script is in the config directory, not in Modules as the # Makefile says. python_lib = get_python_lib(standard_lib=1) ld_so_aix = os.path.join(python_lib, 'config', 'ld_so_aix') python_exp = os.path.join(python_lib, 'config', 'python.exp') g['LDSHARED'] = "%s %s -bI:%s" % (ld_so_aix, g['CC'], python_exp) elif sys.platform == 'beos': # Linker script is in the config directory. In the Makefile it is # relative to the srcdir, which after installation no longer makes # sense. python_lib = get_python_lib(standard_lib=1) linkerscript_name = os.path.basename(string.split(g['LDSHARED'])[0]) linkerscript = os.path.join(python_lib, 'config', linkerscript_name) # XXX this isn't the right place to do this: adding the Python # library to the link, if needed, should be in the "build_ext" # command. (It's also needed for non-MS compilers on Windows, and # it's taken care of for them by the 'build_ext.get_libraries()' # method.) g['LDSHARED'] = ("%s -L%s/lib -lpython%s" % (linkerscript, PREFIX, sys.version[0:3])) global _config_vars _config_vars = g
return self.getdelimited('[', ']\r', 0)
return '[%s]' % self.getdelimited('[', ']\r', 0)
def getdomainliteral(self): """Parse an RFC-822 domain-literal.""" return self.getdelimited('[', ']\r', 0)
def _msgobj(self, filename):
def _msgobj(self, filename, strict=False):
def _msgobj(self, filename): fp = openfile(findfile(filename)) try: msg = email.message_from_file(fp) finally: fp.close() return msg
msg = email.message_from_file(fp)
msg = email.message_from_file(fp, strict=strict)
def _msgobj(self, filename): fp = openfile(findfile(filename)) try: msg = email.message_from_file(fp) finally: fp.close() return msg
eq(msg.get_payload(decode=1), None)
eq(msg.get_payload(decode=True), None)
def test_get_decoded_payload(self): eq = self.assertEqual msg = self._msgobj('msg_10.txt') # The outer message is a multipart eq(msg.get_payload(decode=1), None) # Subpart 1 is 7bit encoded eq(msg.get_payload(0).get_payload(decode=1), 'This is a 7bit encoded message.\n') # Subpart 2 is quopri eq(msg.get_payload(1).get_payload(decode=1), '\xa1This is a Quoted Printable encoded message!\n') # Subpart 3 is base64 eq(msg.get_payload(2).get_payload(decode=1), 'This is a Base64 encoded message.') # Subpart 4 has no Content-Transfer-Encoding: header. eq(msg.get_payload(3).get_payload(decode=1), 'This has no Content-Transfer-Encoding: header.\n')
eq(msg.get_payload(0).get_payload(decode=1),
eq(msg.get_payload(0).get_payload(decode=True),
def test_get_decoded_payload(self): eq = self.assertEqual msg = self._msgobj('msg_10.txt') # The outer message is a multipart eq(msg.get_payload(decode=1), None) # Subpart 1 is 7bit encoded eq(msg.get_payload(0).get_payload(decode=1), 'This is a 7bit encoded message.\n') # Subpart 2 is quopri eq(msg.get_payload(1).get_payload(decode=1), '\xa1This is a Quoted Printable encoded message!\n') # Subpart 3 is base64 eq(msg.get_payload(2).get_payload(decode=1), 'This is a Base64 encoded message.') # Subpart 4 has no Content-Transfer-Encoding: header. eq(msg.get_payload(3).get_payload(decode=1), 'This has no Content-Transfer-Encoding: header.\n')
eq(msg.get_payload(1).get_payload(decode=1),
eq(msg.get_payload(1).get_payload(decode=True),
def test_get_decoded_payload(self): eq = self.assertEqual msg = self._msgobj('msg_10.txt') # The outer message is a multipart eq(msg.get_payload(decode=1), None) # Subpart 1 is 7bit encoded eq(msg.get_payload(0).get_payload(decode=1), 'This is a 7bit encoded message.\n') # Subpart 2 is quopri eq(msg.get_payload(1).get_payload(decode=1), '\xa1This is a Quoted Printable encoded message!\n') # Subpart 3 is base64 eq(msg.get_payload(2).get_payload(decode=1), 'This is a Base64 encoded message.') # Subpart 4 has no Content-Transfer-Encoding: header. eq(msg.get_payload(3).get_payload(decode=1), 'This has no Content-Transfer-Encoding: header.\n')
eq(msg.get_payload(2).get_payload(decode=1),
eq(msg.get_payload(2).get_payload(decode=True),
def test_get_decoded_payload(self): eq = self.assertEqual msg = self._msgobj('msg_10.txt') # The outer message is a multipart eq(msg.get_payload(decode=1), None) # Subpart 1 is 7bit encoded eq(msg.get_payload(0).get_payload(decode=1), 'This is a 7bit encoded message.\n') # Subpart 2 is quopri eq(msg.get_payload(1).get_payload(decode=1), '\xa1This is a Quoted Printable encoded message!\n') # Subpart 3 is base64 eq(msg.get_payload(2).get_payload(decode=1), 'This is a Base64 encoded message.') # Subpart 4 has no Content-Transfer-Encoding: header. eq(msg.get_payload(3).get_payload(decode=1), 'This has no Content-Transfer-Encoding: header.\n')
eq(msg.get_payload(3).get_payload(decode=1),
eq(msg.get_payload(3).get_payload(decode=True),
def test_get_decoded_payload(self): eq = self.assertEqual msg = self._msgobj('msg_10.txt') # The outer message is a multipart eq(msg.get_payload(decode=1), None) # Subpart 1 is 7bit encoded eq(msg.get_payload(0).get_payload(decode=1), 'This is a 7bit encoded message.\n') # Subpart 2 is quopri eq(msg.get_payload(1).get_payload(decode=1), '\xa1This is a Quoted Printable encoded message!\n') # Subpart 3 is base64 eq(msg.get_payload(2).get_payload(decode=1), 'This is a Base64 encoded message.') # Subpart 4 has no Content-Transfer-Encoding: header. eq(msg.get_payload(3).get_payload(decode=1), 'This has no Content-Transfer-Encoding: header.\n')
eq(msg.get_param('importance', unquote=0), '"high value"')
eq(msg.get_param('importance', unquote=False), '"high value"')
def test_set_param(self): eq = self.assertEqual msg = Message() msg.set_param('charset', 'iso-2022-jp') eq(msg.get_param('charset'), 'iso-2022-jp') msg.set_param('importance', 'high value') eq(msg.get_param('importance'), 'high value') eq(msg.get_param('importance', unquote=0), '"high value"') eq(msg.get_params(), [('text/plain', ''), ('charset', 'iso-2022-jp'), ('importance', 'high value')]) eq(msg.get_params(unquote=0), [('text/plain', ''), ('charset', '"iso-2022-jp"'), ('importance', '"high value"')]) msg.set_param('charset', 'iso-9999-xx', header='X-Jimmy') eq(msg.get_param('charset', header='X-Jimmy'), 'iso-9999-xx')
eq(msg.get_params(unquote=0), [('text/plain', ''),
eq(msg.get_params(unquote=False), [('text/plain', ''),
def test_set_param(self): eq = self.assertEqual msg = Message() msg.set_param('charset', 'iso-2022-jp') eq(msg.get_param('charset'), 'iso-2022-jp') msg.set_param('importance', 'high value') eq(msg.get_param('importance'), 'high value') eq(msg.get_param('importance', unquote=0), '"high value"') eq(msg.get_params(), [('text/plain', ''), ('charset', 'iso-2022-jp'), ('importance', 'high value')]) eq(msg.get_params(unquote=0), [('text/plain', ''), ('charset', '"iso-2022-jp"'), ('importance', '"high value"')]) msg.set_param('charset', 'iso-9999-xx', header='X-Jimmy') eq(msg.get_param('charset', header='X-Jimmy'), 'iso-9999-xx')
g = Generator(s, mangle_from_=1)
g = Generator(s, mangle_from_=True)
def test_mangled_from(self): s = StringIO() g = Generator(s, mangle_from_=1) g.flatten(self.msg) self.assertEqual(s.getvalue(), """\
g = Generator(s, mangle_from_=0)
g = Generator(s, mangle_from_=False)
def test_dont_mangle_from(self): s = StringIO() g = Generator(s, mangle_from_=0) g.flatten(self.msg) self.assertEqual(s.getvalue(), """\
p = Parser(strict=1)
p = Parser(strict=True)
def test_bogus_boundary(self): fp = openfile(findfile('msg_15.txt')) try: data = fp.read() finally: fp.close() p = Parser(strict=1) # Note, under a future non-strict parsing mode, this would parse the # message into the intended message tree. self.assertRaises(Errors.BoundaryError, p.parsestr, data)
Utils.parsedate(Utils.formatdate(now, localtime=1))[:6],
Utils.parsedate(Utils.formatdate(now, localtime=True))[:6],
def test_formatdate_localtime(self): now = time.time() self.assertEqual( Utils.parsedate(Utils.formatdate(now, localtime=1))[:6], time.localtime(now)[:6])
eq(he('hello\nworld', keep_eols=1),
eq(he('hello\nworld', keep_eols=True),
def test_header_encode(self): eq = self.assertEqual he = base64MIME.header_encode eq(he('hello'), '=?iso-8859-1?b?aGVsbG8=?=') eq(he('hello\nworld'), '=?iso-8859-1?b?aGVsbG8NCndvcmxk?=') # Test the charset option eq(he('hello', charset='iso-8859-2'), '=?iso-8859-2?b?aGVsbG8=?=') # Test the keep_eols flag eq(he('hello\nworld', keep_eols=1), '=?iso-8859-1?b?aGVsbG8Kd29ybGQ=?=') # Test the maxlinelen argument eq(he('xxxx ' * 20, maxlinelen=40), """\
eq(he('hello\nworld', keep_eols=1), '=?iso-8859-1?q?hello=0Aworld?=')
eq(he('hello\nworld', keep_eols=True), '=?iso-8859-1?q?hello=0Aworld?=')
def test_header_encode(self): eq = self.assertEqual he = quopriMIME.header_encode eq(he('hello'), '=?iso-8859-1?q?hello?=') eq(he('hello\nworld'), '=?iso-8859-1?q?hello=0D=0Aworld?=') # Test the charset option eq(he('hello', charset='iso-8859-2'), '=?iso-8859-2?q?hello?=') # Test the keep_eols flag eq(he('hello\nworld', keep_eols=1), '=?iso-8859-1?q?hello=0Aworld?=') # Test a non-ASCII character eq(he('hello\xc7there'), '=?iso-8859-1?q?hello=C7there?=') # Test the maxlinelen argument eq(he('xxxx ' * 20, maxlinelen=40), """\
eq(msg.get_param('title', unquote=0),
eq(msg.get_param('title', unquote=False),
def test_get_param(self): eq = self.assertEqual msg = self._msgobj('msg_29.txt') eq(msg.get_param('title'), ('us-ascii', 'en', 'This is even more ***fun*** isn\'t it!')) eq(msg.get_param('title', unquote=0), ('us-ascii', 'en', '"This is even more ***fun*** isn\'t it!"'))
if type(self.__optiondb) <> DictType:
if not isinstance(self.__optiondb, DictType):
def __init__(self, initfile): self.__initfile = initfile self.__colordb = None self.__optiondb = {} self.__views = [] self.__red = 0 self.__green = 0 self.__blue = 0 self.__canceled = 0 # read the initialization file fp = None if initfile: try: try: fp = open(initfile) self.__optiondb = marshal.load(fp) if type(self.__optiondb) <> DictType: print >> sys.stderr, \ 'Problem reading options from file:', initfile self.__optiondb = {} except (IOError, EOFError, ValueError): pass finally: if fp: fp.close()
return _getElementsByTagNameHelper(self, name, [])
return _getElementsByTagNameHelper(self, name, NodeList())
def getElementsByTagName(self, name): return _getElementsByTagNameHelper(self, name, [])
return _getElementsByTagNameNSHelper(self, namespaceURI, localName, [])
return _getElementsByTagNameNSHelper(self, namespaceURI, localName, NodeList())
def getElementsByTagNameNS(self, namespaceURI, localName): return _getElementsByTagNameNSHelper(self, namespaceURI, localName, [])
def open_https(self, url):
def open_https(self, url, data=None):
def open_https(self, url): """Use HTTPS protocol.""" import httplib if type(url) is type(""): host, selector = splithost(url) user_passwd, host = splituser(host) else: host, selector = url urltype, rest = splittype(selector) if string.lower(urltype) == 'https': realhost, rest = splithost(rest) user_passwd, realhost = splituser(realhost) if user_passwd: selector = "%s://%s%s" % (urltype, realhost, rest) print "proxy via https:", host, selector if not host: raise IOError, ('https error', 'no host given') if user_passwd: import base64 auth = string.strip(base64.encodestring(user_passwd)) else: auth = None h = httplib.HTTPS(host, 0, key_file=self.key_file, cert_file=self.cert_file) h.putrequest('GET', selector) if auth: h.putheader('Authorization: Basic %s' % auth) for args in self.addheaders: apply(h.putheader, args) h.endheaders() errcode, errmsg, headers = h.getreply() fp = h.getfile() if errcode == 200: return addinfourl(fp, headers, url) else: return self.http_error(url, fp, errcode, errmsg, headers)
h.putrequest('GET', selector)
if data is not None: h.putrequest('POST', selector) h.putheader('Content-type', 'application/x-www-form-urlencoded') h.putheader('Content-length', '%d' % len(data)) else: h.putrequest('GET', selector)
def open_https(self, url): """Use HTTPS protocol.""" import httplib if type(url) is type(""): host, selector = splithost(url) user_passwd, host = splituser(host) else: host, selector = url urltype, rest = splittype(selector) if string.lower(urltype) == 'https': realhost, rest = splithost(rest) user_passwd, realhost = splituser(realhost) if user_passwd: selector = "%s://%s%s" % (urltype, realhost, rest) print "proxy via https:", host, selector if not host: raise IOError, ('https error', 'no host given') if user_passwd: import base64 auth = string.strip(base64.encodestring(user_passwd)) else: auth = None h = httplib.HTTPS(host, 0, key_file=self.key_file, cert_file=self.cert_file) h.putrequest('GET', selector) if auth: h.putheader('Authorization: Basic %s' % auth) for args in self.addheaders: apply(h.putheader, args) h.endheaders() errcode, errmsg, headers = h.getreply() fp = h.getfile() if errcode == 200: return addinfourl(fp, headers, url) else: return self.http_error(url, fp, errcode, errmsg, headers)
import string str = '' email = '' comment = ''
token = [] tokens = []
def parseaddr(address): import string str = '' email = '' comment = '' backslash = 0 dquote = 0 space = 0 paren = 0 bracket = 0 seen_bracket = 0 for c in address: if backslash: str = str + c backslash = 0 continue if c == '\\': backslash = 1 continue if dquote: if c == '"': dquote = 0 else: str = str + c continue if c == '"': dquote = 1 continue if c in string.whitespace: space = 1 continue if space: str = str + ' ' space = 0 if paren: if c == '(': paren = paren + 1 str = str + c continue if c == ')': paren = paren - 1 if paren == 0: comment = comment + str str = '' continue if c == '(': paren = paren + 1 if bracket: email = email + str str = '' elif not seen_bracket: email = email + str str = '' continue if bracket: if c == '>': bracket = 0 email = email + str str = '' continue if c == '<': bracket = 1 seen_bracket = 1 comment = comment + str str = '' email = '' continue if c == '#' and not bracket and not paren: # rest is comment break str = str + c if str: if seen_bracket: if bracket: email = str else: comment = comment + str else: if paren: comment = comment + str else: email = email + str return string.strip(comment), string.strip(email)
bracket = 0 seen_bracket = 0
def parseaddr(address): import string str = '' email = '' comment = '' backslash = 0 dquote = 0 space = 0 paren = 0 bracket = 0 seen_bracket = 0 for c in address: if backslash: str = str + c backslash = 0 continue if c == '\\': backslash = 1 continue if dquote: if c == '"': dquote = 0 else: str = str + c continue if c == '"': dquote = 1 continue if c in string.whitespace: space = 1 continue if space: str = str + ' ' space = 0 if paren: if c == '(': paren = paren + 1 str = str + c continue if c == ')': paren = paren - 1 if paren == 0: comment = comment + str str = '' continue if c == '(': paren = paren + 1 if bracket: email = email + str str = '' elif not seen_bracket: email = email + str str = '' continue if bracket: if c == '>': bracket = 0 email = email + str str = '' continue if c == '<': bracket = 1 seen_bracket = 1 comment = comment + str str = '' email = '' continue if c == '#' and not bracket and not paren: # rest is comment break str = str + c if str: if seen_bracket: if bracket: email = str else: comment = comment + str else: if paren: comment = comment + str else: email = email + str return string.strip(comment), string.strip(email)
str = str + c
token.append(c)
def parseaddr(address): import string str = '' email = '' comment = '' backslash = 0 dquote = 0 space = 0 paren = 0 bracket = 0 seen_bracket = 0 for c in address: if backslash: str = str + c backslash = 0 continue if c == '\\': backslash = 1 continue if dquote: if c == '"': dquote = 0 else: str = str + c continue if c == '"': dquote = 1 continue if c in string.whitespace: space = 1 continue if space: str = str + ' ' space = 0 if paren: if c == '(': paren = paren + 1 str = str + c continue if c == ')': paren = paren - 1 if paren == 0: comment = comment + str str = '' continue if c == '(': paren = paren + 1 if bracket: email = email + str str = '' elif not seen_bracket: email = email + str str = '' continue if bracket: if c == '>': bracket = 0 email = email + str str = '' continue if c == '<': bracket = 1 seen_bracket = 1 comment = comment + str str = '' email = '' continue if c == '#' and not bracket and not paren: # rest is comment break str = str + c if str: if seen_bracket: if bracket: email = str else: comment = comment + str else: if paren: comment = comment + str else: email = email + str return string.strip(comment), string.strip(email)
continue
def parseaddr(address): import string str = '' email = '' comment = '' backslash = 0 dquote = 0 space = 0 paren = 0 bracket = 0 seen_bracket = 0 for c in address: if backslash: str = str + c backslash = 0 continue if c == '\\': backslash = 1 continue if dquote: if c == '"': dquote = 0 else: str = str + c continue if c == '"': dquote = 1 continue if c in string.whitespace: space = 1 continue if space: str = str + ' ' space = 0 if paren: if c == '(': paren = paren + 1 str = str + c continue if c == ')': paren = paren - 1 if paren == 0: comment = comment + str str = '' continue if c == '(': paren = paren + 1 if bracket: email = email + str str = '' elif not seen_bracket: email = email + str str = '' continue if bracket: if c == '>': bracket = 0 email = email + str str = '' continue if c == '<': bracket = 1 seen_bracket = 1 comment = comment + str str = '' email = '' continue if c == '#' and not bracket and not paren: # rest is comment break str = str + c if str: if seen_bracket: if bracket: email = str else: comment = comment + str else: if paren: comment = comment + str else: email = email + str return string.strip(comment), string.strip(email)
continue if c in string.whitespace: space = 1 continue if space: str = str + ' ' space = 0
was_quoted = 1 continue
def parseaddr(address): import string str = '' email = '' comment = '' backslash = 0 dquote = 0 space = 0 paren = 0 bracket = 0 seen_bracket = 0 for c in address: if backslash: str = str + c backslash = 0 continue if c == '\\': backslash = 1 continue if dquote: if c == '"': dquote = 0 else: str = str + c continue if c == '"': dquote = 1 continue if c in string.whitespace: space = 1 continue if space: str = str + ' ' space = 0 if paren: if c == '(': paren = paren + 1 str = str + c continue if c == ')': paren = paren - 1 if paren == 0: comment = comment + str str = '' continue if c == '(': paren = paren + 1 if bracket: email = email + str str = '' elif not seen_bracket: email = email + str str = '' continue if bracket: if c == '>': bracket = 0 email = email + str str = '' continue if c == '<': bracket = 1 seen_bracket = 1 comment = comment + str str = '' email = '' continue if c == '#' and not bracket and not paren: # rest is comment break str = str + c if str: if seen_bracket: if bracket: email = str else: comment = comment + str else: if paren: comment = comment + str else: email = email + str return string.strip(comment), string.strip(email)
str = str + c continue if c == ')':
elif c == ')':
def parseaddr(address): import string str = '' email = '' comment = '' backslash = 0 dquote = 0 space = 0 paren = 0 bracket = 0 seen_bracket = 0 for c in address: if backslash: str = str + c backslash = 0 continue if c == '\\': backslash = 1 continue if dquote: if c == '"': dquote = 0 else: str = str + c continue if c == '"': dquote = 1 continue if c in string.whitespace: space = 1 continue if space: str = str + ' ' space = 0 if paren: if c == '(': paren = paren + 1 str = str + c continue if c == ')': paren = paren - 1 if paren == 0: comment = comment + str str = '' continue if c == '(': paren = paren + 1 if bracket: email = email + str str = '' elif not seen_bracket: email = email + str str = '' continue if bracket: if c == '>': bracket = 0 email = email + str str = '' continue if c == '<': bracket = 1 seen_bracket = 1 comment = comment + str str = '' email = '' continue if c == '#' and not bracket and not paren: # rest is comment break str = str + c if str: if seen_bracket: if bracket: email = str else: comment = comment + str else: if paren: comment = comment + str else: email = email + str return string.strip(comment), string.strip(email)
comment = comment + str str = ''
token = string.join(token, '') tokens.append((2, token)) token = []
def parseaddr(address): import string str = '' email = '' comment = '' backslash = 0 dquote = 0 space = 0 paren = 0 bracket = 0 seen_bracket = 0 for c in address: if backslash: str = str + c backslash = 0 continue if c == '\\': backslash = 1 continue if dquote: if c == '"': dquote = 0 else: str = str + c continue if c == '"': dquote = 1 continue if c in string.whitespace: space = 1 continue if space: str = str + ' ' space = 0 if paren: if c == '(': paren = paren + 1 str = str + c continue if c == ')': paren = paren - 1 if paren == 0: comment = comment + str str = '' continue if c == '(': paren = paren + 1 if bracket: email = email + str str = '' elif not seen_bracket: email = email + str str = '' continue if bracket: if c == '>': bracket = 0 email = email + str str = '' continue if c == '<': bracket = 1 seen_bracket = 1 comment = comment + str str = '' email = '' continue if c == '#' and not bracket and not paren: # rest is comment break str = str + c if str: if seen_bracket: if bracket: email = str else: comment = comment + str else: if paren: comment = comment + str else: email = email + str return string.strip(comment), string.strip(email)
paren = paren + 1 if bracket: email = email + str str = '' elif not seen_bracket: email = email + str str = '' continue if bracket: if c == '>': bracket = 0 email = email + str str = ''
paren = 1 token = string.join(token, '') tokens.append((was_quoted, token)) was_quoted = 0 token = [] continue if c in string.whitespace: space = 1 continue if c in '<>@,;:.[]': token = string.join(token, '') tokens.append((was_quoted, token)) was_quoted = 0 token = [] tokens.append((0, c)) space = 0 continue if space: token = string.join(token, '') tokens.append((was_quoted, token)) was_quoted = 0 token = [] space = 0 token.append(c) token = string.join(token, '') tokens.append((was_quoted, token)) if (0, '<') in tokens: name = [] addr = [] cur = name for token in tokens: if token[1] == '':
def parseaddr(address): import string str = '' email = '' comment = '' backslash = 0 dquote = 0 space = 0 paren = 0 bracket = 0 seen_bracket = 0 for c in address: if backslash: str = str + c backslash = 0 continue if c == '\\': backslash = 1 continue if dquote: if c == '"': dquote = 0 else: str = str + c continue if c == '"': dquote = 1 continue if c in string.whitespace: space = 1 continue if space: str = str + ' ' space = 0 if paren: if c == '(': paren = paren + 1 str = str + c continue if c == ')': paren = paren - 1 if paren == 0: comment = comment + str str = '' continue if c == '(': paren = paren + 1 if bracket: email = email + str str = '' elif not seen_bracket: email = email + str str = '' continue if bracket: if c == '>': bracket = 0 email = email + str str = '' continue if c == '<': bracket = 1 seen_bracket = 1 comment = comment + str str = '' email = '' continue if c == '#' and not bracket and not paren: # rest is comment break str = str + c if str: if seen_bracket: if bracket: email = str else: comment = comment + str else: if paren: comment = comment + str else: email = email + str return string.strip(comment), string.strip(email)
if c == '<': bracket = 1 seen_bracket = 1 comment = comment + str str = '' email = '' continue if c == ' break str = str + c if str: if seen_bracket: if bracket: email = str
if token == (0, '<'): if addr: raise error, 'syntax error' cur = addr elif token == (0, '>'): if cur is not addr: raise error, 'syntax error' cur = name elif token[0] == 2: if cur is name: name.append('(' + token[1] + ')') else: name.append(token[1]) elif token[0] == 1 and cur is addr: if specials.search(token[1]) >= 0: cur.append(quote(token[1])) else: cur.append(token[1])
def parseaddr(address): import string str = '' email = '' comment = '' backslash = 0 dquote = 0 space = 0 paren = 0 bracket = 0 seen_bracket = 0 for c in address: if backslash: str = str + c backslash = 0 continue if c == '\\': backslash = 1 continue if dquote: if c == '"': dquote = 0 else: str = str + c continue if c == '"': dquote = 1 continue if c in string.whitespace: space = 1 continue if space: str = str + ' ' space = 0 if paren: if c == '(': paren = paren + 1 str = str + c continue if c == ')': paren = paren - 1 if paren == 0: comment = comment + str str = '' continue if c == '(': paren = paren + 1 if bracket: email = email + str str = '' elif not seen_bracket: email = email + str str = '' continue if bracket: if c == '>': bracket = 0 email = email + str str = '' continue if c == '<': bracket = 1 seen_bracket = 1 comment = comment + str str = '' email = '' continue if c == '#' and not bracket and not paren: # rest is comment break str = str + c if str: if seen_bracket: if bracket: email = str else: comment = comment + str else: if paren: comment = comment + str else: email = email + str return string.strip(comment), string.strip(email)
comment = comment + str else: if paren: comment = comment + str
cur.append(token[1]) else: name = [] addr = [] for token in tokens: if token[1] == '': continue if token[0] == 2: name.append(token[1]) elif token[0] == 1: if specials.search(token[1]) >= 0: addr.append(quote(token[1])) else: addr.append(token[1])
def parseaddr(address): import string str = '' email = '' comment = '' backslash = 0 dquote = 0 space = 0 paren = 0 bracket = 0 seen_bracket = 0 for c in address: if backslash: str = str + c backslash = 0 continue if c == '\\': backslash = 1 continue if dquote: if c == '"': dquote = 0 else: str = str + c continue if c == '"': dquote = 1 continue if c in string.whitespace: space = 1 continue if space: str = str + ' ' space = 0 if paren: if c == '(': paren = paren + 1 str = str + c continue if c == ')': paren = paren - 1 if paren == 0: comment = comment + str str = '' continue if c == '(': paren = paren + 1 if bracket: email = email + str str = '' elif not seen_bracket: email = email + str str = '' continue if bracket: if c == '>': bracket = 0 email = email + str str = '' continue if c == '<': bracket = 1 seen_bracket = 1 comment = comment + str str = '' email = '' continue if c == '#' and not bracket and not paren: # rest is comment break str = str + c if str: if seen_bracket: if bracket: email = str else: comment = comment + str else: if paren: comment = comment + str else: email = email + str return string.strip(comment), string.strip(email)
email = email + str return string.strip(comment), string.strip(email)
addr.append(token[1]) return string.join(name, ' '), string.join(addr, '')
def parseaddr(address): import string str = '' email = '' comment = '' backslash = 0 dquote = 0 space = 0 paren = 0 bracket = 0 seen_bracket = 0 for c in address: if backslash: str = str + c backslash = 0 continue if c == '\\': backslash = 1 continue if dquote: if c == '"': dquote = 0 else: str = str + c continue if c == '"': dquote = 1 continue if c in string.whitespace: space = 1 continue if space: str = str + ' ' space = 0 if paren: if c == '(': paren = paren + 1 str = str + c continue if c == ')': paren = paren - 1 if paren == 0: comment = comment + str str = '' continue if c == '(': paren = paren + 1 if bracket: email = email + str str = '' elif not seen_bracket: email = email + str str = '' continue if bracket: if c == '>': bracket = 0 email = email + str str = '' continue if c == '<': bracket = 1 seen_bracket = 1 comment = comment + str str = '' email = '' continue if c == '#' and not bracket and not paren: # rest is comment break str = str + c if str: if seen_bracket: if bracket: email = str else: comment = comment + str else: if paren: comment = comment + str else: email = email + str return string.strip(comment), string.strip(email)
r = (24 - currentHour) * 60 * 60 r = r + (59 - currentMinute) * 60 r = r + (59 - currentSecond)
if (currentMinute == 0) and (currentSecond == 0): r = (24 - currentHour) * 60 * 60 else: r = (23 - currentHour) * 60 * 60 r = r + (59 - currentMinute) * 60 r = r + (60 - currentSecond)
def __init__(self, filename, when='h', interval=1, backupCount=0, encoding=None): BaseRotatingHandler.__init__(self, filename, 'a', encoding) self.when = string.upper(when) self.backupCount = backupCount # Calculate the real rollover interval, which is just the number of # seconds between rollovers. Also set the filename suffix used when # a rollover occurs. Current 'when' events supported: # S - Seconds # M - Minutes # H - Hours # D - Days # midnight - roll over at midnight # W{0-6} - roll over on a certain day; 0 - Monday # # Case of the 'when' specifier is not important; lower or upper case # will work. currentTime = int(time.time()) if self.when == 'S': self.interval = 1 # one second self.suffix = "%Y-%m-%d_%H-%M-%S" elif self.when == 'M': self.interval = 60 # one minute self.suffix = "%Y-%m-%d_%H-%M" elif self.when == 'H': self.interval = 60 * 60 # one hour self.suffix = "%Y-%m-%d_%H" elif self.when == 'D' or self.when == 'MIDNIGHT': self.interval = 60 * 60 * 24 # one day self.suffix = "%Y-%m-%d" elif self.when.startswith('W'): self.interval = 60 * 60 * 24 * 7 # one week if len(self.when) != 2: raise ValueError("You must specify a day for weekly rollover from 0 to 6 (0 is Monday): %s" % self.when) if self.when[1] < '0' or self.when[1] > '6': raise ValueError("Invalid day specified for weekly rollover: %s" % self.when) self.dayOfWeek = int(self.when[1]) self.suffix = "%Y-%m-%d" else: raise ValueError("Invalid rollover interval specified: %s" % self.when)
def get(self, section, option, raw=0):
def get(self, section, option, raw=0, vars=None):
def get(self, section, option, raw=0): """Get an option value for a given section.
argument `raw' is true.
argument `raw' is true. Additional substitutions may be provided using the vars keyword argument, which override any pre-existing defaults.
def get(self, section, option, raw=0): """Get an option value for a given section.
try: return rawval % d except KeyError, key: raise InterpolationError(key, option, section, rawval)
value = rawval while 1: if not string.find(value, "%("): try: value = value % d except KeyError, key: raise InterpolationError(key, option, section, rawval) else: return value
def get(self, section, option, raw=0): """Get an option value for a given section.
self.storeName(alias or mod)
if alias: self._resolveDots(name) self.storeName(alias) else: self.storeName(mod)
def visitImport(self, node): self.set_lineno(node) for name, alias in node.names: if VERSION > 1: self.emit('LOAD_CONST', None) self.emit('IMPORT_NAME', name) mod = name.split(".")[0] self.storeName(alias or mod)
return paramre.split(value)[0].lower().strip()
ctype = paramre.split(value)[0].lower().strip() if ctype.count('/') <> 1: return 'text/plain' return ctype
def get_content_type(self): """Returns the message's content type.
if ctype.count('/') <> 1: raise ValueError, 'No maintype found in: %s' % ctype
def get_content_maintype(self): """Returns the message's main content type.
if ctype.count('/') <> 1: raise ValueError, 'No subtype found in: %s' % ctype
def get_content_subtype(self): """Returns the message's sub content type.
sys.ps1 = "[DEBUG ON]>>> "
sys.ps1 = "[DEBUG ON]\n>>> "
def open_debugger(self): import Debugger self.interp.setdebugger(Debugger.Debugger(self)) sys.ps1 = "[DEBUG ON]>>> " self.showprompt() self.top.tkraise() self.text.focus_set()
self.top.tkraise() self.text.focus_set()
def open_debugger(self): import Debugger self.interp.setdebugger(Debugger.Debugger(self)) sys.ps1 = "[DEBUG ON]>>> " self.showprompt() self.top.tkraise() self.text.focus_set()
try: file = open(getsourcefile(object)) except (TypeError, IOError):
file = getsourcefile(object) or getfile(object) lines = linecache.getlines(file) if not lines:
def findsource(object): """Return the entire source file and starting line number for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a list of all the lines in the file and the line number indexes a line in that list. An IOError is raised if the source code cannot be retrieved.""" try: file = open(getsourcefile(object)) except (TypeError, IOError): raise IOError, 'could not get source code' lines = file.readlines() file.close() if ismodule(object): return lines, 0 if isclass(object): name = object.__name__ pat = re.compile(r'^\s*class\s*' + name + r'\b') for i in range(len(lines)): if pat.match(lines[i]): return lines, i else: raise IOError, 'could not find class definition' if ismethod(object): object = object.im_func if isfunction(object): object = object.func_code if istraceback(object): object = object.tb_frame if isframe(object): object = object.f_code if iscode(object): if not hasattr(object, 'co_firstlineno'): raise IOError, 'could not find function definition' lnum = object.co_firstlineno - 1 pat = re.compile(r'^\s*def\s') while lnum > 0: if pat.match(lines[lnum]): break lnum = lnum - 1 return lines, lnum raise IOError, 'could not find code object'
lines = file.readlines() file.close()
def findsource(object): """Return the entire source file and starting line number for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a list of all the lines in the file and the line number indexes a line in that list. An IOError is raised if the source code cannot be retrieved.""" try: file = open(getsourcefile(object)) except (TypeError, IOError): raise IOError, 'could not get source code' lines = file.readlines() file.close() if ismodule(object): return lines, 0 if isclass(object): name = object.__name__ pat = re.compile(r'^\s*class\s*' + name + r'\b') for i in range(len(lines)): if pat.match(lines[i]): return lines, i else: raise IOError, 'could not find class definition' if ismethod(object): object = object.im_func if isfunction(object): object = object.func_code if istraceback(object): object = object.tb_frame if isframe(object): object = object.f_code if iscode(object): if not hasattr(object, 'co_firstlineno'): raise IOError, 'could not find function definition' lnum = object.co_firstlineno - 1 pat = re.compile(r'^\s*def\s') while lnum > 0: if pat.match(lines[lnum]): break lnum = lnum - 1 return lines, lnum raise IOError, 'could not find code object'
filename = getsourcefile(frame)
filename = getsourcefile(frame) or getfile(frame)
def getframeinfo(frame, context=1): """Get information about a frame or traceback object. A tuple of five things is returned: the filename, the line number of the current line, the function name, a list of lines of context from the source code, and the index of the current line within that list. The optional second argument specifies the number of lines of context to return, which are centered around the current line.""" if istraceback(frame): frame = frame.tb_frame if not isframe(frame): raise TypeError, 'arg is not a frame or traceback object' filename = getsourcefile(frame) lineno = getlineno(frame) if context > 0: start = lineno - 1 - context//2 try: lines, lnum = findsource(frame) except IOError: lines = index = None else: start = max(start, 1) start = min(start, len(lines) - context) lines = lines[start:start+context] index = lineno - 1 - start else: lines = index = None return (filename, lineno, frame.f_code.co_name, lines, index)
return rv + '\n'
rv = rv + "\n" sys.stdout.write(rv) return rv
def readline(self): import EasyDialogs # A trick to make the input dialog box a bit more palatable if hasattr(sys.stdout, '_buf'): prompt = sys.stdout._buf else: prompt = "" if not prompt: prompt = "Stdin input:" sys.stdout.flush() rv = EasyDialogs.AskString(prompt) if rv is None: return "" return rv + '\n'
doc = self.markup(value.__doc__, self.preformat)
doc = self.markup(getdoc(value), self.preformat)
def _docdescriptor(self, name, value, mod): results = [] push = results.append
doc = getattr(value, "__doc__", None)
doc = getdoc(value)
def spilldata(msg, attrs, predicate): ok, attrs = _split_list(attrs, predicate) if ok: hr.maybe() push(msg) for name, kind, homecls, value in ok: if callable(value) or inspect.isdatadescriptor(value): doc = getattr(value, "__doc__", None) else: doc = None push(self.docother(getattr(object, name), name, mod, 70, doc) + '\n') return attrs
verify(u'\u20ac'.encode('utf-8') == \ ''.join((chr(0xe2), chr(0x82), chr(0xac))) ) verify(u'\ud800\udc02'.encode('utf-8') == \ ''.join((chr(0xf0), chr(0x90), chr(0x80), chr(0x82))) ) verify(u'\ud84d\udc56'.encode('utf-8') == \ ''.join((chr(0xf0), chr(0xa3), chr(0x91), chr(0x96))) )
verify(u'\u20ac'.encode('utf-8') == '\xe2\x82\xac') verify(u'\ud800\udc02'.encode('utf-8') == '\xf0\x90\x80\x82') verify(u'\ud84d\udc56'.encode('utf-8') == '\xf0\xa3\x91\x96') verify(u'\ud800'.encode('utf-8') == '\xed\xa0\x80') verify(u'\udc00'.encode('utf-8') == '\xed\xb0\x80') verify((u'\ud800\udc02'*1000).encode('utf-8') == '\xf0\x90\x80\x82'*1000)
def __str__(self): return self.x
verify(unicode(''.join((chr(0xf0), chr(0xa3), chr(0x91), chr(0x96))), 'utf-8') == u'\U00023456' ) verify(unicode(''.join((chr(0xf0), chr(0x90), chr(0x80), chr(0x82))), 'utf-8') == u'\U00010002' ) verify(unicode(''.join((chr(0xe2), chr(0x82), chr(0xac))), 'utf-8') == u'\u20ac' )
verify(unicode('\xf0\xa3\x91\x96', 'utf-8') == u'\U00023456' ) verify(unicode('\xf0\x90\x80\x82', 'utf-8') == u'\U00010002' ) verify(unicode('\xe2\x82\xac', 'utf-8') == u'\u20ac' )
def __str__(self): return self.x
def test_SEH(self): import sys if not hasattr(sys, "getobjects"):
import _ctypes if _ctypes.uses_seh(): def test_SEH(self):
def test_SEH(self): # Call functions with invalid arguments, and make sure that access violations # are trapped and raise an exception. # # Normally, in a debug build of the _ctypes extension # module, exceptions are not trapped, so we can only run # this test in a release build. import sys if not hasattr(sys, "getobjects"): self.assertRaises(WindowsError, windll.kernel32.GetModuleHandleA, 32)
key = user, passwd, host, port
key = user, host, port, '/'.join(dirs)
def connect_ftp(self, user, passwd, host, port, dirs): key = user, passwd, host, port if key in self.cache: self.timeout[key] = time.time() + self.delay else: self.cache[key] = ftpwrapper(user, passwd, host, port, dirs) self.timeout[key] = time.time() + self.delay self.check_cache() return self.cache[key]
rep = self__repr(object, context, level - 1)
rep = self.__repr(object, context, level - 1)
def __format(self, object, stream, indent, allowance, context, level):
pprint(object[0], stream, indent, allowance + 1)
self.__format(object[0], stream, indent, allowance + 1, context, level)
def __format(self, object, stream, indent, allowance, context, level):
for base in cls.__bases__: if hasattr(base, "_getDefaults"): defaults.update(base._getDefaults())
def _getDefaults(cls): defaults = {} for name, value in cls.__dict__.items(): if name[0] != "_" and not isinstance(value, (function, classmethod)): defaults[name] = deepcopy(value) for base in cls.__bases__: if hasattr(base, "_getDefaults"): defaults.update(base._getDefaults()) return defaults
raise error, "unterminated index"
raise error, "unterminated group name"
def parse_template(source, pattern): # parse 're' replacement string into list of literals and # group references s = Tokenizer(source) p = [] a = p.append while 1: this = s.get() if this is None: break # end of replacement string if this and this[0] == "\\": if this == "\\g": name = "" if s.match("<"): while 1: char = s.get() if char is None: raise error, "unterminated index" if char == ">": break # FIXME: check for valid character name = name + char if not name: raise error, "bad index" try: index = int(name) except ValueError: try: index = pattern.groupindex[name] except KeyError: raise IndexError, "unknown index" a((MARK, index)) elif len(this) > 1 and this[1] in DIGITS: while s.next in DIGITS: this = this + s.get() a((MARK, int(this[1:]))) else: try: a(ESCAPES[this]) except KeyError: for char in this: a((LITERAL, char)) else: a((LITERAL, this)) return p
raise error, "bad index"
raise error, "bad group name"
def parse_template(source, pattern): # parse 're' replacement string into list of literals and # group references s = Tokenizer(source) p = [] a = p.append while 1: this = s.get() if this is None: break # end of replacement string if this and this[0] == "\\": if this == "\\g": name = "" if s.match("<"): while 1: char = s.get() if char is None: raise error, "unterminated index" if char == ">": break # FIXME: check for valid character name = name + char if not name: raise error, "bad index" try: index = int(name) except ValueError: try: index = pattern.groupindex[name] except KeyError: raise IndexError, "unknown index" a((MARK, index)) elif len(this) > 1 and this[1] in DIGITS: while s.next in DIGITS: this = this + s.get() a((MARK, int(this[1:]))) else: try: a(ESCAPES[this]) except KeyError: for char in this: a((LITERAL, char)) else: a((LITERAL, this)) return p
raise IndexError, "unknown index"
raise IndexError, "unknown group name"
def parse_template(source, pattern): # parse 're' replacement string into list of literals and # group references s = Tokenizer(source) p = [] a = p.append while 1: this = s.get() if this is None: break # end of replacement string if this and this[0] == "\\": if this == "\\g": name = "" if s.match("<"): while 1: char = s.get() if char is None: raise error, "unterminated index" if char == ">": break # FIXME: check for valid character name = name + char if not name: raise error, "bad index" try: index = int(name) except ValueError: try: index = pattern.groupindex[name] except KeyError: raise IndexError, "unknown index" a((MARK, index)) elif len(this) > 1 and this[1] in DIGITS: while s.next in DIGITS: this = this + s.get() a((MARK, int(this[1:]))) else: try: a(ESCAPES[this]) except KeyError: for char in this: a((LITERAL, char)) else: a((LITERAL, this)) return p
isbigendian = struct.pack('=i', 1)[0] == chr(0)
def any_err(func, *args): try: apply(func, args) except (struct.error, OverflowError, TypeError): pass else: raise TestFailed, "%s%s did not raise error" % ( func.__name__, args)
('='+fmt, isbigendian and big or lil)]:
('='+fmt, ISBIGENDIAN and big or lil)]:
def any_err(func, *args): try: apply(func, args) except (struct.error, OverflowError, TypeError): pass else: raise TestFailed, "%s%s did not raise error" % ( func.__name__, args)
def string_reverse(s): chars = list(s) chars.reverse() return "".join(chars) def bigendian_to_native(value): if isbigendian: return value else: return string_reverse(value)
def any_err(func, *args): try: apply(func, args) except (struct.error, OverflowError, TypeError): pass else: raise TestFailed, "%s%s did not raise error" % ( func.__name__, args)
MIN_Q, MAX_Q = 0, 2L**64 - 1 MIN_q, MAX_q = -(2L**63), 2L**63 - 1
def test_native_qQ(): bytes = struct.calcsize('q') # The expected values here are in big-endian format, primarily because # I'm on a little-endian machine and so this is the clearest way (for # me) to force the code to get exercised. for format, input, expected in ( ('q', -1, '\xff' * bytes), ('q', 0, '\x00' * bytes), ('Q', 0, '\x00' * bytes), ('q', 1L, '\x00' * (bytes-1) + '\x01'), ('Q', (1L << (8*bytes))-1, '\xff' * bytes), ('q', (1L << (8*bytes-1))-1, '\x7f' + '\xff' * (bytes - 1))): got = struct.pack(format, input) native_expected = bigendian_to_native(expected) verify(got == native_expected, "%r-pack of %r gave %r, not %r" % (format, input, got, native_expected)) retrieved = struct.unpack(format, got)[0] verify(retrieved == input, "%r-unpack of %r gave %r, not %r" % (format, got, retrieved, input))
def test_one_qQ(x, pack=struct.pack, unpack=struct.unpack, unhexlify=binascii.unhexlify): if verbose: print "trying std q/Q on", x, "==", hex(x) if MIN_q <= x <= MAX_q: expected = long(x) if x < 0: expected += 1L << 64 assert expected > 0 expected = hex(expected)[2:-1] if len(expected) & 1: expected = "0" + expected expected = unhexlify(expected) expected = "\x00" * (8 - len(expected)) + expected got = pack(">q", x) verify(got == expected, "'>q'-pack of %r gave %r, not %r" % (x, got, expected)) retrieved = unpack(">q", got)[0] verify(x == retrieved, "'>q'-unpack of %r gave %r, not %r" % (got, retrieved, x)) any_err(unpack, ">q", '\x01' + got) expected = string_reverse(expected) got = pack("<q", x) verify(got == expected, "'<q'-pack of %r gave %r, not %r" % (x, got, expected)) retrieved = unpack("<q", got)[0] verify(x == retrieved, "'<q'-unpack of %r gave %r, not %r" % (got, retrieved, x)) any_err(unpack, "<q", '\x01' + got) else: any_err(pack, '>q', x) any_err(pack, '<q', x) if MIN_Q <= x <= MAX_Q: expected = long(x) expected = hex(expected)[2:-1] if len(expected) & 1: expected = "0" + expected expected = unhexlify(expected) expected = "\x00" * (8 - len(expected)) + expected got = pack(">Q", x) verify(got == expected, "'>Q'-pack of %r gave %r, not %r" % (x, got, expected)) retrieved = unpack(">Q", got)[0] verify(x == retrieved, "'>Q'-unpack of %r gave %r, not %r" % (got, retrieved, x)) any_err(unpack, ">Q", '\x01' + got) expected = string_reverse(expected) got = pack("<Q", x) verify(got == expected, "'<Q'-pack of %r gave %r, not %r" % (x, got, expected)) retrieved = unpack("<Q", got)[0] verify(x == retrieved, "'<Q'-unpack of %r gave %r, not %r" % (got, retrieved, x)) any_err(unpack, "<Q", '\x01' + got) else: any_err(pack, '>Q', x) any_err(pack, '<Q', x) def test_std_qQ(): from random import randrange values = [] for exp in range(70): values.append(1L << exp) for i in range(50): val = 0L for j in range(8): val = (val << 8) | randrange(256) values.append(val) for base in values: for val in -base, base: for incr in -1, 0, 1: x = val + incr try: x = int(x) except OverflowError: pass test_one_qQ(x) for direction in "<>": for letter in "qQ": for badobject in "a string", 3+42j, randrange: any_err(struct.pack, direction + letter, badobject) test_std_qQ()
class IntTester: BUGGY_RANGE_CHECK = "bBhHIL" def __init__(self, formatpair, bytesize): assert len(formatpair) == 2 self.formatpair = formatpair for direction in "<>!=": for code in formatpair: format = direction + code verify(struct.calcsize(format) == bytesize) self.bytesize = bytesize self.bitsize = bytesize * 8 self.signed_code, self.unsigned_code = formatpair self.unsigned_min = 0 self.unsigned_max = 2L**self.bitsize - 1 self.signed_min = -(2L**(self.bitsize-1)) self.signed_max = 2L**(self.bitsize-1) - 1 def test_one(self, x, pack=struct.pack, unpack=struct.unpack, unhexlify=binascii.unhexlify): if verbose: print "trying std", self.formatpair, "on", x, "==", hex(x) code = self.signed_code if self.signed_min <= x <= self.signed_max: expected = long(x) if x < 0: expected += 1L << self.bitsize assert expected > 0 expected = hex(expected)[2:-1] if len(expected) & 1: expected = "0" + expected expected = unhexlify(expected) expected = "\x00" * (self.bytesize - len(expected)) + expected format = ">" + code got = pack(format, x) verify(got == expected, "'%s'-pack of %r gave %r, not %r" % (format, x, got, expected)) retrieved = unpack(format, got)[0] verify(x == retrieved, "'%s'-unpack of %r gave %r, not %r" % (format, got, retrieved, x)) any_err(unpack, format, '\x01' + got) format = "<" + code expected = string_reverse(expected) got = pack(format, x) verify(got == expected, "'%s'-pack of %r gave %r, not %r" % (format, x, got, expected)) retrieved = unpack(format, got)[0] verify(x == retrieved, "'%s'-unpack of %r gave %r, not %r" % (format, got, retrieved, x)) any_err(unpack, format, '\x01' + got) else: if code in self.BUGGY_RANGE_CHECK: if verbose: print "Skipping buggy range check for code", code else: any_err(pack, ">" + code, x) any_err(pack, "<" + code, x) code = self.unsigned_code if self.unsigned_min <= x <= self.unsigned_max: format = ">" + code expected = long(x) expected = hex(expected)[2:-1] if len(expected) & 1: expected = "0" + expected expected = unhexlify(expected) expected = "\x00" * (self.bytesize - len(expected)) + expected got = pack(format, x) verify(got == expected, "'%s'-pack of %r gave %r, not %r" % (format, x, got, expected)) retrieved = unpack(format, got)[0] verify(x == retrieved, "'%s'-unpack of %r gave %r, not %r" % (format, got, retrieved, x)) any_err(unpack, format, '\x01' + got) format = "<" + code expected = string_reverse(expected) got = pack(format, x) verify(got == expected, "'%s'-pack of %r gave %r, not %r" % (format, x, got, expected)) retrieved = unpack(format, got)[0] verify(x == retrieved, "'%s'-unpack of %r gave %r, not %r" % (format, got, retrieved, x)) any_err(unpack, format, '\x01' + got) else: if code in self.BUGGY_RANGE_CHECK: if verbose: print "Skipping buggy range check for code", code else: any_err(pack, ">" + code, x) any_err(pack, "<" + code, x) def run(self): from random import randrange values = [] for exp in range(self.bitsize + 3): values.append(1L << exp) for i in range(self.bitsize): val = 0L for j in range(self.bytesize): val = (val << 8) | randrange(256) values.append(val) for base in values: for val in -base, base: for incr in -1, 0, 1: x = val + incr try: x = int(x) except OverflowError: pass self.test_one(x) for direction in "<>": for code in self.formatpair: for badobject in "a string", 3+42j, randrange: any_err(struct.pack, direction + code, badobject) for args in [("bB", 1), ("hH", 2), ("iI", 4), ("lL", 4), ("qQ", 8)]: t = IntTester(*args) t.run()
def test_one_qQ(x, pack=struct.pack, unpack=struct.unpack, unhexlify=binascii.unhexlify): if verbose: print "trying std q/Q on", x, "==", hex(x) # Try 'q'. if MIN_q <= x <= MAX_q: # Try '>q'. expected = long(x) if x < 0: expected += 1L << 64 assert expected > 0 expected = hex(expected)[2:-1] # chop "0x" and trailing 'L' if len(expected) & 1: expected = "0" + expected expected = unhexlify(expected) expected = "\x00" * (8 - len(expected)) + expected # >q pack work? got = pack(">q", x) verify(got == expected, "'>q'-pack of %r gave %r, not %r" % (x, got, expected)) # >q unpack work? retrieved = unpack(">q", got)[0] verify(x == retrieved, "'>q'-unpack of %r gave %r, not %r" % (got, retrieved, x)) # Adding any byte should cause a "too big" error. any_err(unpack, ">q", '\x01' + got) # Try '<q'. expected = string_reverse(expected) # <q pack work? got = pack("<q", x) verify(got == expected, "'<q'-pack of %r gave %r, not %r" % (x, got, expected)) # <q unpack work? retrieved = unpack("<q", got)[0] verify(x == retrieved, "'<q'-unpack of %r gave %r, not %r" % (got, retrieved, x)) # Adding any byte should cause a "too big" error. any_err(unpack, "<q", '\x01' + got) else: # x is out of q's range -- verify pack realizes that. any_err(pack, '>q', x) any_err(pack, '<q', x) # Much the same for 'Q'. if MIN_Q <= x <= MAX_Q: # Try '>Q'. expected = long(x) expected = hex(expected)[2:-1] # chop "0x" and trailing 'L' if len(expected) & 1: expected = "0" + expected expected = unhexlify(expected) expected = "\x00" * (8 - len(expected)) + expected # >Q pack work? got = pack(">Q", x) verify(got == expected, "'>Q'-pack of %r gave %r, not %r" % (x, got, expected)) # >Q unpack work? retrieved = unpack(">Q", got)[0] verify(x == retrieved, "'>Q'-unpack of %r gave %r, not %r" % (got, retrieved, x)) # Adding any byte should cause a "too big" error. any_err(unpack, ">Q", '\x01' + got) # Try '<Q'. expected = string_reverse(expected) # <Q pack work? got = pack("<Q", x) verify(got == expected, "'<Q'-pack of %r gave %r, not %r" % (x, got, expected)) # <Q unpack work? retrieved = unpack("<Q", got)[0] verify(x == retrieved, "'<Q'-unpack of %r gave %r, not %r" % (got, retrieved, x)) # Adding any byte should cause a "too big" error. any_err(unpack, "<Q", '\x01' + got) else: # x is out of Q's range -- verify pack realizes that. any_err(pack, '>Q', x) any_err(pack, '<Q', x)
found_docstring = False
def visitModule(self, node): stmt = node.node found_docstring = False for s in stmt.nodes: # Skip over docstrings if not found_docstring and isinstance(s, ast.Discard) \ and isinstance(s.expr, ast.Const) \ and isinstance(s.expr.value, str): found_docstring = True continue if not self.check_stmt(s): break
if not found_docstring and isinstance(s, ast.Discard) \ and isinstance(s.expr, ast.Const) \ and isinstance(s.expr.value, str): found_docstring = True continue
def visitModule(self, node): stmt = node.node found_docstring = False for s in stmt.nodes: # Skip over docstrings if not found_docstring and isinstance(s, ast.Discard) \ and isinstance(s.expr, ast.Const) \ and isinstance(s.expr.value, str): found_docstring = True continue if not self.check_stmt(s): break
Will quote the value if needed or if quote is true.
This will quote the value if needed or if quote is true.
def _formatparam(param, value=None, quote=1): """Convenience function to format and return a key=value pair. Will quote the value if needed or if quote is true. """ if value is not None and len(value) > 0: # BAW: Please check this. I think that if quote is set it should # force quoting even if not necessary. if quote or tspecials.search(value): return '%s="%s"' % (param, Utils.quote(value)) else: return '%s=%s' % (param, value) else: return param