rem
stringlengths 0
322k
| add
stringlengths 0
2.05M
| context
stringlengths 8
228k
|
---|---|---|
def _get_fqdn_hostname(name): | def make_fqdn(name = ''): """Get fully qualified domain name from name. An empty argument is interpreted as meaning the local host. First the hostname returned by socket.gethostbyaddr() is checked, then possibly existing aliases. In case no FQDN is available, hostname is returned. """ | def _get_fqdn_hostname(name): name = string.strip(name) if len(name) == 0: name = socket.gethostname() try: hostname, aliases, ipaddrs = socket.gethostbyaddr(name) except socket.error: pass else: aliases.insert(0, hostname) for name in aliases: if '.' in name: break else: name = hostname return name |
try: hostname, aliases, ipaddrs = socket.gethostbyaddr(name) except socket.error: pass | try: hostname, aliases, ipaddrs = socket.gethostbyaddr(name) except socket.error: pass else: aliases.insert(0, hostname) for name in aliases: if '.' in name: break | def _get_fqdn_hostname(name): name = string.strip(name) if len(name) == 0: name = socket.gethostname() try: hostname, aliases, ipaddrs = socket.gethostbyaddr(name) except socket.error: pass else: aliases.insert(0, hostname) for name in aliases: if '.' in name: break else: name = hostname return name |
aliases.insert(0, hostname) for name in aliases: if '.' in name: break else: name = hostname | name = hostname | def _get_fqdn_hostname(name): name = string.strip(name) if len(name) == 0: name = socket.gethostname() try: hostname, aliases, ipaddrs = socket.gethostbyaddr(name) except socket.error: pass else: aliases.insert(0, hostname) for name in aliases: if '.' in name: break else: name = hostname return name |
self.putcmd("helo", _get_fqdn_hostname(name)) | if name: self.putcmd("helo", name) else: self.putcmd("helo", make_fqdn()) | def helo(self, name=''): """SMTP 'helo' command. Hostname to send for this command defaults to the FQDN of the local host. """ self.putcmd("helo", _get_fqdn_hostname(name)) (code,msg)=self.getreply() self.helo_resp=msg return (code,msg) |
self.putcmd("ehlo", _get_fqdn_hostname(name)) | if name: self.putcmd("ehlo", name) else: self.putcmd("ehlo", make_fqdn()) | def ehlo(self, name=''): """ SMTP 'ehlo' command. Hostname to send for this command defaults to the FQDN of the local host. """ self.putcmd("ehlo", _get_fqdn_hostname(name)) (code,msg)=self.getreply() # According to RFC1869 some (badly written) # MTA's will disconnect on an ehlo. Toss an exception if # that happens -ddm if code == -1 and len(msg) == 0: raise SMTPServerDisconnected("Server not connected") self.ehlo_resp=msg if code<>250: return (code,msg) self.does_esmtp=1 #parse the ehlo response -ddm resp=string.split(self.ehlo_resp,'\n') del resp[0] for each in resp: m=re.match(r'(?P<feature>[A-Za-z0-9][A-Za-z0-9\-]*)',each) if m: feature=string.lower(m.group("feature")) params=string.strip(m.string[m.end("feature"):]) self.esmtp_features[feature]=params return (code,msg) |
tagName = self._current_context[uri] + ":" + localname | prefix = self._current_context[uri] if prefix: tagName = prefix + ":" + localname else: tagName = localname | def startElementNS(self, name, tagName , attrs): uri, localname = name if uri: # When using namespaces, the reader may or may not # provide us with the original name. If not, create # *a* valid tagName from the current context. if tagName is None: tagName = self._current_context[uri] + ":" + localname node = self.document.createElementNS(uri, tagName) else: # When the tagname is not prefixed, it just appears as # localname node = self.document.createElement(localname) |
qname = self._current_context[a_uri] + ":" + a_localname | prefix = self._current_context[a_uri] if prefix: qname = prefix + ":" + a_localname else: qname = a_localname | def startElementNS(self, name, tagName , attrs): uri, localname = name if uri: # When using namespaces, the reader may or may not # provide us with the original name. If not, create # *a* valid tagName from the current context. if tagName is None: tagName = self._current_context[uri] + ":" + localname node = self.document.createElementNS(uri, tagName) else: # When the tagname is not prefixed, it just appears as # localname node = self.document.createElement(localname) |
for attr in dir(self.metadata): meth_name = "get_" + attr setattr(self, meth_name, getattr(self.metadata, meth_name)) | method_basenames = dir(self.metadata) + \ ['fullname', 'contact', 'contact_email'] for basename in method_basenames: method_name = "get_" + basename setattr(self, method_name, getattr(self.metadata, method_name)) | def __init__ (self, attrs=None): """Construct a new Distribution instance: initialize all the attributes of a Distribution, and then uses 'attrs' (a dictionary mapping attribute names to values) to assign some of those attributes their "real" values. (Any attributes not mentioned in 'attrs' will be assigned to some null value: 0, None, an empty list or dictionary, etc.) Most importantly, initialize the 'command_obj' attribute to the empty dictionary; this will be filled in with real command objects by 'parse_command_line()'.""" |
pdir = self.package_dir.get('') if pdir is not None: tail.insert(0, pdir) | def get_package_dir (self, package): """Return the directory, relative to the top of the source distribution, where package 'package' should be found (at least according to the 'package_dir' option, if any).""" |
|
if not os.path.isfile (init_py): | if os.path.isfile (init_py): return init_py else: | def check_package (self, package, package_dir): |
self.check_package (package, package_dir) | init_py = self.check_package (package, package_dir) | def find_modules (self): # Map package names to tuples of useful info about the package: # (package_dir, checked) # package_dir - the directory where we'll find source files for # this package # checked - true if we have checked that the package directory # is valid (exists, contains __init__.py, ... ?) packages = {} |
modules.append ((package, module, module_file)) | modules.append ((package, module_base, module_file)) | def find_modules (self): # Map package names to tuples of useful info about the package: # (package_dir, checked) # package_dir - the directory where we'll find source files for # this package # checked - true if we have checked that the package directory # is valid (exists, contains __init__.py, ... ?) packages = {} |
self._out.write('<?xml version="1.0" encoding="%s"?>\n' % | self._write('<?xml version="1.0" encoding="%s"?>\n' % | def startDocument(self): self._out.write('<?xml version="1.0" encoding="%s"?>\n' % self._encoding) |
self._out.write('<' + name) | self._write('<' + name) | def startElement(self, name, attrs): self._out.write('<' + name) for (name, value) in attrs.items(): self._out.write(' %s=%s' % (name, quoteattr(value))) self._out.write('>') |
self._out.write(' %s=%s' % (name, quoteattr(value))) self._out.write('>') | self._write(' %s=%s' % (name, quoteattr(value))) self._write('>') | def startElement(self, name, attrs): self._out.write('<' + name) for (name, value) in attrs.items(): self._out.write(' %s=%s' % (name, quoteattr(value))) self._out.write('>') |
self._out.write('</%s>' % name) | self._write('</%s>' % name) | def endElement(self, name): self._out.write('</%s>' % name) |
self._out.write('<' + name) | self._write('<' + name) | def startElementNS(self, name, qname, attrs): if name[0] is None: # if the name was not namespace-scoped, use the unqualified part name = name[1] else: # else try to restore the original prefix from the namespace name = self._current_context[name[0]] + ":" + name[1] self._out.write('<' + name) |
self._out.write(' xmlns:%s="%s"' % pair) | self._write(' xmlns:%s="%s"' % pair) | def startElementNS(self, name, qname, attrs): if name[0] is None: # if the name was not namespace-scoped, use the unqualified part name = name[1] else: # else try to restore the original prefix from the namespace name = self._current_context[name[0]] + ":" + name[1] self._out.write('<' + name) |
self._out.write(' %s=%s' % (name, quoteattr(value))) self._out.write('>') | self._write(' %s=%s' % (name, quoteattr(value))) self._write('>') | def startElementNS(self, name, qname, attrs): if name[0] is None: # if the name was not namespace-scoped, use the unqualified part name = name[1] else: # else try to restore the original prefix from the namespace name = self._current_context[name[0]] + ":" + name[1] self._out.write('<' + name) |
self._out.write('</%s>' % name) | self._write('</%s>' % name) | def endElementNS(self, name, qname): if name[0] is None: name = name[1] else: name = self._current_context[name[0]] + ":" + name[1] self._out.write('</%s>' % name) |
self._out.write(escape(content)) | self._write(escape(content)) | def characters(self, content): self._out.write(escape(content)) |
self._out.write(content) | self._write(content) | def ignorableWhitespace(self, content): self._out.write(content) |
self._out.write('<?%s %s?>' % (target, data)) | self._write('<?%s %s?>' % (target, data)) | def processingInstruction(self, target, data): self._out.write('<?%s %s?>' % (target, data)) |
raise TestFailed, 'zip() - no args, expected TypeError, got', e | raise TestFailed, 'zip() - no args, expected TypeError, got %s' % e | def __getitem__(self, i): if i < 0 or i > 2: raise IndexError return i + 4 |
raise TestFailed, 'zip(None) - expected TypeError, got', e | raise TestFailed, 'zip(None) - expected TypeError, got %s' % e | def __getitem__(self, i): if i < 0 or i > 2: raise IndexError return i + 4 |
next = self.index(mark + " lineend +1c") | next = self.index(mark + "+%d lines linestart" % lines_to_get) lines_to_get = min(lines_to_get * 2, 100) | def recolorize_main(self): next = "1.0" was_ok = is_ok = 0 while 1: item = self.tag_nextrange("TODO", next) if not item: break head, tail = item self.tag_remove("SYNC", head, tail) item = self.tag_prevrange("SYNC", head) if item: head = item[1] else: head = "1.0" |
for filename in self._built_objects: os.remove(filename) | try: for filename in self._built_objects: os.remove(filename) except AttributeError: self.announce('unable to remove files (ignored)') | def build_extension(self, ext): |
verify(C.__dynamic__ == 0) | verify(S.__dynamic__ == 0) | def dynamics(): if verbose: print "Testing __dynamic__..." verify(object.__dynamic__ == 0) verify(list.__dynamic__ == 0) class S1: __metaclass__ = type verify(S1.__dynamic__ == 0) class S(object): pass verify(C.__dynamic__ == 0) class D(object): __dynamic__ = 1 verify(D.__dynamic__ == 1) class E(D, S): pass verify(E.__dynamic__ == 1) class F(S, D): pass verify(F.__dynamic__ == 1) try: S.foo = 1 except (AttributeError, TypeError): pass else: verify(0, "assignment to a static class attribute should be illegal") D.foo = 1 verify(D.foo == 1) # Test that dynamic attributes are inherited verify(E.foo == 1) verify(F.foo == 1) class SS(D): __dynamic__ = 0 verify(SS.__dynamic__ == 0) verify(SS.foo == 1) try: SS.foo = 1 except (AttributeError, TypeError): pass else: verify(0, "assignment to SS.foo should be illegal") |
_sys.stderr.write("Exception in thread %s:\n%s\n" % (self.getName(), _format_exc())) | if _sys: _sys.stderr.write("Exception in thread %s:\n%s\n" % (self.getName(), _format_exc())) else: exc_type, exc_value, exc_tb = self.__exc_info() try: print>>self.__stderr, ( "Exception in thread " + self.getName() + " (most likely raised during interpreter shutdown):") print>>self.__stderr, ( "Traceback (most recent call last):") while exc_tb: print>>self.__stderr, ( ' File "%s", line %s, in %s' % (exc_tb.tb_frame.f_code.co_filename, exc_tb.tb_lineno, exc_tb.tb_frame.f_code.co_name)) exc_tb = exc_tb.tb_next print>>self.__stderr, ("%s: %s" % (exc_type, exc_value)) finally: del exc_type, exc_value, exc_tb | def __bootstrap(self): try: self.__started = True _active_limbo_lock.acquire() _active[_get_ident()] = self del _limbo[self] _active_limbo_lock.release() if __debug__: self._note("%s.__bootstrap(): thread started", self) |
def _show(title=None, message=None, icon=None, type=None, **options): if icon: options["icon"] = icon if type: options["type"] = type | def _show(title=None, message=None, _icon=None, _type=None, **options): if _icon and "icon" not in options: options["icon"] = _icon if _type and "type" not in options: options["type"] = _type | def _show(title=None, message=None, icon=None, type=None, **options): if icon: options["icon"] = icon if type: options["type"] = type if title: options["title"] = title if message: options["message"] = message res = Message(**options).show() # In some Tcl installations, Tcl converts yes/no into a boolean if isinstance(res, bool): if res: return YES return NO return res |
continuation_ws=' '): | continuation_ws=' ', errors='strict'): | def __init__(self, s=None, charset=None, maxlinelen=None, header_name=None, continuation_ws=' '): """Create a MIME-compliant header that can contain many character sets. |
self.append(s, charset) | self.append(s, charset, errors) | def __init__(self, s=None, charset=None, maxlinelen=None, header_name=None, continuation_ws=' '): """Create a MIME-compliant header that can contain many character sets. |
def append(self, s, charset=None): | def append(self, s, charset=None, errors='strict'): | def append(self, s, charset=None): """Append a string to the MIME header. |
ustr = unicode(s, incodec) | ustr = unicode(s, incodec, errors) | def append(self, s, charset=None): """Append a string to the MIME header. |
ustr.encode(outcodec) | ustr.encode(outcodec, errors) | def append(self, s, charset=None): """Append a string to the MIME header. |
s = s.encode(outcodec) | s = s.encode(outcodec, errors) | def append(self, s, charset=None): """Append a string to the MIME header. |
raise my_error, 'Protocol family not supported' | raise my_error, 'Protocol family %d not supported' % type | def socket(family, type, *which): if family <> AF_INET: raise my_error, 'Protocol family not supported' if type == SOCK_DGRAM: return _udpsocket() elif type == SOCK_STREAM: return _tcpsocket() raise my_error, 'Protocol type not supported' |
raise my_error, 'Protocol type not supported' | raise my_error, 'Protocol type %d not supported' % type | def socket(family, type, *which): if family <> AF_INET: raise my_error, 'Protocol family not supported' if type == SOCK_DGRAM: return _udpsocket() elif type == SOCK_STREAM: return _tcpsocket() raise my_error, 'Protocol type not supported' |
def accept(self, *args): | def unsupported(self, *args): | def accept(self, *args): raise my_error, 'Operation not supported on this socket' |
bind = accept close = accept connect = accept fileno = accept getpeername = accept getsockname = accept getsockopt = accept listen = accept recv = accept recvfrom = accept send = accept sendto = accept setblocking = accept setsockopt = accept shutdown = accept | accept = unsupported bind = unsupported close = unsupported connect = unsupported fileno = unsupported getpeername = unsupported getsockname = unsupported getsockopt = unsupported listen = unsupported recv = unsupported recvfrom = unsupported send = unsupported sendto = unsupported setblocking = unsupported setsockopt = unsupported shutdown = unsupported | def accept(self, *args): raise my_error, 'Operation not supported on this socket' |
def bind(self, host, port): | def bind(self, a1, a2=None): if a2 is None: host, port = a1 else: host, port = a1, a2 | def accept(self): if not self.listening: raise my_error, 'Not listening' self.listening = 0 self.stream.wait() self.accepted = 1 return self, self.getsockname() |
def connect(self, host, port): | def connect(self, a1, a2=None): if a2 is None: host, port = a1 else: host, port = a1, a2 | def close(self): if self.accepted: self.accepted = 0 return self.stream.Abort() |
def makefile(self, rw): return _socketfile(self) | def makefile(self, rw = 'r'): return _socketfile(self, rw) | def makefile(self, rw): return _socketfile(self) |
def __init__(self, sock): | def __init__(self, sock, rw): if rw not in ('r', 'w'): raise ValueError, "mode must be 'r' or 'w'" | def __init__(self, sock): self.sock = sock self.buf = '' |
def read(self, *arg): if arg: length = arg else: | def read(self, length = 0): if length <= 0: | def read(self, *arg): if arg: length = arg else: length = 0x7fffffff while len(self.buf) < length: new = self.sock.recv(0x7fffffff) if not new: break self.buf = self.buf + new rv = self.buf[:length] self.buf = self.buf[length:] return rv |
self.sock.send(buf) | BS = 512 if len(buf) >= BS: self.flush() self.sock.send(buf) elif len(buf) + len(self.buf) >= BS: self.flush() self.buf = buf else: self.buf = self.buf + buf def flush(self): if self.buf and self.rw == 'w': self.sock.send(self.buf) self.buf = '' | def write(self, buf): self.sock.send(buf) |
self.sock.close() | self.flush() | def close(self): self.sock.close() del self.sock |
self.finish_request(request, client_address) self.close_request(request) | try: self.finish_request(request, client_address) self.close_request(request) except: self.handle_error(request, client_address) self.close_request(request) | def process_request_thread(self, request, client_address): """Same as in BaseServer but as a thread.""" self.finish_request(request, client_address) self.close_request(request) |
err = PyMac_GetFullPathname(&_self->ob_itself, strbuf, sizeof(strbuf)); | err = _PyMac_GetFullPathname(&_self->ob_itself, strbuf, sizeof(strbuf)); | def parseArgumentList(self, args): args0, arg1, argsrest = args[:1], args[1], args[2:] t0, n0, m0 = arg1 args = args0 + argsrest if m0 != InMode: raise ValueError, "method's 'self' must be 'InMode'" self.itself = Variable(t0, "_self->ob_itself", SelfMode) FunctionGenerator.parseArgumentList(self, args) self.argumentList.insert(2, self.itself) |
eq(int(time.mktime(timetup)), 1044470846) | t = int(time.mktime(timetup)) eq(time.localtime(t)[:6], timetup[:6]) | def test_parsedate_acceptable_to_time_functions(self): eq = self.assertEqual timetup = Utils.parsedate('5 Feb 2003 13:47:26 -0800') eq(int(time.mktime(timetup)), 1044470846) eq(int(time.strftime('%Y', timetup)), 2003) timetup = Utils.parsedate_tz('5 Feb 2003 13:47:26 -0800') eq(int(time.mktime(timetup[:9])), 1044470846) eq(int(time.strftime('%Y', timetup[:9])), 2003) |
eq(int(time.mktime(timetup[:9])), 1044470846) | t = int(time.mktime(timetup[:9])) eq(time.localtime(t)[:6], timetup[:6]) | def test_parsedate_acceptable_to_time_functions(self): eq = self.assertEqual timetup = Utils.parsedate('5 Feb 2003 13:47:26 -0800') eq(int(time.mktime(timetup)), 1044470846) eq(int(time.strftime('%Y', timetup)), 2003) timetup = Utils.parsedate_tz('5 Feb 2003 13:47:26 -0800') eq(int(time.mktime(timetup[:9])), 1044470846) eq(int(time.strftime('%Y', timetup[:9])), 2003) |
func, targs, kargs = _exithandlers[-1] | func, targs, kargs = _exithandlers.pop() | def _run_exitfuncs(): """run any registered exit functions _exithandlers is traversed in reverse order so functions are executed last in, first out. """ while _exithandlers: func, targs, kargs = _exithandlers[-1] apply(func, targs, kargs) _exithandlers.remove(_exithandlers[-1]) |
_exithandlers.remove(_exithandlers[-1]) | def _run_exitfuncs(): """run any registered exit functions _exithandlers is traversed in reverse order so functions are executed last in, first out. """ while _exithandlers: func, targs, kargs = _exithandlers[-1] apply(func, targs, kargs) _exithandlers.remove(_exithandlers[-1]) |
|
real_ofp = ofp | def subconvert(line, ofp, table, discards, autoclosing, knownempty, endchar=None): stack = [] while line: if line[0] == endchar and not stack: return line[1:] m = _comment_rx.match(line) if m: text = m.group(1) if text: ofp.write("(COMMENT\n") ofp.write("-%s\n" % encode(text)) ofp.write(")COMMENT\n") ofp.write("-\\n\n") else: ofp.write("-\\n\n") line = line[m.end():] continue m = _begin_env_rx.match(line) if m: # re-write to use the macro handler line = r"\%s%s" % (m.group(1), line[m.end():]) continue m =_end_env_rx.match(line) if m: # end of environment envname = m.group(1) if envname == "document": # special magic for n in stack[1:]: if n not in autoclosing: raise LaTeXFormatError("open element on stack: " + `n`) # should be more careful, but this is easier to code: stack = [] ofp.write(")document\n") elif envname == stack[-1]: ofp.write(")%s\n" % envname) del stack[-1] else: |
|
if type(conversion) is type(""): line = "&%s;%s" % (conversion, line[m.end(1):]) continue | def subconvert(line, ofp, table, discards, autoclosing, knownempty, endchar=None): stack = [] while line: if line[0] == endchar and not stack: return line[1:] m = _comment_rx.match(line) if m: text = m.group(1) if text: ofp.write("(COMMENT\n") ofp.write("-%s\n" % encode(text)) ofp.write(")COMMENT\n") ofp.write("-\\n\n") else: ofp.write("-\\n\n") line = line[m.end():] continue m = _begin_env_rx.match(line) if m: # re-write to use the macro handler line = r"\%s%s" % (m.group(1), line[m.end():]) continue m =_end_env_rx.match(line) if m: # end of environment envname = m.group(1) if envname == "document": # special magic for n in stack[1:]: if n not in autoclosing: raise LaTeXFormatError("open element on stack: " + `n`) # should be more careful, but this is easier to code: stack = [] ofp.write(")document\n") elif envname == stack[-1]: ofp.write(")%s\n" % envname) del stack[-1] else: |
|
line = line[m.end() - 1:] | line = line[m.end(1):] elif empty: line = line[m.end(1):] | def subconvert(line, ofp, table, discards, autoclosing, knownempty, endchar=None): stack = [] while line: if line[0] == endchar and not stack: return line[1:] m = _comment_rx.match(line) if m: text = m.group(1) if text: ofp.write("(COMMENT\n") ofp.write("-%s\n" % encode(text)) ofp.write(")COMMENT\n") ofp.write("-\\n\n") else: ofp.write("-\\n\n") line = line[m.end():] continue m = _begin_env_rx.match(line) if m: # re-write to use the macro handler line = r"\%s%s" % (m.group(1), line[m.end():]) continue m =_end_env_rx.match(line) if m: # end of environment envname = m.group(1) if envname == "document": # special magic for n in stack[1:]: if n not in autoclosing: raise LaTeXFormatError("open element on stack: " + `n`) # should be more careful, but this is easier to code: stack = [] ofp.write(")document\n") elif envname == stack[-1]: ofp.write(")%s\n" % envname) del stack[-1] else: |
if type(conversion) is not type(""): ofp.write("(%s\n" % macroname) | ofp.write("(%s\n" % macroname) | def subconvert(line, ofp, table, discards, autoclosing, knownempty, endchar=None): stack = [] while line: if line[0] == endchar and not stack: return line[1:] m = _comment_rx.match(line) if m: text = m.group(1) if text: ofp.write("(COMMENT\n") ofp.write("-%s\n" % encode(text)) ofp.write(")COMMENT\n") ofp.write("-\\n\n") else: ofp.write("-\\n\n") line = line[m.end():] continue m = _begin_env_rx.match(line) if m: # re-write to use the macro handler line = r"\%s%s" % (m.group(1), line[m.end():]) continue m =_end_env_rx.match(line) if m: # end of environment envname = m.group(1) if envname == "document": # special magic for n in stack[1:]: if n not in autoclosing: raise LaTeXFormatError("open element on stack: " + `n`) # should be more careful, but this is easier to code: stack = [] ofp.write(")document\n") elif envname == stack[-1]: ofp.write(")%s\n" % envname) del stack[-1] else: |
return subconvert(ifp.read(), ofp, table, discards, autoclosing, d.has_key) | try: subconvert(ifp.read(), ofp, table, discards, autoclosing, d.has_key) except IOError, (err, msg): if err != errno.EPIPE: raise | def convert(ifp, ofp, table={}, discards=(), autoclosing=(), knownempties=()): d = {} for gi in knownempties: d[gi] = gi return subconvert(ifp.read(), ofp, table, discards, autoclosing, d.has_key) |
"ABC": "ABC", "ASCII": "ASCII", "C": "C", "Cpp": "Cpp", "EOF": "EOF", "e": "backslash", "ldots": "ldots", "NULL": "NULL", "POSIX": "POSIX", "UNIX": "Unix", | "ABC": ([], 0, 1), "ASCII": ([], 0, 1), "C": ([], 0, 1), "Cpp": ([], 0, 1), "EOF": ([], 0, 1), "e": ([], 0, 1), "ldots": ([], 0, 1), "NULL": ([], 0, 1), "POSIX": ([], 0, 1), "UNIX": ([], 0, 1), | def main(): if len(sys.argv) == 2: ifp = open(sys.argv[1]) ofp = sys.stdout elif len(sys.argv) == 3: ifp = open(sys.argv[1]) ofp = open(sys.argv[2], "w") else: usage() sys.exit(2) convert(ifp, ofp, { # entries are name # -> ([list of attribute names], first_is_optional, empty) "cfuncdesc": (["type", "name", ("args",)], 0, 0), "chapter": ([("title",)], 0, 0), "chapter*": ([("title",)], 0, 0), "classdesc": (["name", ("constructor-args",)], 0, 0), "ctypedesc": (["name"], 0, 0), "cvardesc": (["type", "name"], 0, 0), "datadesc": (["name"], 0, 0), "declaremodule": (["id", "type", "name"], 1, 1), "deprecated": (["release"], 0, 1), "documentclass": (["classname"], 0, 1), "excdesc": (["name"], 0, 0), "funcdesc": (["name", ("args",)], 0, 0), "funcdescni": (["name", ("args",)], 0, 0), "indexii": (["ie1", "ie2"], 0, 1), "indexiii": (["ie1", "ie2", "ie3"], 0, 1), "indexiv": (["ie1", "ie2", "ie3", "ie4"], 0, 1), "input": (["source"], 0, 1), "item": ([("leader",)], 1, 0), "label": (["id"], 0, 1), "manpage": (["name", "section"], 0, 1), "memberdesc": (["class", "name"], 1, 0), "methoddesc": (["class", "name", ("args",)], 1, 0), "methoddescni": (["class", "name", ("args",)], 1, 0), "opcodedesc": (["name", "var"], 0, 0), "par": ([], 0, 1), "rfc": (["number"], 0, 1), "section": ([("title",)], 0, 0), "seemodule": (["ref", "name"], 1, 0), "tableii": (["colspec", "style", "head1", "head2"], 0, 0), "tableiii": (["colspec", "style", "head1", "head2", "head3"], 0, 0), "tableiv": (["colspec", "style", "head1", "head2", "head3", "head4"], 0, 0), "versionadded": (["version"], 0, 1), "versionchanged": (["version"], 0, 1), # "ABC": "ABC", "ASCII": "ASCII", "C": "C", "Cpp": "Cpp", "EOF": "EOF", "e": "backslash", "ldots": "ldots", "NULL": "NULL", "POSIX": "POSIX", "UNIX": "Unix", # # Things that will actually be going away! # "fi": ([], 0, 1), "ifhtml": ([], 0, 1), "makeindex": ([], 0, 1), "makemodindex": ([], 0, 1), "maketitle": ([], 0, 1), "noindent": ([], 0, 1), "tableofcontents": ([], 0, 1), }, discards=["fi", "ifhtml", "makeindex", "makemodindex", "maketitle", "noindent", "tableofcontents"], autoclosing=["chapter", "section", "subsection", "subsubsection", "paragraph", "subparagraph", ], knownempties=["rfc", "declaremodule", "appendix", "maketitle", "makeindex", "makemodindex", "localmoduletable", "manpage", "input"]) |
knownempties=["rfc", "declaremodule", "appendix", | knownempties=["appendix", | def main(): if len(sys.argv) == 2: ifp = open(sys.argv[1]) ofp = sys.stdout elif len(sys.argv) == 3: ifp = open(sys.argv[1]) ofp = open(sys.argv[2], "w") else: usage() sys.exit(2) convert(ifp, ofp, { # entries are name # -> ([list of attribute names], first_is_optional, empty) "cfuncdesc": (["type", "name", ("args",)], 0, 0), "chapter": ([("title",)], 0, 0), "chapter*": ([("title",)], 0, 0), "classdesc": (["name", ("constructor-args",)], 0, 0), "ctypedesc": (["name"], 0, 0), "cvardesc": (["type", "name"], 0, 0), "datadesc": (["name"], 0, 0), "declaremodule": (["id", "type", "name"], 1, 1), "deprecated": (["release"], 0, 1), "documentclass": (["classname"], 0, 1), "excdesc": (["name"], 0, 0), "funcdesc": (["name", ("args",)], 0, 0), "funcdescni": (["name", ("args",)], 0, 0), "indexii": (["ie1", "ie2"], 0, 1), "indexiii": (["ie1", "ie2", "ie3"], 0, 1), "indexiv": (["ie1", "ie2", "ie3", "ie4"], 0, 1), "input": (["source"], 0, 1), "item": ([("leader",)], 1, 0), "label": (["id"], 0, 1), "manpage": (["name", "section"], 0, 1), "memberdesc": (["class", "name"], 1, 0), "methoddesc": (["class", "name", ("args",)], 1, 0), "methoddescni": (["class", "name", ("args",)], 1, 0), "opcodedesc": (["name", "var"], 0, 0), "par": ([], 0, 1), "rfc": (["number"], 0, 1), "section": ([("title",)], 0, 0), "seemodule": (["ref", "name"], 1, 0), "tableii": (["colspec", "style", "head1", "head2"], 0, 0), "tableiii": (["colspec", "style", "head1", "head2", "head3"], 0, 0), "tableiv": (["colspec", "style", "head1", "head2", "head3", "head4"], 0, 0), "versionadded": (["version"], 0, 1), "versionchanged": (["version"], 0, 1), # "ABC": "ABC", "ASCII": "ASCII", "C": "C", "Cpp": "Cpp", "EOF": "EOF", "e": "backslash", "ldots": "ldots", "NULL": "NULL", "POSIX": "POSIX", "UNIX": "Unix", # # Things that will actually be going away! # "fi": ([], 0, 1), "ifhtml": ([], 0, 1), "makeindex": ([], 0, 1), "makemodindex": ([], 0, 1), "maketitle": ([], 0, 1), "noindent": ([], 0, 1), "tableofcontents": ([], 0, 1), }, discards=["fi", "ifhtml", "makeindex", "makemodindex", "maketitle", "noindent", "tableofcontents"], autoclosing=["chapter", "section", "subsection", "subsubsection", "paragraph", "subparagraph", ], knownempties=["rfc", "declaremodule", "appendix", "maketitle", "makeindex", "makemodindex", "localmoduletable", "manpage", "input"]) |
"localmoduletable", "manpage", "input"]) | "localmoduletable"]) | def main(): if len(sys.argv) == 2: ifp = open(sys.argv[1]) ofp = sys.stdout elif len(sys.argv) == 3: ifp = open(sys.argv[1]) ofp = open(sys.argv[2], "w") else: usage() sys.exit(2) convert(ifp, ofp, { # entries are name # -> ([list of attribute names], first_is_optional, empty) "cfuncdesc": (["type", "name", ("args",)], 0, 0), "chapter": ([("title",)], 0, 0), "chapter*": ([("title",)], 0, 0), "classdesc": (["name", ("constructor-args",)], 0, 0), "ctypedesc": (["name"], 0, 0), "cvardesc": (["type", "name"], 0, 0), "datadesc": (["name"], 0, 0), "declaremodule": (["id", "type", "name"], 1, 1), "deprecated": (["release"], 0, 1), "documentclass": (["classname"], 0, 1), "excdesc": (["name"], 0, 0), "funcdesc": (["name", ("args",)], 0, 0), "funcdescni": (["name", ("args",)], 0, 0), "indexii": (["ie1", "ie2"], 0, 1), "indexiii": (["ie1", "ie2", "ie3"], 0, 1), "indexiv": (["ie1", "ie2", "ie3", "ie4"], 0, 1), "input": (["source"], 0, 1), "item": ([("leader",)], 1, 0), "label": (["id"], 0, 1), "manpage": (["name", "section"], 0, 1), "memberdesc": (["class", "name"], 1, 0), "methoddesc": (["class", "name", ("args",)], 1, 0), "methoddescni": (["class", "name", ("args",)], 1, 0), "opcodedesc": (["name", "var"], 0, 0), "par": ([], 0, 1), "rfc": (["number"], 0, 1), "section": ([("title",)], 0, 0), "seemodule": (["ref", "name"], 1, 0), "tableii": (["colspec", "style", "head1", "head2"], 0, 0), "tableiii": (["colspec", "style", "head1", "head2", "head3"], 0, 0), "tableiv": (["colspec", "style", "head1", "head2", "head3", "head4"], 0, 0), "versionadded": (["version"], 0, 1), "versionchanged": (["version"], 0, 1), # "ABC": "ABC", "ASCII": "ASCII", "C": "C", "Cpp": "Cpp", "EOF": "EOF", "e": "backslash", "ldots": "ldots", "NULL": "NULL", "POSIX": "POSIX", "UNIX": "Unix", # # Things that will actually be going away! # "fi": ([], 0, 1), "ifhtml": ([], 0, 1), "makeindex": ([], 0, 1), "makemodindex": ([], 0, 1), "maketitle": ([], 0, 1), "noindent": ([], 0, 1), "tableofcontents": ([], 0, 1), }, discards=["fi", "ifhtml", "makeindex", "makemodindex", "maketitle", "noindent", "tableofcontents"], autoclosing=["chapter", "section", "subsection", "subsubsection", "paragraph", "subparagraph", ], knownempties=["rfc", "declaremodule", "appendix", "maketitle", "makeindex", "makemodindex", "localmoduletable", "manpage", "input"]) |
auth = base64.encodestring(auth) | auth = base64.encodestring(urllib.unquote(auth)) | def get_host_info(self, host): |
__version__ = "1.0b2" | __version__ = "1.0b3" | def _stringify(string): return string |
class Error: | class Error(Exception): | def _stringify(string): return string |
self.fail("Error testing host resolution mechanisms.") | self.fail("Error testing host resolution mechanisms. (fqdn: %s, all: %s)" % (fqdn, repr(all_host_names))) | def testHostnameRes(self): # Testing hostname resolution mechanisms hostname = socket.gethostname() try: ip = socket.gethostbyname(hostname) except socket.error: # Probably name lookup wasn't set up right; skip this test return self.assert_(ip.find('.') >= 0, "Error resolving host to ip.") try: hname, aliases, ipaddrs = socket.gethostbyaddr(ip) except socket.error: # Probably a similar problem as above; skip this test return all_host_names = [hostname, hname] + aliases fqhn = socket.getfqdn() if not fqhn in all_host_names: self.fail("Error testing host resolution mechanisms.") |
e.append(fd) if obj.readable(): | is_r = obj.readable() is_w = obj.writable() if is_r: | def poll(timeout=0.0, map=None): if map is None: map = socket_map if map: r = []; w = []; e = [] for fd, obj in map.items(): e.append(fd) if obj.readable(): r.append(fd) if obj.writable(): w.append(fd) if [] == r == w == e: time.sleep(timeout) else: try: r, w, e = select.select(r, w, e, timeout) except select.error, err: if err[0] != EINTR: raise else: return for fd in r: obj = map.get(fd) if obj is None: continue read(obj) for fd in w: obj = map.get(fd) if obj is None: continue write(obj) for fd in e: obj = map.get(fd) if obj is None: continue _exception(obj) |
if obj.writable(): | if is_w: | def poll(timeout=0.0, map=None): if map is None: map = socket_map if map: r = []; w = []; e = [] for fd, obj in map.items(): e.append(fd) if obj.readable(): r.append(fd) if obj.writable(): w.append(fd) if [] == r == w == e: time.sleep(timeout) else: try: r, w, e = select.select(r, w, e, timeout) except select.error, err: if err[0] != EINTR: raise else: return for fd in r: obj = map.get(fd) if obj is None: continue read(obj) for fd in w: obj = map.get(fd) if obj is None: continue write(obj) for fd in e: obj = map.get(fd) if obj is None: continue _exception(obj) |
flags = select.POLLERR | select.POLLHUP | select.POLLNVAL | flags = 0 | def poll2(timeout=0.0, map=None): # Use the poll() support added to the select module in Python 2.0 if map is None: map = socket_map if timeout is not None: # timeout is in milliseconds timeout = int(timeout*1000) pollster = select.poll() if map: for fd, obj in map.items(): flags = select.POLLERR | select.POLLHUP | select.POLLNVAL if obj.readable(): flags |= select.POLLIN | select.POLLPRI if obj.writable(): flags |= select.POLLOUT if flags: pollster.register(fd, flags) try: r = pollster.poll(timeout) except select.error, err: if err[0] != EINTR: raise r = [] for fd, flags in r: obj = map.get(fd) if obj is None: continue readwrite(obj, flags) |
def buffer_inherit(): import binascii if verbose: print "Testing that buffer interface is inherited ..." class MyStr(str): pass base = 'abc' m = MyStr(base) vereq(binascii.b2a_hex(m), binascii.b2a_hex(base)) class MyUni(unicode): pass base = u'abc' m = MyUni(base) vereq(binascii.b2a_hex(m), binascii.b2a_hex(base)) class MyInt(int): pass m = MyInt(42) try: binascii.b2a_hex(m) raise TestFailed('subclass of int should not have a buffer interface') except TypeError: pass | def __getattr__(self, name): if name in ("spam", "foo", "bar"): return "hello" raise AttributeError, name |
|
if completekey: try: import readline readline.set_completer(self.complete) readline.parse_and_bind(completekey+": complete") except ImportError: pass | self.completekey = completekey | def __init__(self, completekey='tab'): """Instantiate a line-oriented interpreter framework. |
pass | if self.completekey: try: import readline self.old_completer = readline.get_completer() readline.set_completer(self.complete) readline.parse_and_bind(self.completekey+": complete") except ImportError: pass | def preloop(self): """Hook method executed once when the cmdloop() method is called.""" pass |
pass | if self.completekey: try: import readline readline.set_completer(self.old_completer) except ImportError: pass | def postloop(self): """Hook method executed once when the cmdloop() method is about to return. |
def add_suffix(self, suffix, importer): assert isinstance(importer, SuffixImporter) self.suffixes.append((suffix, importer)) | def add_suffix(self, suffix, importFunc): assert callable(importFunc) self.fs_imp.add_suffix(suffix, importFunc) | def add_suffix(self, suffix, importer): assert isinstance(importer, SuffixImporter) self.suffixes.append((suffix, importer)) |
def __init__(self): | clsFilesystemImporter = None def __init__(self, fs_imp=None): | def __init__(self): # we're definitely going to be importing something in the future, # so let's just load the OS-related facilities. if not _os_stat: _os_bootstrap() |
self.suffixes = [ ] | def __init__(self): # we're definitely going to be importing something in the future, # so let's just load the OS-related facilities. if not _os_stat: _os_bootstrap() |
|
self.suffixes.append((desc[0], DynLoadSuffixImporter(desc))) self.suffixes.append(('.py', PySuffixImporter())) self.fs_imp = _FilesystemImporter(self.suffixes) | self.add_suffix(desc[0], DynLoadSuffixImporter(desc).import_file) self.add_suffix('.py', py_suffix_importer) | def __init__(self): # we're definitely going to be importing something in the future, # so let's just load the OS-related facilities. if not _os_stat: _os_bootstrap() |
def install(self): sys.path.insert(0, self) | def install(self): sys.path.insert(0, self) |
|
if len(result) == 2: result = result + ({},) | def _import_one(self, parent, modname, fqname): "Import a single module." |
|
def __init__(self, suffixes): self.suffixes = suffixes | def __init__(self): self.suffixes = [ ] def add_suffix(self, suffix, importFunc): assert callable(importFunc) self.suffixes.append((suffix, importFunc)) | def __init__(self, suffixes): # this list is shared with the ImportManager. self.suffixes = suffixes |
for suffix, importer in self.suffixes: | for suffix, importFunc in self.suffixes: | def _import_pathname(self, pathname, fqname): if _os_path_isdir(pathname): result = self._import_pathname(_os_path_join(pathname, '__init__'), fqname) if result: values = result[2] values['__pkgdir__'] = pathname values['__path__'] = [ pathname ] return 1, result[1], values return None |
return importer.import_file(filename, finfo, fqname) | return importFunc(filename, finfo, fqname) | def _import_pathname(self, pathname, fqname): if _os_path_isdir(pathname): result = self._import_pathname(_os_path_join(pathname, '__init__'), fqname) if result: values = result[2] values['__pkgdir__'] = pathname values['__path__'] = [ pathname ] return 1, result[1], values return None |
class SuffixImporter: def import_file(self, filename, finfo, fqname): raise RuntimeError class PySuffixImporter(SuffixImporter): def import_file(self, filename, finfo, fqname): file = filename[:-3] + _suffix t_py = long(finfo[8]) t_pyc = _timestamp(file) code = None if t_pyc is not None and t_pyc >= t_py: f = open(file, 'rb') if f.read(4) == imp.get_magic(): t = struct.unpack('<I', f.read(4))[0] if t == t_py: code = marshal.load(f) f.close() if code is None: file = filename code = _compile(file, t_py) return 0, code, { '__file__' : file } class DynLoadSuffixImporter(SuffixImporter): | def py_suffix_importer(filename, finfo, fqname): file = filename[:-3] + _suffix t_py = long(finfo[8]) t_pyc = _timestamp(file) code = None if t_pyc is not None and t_pyc >= t_py: f = open(file, 'rb') if f.read(4) == imp.get_magic(): t = struct.unpack('<I', f.read(4))[0] if t == t_py: code = marshal.load(f) f.close() if code is None: file = filename code = _compile(file, t_py) return 0, code, { '__file__' : file } class DynLoadSuffixImporter: | def _import_pathname(self, pathname, fqname): if _os_path_isdir(pathname): result = self._import_pathname(_os_path_join(pathname, '__init__'), fqname) if result: values = result[2] values['__pkgdir__'] = pathname values['__path__'] = [ pathname ] return 1, result[1], values return None |
self.assertTrue(data.endswith('\n')) | self.assertTrue(data == '' or data.endswith('\n')) | def verify_valid_flag(self, cmd_line): data = self.start_python(cmd_line) self.assertTrue(data.endswith('\n')) self.assertTrue('Traceback' not in data) |
self.assertRaises(ValueError, msg.get_content_maintype) | self.assertEqual(msg.get_content_maintype(), 'text') | def test_get_content_maintype_error(self): msg = Message() msg['Content-Type'] = 'no-slash-in-this-string' self.assertRaises(ValueError, msg.get_content_maintype) |
self.assertRaises(ValueError, msg.get_content_subtype) | self.assertEqual(msg.get_content_subtype(), 'plain') | def test_get_content_subtype_error(self): msg = Message() msg['Content-Type'] = 'no-slash-in-this-string' self.assertRaises(ValueError, msg.get_content_subtype) |
print "found", `title[start:m.end()]` | def clean_title(title): title = raisebox_rx.sub("", title) title = hackscore_rx.sub(r"\\_", title) pos = 0 while 1: m = title_rx.search(title, pos) if m: start = m.start() print "found", `title[start:m.end()]` if title[start:start+15] != "\\textunderscore": title = title[:start] + title[m.end():] pos = start + 1 else: break title = string.translate(title, title_trans, "{}") print `title` return title |
|
print `title` | def clean_title(title): title = raisebox_rx.sub("", title) title = hackscore_rx.sub(r"\\_", title) pos = 0 while 1: m = title_rx.search(title, pos) if m: start = m.start() print "found", `title[start:m.end()]` if title[start:start+15] != "\\textunderscore": title = title[:start] + title[m.end():] pos = start + 1 else: break title = string.translate(title, title_trans, "{}") print `title` return title |
|
if sys.platform.startswith("win"): lookfor = " denied" | if sys.platform == 'win32': expected_exit_code = 2 | def test_directories(self): # Does this test make sense? The message for "< ." may depend on # the command shell, and the message for "." depends on the OS. if sys.platform.startswith("win"): # On WinXP w/ cmd.exe, # "< ." gives "Access is denied.\n" # "." gives "C:\\Code\\python\\PCbuild\\python.exe: " + # "can't open file '.':" + # "[Errno 13] Permission denied\n" lookfor = " denied" # common to both cases else: # This is what the test looked for originally, on all platforms. lookfor = "is a directory" self.assertTrue(lookfor in self.start_python('.')) self.assertTrue(lookfor in self.start_python('< .')) |
lookfor = "is a directory" self.assertTrue(lookfor in self.start_python('.')) self.assertTrue(lookfor in self.start_python('< .')) | expected_exit_code = 0 self.assertEqual(self.exit_code('.'), expected_exit_code) self.assertTrue(self.exit_code('< .') != 0) | def test_directories(self): # Does this test make sense? The message for "< ." may depend on # the command shell, and the message for "." depends on the OS. if sys.platform.startswith("win"): # On WinXP w/ cmd.exe, # "< ." gives "Access is denied.\n" # "." gives "C:\\Code\\python\\PCbuild\\python.exe: " + # "can't open file '.':" + # "[Errno 13] Permission denied\n" lookfor = " denied" # common to both cases else: # This is what the test looked for originally, on all platforms. lookfor = "is a directory" self.assertTrue(lookfor in self.start_python('.')) self.assertTrue(lookfor in self.start_python('< .')) |
if os.path.isdir(dir) and dir not in dirlist: | if dir is not None and os.path.isdir(dir) and dir not in dirlist: | def add_dir_to_list(dirlist, dir): """Add the directory 'dir' to the list 'dirlist' (at the front) if 1) 'dir' is not already in 'dirlist' 2) 'dir' actually exists, and is a directory.""" if os.path.isdir(dir) and dir not in dirlist: dirlist.insert(0, dir) |
if platform == 'darwin': | if platform in ('darwin', 'mac'): | def build_extensions(self): |
input = text_file.TextFile('Modules/Setup', join_lines=1) remove_modules = [] while 1: line = input.readline() if not line: break line = line.split() remove_modules.append( line[0] ) input.close() for ext in self.extensions[:]: if ext.name in remove_modules: self.extensions.remove(ext) | if platform != 'mac': input = text_file.TextFile('Modules/Setup', join_lines=1) remove_modules = [] while 1: line = input.readline() if not line: break line = line.split() remove_modules.append( line[0] ) input.close() for ext in self.extensions[:]: if ext.name in remove_modules: self.extensions.remove(ext) | def build_extensions(self): |
if platform in ['darwin', 'beos']: | if platform in ['darwin', 'beos', 'mac']: | def detect_modules(self): # Ensure that /usr/local is always used add_dir_to_list(self.compiler.library_dirs, '/usr/local/lib') add_dir_to_list(self.compiler.include_dirs, '/usr/local/include') |
By default, the diff control lines (those with *** or ---) are | By default, the diff control lines (those with ---, +++, or @@) are | def unified_diff(a, b, fromfile='', tofile='', fromfiledate='', tofiledate='', n=3, lineterm='\n'): r""" Compare two sequences of lines; generate the delta as a unified diff. Unified diffs are a compact way of showing line changes and a few lines of context. The number of context lines is set by 'n' which defaults to three. By default, the diff control lines (those with *** or ---) are created with a trailing newline. This is helpful so that inputs created from file.readlines() result in diffs that are suitable for file.writelines() since both the inputs and outputs have trailing newlines. For inputs that do not have trailing newlines, set the lineterm argument to "" so that the output will be uniformly newline free. The unidiff format normally has a header for filenames and modification times. Any or all of these may be specified using strings for 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'. The modification times are normally expressed in the format returned by time.ctime(). Example: >>> for line in unified_diff('one two three four'.split(), ... 'zero one tree four'.split(), 'Original', 'Current', ... 'Sat Jan 26 23:30:50 1991', 'Fri Jun 06 10:20:52 2003', ... lineterm=''): ... print line --- Original Sat Jan 26 23:30:50 1991 +++ Current Fri Jun 06 10:20:52 2003 @@ -1,4 +1,4 @@ +zero one -two -three +tree four """ started = False for group in SequenceMatcher(None,a,b).get_grouped_opcodes(n): if not started: yield '--- %s %s%s' % (fromfile, fromfiledate, lineterm) yield '+++ %s %s%s' % (tofile, tofiledate, lineterm) started = True i1, i2, j1, j2 = group[0][1], group[-1][2], group[0][3], group[-1][4] yield "@@ -%d,%d +%d,%d @@%s" % (i1+1, i2-i1, j1+1, j2-j1, lineterm) for tag, i1, i2, j1, j2 in group: if tag == 'equal': for line in a[i1:i2]: yield ' ' + line continue if tag == 'replace' or tag == 'delete': for line in a[i1:i2]: yield '-' + line if tag == 'replace' or tag == 'insert': for line in b[j1:j2]: yield '+' + line |
return bool() | return bool(self._table.optimized & (OPT_EXEC | OPT_BARE_EXEC)) def has_import_star(self): """Return true if the scope uses import *""" return bool(self._table.optimized & OPT_IMPORT_STAR) | def has_exec(self): return bool() |
return bool(self.flag & DEF_STAR) | return bool(self.__flags & DEF_STAR) | def is_vararg(self): return bool(self.flag & DEF_STAR) |
return bool(self.__flags & DEF_STARSTAR) | return bool(self.__flags & DEF_DOUBLESTAR) | def is_keywordarg(self): return bool(self.__flags & DEF_STARSTAR) |
('dbserv2.theopalgroup.com', '/mediumfile'), ('dbserv2.theopalgroup.com', '/smallfile'), | def test(): """Test this module. A hodge podge of tests collected here, because they have too many external dependencies for the regular test suite. """ import sys import getopt opts, args = getopt.getopt(sys.argv[1:], 'd') dl = 0 for o, a in opts: if o == '-d': dl = dl + 1 host = 'www.python.org' selector = '/' if args[0:]: host = args[0] if args[1:]: selector = args[1] h = HTTP() h.set_debuglevel(dl) h.connect(host) h.putrequest('GET', selector) h.endheaders() status, reason, headers = h.getreply() print 'status =', status print 'reason =', reason print "read", len(h.getfile().read()) print if headers: for header in headers.headers: print header.strip() print # minimal test that code to extract host from url works class HTTP11(HTTP): _http_vsn = 11 _http_vsn_str = 'HTTP/1.1' h = HTTP11('www.python.org') h.putrequest('GET', 'http://www.python.org/~jeremy/') h.endheaders() h.getreply() h.close() if hasattr(socket, 'ssl'): for host, selector in (('sourceforge.net', '/projects/python'), ('dbserv2.theopalgroup.com', '/mediumfile'), ('dbserv2.theopalgroup.com', '/smallfile'), ): print "https://%s%s" % (host, selector) hs = HTTPS() hs.set_debuglevel(dl) hs.connect(host) hs.putrequest('GET', selector) hs.endheaders() status, reason, headers = hs.getreply() print 'status =', status print 'reason =', reason print "read", len(hs.getfile().read()) print if headers: for header in headers.headers: print header.strip() print # Test a buggy server -- returns garbled status line. # http://www.yahoo.com/promotions/mom_com97/supermom.html c = HTTPConnection("promotions.yahoo.com") c.set_debuglevel(1) c.connect() c.request("GET", "/promotions/mom_com97/supermom.html") r = c.getresponse() print r.status, r.version lines = r.read().split("\n") print "\n".join(lines[:5]) c = HTTPConnection("promotions.yahoo.com", strict=1) c.set_debuglevel(1) c.connect() c.request("GET", "/promotions/mom_com97/supermom.html") try: r = c.getresponse() except BadStatusLine, err: print "strict mode failed as expected" print err else: print "XXX strict mode should have failed" for strict in 0, 1: h = HTTP(strict=strict) h.connect("promotions.yahoo.com") h.putrequest('GET', "/promotions/mom_com97/supermom.html") h.endheaders() status, reason, headers = h.getreply() assert (strict and status == -1) or status == 200, (strict, status) |
|
c = HTTPConnection("promotions.yahoo.com") c.set_debuglevel(1) c.connect() c.request("GET", "/promotions/mom_com97/supermom.html") r = c.getresponse() print r.status, r.version lines = r.read().split("\n") print "\n".join(lines[:5]) c = HTTPConnection("promotions.yahoo.com", strict=1) c.set_debuglevel(1) c.connect() c.request("GET", "/promotions/mom_com97/supermom.html") try: r = c.getresponse() except BadStatusLine, err: print "strict mode failed as expected" print err else: print "XXX strict mode should have failed" for strict in 0, 1: h = HTTP(strict=strict) h.connect("promotions.yahoo.com") h.putrequest('GET', "/promotions/mom_com97/supermom.html") h.endheaders() status, reason, headers = h.getreply() assert (strict and status == -1) or status == 200, (strict, status) | def test(): """Test this module. A hodge podge of tests collected here, because they have too many external dependencies for the regular test suite. """ import sys import getopt opts, args = getopt.getopt(sys.argv[1:], 'd') dl = 0 for o, a in opts: if o == '-d': dl = dl + 1 host = 'www.python.org' selector = '/' if args[0:]: host = args[0] if args[1:]: selector = args[1] h = HTTP() h.set_debuglevel(dl) h.connect(host) h.putrequest('GET', selector) h.endheaders() status, reason, headers = h.getreply() print 'status =', status print 'reason =', reason print "read", len(h.getfile().read()) print if headers: for header in headers.headers: print header.strip() print # minimal test that code to extract host from url works class HTTP11(HTTP): _http_vsn = 11 _http_vsn_str = 'HTTP/1.1' h = HTTP11('www.python.org') h.putrequest('GET', 'http://www.python.org/~jeremy/') h.endheaders() h.getreply() h.close() if hasattr(socket, 'ssl'): for host, selector in (('sourceforge.net', '/projects/python'), ('dbserv2.theopalgroup.com', '/mediumfile'), ('dbserv2.theopalgroup.com', '/smallfile'), ): print "https://%s%s" % (host, selector) hs = HTTPS() hs.set_debuglevel(dl) hs.connect(host) hs.putrequest('GET', selector) hs.endheaders() status, reason, headers = hs.getreply() print 'status =', status print 'reason =', reason print "read", len(hs.getfile().read()) print if headers: for header in headers.headers: print header.strip() print # Test a buggy server -- returns garbled status line. # http://www.yahoo.com/promotions/mom_com97/supermom.html c = HTTPConnection("promotions.yahoo.com") c.set_debuglevel(1) c.connect() c.request("GET", "/promotions/mom_com97/supermom.html") r = c.getresponse() print r.status, r.version lines = r.read().split("\n") print "\n".join(lines[:5]) c = HTTPConnection("promotions.yahoo.com", strict=1) c.set_debuglevel(1) c.connect() c.request("GET", "/promotions/mom_com97/supermom.html") try: r = c.getresponse() except BadStatusLine, err: print "strict mode failed as expected" print err else: print "XXX strict mode should have failed" for strict in 0, 1: h = HTTP(strict=strict) h.connect("promotions.yahoo.com") h.putrequest('GET', "/promotions/mom_com97/supermom.html") h.endheaders() status, reason, headers = h.getreply() assert (strict and status == -1) or status == 200, (strict, status) |
|
self.draw.bind(fred, "<Any-Enter>", self.mouseEnter) self.draw.bind(fred, "<Any-Leave>", self.mouseLeave) | self.draw.tag_bind(fred, "<Any-Enter>", self.mouseEnter) self.draw.tag_bind(fred, "<Any-Leave>", self.mouseLeave) | def createWidgets(self): |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.