rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
if flags & select.POLLIN:
if flags & (select.POLLIN | select.POLLPRI):
def readwrite(obj, flags): try: if flags & select.POLLIN: obj.handle_read_event() if flags & select.POLLOUT: obj.handle_write_event() except ExitNow: raise except: obj.handle_error()
self.putsequences()
self.putsequences(sequences)
def removefromallsequences(self, list): if hasattr(self, 'last') and self.last in list: del self.last sequences = self.getsequences() changed = 0 for name, seq in sequences.items(): for n in list: if n in seq: seq.remove(n) changed = 1 if not seq: del sequences[name] if changed: self.putsequences()
import saxutils
from . import saxutils
def parse(self, source): import saxutils source = saxutils.prepare_input_source(source)
"unsupported format character '\000' (0x3000) at index 5")
"unsupported format character '?' (0x3000) at index 5")
def test_exc(formatstr, args, exception, excmsg): try: testformat(formatstr, args) except exception, exc: if str(exc) == excmsg: if verbose: print "yes" else: if verbose: print 'no' print 'Unexpected ', exception, ':', repr(str(exc)) except: if verbose: print 'no' print 'Unexpected exception' raise
flags = 0
flags = select.POLLERR | select.POLLHUP | select.POLLNVAL
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 = 0 if obj.readable(): flags = select.P...
flags = select.POLLIN
flags = select.POLLIN | select.POLLPRI
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 = 0 if obj.readable(): flags = select.P...
def rewind(self):
def reopen(self):
def rewind(self): self.fp.seek(0) x = self.initfp(self.fp, self.filename)
def getnextframedata(self, (size, chromsize)):
def getnextframedata(self, size, chromsize):
def getnextframedata(self, (size, chromsize)): if self.hascache: self.position() self.frameno = self.frameno + 1 data = self.fp.read(size) if len(data) <> size: raise EOFError if chromsize: chromdata = self.fp.read(chromsize) if len(chromdata) <> chromsize: raise EOFError else: chromdata = None # return data, chromdata
def skipnextframedata(self, (size, chromsize)):
def skipnextframedata(self, size, chromsize):
def skipnextframedata(self, (size, chromsize)): if self.hascache: self.frameno = self.frameno + 1 return # Note that this won't raise EOFError for a partial frame. try: self.fp.seek(size + chromsize, 1) # Relative seek except: # Assume it's a pipe -- read the data to discard it dummy = self.fp.read(size + chromsize)
def showframe(self, (data, chromdata)):
def showframe(self, data, chromdata):
def showframe(self, (data, chromdata)): w, h, pf = self.width, self.height, self.packfactor if not self.colormapinited: self.initcolormap() factor = self.magnify if pf: factor = factor * pf if chromdata and not self.skipchrom: cp = self.chrompack cw = (w+cp-1)/cp ch = (h+cp-1)/cp gl.rectzoom(factor*cp, factor*cp) gl.pi...
sys.stderr.write('Initializing color map...')
if not self.quiet: sys.stderr.write('Initializing color map...')
def initcolormap(self): self.colormapinited = 1 if self.format == 'rgb': gl.RGBmode() gl.gconfig() return gl.cmode() gl.gconfig() self.skipchrom = 0 sys.stderr.write('Initializing color map...') self.initcmap() sys.stderr.write(' Done.\n') if self.offset == 0: gl.color(0x800) gl.clear() self.mask = 0x7ff else: self.mas...
sys.stderr.write(' Done.\n')
if not self.quiet: sys.stderr.write(' Done.\n')
def initcolormap(self): self.colormapinited = 1 if self.format == 'rgb': gl.RGBmode() gl.gconfig() return gl.cmode() gl.gconfig() self.skipchrom = 0 sys.stderr.write('Initializing color map...') self.initcmap() sys.stderr.write(' Done.\n') if self.offset == 0: gl.color(0x800) gl.clear() self.mask = 0x7ff else: self.mas...
data = ('grey', 0)
data = ('grey', self.c0bits)
def writeheader(self): self.headerwritten = 1 if self.format == 'rgb': self.packfactor = 0 elif self.packfactor == 0: self.packfactor = 1 self.fp.write('CMIF video 3.0\n') if self.format == 'rgb': data = ('rgb', 0) elif self.format == 'grey': data = ('grey', 0) else: data = (self.format, (self.c0bits, self.c1bits, \ se...
variable=self.__hexp)
variable=self.__hexp, command=self.__togglehex)
def __init__(self, switchboard, parent=None): # non-gui ivars self.__sb = switchboard self.__hexp = BooleanVar() self.__uwtyping = BooleanVar() # create the gui self.__frame = Frame(parent, relief=GROOVE, borderwidth=2) self.__frame.pack(side=RIGHT) # Red self.__xl = Label(self.__frame, text='Red:') self.__xl.grid(row=...
contents = contents[:-1]
i = ew.index(INSERT) contents = contents[:i-1] + contents[i:]
def __normalize(self, event=None): ew = event.widget contents = ew.get() if contents == '': contents = '0' # figure out what the contents value is in the current base try: if self.__hexp.get(): v = string.atoi(contents, 16) else: v = string.atoi(contents) except ValueError: v = None # if value is not legal, delete the ...
def pickle(ob_type, pickle_function, constructor_ob = None):
def pickle(ob_type, pickle_function, constructor_ob=None): if type(ob_type) is _ClassType: raise TypeError("copy_reg is not intended for use with classes") if not callable(pickle_function): raise TypeError("reduction functions must be callable")
def pickle(ob_type, pickle_function, constructor_ob = None): dispatch_table[ob_type] = pickle_function if constructor_ob is not None: constructor(constructor_ob)
return self.decode(self.stream.read())[0]
return self.decode(self.stream.read(), self.errors)[0]
def read(self, size=-1):
object, decodedbytes = decode(data)
object, decodedbytes = decode(data, self.errors)
def read(self, size=-1):
return self.decode(line)[0]
return self.decode(line,self.errors)[0]
def readline(self, size=None):
return self.decode(data)[0].splitlines(1)
return self.decode(data,self.errors)[0].splitlines(1)
def readlines(self, sizehint=0):
u = u'\U00010001\U00020002\U00030003\U00040004\U00050005' for encoding in ('utf-8', 'utf-16', 'utf-16-le', 'utf-16-be', 'unicode_escape', 'unicode_internal'): verify(unicode(u.encode(encoding),encoding) == u)
def __str__(self): return self.x
self._cont_handler.startElement(name, attrs)
self._cont_handler.startElementNS(name, qname, attrs)
def startElementNS(self, name, qname, attrs): self._cont_handler.startElement(name, attrs)
print "open", askopenfilename(filetypes=[("all filez", "*")]) print "saveas", asksaveasfilename()
enc = "utf-8" try: import locale enc = locale.nl_langinfo(locale.CODESET) except (ImportError, AttributeError): pass print "open", askopenfilename(filetypes=[("all filez", "*")]).encode(enc) print "saveas", asksaveasfilename().encode(enc)
def askdirectory (**options): "Ask for a directory, and return the file name" return Directory(**options).show()
self.log_error("command: %s", cmdline)
self.log_message("command: %s", cmdline)
def run_cgi(self): """Execute a CGI script.""" dir, rest = self.cgi_info i = rest.rfind('?') if i >= 0: rest, query = rest[:i], rest[i+1:] else: query = '' i = rest.find('/') if i >= 0: script, rest = rest[:i], rest[i:] else: script, rest = rest, '' scriptname = dir + '/' + script scriptfile = self.translate_path(scrip...
self.log_error("CGI script exited OK")
self.log_message("CGI script exited OK")
def run_cgi(self): """Execute a CGI script.""" dir, rest = self.cgi_info i = rest.rfind('?') if i >= 0: rest, query = rest[:i], rest[i+1:] else: query = '' i = rest.find('/') if i >= 0: script, rest = rest[:i], rest[i:] else: script, rest = rest, '' scriptname = dir + '/' + script scriptfile = self.translate_path(scrip...
if os.name == 'mac': import macfs fss, ok = macfs.GetDirectory('Directory to zap pyc files in') if not ok: sys.exit(0) dir = fss.as_pathname() zappyc(dir) else: if not sys.argv[1:]:
if not sys.argv[1:]: if os.name == 'mac': import macfs fss, ok = macfs.GetDirectory('Directory to zap pyc files in') if not ok: sys.exit(0) dir = fss.as_pathname() zappyc(dir) else:
def main(): if os.name == 'mac': import macfs fss, ok = macfs.GetDirectory('Directory to zap pyc files in') if not ok: sys.exit(0) dir = fss.as_pathname() zappyc(dir) else: if not sys.argv[1:]: print 'Usage: zappyc dir ...' sys.exit(1) for dir in sys.argv[1:]: zappyc(dir)
def doc(thing, title='Python Library Documentation: '):
def doc(thing, title='Python Library Documentation: %s'):
def doc(thing, title='Python Library Documentation: '): """Display text documentation, given an object or a path to an object.""" suffix, name = '', None if type(thing) is type(''): try: object = locate(thing) except ErrorDuringImport, value: print value return if not object: print 'no Python documentation found for %s...
pager(title + desc + suffix + '\n\n' + text.document(object, name))
pager(title % (desc + suffix) + '\n\n' + text.document(thing, name))
def doc(thing, title='Python Library Documentation: '): """Display text documentation, given an object or a path to an object.""" suffix, name = '', None if type(thing) is type(''): try: object = locate(thing) except ErrorDuringImport, value: print value return if not object: print 'no Python documentation found for %s...
def run(self, key, callback, completer=None): key = lower(key)
def run(self, callback, key=None, completer=None): if key: key = lower(key)
def run(self, key, callback, completer=None): key = lower(key) self.quit = 0 seen = {}
desc = split(freshimport(modname).__doc__ or '', '\n')[0] if find(lower(modname + ' - ' + desc), key) >= 0: callback(None, modname, desc)
if key is None: callback(None, modname, '') else: desc = split(freshimport(modname).__doc__ or '', '\n')[0] if find(lower(modname + ' - ' + desc), key) >= 0: callback(None, modname, desc)
def run(self, key, callback, completer=None): key = lower(key) self.quit = 0 seen = {}
if key:
if key is None: callback(path, modname, '') else:
def run(self, key, callback, completer=None): key = lower(key) self.quit = 0 seen = {}
else: callback(path, modname, '')
def run(self, key, callback, completer=None): key = lower(key) self.quit = 0 seen = {}
ModuleScanner().run(key, callback)
ModuleScanner().run(callback, key)
def callback(path, modname, desc): if modname[-9:] == '.__init__': modname = modname[:-9] + ' (package)' print modname, desc and '- ' + desc
def serve(port, callback=None, finalizer=None):
def serve(port, callback=None, completer=None):
def serve(port, callback=None, finalizer=None): import BaseHTTPServer, SocketServer, mimetools, select # Patch up mimetools.Message so it doesn't break if rfc822 is reloaded. class Message(mimetools.Message): def __init__(self, fp, seekable=1): Message = self.__class__ Message.__bases__[0].__bases__[0].__init__(self, ...
if finalizer: finalizer()
if completer: completer()
def server_activate(self): self.base.server_activate(self) if self.callback: self.callback(self)
return 'pwpc'
return 'pwpc', 1
def interact(scriptname): if PPC_ONLY: return 'pwpc' d = Dlg.GetNewDialog(DLG_ID, -1) if not d: print "Can't get DLOG resource with id =", DLG_ID return d.SetDialogDefaultItem(OK_BUTTON) d.SetDialogCancelItem(CANCEL_BUTTON) Dlg.ParamText(scriptname, "", "", "") radiogroup = radio(d, GENFAT_BUTTON, GENPPC_BUTTON, GEN68...
print "Can't get DLOG resource with id =", DLG_ID return
raise "Can't get DLOG resource with id =", DLG_ID
def interact(scriptname): if PPC_ONLY: return 'pwpc' d = Dlg.GetNewDialog(DLG_ID, -1) if not d: print "Can't get DLOG resource with id =", DLG_ID return d.SetDialogDefaultItem(OK_BUTTON) d.SetDialogCancelItem(CANCEL_BUTTON) Dlg.ParamText(scriptname, "", "", "") radiogroup = radio(d, GENFAT_BUTTON, GENPPC_BUTTON, GEN68...
... SyntaxError: 'return' with argument inside generator (<string>, line 2) >>> def f():
.. SyntaxError: 'return' with argument inside generator (..., line 2) >>> def f():
>>> def f():
... SyntaxError: 'return' with argument inside generator (<string>, line 3)
.. SyntaxError: 'return' with argument inside generator (..., line 3)
>>> def f():
... SyntaxError: 'yield' not allowed in a 'try' block with a 'finally' clause (<string>, line 3) >>> def f():
.. SyntaxError: 'yield' not allowed in a 'try' block with a 'finally' clause (..., line 3) >>> def f():
>>> def f():
SyntaxError: 'yield' not allowed in a 'try' block with a 'finally' clause (<string>, line 6)
SyntaxError: 'yield' not allowed in a 'try' block with a 'finally' clause (..., line 6)
>>> def f():
SyntaxError: 'return' with argument inside generator (<string>, line 8)
SyntaxError: 'return' with argument inside generator (..., line 8)
... def f(i):
'gopher://gopher.lib.ncsu.edu/11/library/stacks/Alex', 'gopher://gopher.vt.edu:10010/10/33',
'gopher://gopher.lib.ncsu.edu./11/library/stacks/Alex', 'gopher://gopher.vt.edu.:10010/10/33',
def test_gopher(self): import warnings warnings.filterwarnings("ignore", "the gopherlib module is deprecated", DeprecationWarning, "urllib2$") urls = [ # Thanks to Fred for finding these! 'gopher://gopher.lib.ncsu.edu/11/library/stacks/Alex', 'gopher://gopher.vt.edu:10010/10/33', ] self._test_urls(urls, self._extra_han...
self.assert_(isinstance(err, expected_err))
msg = ("Didn't get expected error(s) %s for %s %s, got %s" % (expected_err, url, req, err)) self.assert_(isinstance(err, expected_err), msg)
def _test_urls(self, urls, handlers): import socket import time import logging debug = logging.getLogger("test_urllib2").debug
import sys
def whichmodule(cls, clsname): """Figure out the module in which a class occurs. Search sys.modules for the module. Cache in classmap. Return a module name. If the class cannot be found, return __main__. """ if classmap.has_key(cls): return classmap[cls] import sys for name, module in sys.modules.items(): if name != ...
value = apply(klass, args)
try: value = apply(klass, args) except TypeError, err: raise TypeError, "in constructor for %s: %s" % ( klass.__name__, str(err)), sys.exc_info()[2]
def load_inst(self): k = self.marker() args = tuple(self.stack[k+1:]) del self.stack[k:] module = self.readline()[:-1] name = self.readline()[:-1] klass = self.find_class(module, name) instantiated = 0 if (not args and type(klass) is ClassType and not hasattr(klass, "__getinitargs__")): try: value = _EmptyClass() value...
socket = _socketobject
socket = SocketType = _socketobject
_s = ("def %s(self, *args): return self._sock.%s(*args)\n\n" "%s.__doc__ = _realsocket.%s.__doc__\n")
ef = codecs.EncodedFile(f, 'utf-16', 'utf-8') self.assertEquals(ef.read(), '\xff\xfe\\\xd5\n\x00\x00\xae')
ef = codecs.EncodedFile(f, 'utf-16-le', 'utf-8') self.assertEquals(ef.read(), '\\\xd5\n\x00\x00\xae')
def test_basic(self): f = StringIO.StringIO('\xed\x95\x9c\n\xea\xb8\x80') ef = codecs.EncodedFile(f, 'utf-16', 'utf-8') self.assertEquals(ef.read(), '\xff\xfe\\\xd5\n\x00\x00\xae')
except error:
except (error, TypeError):
def subn(self, repl, source, count=0): """subn(repl, string[, count=0]) -> tuple
want = int((have - 1) / self.indentwidth) * self.indentwidth
want = ((have - 1) // self.indentwidth) * self.indentwidth
def smart_backspace_event(self, event): text = self.text first, last = self.editwin.get_selection_indices() if first and last: text.delete(first, last) text.mark_set("insert", first) return "break" # Delete whitespace left, until hitting a real char or closest # preceding virtual tab stop. chars = text.get("insert line...
effective = (int(effective / tabwidth) + 1) * tabwidth
effective = (effective // tabwidth + 1) * tabwidth
def classifyws(s, tabwidth): raw = effective = 0 for ch in s: if ch == ' ': raw = raw + 1 effective = effective + 1 elif ch == '\t': raw = raw + 1 effective = (int(effective / tabwidth) + 1) * tabwidth else: break return raw, effective
self.preffilepath = ":Python:PythonIDE preferences"
self.preffilepath = os.path.join("Python", "PythonIDE preferences")
def __init__(self): self.preffilepath = ":Python:PythonIDE preferences" Wapplication.Application.__init__(self, 'Pide') from Carbon import AE from Carbon import AppleEvents AE.AEInstallEventHandler(AppleEvents.kCoreEventClass, AppleEvents.kAEOpenApplication, self.ignoreevent) AE.AEInstallEventHandler(AppleEvents.kCore...
exclude=0, single=0, randomize=0):
exclude=0, single=0, randomize=0, leakdebug=0):
def main(tests=None, testdir=None, verbose=0, quiet=0, generate=0, exclude=0, single=0, randomize=0): """Execute a test suite. This also parses command-line options and modifies its behavior accordingly. tests -- a list of strings containing test names (optional) testdir -- the directory in which to look for tests (o...
The other six default arguments (verbose, quiet, generate, exclude, single, and randomize) allow programmers calling main() directly to set the values that would normally be set by flags on the command line.
The other seven default arguments (verbose, quiet, generate, exclude, single, randomize, and leakdebug) allow programmers calling main() directly to set the values that would normally be set by flags on the command line.
def main(tests=None, testdir=None, verbose=0, quiet=0, generate=0, exclude=0, single=0, randomize=0): """Execute a test suite. This also parses command-line options and modifies its behavior accordingly. tests -- a list of strings containing test names (optional) testdir -- the directory in which to look for tests (o...
opts, args = getopt.getopt(sys.argv[1:], 'vgqxsr')
opts, args = getopt.getopt(sys.argv[1:], 'vgqxsrl')
def main(tests=None, testdir=None, verbose=0, quiet=0, generate=0, exclude=0, single=0, randomize=0): """Execute a test suite. This also parses command-line options and modifies its behavior accordingly. tests -- a list of strings containing test names (optional) testdir -- the directory in which to look for tests (o...
if a_uri:
if a_uri == xmlns_uri: if a_localname == 'xmlns': qname = a_localname else: qname = 'xmlns:' + a_localname attr = self.document.createAttributeNS(a_uri, qname) node.setAttributeNodeNS(attr) elif a_uri:
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: prefix = self._current_context[uri] if prefix: tagName = prefix + ":" + ...
UpdateEditIdle = "UpdateEditIDLE"
UpdateEditIDLE = "UpdateEditIDLE"
def add_ui(db): x = y = 50 w = 370 h = 300 title = "[ProductName] Setup" # see "Dialog Style Bits" modal = 3 # visible | modal modeless = 1 # visible track_disk_space = 32 add_data(db, 'ActionText', uisample.ActionText) add_data(db, 'UIText', uisample.UIText) # Bitmaps if not os.path.exists(srcdir+r"\PC\pytho...
self._policy._now = self._now = int(time.time()) cookies = self._cookies_for_request(request) attrs = self._cookie_attrs(cookies) if attrs: if not request.has_header("Cookie"): request.add_unredirected_header( "Cookie", "; ".join(attrs)) if (self._policy.rfc2965 and not self._policy.hide_cookie2 and not request.has...
try: self._policy._now = self._now = int(time.time()) cookies = self._cookies_for_request(request) attrs = self._cookie_attrs(cookies) if attrs: if not request.has_header("Cookie"): request.add_unredirected_header( "Cookie", "; ".join(attrs)) if (self._policy.rfc2965 and not self._policy.hide_cookie2 and not reque...
def add_cookie_header(self, request): """Add correct Cookie: header to request (urllib2.Request object).
self._policy._now = self._now = int(time.time()) if self._policy.set_ok(cookie, request): self.set_cookie(cookie) self._cookies_lock.release()
try: self._policy._now = self._now = int(time.time()) if self._policy.set_ok(cookie, request): self.set_cookie(cookie) finally: self._cookies_lock.release()
def set_cookie_if_ok(self, cookie, request): """Set a cookie if policy says it's OK to do so.""" self._cookies_lock.acquire() self._policy._now = self._now = int(time.time())
self._policy._now = self._now = int(time.time()) for cookie in self.make_cookies(response, request): if self._policy.set_ok(cookie, request): _debug(" setting cookie: %s", cookie) self.set_cookie(cookie) self._cookies_lock.release()
try: self._policy._now = self._now = int(time.time()) for cookie in self.make_cookies(response, request): if self._policy.set_ok(cookie, request): _debug(" setting cookie: %s", cookie) self.set_cookie(cookie) finally: self._cookies_lock.release()
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 cookie in self: if cookie.discard: self.clear(cookie.domain, cookie.path, cookie.name) self._cookies_lock.release()
try: for cookie in self: if cookie.discard: self.clear(cookie.domain, cookie.path, cookie.name) finally: self._cookies_lock.release()
def clear_session_cookies(self): """Discard all session cookies.
now = time.time() for cookie in self: if cookie.is_expired(now): self.clear(cookie.domain, cookie.path, cookie.name) self._cookies_lock.release()
try: now = time.time() for cookie in self: if cookie.is_expired(now): self.clear(cookie.domain, cookie.path, cookie.name) finally: self._cookies_lock.release()
def clear_expired_cookies(self): """Discard all expired cookies.
old_state = copy.deepcopy(self._cookies) self._cookies = {}
def revert(self, filename=None, ignore_discard=False, ignore_expires=False): """Clear all cookies and reload cookies from a saved file.
self.load(filename, ignore_discard, ignore_expires) except (LoadError, IOError): self._cookies = old_state raise self._cookies_lock.release()
old_state = copy.deepcopy(self._cookies) self._cookies = {} try: self.load(filename, ignore_discard, ignore_expires) except (LoadError, IOError): self._cookies = old_state raise finally: self._cookies_lock.release()
def revert(self, filename=None, ignore_discard=False, ignore_expires=False): """Clear all cookies and reload cookies from a saved file.
self._note("%s.acquire(%s): initial succes", self, blocking)
self._note("%s.acquire(%s): initial success", self, blocking)
def acquire(self, blocking=1): me = currentThread() if self.__owner is me: self.__count = self.__count + 1 if __debug__: self._note("%s.acquire(%s): recursive success", self, blocking) return 1 rc = self.__block.acquire(blocking) if rc: self.__owner = me self.__count = 1 if __debug__: self._note("%s.acquire(%s): initia...
def __init__(self, filename, etype, evalue):
def __init__(self, filename, (type, value, tb)):
def __init__(self, filename, etype, evalue): self.filename = filename self.etype = etype self.evalue = evalue if type(etype) is types.ClassType: etype = etype.__name__ self.args = '%s: %s' % (etype, evalue)
self.etype = etype self.evalue = evalue if type(etype) is types.ClassType: etype = etype.__name__ self.args = '%s: %s' % (etype, evalue)
self.type = type self.value = value self.tb = tb def __str__(self): t = self.type if type(t) is types.ClassType: t = t.__name__ return 'problem in %s - %s: %s' % (self.filename, t, self.value)
def __init__(self, filename, etype, evalue): self.filename = filename self.etype = etype self.evalue = evalue if type(etype) is types.ClassType: etype = etype.__name__ self.args = '%s: %s' % (etype, evalue)
raise DocImportError(path, sys.exc_type, sys.exc_value)
raise DocImportError(path, sys.exc_info())
def importfile(path): """Import a Python source file or compiled file given its path.""" magic = imp.get_magic() file = open(path, 'r') if file.read(len(magic)) == magic: kind = imp.PY_COMPILED else: kind = imp.PY_SOURCE file.close() filename = os.path.basename(path) name, ext = os.path.splitext(filename) file = open(p...
init = os.path.join(path, '__init__.py') initc = os.path.join(path, '__init__.pyc') if os.path.isfile(init) or os.path.isfile(initc): return 1
for ext in ['.py', '.pyc', '.pyo']: if os.path.isfile(os.path.join(path, '__init__' + ext)): return 1
def ispackage(path): """Guess whether a path refers to a package directory.""" if os.path.isdir(path): init = os.path.join(path, '__init__.py') initc = os.path.join(path, '__init__.pyc') if os.path.isfile(init) or os.path.isfile(initc): return 1
def document(self, object, *args):
def document(self, object, name=None, *args):
def document(self, object, *args): """Generate documentation for an object.""" args = (object,) + args if inspect.ismodule(object): return apply(self.docmodule, args) if inspect.isclass(object): return apply(self.docclass, args) if inspect.isroutine(object): return apply(self.docroutine, args) raise TypeError, "don't k...
args = (object,) + args
args = (object, name) + args
def document(self, object, *args): """Generate documentation for an object.""" args = (object,) + args if inspect.ismodule(object): return apply(self.docmodule, args) if inspect.isclass(object): return apply(self.docclass, args) if inspect.isroutine(object): return apply(self.docroutine, args) raise TypeError, "don't k...
raise TypeError, "don't know how to document objects of type " + \ type(object).__name__
return apply(self.docother, args) def fail(self, object, name=None, *args): """Raise an exception for unimplemented types.""" message = "don't know how to document object%s of type %s" % ( name and ' ' + repr(name), type(object).__name__) raise TypeError, message docmodule = docclass = docroutine = docother = fail
def document(self, object, *args): """Generate documentation for an object.""" args = (object,) + args if inspect.ismodule(object): return apply(self.docmodule, args) if inspect.isclass(object): return apply(self.docclass, args) if inspect.isroutine(object): return apply(self.docroutine, args) raise TypeError, "don't k...
self.maxstring = self.maxother = 50
self.maxstring = self.maxother = 100
def __init__(self): Repr.__init__(self) self.maxlist = self.maxtuple = self.maxdict = 10 self.maxstring = self.maxother = 50
result = Repr.repr(self, object) return result
return Repr.repr(self, object)
def repr(self, object): result = Repr.repr(self, object) return result
return cram(stripid(repr(x)), self.maxstring)
return self.escape(cram(stripid(repr(x)), self.maxstring))
def repr_instance(self, x, level): try: return cram(stripid(repr(x)), self.maxstring) except: return self.escape('<%s instance>' % x.__class__.__name__)
def heading(self, title, fgcol, bgcol, extras=''): """Format a page heading.""" return """ <p><table width="100%%" cellspacing=0 cellpadding=0 border=0> <tr bgcolor="%s"><td>&nbsp;</td> <td valign=bottom><small><small><br></small></small ><font color="%s" face="helvetica"><br>&nbsp;%s</font></td ><td align=right valign...
def small(self, text): return '<small>%s</small>' % text def grey(self, text): return '<font color="
def heading(self, title, fgcol, bgcol, extras=''): """Format a page heading.""" return """
return '<font color="
return self.grey(name)
def modpkglink(self, (name, path, ispackage, shadowed)): """Make a link for a module or package to display in an index.""" if shadowed: return '<font color="#909090">%s</font>' % name if path: url = '%s.%s.html' % (path, name) else: url = '%s.html' % name if ispackage: text = '<strong>%s</strong>&nbsp;(package)' % name...
def doctree(self, tree, modname, classes={}, parent=None):
def formattree(self, tree, modname, classes={}, parent=None):
def doctree(self, tree, modname, classes={}, parent=None): """Produce HTML for a class tree as given by inspect.getclasstree().""" result = '' for entry in tree: if type(entry) is type(()): c, bases = entry result = result + '<dt><font face="helvetica, arial"><small>' result = result + self.classlink(c, modname, classe...
result = result + \ '<dd>\n%s</dd>\n' % self.doctree(entry, modname, classes, c)
result = result + '<dd>\n%s</dd>\n' % self.formattree( entry, modname, classes, c)
def doctree(self, tree, modname, classes={}, parent=None): """Produce HTML for a class tree as given by inspect.getclasstree().""" result = '' for entry in tree: if type(entry) is type(()): c, bases = entry result = result + '<dt><font face="helvetica, arial"><small>' result = result + self.classlink(c, modname, classe...
def docmodule(self, object):
def docmodule(self, object, name=None):
def docmodule(self, object): """Produce HTML documentation for a module object.""" name = object.__name__ parts = split(name, '.') links = [] for i in range(len(parts)-1): links.append( '<a href="%s.html"><font color="#ffffff">%s</font></a>' % (join(parts[:i+1], '.'), parts[i])) linkedname = join(links + parts[-1:], '....
second = lambda list: list[1] modules = map(second, inspect.getmembers(object, inspect.ismodule))
modules = inspect.getmembers(object, inspect.ismodule) if 0 and hasattr(object, '__all__'): visible = lambda key, all=object.__all__: key in all else: visible = lambda key: key[:1] != '_'
def docmodule(self, object): """Produce HTML documentation for a module object.""" name = object.__name__ parts = split(name, '.') links = [] for i in range(len(parts)-1): links.append( '<a href="%s.html"><font color="#ffffff">%s</font></a>' % (join(parts[:i+1], '.'), parts[i])) linkedname = join(links + parts[-1:], '....
if (inspect.getmodule(value) or object) is object: classes.append(value)
if visible(key) and ( inspect.getmodule(value) or object) is object: classes.append((key, value))
def docmodule(self, object): """Produce HTML documentation for a module object.""" name = object.__name__ parts = split(name, '.') links = [] for i in range(len(parts)-1): links.append( '<a href="%s.html"><font color="#ffffff">%s</font></a>' % (join(parts[:i+1], '.'), parts[i])) linkedname = join(links + parts[-1:], '....
if inspect.isbuiltin(value) or inspect.getmodule(value) is object: funcs.append(value)
if visible(key) and (inspect.isbuiltin(value) or inspect.getmodule(value) is object): funcs.append((key, value))
def docmodule(self, object): """Produce HTML documentation for a module object.""" name = object.__name__ parts = split(name, '.') links = [] for i in range(len(parts)-1): links.append( '<a href="%s.html"><font color="#ffffff">%s</font></a>' % (join(parts[:i+1], '.'), parts[i])) linkedname = join(links + parts[-1:], '....
for c in classes: for base in c.__bases__: key, modname = base.__name__, base.__module__ if modname != name and sys.modules.has_key(modname): module = sys.modules[modname] if hasattr(module, key) and getattr(module, key) is base: if not cdict.has_key(key): cdict[key] = cdict[base] = modname + '.html
def docmodule(self, object): """Produce HTML documentation for a module object.""" name = object.__name__ parts = split(name, '.') links = [] for i in range(len(parts)-1): links.append( '<a href="%s.html"><font color="#ffffff">%s</font></a>' % (join(parts[:i+1], '.'), parts[i])) linkedname = join(links + parts[-1:], '....
if key[:1] != '_':
if visible(key):
def docmodule(self, object): """Produce HTML documentation for a module object.""" name = object.__name__ parts = split(name, '.') links = [] for i in range(len(parts)-1): links.append( '<a href="%s.html"><font color="#ffffff">%s</font></a>' % (join(parts[:i+1], '.'), parts[i])) linkedname = join(links + parts[-1:], '....
result = result + '<p><small>%s</small></p>\n' % doc
result = result + '<p>%s\n' % self.small(doc)
def docmodule(self, object): """Produce HTML documentation for a module object.""" name = object.__name__ parts = split(name, '.') links = [] for i in range(len(parts)-1): links.append( '<a href="%s.html"><font color="#ffffff">%s</font></a>' % (join(parts[:i+1], '.'), parts[i])) linkedname = join(links + parts[-1:], '....
contents = self.multicolumn(modules, self.modulelink)
contents = self.multicolumn( modules, lambda (key, value), s=self: s.modulelink(value))
def docmodule(self, object): """Produce HTML documentation for a module object.""" name = object.__name__ parts = split(name, '.') links = [] for i in range(len(parts)-1): links.append( '<a href="%s.html"><font color="#ffffff">%s</font></a>' % (join(parts[:i+1], '.'), parts[i])) linkedname = join(links + parts[-1:], '....
contents = self.doctree( inspect.getclasstree(classes, 1), name, cdict) for item in classes: contents = contents + self.document(item, fdict, cdict)
classlist = map(lambda (key, value): value, classes) contents = [self.formattree( inspect.getclasstree(classlist, 1), name, cdict)] for key, value in classes: contents.append(self.document(value, key, fdict, cdict))
def docmodule(self, object): """Produce HTML documentation for a module object.""" name = object.__name__ parts = split(name, '.') links = [] for i in range(len(parts)-1): links.append( '<a href="%s.html"><font color="#ffffff">%s</font></a>' % (join(parts[:i+1], '.'), parts[i])) linkedname = join(links + parts[-1:], '....
contents = '' for item in funcs: contents = contents + self.document(item, fdict, cdict)
contents = [] for key, value in funcs: contents.append(self.document(value, key, fdict, cdict))
def docmodule(self, object): """Produce HTML documentation for a module object.""" name = object.__name__ parts = split(name, '.') links = [] for i in range(len(parts)-1): links.append( '<a href="%s.html"><font color="#ffffff">%s</font></a>' % (join(parts[:i+1], '.'), parts[i])) linkedname = join(links + parts[-1:], '....
contents = ''
contents = []
def docmodule(self, object): """Produce HTML documentation for a module object.""" name = object.__name__ parts = split(name, '.') links = [] for i in range(len(parts)-1): links.append( '<a href="%s.html"><font color="#ffffff">%s</font></a>' % (join(parts[:i+1], '.'), parts[i])) linkedname = join(links + parts[-1:], '....
contents = contents + ('<br><strong>%s</strong> = %s' % (key, self.repr(value)))
contents.append(self.document(value, key))
def docmodule(self, object): """Produce HTML documentation for a module object.""" name = object.__name__ parts = split(name, '.') links = [] for i in range(len(parts)-1): links.append( '<a href="%s.html"><font color="#ffffff">%s</font></a>' % (join(parts[:i+1], '.'), parts[i])) linkedname = join(links + parts[-1:], '....
def docclass(self, object, funcs={}, classes={}):
def docclass(self, object, name=None, funcs={}, classes={}):
def docclass(self, object, funcs={}, classes={}): """Produce HTML documentation for a class object.""" name = object.__name__ bases = object.__bases__ contents = ''
name = object.__name__
realname = object.__name__ name = name or realname
def docclass(self, object, funcs={}, classes={}): """Produce HTML documentation for a class object.""" name = object.__name__ bases = object.__bases__ contents = ''
methods.append(value)
methods.append((key, value))
def docclass(self, object, funcs={}, classes={}): """Produce HTML documentation for a class object.""" name = object.__name__ bases = object.__bases__ contents = ''
for item in methods:
for key, value in methods:
def docclass(self, object, funcs={}, classes={}): """Produce HTML documentation for a class object.""" name = object.__name__ bases = object.__bases__ contents = ''
item, funcs, classes, mdict, name) title = '<a name="%s">class <strong>%s</strong></a>' % (name, name)
value, key, funcs, classes, mdict, name) if name == realname: title = '<a name="%s">class <strong>%s</strong></a>' % ( name, realname) else: title = '<strong>%s</strong> = <a name="%s">class %s</a>' % ( name, name, realname)
def docclass(self, object, funcs={}, classes={}): """Produce HTML documentation for a class object.""" name = object.__name__ bases = object.__bases__ contents = ''
doc = self.markup(getdoc(object), self.preformat, funcs, classes, mdict) if doc: doc = '<small><tt>' + doc + '</tt></small>'
doc = self.markup( getdoc(object), self.preformat, funcs, classes, mdict) if doc: doc = self.small('<tt>%s</tt>' % doc)
def docclass(self, object, funcs={}, classes={}): """Produce HTML documentation for a class object.""" name = object.__name__ bases = object.__bases__ contents = ''
return ('<small><font color=" self.repr(object)) def docroutine(self, object, funcs={}, classes={}, methods={}, clname=''):
return self.small(self.grey('=' + self.repr(object))) def docroutine(self, object, name=None, funcs={}, classes={}, methods={}, clname=''):
def formatvalue(self, object): """Format an argument default value as text.""" return ('<small><font color="#909090">=%s</font></small>' % self.repr(object))
if inspect.ismethod(object): object = object.im_func
realname = object.__name__ name = name or realname anchor = clname + '-' + realname note = '' if inspect.ismethod(object): if not clname: note = self.small(self.grey( object.im_self and 'method of ' + self.repr(object.im_self) or ' unbound %s method' % object.im_class.__name__)) object = object.im_func if name == real...
def docroutine(self, object, funcs={}, classes={}, methods={}, clname=''): """Produce HTML documentation for a function or method object.""" if inspect.ismethod(object): object = object.im_func if inspect.isbuiltin(object): decl = '<a name="%s"><strong>%s</strong>(...)</a>\n' % ( clname + '-' + object.__name__, object....
decl = '<a name="%s"><strong>%s</strong>(...)</a>\n' % ( clname + '-' + object.__name__, object.__name__)
argspec = '(...)'
def docroutine(self, object, funcs={}, classes={}, methods={}, clname=''): """Produce HTML documentation for a function or method object.""" if inspect.ismethod(object): object = object.im_func if inspect.isbuiltin(object): decl = '<a name="%s"><strong>%s</strong>(...)</a>\n' % ( clname + '-' + object.__name__, object....