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, LargerThanAn...
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 ...
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 ...
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...
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...
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...
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...
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...
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...
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...
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...
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...
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 p...
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_...
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_ms...
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_...
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_...
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_...
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_...
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_...
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(), [('t...
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(), [('t...
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\n...
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'...
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.__...
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 = s...
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 = s...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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:...
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 ...
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...
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 ...
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 ...
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 ...
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 filen...
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 r...
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 r...
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 ar...
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) + ...
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('ut...
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, "getobje...
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 =...
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 =...
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 =...
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), ...
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...
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 ...
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 '...
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...