rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
self.reset()
self.trace = None del self.trace self.forget() print '!!! Post-mortem debugging' self.pmd(t) def pmd(self, traceback): t = traceback if self.botframe is not None: while t is not None: if t.tb_frame is not self.botframe: break t = t.tb_next else: t = sys.exc_traceback try: self.ask_user(self.botframe, t) except PdbQuit: pass finally: self.forget()
def runctx(self, cmd, globals, locals): self.reset() sys.trace = self.dispatch try: exec(cmd + '\n', globals, locals) except PdbQuit: pass except: print '***', sys.exc_type + ':', `sys.exc_value` print '*** Post Mortem Debugging:' sys.trace = None del sys.trace try: self.ask_user(None, sys.exc_traceback) except PdbQuit: pass finally: self.reset()
return
return None
def dispatch_call(self, frame, arg): if self.botframe is None: self.botframe = frame return if not (self.stop_here(frame) or self.break_anywhere(frame)): return frame.f_locals['__args__'] = arg return self.dispatch
return frame.f_locals['__args__'] = arg
return None if arg is None: print '[Entering non-function block.]' else: frame.f_locals['__args__'] = arg
def dispatch_call(self, frame, arg): if self.botframe is None: self.botframe = frame return if not (self.stop_here(frame) or self.break_anywhere(frame)): return frame.f_locals['__args__'] = arg return self.dispatch
if self.stop_here(frame): print '!!! return', `arg` return
self.lastretval = arg return None
def dispatch_return(self, frame, arg): if self.stop_here(frame): print '!!! return', `arg` return
print '!!! exception', arg[0] + ':', `arg[1]`
print '!!!', arg[0] + ':', `arg[1]`
def dispatch_exception(self, frame, arg): if self.stop_here(frame): print '!!! exception', arg[0] + ':', `arg[1]` self.ask_user(frame, arg[2]) return self.dispatch
(code, resp) = self.docmd(encode_base64(user, eol=""))
(code, resp) = self.docmd(encode_base64(password, eol=""))
def encode_plain(user, password): return encode_base64("%s\0%s\0%s" % (user, user, password), eol="")
os.rename(tmp_file.name, dest)
try: if hasattr(os, 'link'): os.link(tmp_file.name, dest) os.remove(tmp_file.name) else: os.rename(tmp_file.name, dest) except OSError, e: os.remove(tmp_file.name) if e.errno == errno.EEXIST: raise ExternalClashError('Name clash with existing message: %s' % dest) else: raise
def add(self, message): """Add message and return assigned key.""" tmp_file = self._create_tmp() try: self._dump_message(message, tmp_file) finally: _sync_close(tmp_file) if isinstance(message, MaildirMessage): subdir = message.get_subdir() suffix = self.colon + message.get_info() if suffix == self.colon: suffix = '' else: subdir = 'new' suffix = '' uniq = os.path.basename(tmp_file.name).split(self.colon)[0] dest = os.path.join(self._path, subdir, uniq + suffix) os.rename(tmp_file.name, dest) if isinstance(message, MaildirMessage): os.utime(dest, (os.path.getatime(dest), message.get_date())) return uniq
return open(path, 'wb+')
try: return _create_carefully(path) except OSError, e: if e.errno != errno.EEXIST: raise
def _create_tmp(self): """Create a file in the tmp subdirectory and open and return it.""" now = time.time() hostname = socket.gethostname() if '/' in hostname: hostname = hostname.replace('/', r'\057') if ':' in hostname: hostname = hostname.replace(':', r'\072') uniq = "%s.M%sP%sQ%s.%s" % (int(now), int(now % 1 * 1e6), os.getpid(), Maildir._count, hostname) path = os.path.join(self._path, 'tmp', uniq) try: os.stat(path) except OSError, e: if e.errno == errno.ENOENT: Maildir._count += 1 return open(path, 'wb+') else: raise else: raise ExternalClashError('Name clash prevented file creation: %s' % path)
else: raise ExternalClashError('Name clash prevented file creation: %s' % path)
raise ExternalClashError('Name clash prevented file creation: %s' % path)
def _create_tmp(self): """Create a file in the tmp subdirectory and open and return it.""" now = time.time() hostname = socket.gethostname() if '/' in hostname: hostname = hostname.replace('/', r'\057') if ':' in hostname: hostname = hostname.replace(':', r'\072') uniq = "%s.M%sP%sQ%s.%s" % (int(now), int(now % 1 * 1e6), os.getpid(), Maildir._count, hostname) path = os.path.join(self._path, 'tmp', uniq) try: os.stat(path) except OSError, e: if e.errno == errno.ENOENT: Maildir._count += 1 return open(path, 'wb+') else: raise else: raise ExternalClashError('Name clash prevented file creation: %s' % path)
addbase.close(self)
def close(self): if self.closehook: apply(self.closehook, self.hookargs) self.closehook = None self.hookargs = None addbase.close(self)
elif type(in_file) == type(''):
elif isinstance(in_file, StringType):
def encode(in_file, out_file, name=None, mode=None): """Uuencode file""" # # If in_file is a pathname open it and change defaults # if in_file == '-': in_file = sys.stdin elif type(in_file) == type(''): if name is None: name = os.path.basename(in_file) if mode is None: try: mode = os.stat(in_file)[0] except AttributeError: pass in_file = open(in_file, 'rb') # # Open out_file if it is a pathname # if out_file == '-': out_file = sys.stdout elif type(out_file) == type(''): out_file = open(out_file, 'w') # # Set defaults for name and mode # if name is None: name = '-' if mode is None: mode = 0666 # # Write the data # out_file.write('begin %o %s\n' % ((mode&0777),name)) str = in_file.read(45) while len(str) > 0: out_file.write(binascii.b2a_uu(str)) str = in_file.read(45) out_file.write(' \nend\n')
elif type(out_file) == type(''):
elif isinstance(out_file, StringType):
def encode(in_file, out_file, name=None, mode=None): """Uuencode file""" # # If in_file is a pathname open it and change defaults # if in_file == '-': in_file = sys.stdin elif type(in_file) == type(''): if name is None: name = os.path.basename(in_file) if mode is None: try: mode = os.stat(in_file)[0] except AttributeError: pass in_file = open(in_file, 'rb') # # Open out_file if it is a pathname # if out_file == '-': out_file = sys.stdout elif type(out_file) == type(''): out_file = open(out_file, 'w') # # Set defaults for name and mode # if name is None: name = '-' if mode is None: mode = 0666 # # Write the data # out_file.write('begin %o %s\n' % ((mode&0777),name)) str = in_file.read(45) while len(str) > 0: out_file.write(binascii.b2a_uu(str)) str = in_file.read(45) out_file.write(' \nend\n')
def decode(in_file, out_file=None, mode=None):
def decode(in_file, out_file=None, mode=None, quiet=0):
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 = hdr.split(" ", 2) if len(hdrfields) == 3 and hdrfields[0] == 'begin': try: int(hdrfields[1], 8) break except ValueError: pass if out_file is None: out_file = hdrfields[2].rstrip() if mode is None: mode = int(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 # s = in_file.readline() while s and s != 'end\n': try: data = binascii.a2b_uu(s) except binascii.Error, v: # Workaround for broken uuencoders by /Fredrik Lundh 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() if not s: raise Error, 'Truncated input file'
elif type(in_file) == type(''):
elif isinstance(in_file, StringType):
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 = hdr.split(" ", 2) if len(hdrfields) == 3 and hdrfields[0] == 'begin': try: int(hdrfields[1], 8) break except ValueError: pass if out_file is None: out_file = hdrfields[2].rstrip() if mode is None: mode = int(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 # s = in_file.readline() while s and s != 'end\n': try: data = binascii.a2b_uu(s) except binascii.Error, v: # Workaround for broken uuencoders by /Fredrik Lundh 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() if not s: raise Error, 'Truncated input file'
elif type(out_file) == type(''):
elif isinstance(out_file, StringType):
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 = hdr.split(" ", 2) if len(hdrfields) == 3 and hdrfields[0] == 'begin': try: int(hdrfields[1], 8) break except ValueError: pass if out_file is None: out_file = hdrfields[2].rstrip() if mode is None: mode = int(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 # s = in_file.readline() while s and s != 'end\n': try: data = binascii.a2b_uu(s) except binascii.Error, v: # Workaround for broken uuencoders by /Fredrik Lundh 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() if not s: raise Error, 'Truncated input file'
while s and s != 'end\n':
while s and s.strip() != 'end':
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 = hdr.split(" ", 2) if len(hdrfields) == 3 and hdrfields[0] == 'begin': try: int(hdrfields[1], 8) break except ValueError: pass if out_file is None: out_file = hdrfields[2].rstrip() if mode is None: mode = int(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 # s = in_file.readline() while s and s != 'end\n': try: data = binascii.a2b_uu(s) except binascii.Error, v: # Workaround for broken uuencoders by /Fredrik Lundh 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() if not s: raise Error, 'Truncated input file'
sys.stderr.write("Warning: %s\n" % str(v))
if not quiet: sys.stderr.write("Warning: %s\n" % str(v))
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 = hdr.split(" ", 2) if len(hdrfields) == 3 and hdrfields[0] == 'begin': try: int(hdrfields[1], 8) break except ValueError: pass if out_file is None: out_file = hdrfields[2].rstrip() if mode is None: mode = int(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 # s = in_file.readline() while s and s != 'end\n': try: data = binascii.a2b_uu(s) except binascii.Error, v: # Workaround for broken uuencoders by /Fredrik Lundh 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() if not s: raise Error, 'Truncated input file'
if type(output) == type(''):
if isinstance(output, StringType):
def test(): """uuencode/uudecode main program""" import getopt dopt = 0 topt = 0 input = sys.stdin output = sys.stdout ok = 1 try: optlist, args = getopt.getopt(sys.argv[1:], 'dt') except getopt.error: ok = 0 if not ok or len(args) > 2: print 'Usage:', sys.argv[0], '[-d] [-t] [input [output]]' print ' -d: Decode (in stead of encode)' print ' -t: data is text, encoded format unix-compatible text' sys.exit(1) for o, a in optlist: if o == '-d': dopt = 1 if o == '-t': topt = 1 if len(args) > 0: input = args[0] if len(args) > 1: output = args[1] if dopt: if topt: if type(output) == type(''): output = open(output, 'w') else: print sys.argv[0], ': cannot do -t to stdout' sys.exit(1) decode(input, output) else: if topt: if type(input) == type(''): input = open(input, 'r') else: print sys.argv[0], ': cannot do -t from stdin' sys.exit(1) encode(input, output)
if type(input) == type(''):
if isinstance(input, StringType):
def test(): """uuencode/uudecode main program""" import getopt dopt = 0 topt = 0 input = sys.stdin output = sys.stdout ok = 1 try: optlist, args = getopt.getopt(sys.argv[1:], 'dt') except getopt.error: ok = 0 if not ok or len(args) > 2: print 'Usage:', sys.argv[0], '[-d] [-t] [input [output]]' print ' -d: Decode (in stead of encode)' print ' -t: data is text, encoded format unix-compatible text' sys.exit(1) for o, a in optlist: if o == '-d': dopt = 1 if o == '-t': topt = 1 if len(args) > 0: input = args[0] if len(args) > 1: output = args[1] if dopt: if topt: if type(output) == type(''): output = open(output, 'w') else: print sys.argv[0], ': cannot do -t to stdout' sys.exit(1) decode(input, output) else: if topt: if type(input) == type(''): input = open(input, 'r') else: print sys.argv[0], ': cannot do -t from stdin' sys.exit(1) encode(input, output)
again = meth(ts, tzinfo=off42)
again = meth(ts, tz=off42)
def test_tzinfo_fromtimestamp(self): import time meth = self.theclass.fromtimestamp ts = time.time() # Ensure it doesn't require tzinfo (i.e., that this doesn't blow up). base = meth(ts) # Try with and without naming the keyword. off42 = FixedOffset(42, "42") another = meth(ts, off42) again = meth(ts, tzinfo=off42) self.failUnless(another.tzinfo is again.tzinfo) self.assertEqual(another.utcoffset(), timedelta(minutes=42)) # Bad argument with and w/o naming the keyword. self.assertRaises(TypeError, meth, ts, 16) self.assertRaises(TypeError, meth, ts, tzinfo=16) # Bad keyword name. self.assertRaises(TypeError, meth, ts, tinfo=off42) # Too many args. self.assertRaises(TypeError, meth, ts, off42, off42) # Too few args. self.assertRaises(TypeError, meth)
debug("nonnumeric port: '%s'", port)
_debug("nonnumeric port: '%s'", port)
def request_port(request): host = request.get_host() i = host.find(':') if i >= 0: port = host[i+1:] try: int(port) except ValueError: debug("nonnumeric port: '%s'", port) return None else: port = DEFAULT_HTTP_PORT return port
debug(" - checking cookie %s=%s", cookie.name, cookie.value)
_debug(" - checking cookie %s=%s", cookie.name, cookie.value)
def set_ok(self, cookie, request): """ If you override .set_ok(), be sure to call this method. If it returns false, so should your subclass (assuming your subclass wants to be more strict about which cookies to accept).
debug(" Set-Cookie2 without version attribute (%s=%s)", cookie.name, cookie.value)
_debug(" Set-Cookie2 without version attribute (%s=%s)", cookie.name, cookie.value)
def set_ok_version(self, cookie, request): if cookie.version is None: # Version is always set to 0 by parse_ns_headers if it's a Netscape # cookie, so this must be an invalid RFC 2965 cookie. debug(" Set-Cookie2 without version attribute (%s=%s)", cookie.name, cookie.value) return False if cookie.version > 0 and not self.rfc2965: debug(" RFC 2965 cookies are switched off") return False elif cookie.version == 0 and not self.netscape: debug(" Netscape cookies are switched off") return False return True
debug(" RFC 2965 cookies are switched off")
_debug(" RFC 2965 cookies are switched off")
def set_ok_version(self, cookie, request): if cookie.version is None: # Version is always set to 0 by parse_ns_headers if it's a Netscape # cookie, so this must be an invalid RFC 2965 cookie. debug(" Set-Cookie2 without version attribute (%s=%s)", cookie.name, cookie.value) return False if cookie.version > 0 and not self.rfc2965: debug(" RFC 2965 cookies are switched off") return False elif cookie.version == 0 and not self.netscape: debug(" Netscape cookies are switched off") return False return True
debug(" Netscape cookies are switched off")
_debug(" Netscape cookies are switched off")
def set_ok_version(self, cookie, request): if cookie.version is None: # Version is always set to 0 by parse_ns_headers if it's a Netscape # cookie, so this must be an invalid RFC 2965 cookie. debug(" Set-Cookie2 without version attribute (%s=%s)", cookie.name, cookie.value) return False if cookie.version > 0 and not self.rfc2965: debug(" RFC 2965 cookies are switched off") return False elif cookie.version == 0 and not self.netscape: debug(" Netscape cookies are switched off") return False return True
debug(" third-party RFC 2965 cookie during "
_debug(" third-party RFC 2965 cookie during "
def set_ok_verifiability(self, cookie, request): if request.is_unverifiable() and is_third_party(request): if cookie.version > 0 and self.strict_rfc2965_unverifiable: debug(" third-party RFC 2965 cookie during " "unverifiable transaction") return False elif cookie.version == 0 and self.strict_ns_unverifiable: debug(" third-party Netscape cookie during " "unverifiable transaction") return False return True
debug(" third-party Netscape cookie during "
_debug(" third-party Netscape cookie during "
def set_ok_verifiability(self, cookie, request): if request.is_unverifiable() and is_third_party(request): if cookie.version > 0 and self.strict_rfc2965_unverifiable: debug(" third-party RFC 2965 cookie during " "unverifiable transaction") return False elif cookie.version == 0 and self.strict_ns_unverifiable: debug(" third-party Netscape cookie during " "unverifiable transaction") return False return True
debug(" illegal name (starts with '$'): '%s'", cookie.name)
_debug(" illegal name (starts with '$'): '%s'", cookie.name)
def set_ok_name(self, cookie, request): # Try and stop servers setting V0 cookies designed to hack other # servers that know both V0 and V1 protocols. if (cookie.version == 0 and self.strict_ns_set_initial_dollar and cookie.name.startswith("$")): debug(" illegal name (starts with '$'): '%s'", cookie.name) return False return True
debug(" path attribute %s is not a prefix of request " "path %s", cookie.path, req_path)
_debug(" path attribute %s is not a prefix of request " "path %s", cookie.path, req_path)
def set_ok_path(self, cookie, request): if cookie.path_specified: req_path = request_path(request) if ((cookie.version > 0 or (cookie.version == 0 and self.strict_ns_set_path)) and not req_path.startswith(cookie.path)): debug(" path attribute %s is not a prefix of request " "path %s", cookie.path, req_path) return False return True
debug(" domain %s is in user block-list", cookie.domain)
_debug(" domain %s is in user block-list", cookie.domain)
def set_ok_domain(self, cookie, request): if self.is_blocked(cookie.domain): debug(" domain %s is in user block-list", cookie.domain) return False if self.is_not_allowed(cookie.domain): debug(" domain %s is not in user allow-list", cookie.domain) return False if cookie.domain_specified: req_host, erhn = eff_request_host(request) domain = cookie.domain if self.strict_domain and (domain.count(".") >= 2): # XXX This should probably be compared with the Konqueror # (kcookiejar.cpp) and Mozilla implementations, but it's a # losing battle. i = domain.rfind(".") j = domain.rfind(".", 0, i) if j == 0: # domain like .foo.bar tld = domain[i+1:] sld = domain[j+1:i] if sld.lower() in ("co", "ac", "com", "edu", "org", "net", "gov", "mil", "int", "aero", "biz", "cat", "coop", "info", "jobs", "mobi", "museum", "name", "pro", "travel", "eu") and len(tld) == 2: # domain like .co.uk debug(" country-code second level domain %s", domain) return False if domain.startswith("."): undotted_domain = domain[1:] else: undotted_domain = domain embedded_dots = (undotted_domain.find(".") >= 0) if not embedded_dots and domain != ".local": debug(" non-local domain %s contains no embedded dot", domain) return False if cookie.version == 0: if (not erhn.endswith(domain) and (not erhn.startswith(".") and not ("."+erhn).endswith(domain))): debug(" effective request-host %s (even with added " "initial dot) does not end end with %s", erhn, domain) return False if (cookie.version > 0 or (self.strict_ns_domain & self.DomainRFC2965Match)): if not domain_match(erhn, domain): debug(" effective request-host %s does not domain-match " "%s", erhn, domain) return False if (cookie.version > 0 or (self.strict_ns_domain & self.DomainStrictNoDots)): host_prefix = req_host[:-len(domain)] if (host_prefix.find(".") >= 0 and not IPV4_RE.search(req_host)): debug(" host prefix %s for domain %s contains a dot", host_prefix, domain) return False return True
debug(" domain %s is not in user allow-list", cookie.domain)
_debug(" domain %s is not in user allow-list", cookie.domain)
def set_ok_domain(self, cookie, request): if self.is_blocked(cookie.domain): debug(" domain %s is in user block-list", cookie.domain) return False if self.is_not_allowed(cookie.domain): debug(" domain %s is not in user allow-list", cookie.domain) return False if cookie.domain_specified: req_host, erhn = eff_request_host(request) domain = cookie.domain if self.strict_domain and (domain.count(".") >= 2): # XXX This should probably be compared with the Konqueror # (kcookiejar.cpp) and Mozilla implementations, but it's a # losing battle. i = domain.rfind(".") j = domain.rfind(".", 0, i) if j == 0: # domain like .foo.bar tld = domain[i+1:] sld = domain[j+1:i] if sld.lower() in ("co", "ac", "com", "edu", "org", "net", "gov", "mil", "int", "aero", "biz", "cat", "coop", "info", "jobs", "mobi", "museum", "name", "pro", "travel", "eu") and len(tld) == 2: # domain like .co.uk debug(" country-code second level domain %s", domain) return False if domain.startswith("."): undotted_domain = domain[1:] else: undotted_domain = domain embedded_dots = (undotted_domain.find(".") >= 0) if not embedded_dots and domain != ".local": debug(" non-local domain %s contains no embedded dot", domain) return False if cookie.version == 0: if (not erhn.endswith(domain) and (not erhn.startswith(".") and not ("."+erhn).endswith(domain))): debug(" effective request-host %s (even with added " "initial dot) does not end end with %s", erhn, domain) return False if (cookie.version > 0 or (self.strict_ns_domain & self.DomainRFC2965Match)): if not domain_match(erhn, domain): debug(" effective request-host %s does not domain-match " "%s", erhn, domain) return False if (cookie.version > 0 or (self.strict_ns_domain & self.DomainStrictNoDots)): host_prefix = req_host[:-len(domain)] if (host_prefix.find(".") >= 0 and not IPV4_RE.search(req_host)): debug(" host prefix %s for domain %s contains a dot", host_prefix, domain) return False return True
debug(" country-code second level domain %s", domain)
_debug(" country-code second level domain %s", domain)
def set_ok_domain(self, cookie, request): if self.is_blocked(cookie.domain): debug(" domain %s is in user block-list", cookie.domain) return False if self.is_not_allowed(cookie.domain): debug(" domain %s is not in user allow-list", cookie.domain) return False if cookie.domain_specified: req_host, erhn = eff_request_host(request) domain = cookie.domain if self.strict_domain and (domain.count(".") >= 2): # XXX This should probably be compared with the Konqueror # (kcookiejar.cpp) and Mozilla implementations, but it's a # losing battle. i = domain.rfind(".") j = domain.rfind(".", 0, i) if j == 0: # domain like .foo.bar tld = domain[i+1:] sld = domain[j+1:i] if sld.lower() in ("co", "ac", "com", "edu", "org", "net", "gov", "mil", "int", "aero", "biz", "cat", "coop", "info", "jobs", "mobi", "museum", "name", "pro", "travel", "eu") and len(tld) == 2: # domain like .co.uk debug(" country-code second level domain %s", domain) return False if domain.startswith("."): undotted_domain = domain[1:] else: undotted_domain = domain embedded_dots = (undotted_domain.find(".") >= 0) if not embedded_dots and domain != ".local": debug(" non-local domain %s contains no embedded dot", domain) return False if cookie.version == 0: if (not erhn.endswith(domain) and (not erhn.startswith(".") and not ("."+erhn).endswith(domain))): debug(" effective request-host %s (even with added " "initial dot) does not end end with %s", erhn, domain) return False if (cookie.version > 0 or (self.strict_ns_domain & self.DomainRFC2965Match)): if not domain_match(erhn, domain): debug(" effective request-host %s does not domain-match " "%s", erhn, domain) return False if (cookie.version > 0 or (self.strict_ns_domain & self.DomainStrictNoDots)): host_prefix = req_host[:-len(domain)] if (host_prefix.find(".") >= 0 and not IPV4_RE.search(req_host)): debug(" host prefix %s for domain %s contains a dot", host_prefix, domain) return False return True
debug(" non-local domain %s contains no embedded dot", domain)
_debug(" non-local domain %s contains no embedded dot", domain)
def set_ok_domain(self, cookie, request): if self.is_blocked(cookie.domain): debug(" domain %s is in user block-list", cookie.domain) return False if self.is_not_allowed(cookie.domain): debug(" domain %s is not in user allow-list", cookie.domain) return False if cookie.domain_specified: req_host, erhn = eff_request_host(request) domain = cookie.domain if self.strict_domain and (domain.count(".") >= 2): # XXX This should probably be compared with the Konqueror # (kcookiejar.cpp) and Mozilla implementations, but it's a # losing battle. i = domain.rfind(".") j = domain.rfind(".", 0, i) if j == 0: # domain like .foo.bar tld = domain[i+1:] sld = domain[j+1:i] if sld.lower() in ("co", "ac", "com", "edu", "org", "net", "gov", "mil", "int", "aero", "biz", "cat", "coop", "info", "jobs", "mobi", "museum", "name", "pro", "travel", "eu") and len(tld) == 2: # domain like .co.uk debug(" country-code second level domain %s", domain) return False if domain.startswith("."): undotted_domain = domain[1:] else: undotted_domain = domain embedded_dots = (undotted_domain.find(".") >= 0) if not embedded_dots and domain != ".local": debug(" non-local domain %s contains no embedded dot", domain) return False if cookie.version == 0: if (not erhn.endswith(domain) and (not erhn.startswith(".") and not ("."+erhn).endswith(domain))): debug(" effective request-host %s (even with added " "initial dot) does not end end with %s", erhn, domain) return False if (cookie.version > 0 or (self.strict_ns_domain & self.DomainRFC2965Match)): if not domain_match(erhn, domain): debug(" effective request-host %s does not domain-match " "%s", erhn, domain) return False if (cookie.version > 0 or (self.strict_ns_domain & self.DomainStrictNoDots)): host_prefix = req_host[:-len(domain)] if (host_prefix.find(".") >= 0 and not IPV4_RE.search(req_host)): debug(" host prefix %s for domain %s contains a dot", host_prefix, domain) return False return True
debug(" effective request-host %s (even with added " "initial dot) does not end end with %s", erhn, domain)
_debug(" effective request-host %s (even with added " "initial dot) does not end end with %s", erhn, domain)
def set_ok_domain(self, cookie, request): if self.is_blocked(cookie.domain): debug(" domain %s is in user block-list", cookie.domain) return False if self.is_not_allowed(cookie.domain): debug(" domain %s is not in user allow-list", cookie.domain) return False if cookie.domain_specified: req_host, erhn = eff_request_host(request) domain = cookie.domain if self.strict_domain and (domain.count(".") >= 2): # XXX This should probably be compared with the Konqueror # (kcookiejar.cpp) and Mozilla implementations, but it's a # losing battle. i = domain.rfind(".") j = domain.rfind(".", 0, i) if j == 0: # domain like .foo.bar tld = domain[i+1:] sld = domain[j+1:i] if sld.lower() in ("co", "ac", "com", "edu", "org", "net", "gov", "mil", "int", "aero", "biz", "cat", "coop", "info", "jobs", "mobi", "museum", "name", "pro", "travel", "eu") and len(tld) == 2: # domain like .co.uk debug(" country-code second level domain %s", domain) return False if domain.startswith("."): undotted_domain = domain[1:] else: undotted_domain = domain embedded_dots = (undotted_domain.find(".") >= 0) if not embedded_dots and domain != ".local": debug(" non-local domain %s contains no embedded dot", domain) return False if cookie.version == 0: if (not erhn.endswith(domain) and (not erhn.startswith(".") and not ("."+erhn).endswith(domain))): debug(" effective request-host %s (even with added " "initial dot) does not end end with %s", erhn, domain) return False if (cookie.version > 0 or (self.strict_ns_domain & self.DomainRFC2965Match)): if not domain_match(erhn, domain): debug(" effective request-host %s does not domain-match " "%s", erhn, domain) return False if (cookie.version > 0 or (self.strict_ns_domain & self.DomainStrictNoDots)): host_prefix = req_host[:-len(domain)] if (host_prefix.find(".") >= 0 and not IPV4_RE.search(req_host)): debug(" host prefix %s for domain %s contains a dot", host_prefix, domain) return False return True
debug(" effective request-host %s does not domain-match " "%s", erhn, domain)
_debug(" effective request-host %s does not domain-match " "%s", erhn, domain)
def set_ok_domain(self, cookie, request): if self.is_blocked(cookie.domain): debug(" domain %s is in user block-list", cookie.domain) return False if self.is_not_allowed(cookie.domain): debug(" domain %s is not in user allow-list", cookie.domain) return False if cookie.domain_specified: req_host, erhn = eff_request_host(request) domain = cookie.domain if self.strict_domain and (domain.count(".") >= 2): # XXX This should probably be compared with the Konqueror # (kcookiejar.cpp) and Mozilla implementations, but it's a # losing battle. i = domain.rfind(".") j = domain.rfind(".", 0, i) if j == 0: # domain like .foo.bar tld = domain[i+1:] sld = domain[j+1:i] if sld.lower() in ("co", "ac", "com", "edu", "org", "net", "gov", "mil", "int", "aero", "biz", "cat", "coop", "info", "jobs", "mobi", "museum", "name", "pro", "travel", "eu") and len(tld) == 2: # domain like .co.uk debug(" country-code second level domain %s", domain) return False if domain.startswith("."): undotted_domain = domain[1:] else: undotted_domain = domain embedded_dots = (undotted_domain.find(".") >= 0) if not embedded_dots and domain != ".local": debug(" non-local domain %s contains no embedded dot", domain) return False if cookie.version == 0: if (not erhn.endswith(domain) and (not erhn.startswith(".") and not ("."+erhn).endswith(domain))): debug(" effective request-host %s (even with added " "initial dot) does not end end with %s", erhn, domain) return False if (cookie.version > 0 or (self.strict_ns_domain & self.DomainRFC2965Match)): if not domain_match(erhn, domain): debug(" effective request-host %s does not domain-match " "%s", erhn, domain) return False if (cookie.version > 0 or (self.strict_ns_domain & self.DomainStrictNoDots)): host_prefix = req_host[:-len(domain)] if (host_prefix.find(".") >= 0 and not IPV4_RE.search(req_host)): debug(" host prefix %s for domain %s contains a dot", host_prefix, domain) return False return True
debug(" host prefix %s for domain %s contains a dot", host_prefix, domain)
_debug(" host prefix %s for domain %s contains a dot", host_prefix, domain)
def set_ok_domain(self, cookie, request): if self.is_blocked(cookie.domain): debug(" domain %s is in user block-list", cookie.domain) return False if self.is_not_allowed(cookie.domain): debug(" domain %s is not in user allow-list", cookie.domain) return False if cookie.domain_specified: req_host, erhn = eff_request_host(request) domain = cookie.domain if self.strict_domain and (domain.count(".") >= 2): # XXX This should probably be compared with the Konqueror # (kcookiejar.cpp) and Mozilla implementations, but it's a # losing battle. i = domain.rfind(".") j = domain.rfind(".", 0, i) if j == 0: # domain like .foo.bar tld = domain[i+1:] sld = domain[j+1:i] if sld.lower() in ("co", "ac", "com", "edu", "org", "net", "gov", "mil", "int", "aero", "biz", "cat", "coop", "info", "jobs", "mobi", "museum", "name", "pro", "travel", "eu") and len(tld) == 2: # domain like .co.uk debug(" country-code second level domain %s", domain) return False if domain.startswith("."): undotted_domain = domain[1:] else: undotted_domain = domain embedded_dots = (undotted_domain.find(".") >= 0) if not embedded_dots and domain != ".local": debug(" non-local domain %s contains no embedded dot", domain) return False if cookie.version == 0: if (not erhn.endswith(domain) and (not erhn.startswith(".") and not ("."+erhn).endswith(domain))): debug(" effective request-host %s (even with added " "initial dot) does not end end with %s", erhn, domain) return False if (cookie.version > 0 or (self.strict_ns_domain & self.DomainRFC2965Match)): if not domain_match(erhn, domain): debug(" effective request-host %s does not domain-match " "%s", erhn, domain) return False if (cookie.version > 0 or (self.strict_ns_domain & self.DomainStrictNoDots)): host_prefix = req_host[:-len(domain)] if (host_prefix.find(".") >= 0 and not IPV4_RE.search(req_host)): debug(" host prefix %s for domain %s contains a dot", host_prefix, domain) return False return True
debug(" bad port %s (not numeric)", p)
_debug(" bad port %s (not numeric)", p)
def set_ok_port(self, cookie, request): if cookie.port_specified: req_port = request_port(request) if req_port is None: req_port = "80" else: req_port = str(req_port) for p in cookie.port.split(","): try: int(p) except ValueError: debug(" bad port %s (not numeric)", p) return False if p == req_port: break else: debug(" request port (%s) not found in %s", req_port, cookie.port) return False return True
debug(" request port (%s) not found in %s", req_port, cookie.port)
_debug(" request port (%s) not found in %s", req_port, cookie.port)
def set_ok_port(self, cookie, request): if cookie.port_specified: req_port = request_port(request) if req_port is None: req_port = "80" else: req_port = str(req_port) for p in cookie.port.split(","): try: int(p) except ValueError: debug(" bad port %s (not numeric)", p) return False if p == req_port: break else: debug(" request port (%s) not found in %s", req_port, cookie.port) return False return True
debug(" - checking cookie %s=%s", cookie.name, cookie.value)
_debug(" - checking cookie %s=%s", cookie.name, cookie.value)
def return_ok(self, cookie, request): """ If you override .return_ok(), be sure to call this method. If it returns false, so should your subclass (assuming your subclass wants to be more strict about which cookies to return).
debug(" RFC 2965 cookies are switched off")
_debug(" RFC 2965 cookies are switched off")
def return_ok_version(self, cookie, request): if cookie.version > 0 and not self.rfc2965: debug(" RFC 2965 cookies are switched off") return False elif cookie.version == 0 and not self.netscape: debug(" Netscape cookies are switched off") return False return True
debug(" Netscape cookies are switched off")
_debug(" Netscape cookies are switched off")
def return_ok_version(self, cookie, request): if cookie.version > 0 and not self.rfc2965: debug(" RFC 2965 cookies are switched off") return False elif cookie.version == 0 and not self.netscape: debug(" Netscape cookies are switched off") return False return True
debug(" third-party RFC 2965 cookie during unverifiable " "transaction")
_debug(" third-party RFC 2965 cookie during unverifiable " "transaction")
def return_ok_verifiability(self, cookie, request): if request.is_unverifiable() and is_third_party(request): if cookie.version > 0 and self.strict_rfc2965_unverifiable: debug(" third-party RFC 2965 cookie during unverifiable " "transaction") return False elif cookie.version == 0 and self.strict_ns_unverifiable: debug(" third-party Netscape cookie during unverifiable " "transaction") return False return True
debug(" third-party Netscape cookie during unverifiable " "transaction")
_debug(" third-party Netscape cookie during unverifiable " "transaction")
def return_ok_verifiability(self, cookie, request): if request.is_unverifiable() and is_third_party(request): if cookie.version > 0 and self.strict_rfc2965_unverifiable: debug(" third-party RFC 2965 cookie during unverifiable " "transaction") return False elif cookie.version == 0 and self.strict_ns_unverifiable: debug(" third-party Netscape cookie during unverifiable " "transaction") return False return True
debug(" secure cookie with non-secure request")
_debug(" secure cookie with non-secure request")
def return_ok_secure(self, cookie, request): if cookie.secure and request.get_type() != "https": debug(" secure cookie with non-secure request") return False return True
debug(" cookie expired")
_debug(" cookie expired")
def return_ok_expires(self, cookie, request): if cookie.is_expired(self._now): debug(" cookie expired") return False return True
debug(" request port %s does not match cookie port %s", req_port, cookie.port)
_debug(" request port %s does not match cookie port %s", req_port, cookie.port)
def return_ok_port(self, cookie, request): if cookie.port: req_port = request_port(request) if req_port is None: req_port = "80" for p in cookie.port.split(","): if p == req_port: break else: debug(" request port %s does not match cookie port %s", req_port, cookie.port) return False return True
debug(" cookie with unspecified domain does not string-compare " "equal to request domain")
_debug(" cookie with unspecified domain does not string-compare " "equal to request domain")
def return_ok_domain(self, cookie, request): req_host, erhn = eff_request_host(request) domain = cookie.domain
debug(" effective request-host name %s does not domain-match " "RFC 2965 cookie domain %s", erhn, domain)
_debug(" effective request-host name %s does not domain-match " "RFC 2965 cookie domain %s", erhn, domain)
def return_ok_domain(self, cookie, request): req_host, erhn = eff_request_host(request) domain = cookie.domain
debug(" request-host %s does not match Netscape cookie domain " "%s", req_host, domain)
_debug(" request-host %s does not match Netscape cookie domain " "%s", req_host, domain)
def return_ok_domain(self, cookie, request): req_host, erhn = eff_request_host(request) domain = cookie.domain
debug(" domain %s is in user block-list", domain)
_debug(" domain %s is in user block-list", domain)
def domain_return_ok(self, domain, request): # Liberal check of. This is here as an optimization to avoid # having to load lots of MSIE cookie files unless necessary. req_host, erhn = eff_request_host(request) if not req_host.startswith("."): req_host = "."+req_host if not erhn.startswith("."): erhn = "."+erhn if not (req_host.endswith(domain) or erhn.endswith(domain)): #debug(" request domain %s does not match cookie domain %s", # req_host, domain) return False
debug(" domain %s is not in user allow-list", domain)
_debug(" domain %s is not in user allow-list", domain)
def domain_return_ok(self, domain, request): # Liberal check of. This is here as an optimization to avoid # having to load lots of MSIE cookie files unless necessary. req_host, erhn = eff_request_host(request) if not req_host.startswith("."): req_host = "."+req_host if not erhn.startswith("."): erhn = "."+erhn if not (req_host.endswith(domain) or erhn.endswith(domain)): #debug(" request domain %s does not match cookie domain %s", # req_host, domain) return False
debug("- checking cookie path=%s", path)
_debug("- checking cookie path=%s", path)
def path_return_ok(self, path, request): debug("- checking cookie path=%s", path) req_path = request_path(request) if not req_path.startswith(path): debug(" %s does not path-match %s", req_path, path) return False return True
debug(" %s does not path-match %s", req_path, path)
_debug(" %s does not path-match %s", req_path, path)
def path_return_ok(self, path, request): debug("- checking cookie path=%s", path) req_path = request_path(request) if not req_path.startswith(path): debug(" %s does not path-match %s", req_path, path) return False return True
debug("Checking %s for cookies to return", domain)
_debug("Checking %s for cookies to return", domain)
def _cookies_for_domain(self, domain, request): cookies = [] if not self._policy.domain_return_ok(domain, request): return [] debug("Checking %s for cookies to return", domain) cookies_by_path = self._cookies[domain] for path in cookies_by_path.keys(): if not self._policy.path_return_ok(path, request): continue cookies_by_name = cookies_by_path[path] for cookie in cookies_by_name.values(): if not self._policy.return_ok(cookie, request): debug(" not returning cookie") continue debug(" it's a match") cookies.append(cookie) return cookies
debug(" not returning cookie")
_debug(" not returning cookie")
def _cookies_for_domain(self, domain, request): cookies = [] if not self._policy.domain_return_ok(domain, request): return [] debug("Checking %s for cookies to return", domain) cookies_by_path = self._cookies[domain] for path in cookies_by_path.keys(): if not self._policy.path_return_ok(path, request): continue cookies_by_name = cookies_by_path[path] for cookie in cookies_by_name.values(): if not self._policy.return_ok(cookie, request): debug(" not returning cookie") continue debug(" it's a match") cookies.append(cookie) return cookies
debug(" it's a match")
_debug(" it's a match")
def _cookies_for_domain(self, domain, request): cookies = [] if not self._policy.domain_return_ok(domain, request): return [] debug("Checking %s for cookies to return", domain) cookies_by_path = self._cookies[domain] for path in cookies_by_path.keys(): if not self._policy.path_return_ok(path, request): continue cookies_by_name = cookies_by_path[path] for cookie in cookies_by_name.values(): if not self._policy.return_ok(cookie, request): debug(" not returning cookie") continue debug(" it's a match") cookies.append(cookie) return cookies
debug("add_cookie_header")
_debug("add_cookie_header")
def add_cookie_header(self, request): """Add correct Cookie: header to request (urllib2.Request object).
debug(" missing value for domain attribute")
_debug(" missing value for domain attribute")
def _normalized_cookie_tuples(self, attrs_set): """Return list of tuples containing normalised cookie information.
debug(" missing or invalid value for expires "
_debug(" missing or invalid value for expires "
def _normalized_cookie_tuples(self, attrs_set): """Return list of tuples containing normalised cookie information.
debug(" missing or invalid (non-numeric) value for "
_debug(" missing or invalid (non-numeric) value for "
def _normalized_cookie_tuples(self, attrs_set): """Return list of tuples containing normalised cookie information.
debug(" missing value for %s attribute" % k)
_debug(" missing value for %s attribute" % k)
def _normalized_cookie_tuples(self, attrs_set): """Return list of tuples containing normalised cookie information.
debug("Expiring cookie, domain='%s', path='%s', name='%s'", domain, path, name)
_debug("Expiring cookie, domain='%s', path='%s', name='%s'", domain, path, name)
def _cookie_from_cookie_tuple(self, tup, request): # standard is dict of standard cookie-attributes, rest is dict of the # rest of them name, value, standard, rest = tup
debug("extract_cookies: %s", response.info())
_debug("extract_cookies: %s", response.info())
def extract_cookies(self, response, request): """Extract cookies from response, where allowable given the request.""" debug("extract_cookies: %s", response.info()) self._cookies_lock.acquire() self._policy._now = self._now = int(time.time())
debug(" setting cookie: %s", cookie)
_debug(" setting cookie: %s", cookie)
def extract_cookies(self, response, request): """Extract cookies from response, where allowable given the request.""" debug("extract_cookies: %s", response.info()) self._cookies_lock.acquire() self._policy._now = self._now = int(time.time())
for ending in ['.py', '.pyc', '.pyd', '.pyo', 'module.so', 'module.so.1', '.so']: if len(filename) > len(ending) and filename[-len(ending):] == ending: return filename[:-len(ending)]
suffixes = map(lambda (suffix, mode, kind): (len(suffix), suffix), imp.get_suffixes()) suffixes.sort() suffixes.reverse() for length, suffix in suffixes: if len(filename) > length and filename[-length:] == suffix: return filename[:-length]
def modulename(path): """Return the Python module name for a given path, or None.""" filename = os.path.basename(path) for ending in ['.py', '.pyc', '.pyd', '.pyo', 'module.so', 'module.so.1', '.so']: if len(filename) > len(ending) and filename[-len(ending):] == ending: return filename[:-len(ending)]
text = self.escape(cram(x, self.maxstring)) return re.sub(r'((\\[\\abfnrtv]|\\x..|\\u....)+)', r'<font color="
test = cram(x, self.maxstring) testrepr = repr(test) if '\\' in test and '\\' not in replace(testrepr, (r'\\', '')): return 'r' + testrepr[0] + self.escape(test) + testrepr[0] return re.sub(r'((\\[\\abfnrtv\'"]|\\x..|\\u....)+)', r'<font color=" self.escape(testrepr))
def repr_string(self, x, level): text = self.escape(cram(x, self.maxstring)) return re.sub(r'((\\[\\abfnrtv]|\\x..|\\u....)+)', r'<font color="#c040c0">\1</font>', repr(text))
for pattern in [' at 0x[0-9a-f]{6,}(>+)$', ' at [0-9A-F]{8,}(>+)$']: if re.search(pattern, repr(Exception)): return re.sub(pattern, '\\1', text)
if _re_stripid.search(repr(Exception)): return _re_stripid.sub(r'\1', text)
def stripid(text): """Remove the hexadecimal id from a Python object representation.""" # The behaviour of %p is implementation-dependent; we check two cases. for pattern in [' at 0x[0-9a-f]{6,}(>+)$', ' at [0-9A-F]{8,}(>+)$']: if re.search(pattern, repr(Exception)): return re.sub(pattern, '\\1', text) return text
def _is_some_method(object): return inspect.ismethod(object) or inspect.ismethoddescriptor(object)
def _is_some_method(obj): return inspect.ismethod(obj) or inspect.ismethoddescriptor(obj)
def _is_some_method(object): return inspect.ismethod(object) or inspect.ismethoddescriptor(object)
try: str(u'Hello \u00E1') except Exception, e: sampleUnicodeEncodeError = e try: unicode('\xff') except Exception, e: sampleUnicodeDecodeError = e
def testAttributes(self): # test that exception attributes are happy try: str(u'Hello \u00E1') except Exception, e: sampleUnicodeEncodeError = e
(sampleUnicodeEncodeError, {'message' : '', 'args' : ('ascii', u'Hello \xe1', 6, 7, 'ordinal not in range(128)'), 'encoding' : 'ascii', 'object' : u'Hello \xe1', 'start' : 6, 'reason' : 'ordinal not in range(128)'}), (sampleUnicodeDecodeError,
(UnicodeEncodeError, ('ascii', u'a', 0, 1, 'ordinal not in range'), {'message' : '', 'args' : ('ascii', u'a', 0, 1, 'ordinal not in range'), 'encoding' : 'ascii', 'object' : u'a', 'start' : 0, 'reason' : 'ordinal not in range'}), (UnicodeDecodeError, ('ascii', '\xff', 0, 1, 'ordinal not in range'),
def testAttributes(self): # test that exception attributes are happy try: str(u'Hello \u00E1') except Exception, e: sampleUnicodeEncodeError = e
'ordinal not in range(128)'),
'ordinal not in range'),
def testAttributes(self): # test that exception attributes are happy try: str(u'Hello \u00E1') except Exception, e: sampleUnicodeEncodeError = e
'start' : 0, 'reason' : 'ordinal not in range(128)'}),
'start' : 0, 'reason' : 'ordinal not in range'}),
def testAttributes(self): # test that exception attributes are happy try: str(u'Hello \u00E1') except Exception, e: sampleUnicodeEncodeError = e
for args in exceptionList: expected = args[-1] try: exc = args[0] if len(args) == 2: raise exc else: raise exc(*args[1])
for exc, args, expected in exceptionList: try: raise exc(*args)
def testAttributes(self): # test that exception attributes are happy try: str(u'Hello \u00E1') except Exception, e: sampleUnicodeEncodeError = e
if (e is not exc and type(e) is not exc):
if type(e) is not exc:
def testAttributes(self): # test that exception attributes are happy try: str(u'Hello \u00E1') except Exception, e: sampleUnicodeEncodeError = e
include_dirs += ['/usr/5include']
inc_dirs += ['/usr/5include']
def detect_modules(self): # Ensure that /usr/local is always used if '/usr/local/lib' not in self.compiler.library_dirs: self.compiler.library_dirs.append('/usr/local/lib') if '/usr/local/include' not in self.compiler.include_dirs: self.compiler.include_dirs.append( '/usr/local/include' )
del(self)
def delete(self): self.tk.call(self.stylename, 'delete') del(self)
test(r"""sre.match("\x%02x" % i, chr(i)) != None""", 1) test(r"""sre.match("\x%02x0" % i, chr(i)+"0") != None""", 1) test(r"""sre.match("\x%02xz" % i, chr(i)+"z") != None""", 1)
test(r"""sre.match(r"\x%02x" % i, chr(i)) != None""", 1) test(r"""sre.match(r"\x%02x0" % i, chr(i)+"0") != None""", 1) test(r"""sre.match(r"\x%02xz" % i, chr(i)+"z") != None""", 1)
def test(expression, result, exception=None): try: r = eval(expression) except: if exception: if not isinstance(sys.exc_value, exception): print expression, "FAILED" # display name, not actual value if exception is sre.error: print "expected", "sre.error" else: print "expected", exception.__name__ print "got", sys.exc_type.__name__, str(sys.exc_value) else: print expression, "FAILED" traceback.print_exc(file=sys.stdout) else: if exception: print expression, "FAILED" if exception is sre.error: print "expected", "sre.error" else: print "expected", exception.__name__ print "got result", repr(r) else: if r != result: print expression, "FAILED" print "expected", repr(result) print "got result", repr(r)
raise error, 'option --%s requires argument' % opt
raise GetoptError('option --%s requires argument' % opt, opt)
def do_longs(opts, opt, longopts, args): try: i = string.index(opt, '=') opt, optarg = opt[:i], opt[i+1:] except ValueError: optarg = None has_arg, opt = long_has_args(opt, longopts) if has_arg: if optarg is None: if not args: raise error, 'option --%s requires argument' % opt optarg, args = args[0], args[1:] elif optarg: raise error, 'option --%s must not have an argument' % opt opts.append(('--' + opt, optarg or '')) return opts, args
raise error, 'option --%s must not have an argument' % opt
raise GetoptError('option --%s must not have an argument' % opt, opt)
def do_longs(opts, opt, longopts, args): try: i = string.index(opt, '=') opt, optarg = opt[:i], opt[i+1:] except ValueError: optarg = None has_arg, opt = long_has_args(opt, longopts) if has_arg: if optarg is None: if not args: raise error, 'option --%s requires argument' % opt optarg, args = args[0], args[1:] elif optarg: raise error, 'option --%s must not have an argument' % opt opts.append(('--' + opt, optarg or '')) return opts, args
raise error, 'option --%s not a unique prefix' % opt
raise GetoptError('option --%s not a unique prefix' % opt, opt)
def long_has_args(opt, longopts): optlen = len(opt) for i in range(len(longopts)): x, y = longopts[i][:optlen], longopts[i][optlen:] if opt != x: continue if y != '' and y != '=' and i+1 < len(longopts): if opt == longopts[i+1][:optlen]: raise error, 'option --%s not a unique prefix' % opt if longopts[i][-1:] in ('=', ): return 1, longopts[i][:-1] return 0, longopts[i] raise error, 'option --' + opt + ' not recognized'
raise error, 'option --' + opt + ' not recognized'
raise GetoptError('option --%s not recognized' % opt, opt)
def long_has_args(opt, longopts): optlen = len(opt) for i in range(len(longopts)): x, y = longopts[i][:optlen], longopts[i][optlen:] if opt != x: continue if y != '' and y != '=' and i+1 < len(longopts): if opt == longopts[i+1][:optlen]: raise error, 'option --%s not a unique prefix' % opt if longopts[i][-1:] in ('=', ): return 1, longopts[i][:-1] return 0, longopts[i] raise error, 'option --' + opt + ' not recognized'
raise error, 'option -%s requires argument' % opt
raise GetoptError('option -%s requires argument' % opt, opt)
def do_shorts(opts, optstring, shortopts, args): while optstring != '': opt, optstring = optstring[0], optstring[1:] if short_has_arg(opt, shortopts): if optstring == '': if not args: raise error, 'option -%s requires argument' % opt optstring, args = args[0], args[1:] optarg, optstring = optstring, '' else: optarg = '' opts.append(('-' + opt, optarg)) return opts, args
raise error, 'option -%s not recognized' % opt
raise GetoptError('option -%s not recognized' % opt, opt)
def short_has_arg(opt, shortopts): for i in range(len(shortopts)): if opt == shortopts[i] != ':': return shortopts[i+1:i+2] == ':' raise error, 'option -%s not recognized' % opt
_res = (PyObject *)PyUnicode_FromUnicode(data, size);
_res = (PyObject *)PyUnicode_FromUnicode(data, size-1);
def outputRepr(self): Output() Output("static PyObject * %s_repr(%s *self)", self.prefix, self.objecttype) OutLbrace() Output("char buf[100];") Output("""sprintf(buf, "<CFURL object at 0x%%8.8x for 0x%%8.8x>", (unsigned)self, (unsigned)self->ob_itself);""") Output("return PyString_FromString(buf);") OutRbrace()
if sys.platform=="win32" and win32api is not None: HKEY_LOCAL_MACHINE = 0x80000002
if sys.platform=="win32": import _winreg from _winreg import HKEY_LOCAL_MACHINE
def find_module(self, name, path): if name in self.excludes: self.msgout(3, "find_module -> Excluded") raise ImportError, name
pathname = win32api.RegQueryValue(HKEY_LOCAL_MACHINE, "Software\\Python\\PythonCore\\%s\\Modules\\%s" % (sys.winver, name))
pathname = _winreg.QueryValueEx(HKEY_LOCAL_MACHINE, \ "Software\\Python\\PythonCore\\%s\\Modules\\%s" % (sys.winver, name))
def find_module(self, name, path): if name in self.excludes: self.msgout(3, "find_module -> Excluded") raise ImportError, name
except win32api.error:
except _winreg.error:
def find_module(self, name, path): if name in self.excludes: self.msgout(3, "find_module -> Excluded") raise ImportError, name
raise SGMLParserError('neither < nor & ??')
raise SGMLParseError('neither < nor & ??')
def goahead(self, end): rawdata = self.rawdata i = 0 n = len(rawdata) while i < n: if self.nomoretags: self.handle_data(rawdata[i:n]) i = n break match = interesting.search(rawdata, i) if match: j = match.start(0) else: j = n if i < j: self.handle_data(rawdata[i:j]) i = j if i == n: break if rawdata[i] == '<': if starttagopen.match(rawdata, i): if self.literal: self.handle_data(rawdata[i]) i = i+1 continue k = self.parse_starttag(i) if k < 0: break i = k continue if endtagopen.match(rawdata, i): k = self.parse_endtag(i) if k < 0: break i = k self.literal = 0 continue if commentopen.match(rawdata, i): if self.literal: self.handle_data(rawdata[i]) i = i+1 continue k = self.parse_comment(i) if k < 0: break i = i+k continue if piopen.match(rawdata, i): if self.literal: self.handle_data(rawdata[i]) i = i+1 continue k = self.parse_pi(i) if k < 0: break i = i+k continue match = special.match(rawdata, i) if match: if self.literal: self.handle_data(rawdata[i]) i = i+1 continue # This is some sort of declaration; in "HTML as # deployed," this should only be the document type # declaration ("<!DOCTYPE html...>"). k = self.parse_declaration(i) if k < 0: break i = k continue elif rawdata[i] == '&': match = charref.match(rawdata, i) if match: name = match.group(1) self.handle_charref(name) i = match.end(0) if rawdata[i-1] != ';': i = i-1 continue match = entityref.match(rawdata, i) if match: name = match.group(1) self.handle_entityref(name) i = match.end(0) if rawdata[i-1] != ';': i = i-1 continue else: raise SGMLParserError('neither < nor & ??') # We get here only if incomplete matches but # nothing else match = incomplete.match(rawdata, i) if not match: self.handle_data(rawdata[i]) i = i+1 continue j = match.end(0) if j == n: break # Really incomplete self.handle_data(rawdata[i:j]) i = j # end while if end and i < n: self.handle_data(rawdata[i:n]) i = n self.rawdata = rawdata[i:] # XXX if end: check for empty stack
except pwd.error:
except KeyError:
def nobody_uid(): """Internal routine to get nobody's uid""" global nobody if nobody: return nobody import pwd try: nobody = pwd.getpwnam('nobody')[2] except pwd.error: nobody = 1 + max(map(lambda x: x[2], pwd.getpwall())) return nobody
('a, = 1,', 'LOAD_CONST',), ('a, b = 1, 2', 'ROT_TWO',), ('a, b, c = 1, 2, 3', 'ROT_THREE',),
('a, = a,', 'LOAD_CONST',), ('a, b = a, b', 'ROT_TWO',), ('a, b, c = a, b, c', 'ROT_THREE',),
def test_pack_unpack(self): for line, elem in ( ('a, = 1,', 'LOAD_CONST',), ('a, b = 1, 2', 'ROT_TWO',), ('a, b, c = 1, 2, 3', 'ROT_THREE',), ): asm = dis_single(line) self.assert_(elem in asm) self.assert_('BUILD_TUPLE' not in asm) self.assert_('UNPACK_TUPLE' not in asm)
self.text.insert(mark, str(s), tags)
self.text.insert(mark, s, tags)
def write(self, s, tags=(), mark="insert"): self.text.insert(mark, str(s), tags) self.text.see(mark) self.text.update()
time.sleep(1)
time.sleep(1.1)
def test_autoseed(self): self.gen.seed() state1 = self.gen.getstate() time.sleep(1) self.gen.seed() # diffent seeds at different times state2 = self.gen.getstate() self.assertNotEqual(state1, state2)
"Escape all non-alphanumeric characters in pattern."
def escape(pattern): "Escape all non-alphanumeric characters in pattern." result = list(pattern) alphanum=string.letters+'_'+string.digits for i in range(len(pattern)): char = pattern[i] if char not in alphanum: if char=='\000': result[i] = '\\000' else: result[i] = '\\'+char return string.join(result, '')
"Compile a regular expression pattern, returning a RegexObject."
def compile(pattern, flags=0): "Compile a regular expression pattern, returning a RegexObject." groupindex={} code=pcre_compile(pattern, flags, groupindex) return RegexObject(pattern, flags, code, groupindex)
"""Return a list of all non-overlapping matches in the string. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result.
"""findall(source) -> list Return a list of all non-overlapping matches of the compiled pattern in string. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result.
def findall(self, source): """Return a list of all non-overlapping matches in the string.
"Return the start of the substring matched by group g"
def start(self, g = 0): "Return the start of the substring matched by group g" if type(g) == type(''): try: g = self.re.groupindex[g] except (KeyError, TypeError): raise IndexError, 'group %s is undefined' % `g` return self.regs[g][0]
"Return the end of the substring matched by group g"
def end(self, g = 0): "Return the end of the substring matched by group g" if type(g) == type(''): try: g = self.re.groupindex[g] except (KeyError, TypeError): raise IndexError, 'group %s is undefined' % `g` return self.regs[g][1]
"Return (start, end) of the substring matched by group g"
def span(self, g = 0): "Return (start, end) of the substring matched by group g" if type(g) == type(''): try: g = self.re.groupindex[g] except (KeyError, TypeError): raise IndexError, 'group %s is undefined' % `g` return self.regs[g]
"Return a tuple containing all subgroups of the match object"
def groups(self, default=None): "Return a tuple containing all subgroups of the match object" result = [] for g in range(1, self.re._num_regs): a, b = self.regs[g] if a == -1 or b == -1: result.append(default) else: result.append(self.string[a:b]) return tuple(result)
"Return one or more groups of the match"
def group(self, *groups): "Return one or more groups of the match" if len(groups) == 0: groups = (0,) result = [] for g in groups: if type(g) == type(''): try: g = self.re.groupindex[g] except (KeyError, TypeError): raise IndexError, 'group %s is undefined' % `g` if g >= len(self.regs): raise IndexError, 'group %s is undefined' % `g` a, b = self.regs[g] if a == -1 or b == -1: result.append(None) else: result.append(self.string[a:b]) if len(result) > 1: return tuple(result) elif len(result) == 1: return result[0] else: return ()