bugged
stringlengths
4
228k
fixed
stringlengths
0
96.3M
__index_level_0__
int64
0
481k
def splitbins(bins): # split a sparse integer table into two tables, such as: # value = t2[(t1[char>>shift]<<shift)+(char&mask)] # and value == 0 means no data bytes = sys.maxint for shift in range(16): bin1 = [] bin2 = [] size = 2**shift bincache = {} for i in range(0, len(bins), size): bin = bins[i:i+size] index = bincache.get(tuple(bin)) if index is None: index = len(bin2) bincache[tuple(bin)] = index for v in bin: if v is None: bin2.append(0) else: bin2.append(v) bin1.append(index>>shift) # determine memory size b = len(bin1)*getsize(bin1) + len(bin2)*getsize(bin2) if b < bytes: best = shift, bin1, bin2 bytes = b shift, bin1, bin2 = best
def splitbins(bins): # split a sparse integer table into two tables, such as: # value = t2[(t1[char>>shift]<<shift)+(char&mask)] # and value == 0 means no data bytes = sys.maxint for shift in range(16): bin1 = [] bin2 = [] size = 2**shift bincache = {} for i in range(0, len(bins), size): bin = bins[i:i+size] index = bincache.get(tuple(bin)) if index is None: index = len(bin2) bincache[tuple(bin)] = index for v in bin: if v is None: bin2.append(0) else: bin2.append(v) bin1.append(index>>shift) # determine memory size b = len(bin1)*getsize(bin1) + len(bin2)*getsize(bin2) if b < bytes: best = t1, t2, shift bytes = b shift, bin1, bin2 = best
10,300
def splitbins(bins): # split a sparse integer table into two tables, such as: # value = t2[(t1[char>>shift]<<shift)+(char&mask)] # and value == 0 means no data bytes = sys.maxint for shift in range(16): bin1 = [] bin2 = [] size = 2**shift bincache = {} for i in range(0, len(bins), size): bin = bins[i:i+size] index = bincache.get(tuple(bin)) if index is None: index = len(bin2) bincache[tuple(bin)] = index for v in bin: if v is None: bin2.append(0) else: bin2.append(v) bin1.append(index>>shift) # determine memory size b = len(bin1)*getsize(bin1) + len(bin2)*getsize(bin2) if b < bytes: best = shift, bin1, bin2 bytes = b shift, bin1, bin2 = best
def splitbins(bins): # split a sparse integer table into two tables, such as: # value = t2[(t1[char>>shift]<<shift)+(char&mask)] # and value == 0 means no data bytes = sys.maxint for shift in range(16): bin1 = [] bin2 = [] size = 2**shift bincache = {} for i in range(0, len(bins), size): bin = bins[i:i+size] index = bincache.get(tuple(bin)) if index is None: index = len(bin2) bincache[tuple(bin)] = index for v in bin: if v is None: bin2.append(0) else: bin2.append(v) bin1.append(index>>shift) # determine memory size b = len(bin1)*getsize(bin1) + len(bin2)*getsize(bin2) if b < bytes: best = shift, bin1, bin2 bytes = b shift, bin1, bin2 = best
10,301
def check_close(x, y): """Return true iff complexes x and y "are close\"""" return fcmp(x.real, y.real) == 0 == fcmp(x.imag, y.imag)
def check_close_real(x, y, eps=1e-9): """Return true iff floats x and y "are close\"""" if abs(x) > abs(y): x, y = y, x if y == 0: return abs(x) < eps if x == 0: return abs(y) < eps return abs((x-y)/y) < eps def check_close(x, y, eps=1e-9): """Return true iff complexes x and y "are close\"""" return fcmp(x.real, y.real) == 0 == fcmp(x.imag, y.imag)
10,302
def check_close(x, y): """Return true iff complexes x and y "are close\"""" return fcmp(x.real, y.real) == 0 == fcmp(x.imag, y.imag)
def check_close(x, y): """Return true iff complexes x and y "are close\"""" return check_close_real(x.real, y.real, eps) and \ check_close_real(x.imag, y.imag, eps)
10,303
def import_module(self, partname, fqname, parent): self.msgin(3, "import_module", partname, fqname, parent) try: m = self.modules[fqname] except KeyError: pass else: self.msgout(3, "import_module ->", m) return m if self.badmodules.has_key(fqname): self.msgout(3, "import_module -> None") return None try: fp, pathname, stuff = self.find_module(partname, parent and parent.__path__) except ImportError: self.msgout(3, "import_module ->", None) return None try: m = self.load_module(fqname, fp, pathname, stuff) finally: if fp: fp.close() if parent: setattr(parent, partname, m) self.msgout(3, "import_module ->", m) return m
def import_module(self, partname, fqname, parent): self.msgin(3, "import_module", partname, fqname, parent) try: m = self.modules[fqname] except KeyError: pass else: self.msgout(3, "import_module ->", m) return m if self.badmodules.has_key(fqname): self.msgout(3, "import_module -> None") return None try: fp, pathname, stuff = self.find_module(partname, parent and parent.__path__, parent) except ImportError: self.msgout(3, "import_module ->", None) return None try: m = self.load_module(fqname, fp, pathname, stuff) finally: if fp: fp.close() if parent: setattr(parent, partname, m) self.msgout(3, "import_module ->", m) return m
10,304
def find_module(self, name, path): if path: fullname = '.'.join(path)+'.'+name else: fullname = name if fullname in self.excludes: self.msgout(3, "find_module -> Excluded", fullname) raise ImportError, name
def find_module(self, name, path, parent=None): if parent is not None: fullname = parent.__name__+'.'+name else: fullname = name if fullname in self.excludes: self.msgout(3, "find_module -> Excluded", fullname) raise ImportError, name
10,305
def formatdate(timeval=None): """Returns time format preferred for Internet standards. Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123 """ if timeval is None: timeval = time.time() return "%s" % time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime(timeval))
def formatdate(timeval=None): """Returns time format preferred for Internet standards. Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123 """ if timeval is None: timeval = time.time() return "%s" % time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime(timeval))
10,306
def remove_section(self, section): """Remove a file section.""" if self.__sections.has_key(section): del self.__sections[section] return 1 else: return 0
def remove_section(self, section): """Remove a file section.""" if self.__sections.has_key(section): del self.__sections[section] return 1 else: return 0
10,307
def __init__(self, locale_time=LocaleTime()): """Init inst with non-locale regexes and store LocaleTime object.""" # XXX: should 0 be valid for: # day (d), julian day (j), month (m), and hour12 (I)? super(TimeRE,self).__init__({ # The " \d" option is to make %c from ANSI C work 'd': r"(?P<d>3[0-1]|[0-2]\d|\d| \d)", 'H': r"(?P<H>2[0-3]|[0-1]\d|\d)", 'I': r"(?P<I>0\d|1[0-2]|\d)", 'j': r"(?P<j>(?:3[0-5]\d|36[0-6])|[0-2]\d\d|\d\d|\d)", 'm': r"(?P<m>0\d|1[0-2]|\d)", 'M': r"(?P<M>[0-5]\d|\d)", 'S': r"(?P<S>6[0-1]|[0-5]\d|\d)", 'U': r"(?P<U>5[0-3]|[0-4]\d|\d)", 'w': r"(?P<w>[0-6])", 'W': r"(?P<W>5[0-3]|[0-4]\d|\d)", # Same as U 'y': r"(?P<y>\d\d)", 'Y': r"(?P<Y>\d\d\d\d)"}) self.locale_time = locale_time
def __init__(self, locale_time=LocaleTime()): """Init inst with non-locale regexes and store LocaleTime object.""" # XXX: should 0 be valid for: # day (d), julian day (j), month (m), and hour12 (I)? super(TimeRE,self).__init__({ # The " \d" option is to make %c from ANSI C work 'd': r"(?P<d>3[0-1]|[0-2]\d|\d| \d)", 'H': r"(?P<H>2[0-3]|[0-1]\d|\d)", 'I': r"(?P<I>0\d|1[0-2]|\d)", 'j': r"(?P<j>(?:3[0-5]\d|36[0-6])|[0-2]\d\d|\d\d|\d)", 'm': r"(?P<m>0\d|1[0-2]|\d)", 'M': r"(?P<M>[0-5]\d|\d)", 'S': r"(?P<S>6[0-1]|[0-5]\d|\d)", 'U': r"(?P<U>5[0-3]|[0-4]\d|\d)", 'w': r"(?P<w>[0-6])", 'W': r"(?P<W>5[0-3]|[0-4]\d|\d)", # Same as U 'y': r"(?P<y>\d\d)", 'Y': r"(?P<Y>\d\d\d\d)"}) self.locale_time = locale_time
10,308
def __init__(self, locale_time=LocaleTime()): """Init inst with non-locale regexes and store LocaleTime object.""" # XXX: should 0 be valid for: # day (d), julian day (j), month (m), and hour12 (I)? super(TimeRE,self).__init__({ # The " \d" option is to make %c from ANSI C work 'd': r"(?P<d>3[0-1]|[0-2]\d|\d| \d)", 'H': r"(?P<H>2[0-3]|[0-1]\d|\d)", 'I': r"(?P<I>0\d|1[0-2]|\d)", 'j': r"(?P<j>(?:3[0-5]\d|36[0-6])|[0-2]\d\d|\d\d|\d)", 'm': r"(?P<m>0\d|1[0-2]|\d)", 'M': r"(?P<M>[0-5]\d|\d)", 'S': r"(?P<S>6[0-1]|[0-5]\d|\d)", 'U': r"(?P<U>5[0-3]|[0-4]\d|\d)", 'w': r"(?P<w>[0-6])", 'W': r"(?P<W>5[0-3]|[0-4]\d|\d)", # Same as U 'y': r"(?P<y>\d\d)", 'Y': r"(?P<Y>\d\d\d\d)"}) self.locale_time = locale_time
def __init__(self, locale_time=LocaleTime()): """Init inst with non-locale regexes and store LocaleTime object.""" # XXX: should 0 be valid for: # day (d), julian day (j), month (m), and hour12 (I)? super(TimeRE,self).__init__({ # The " \d" option is to make %c from ANSI C work 'd': r"(?P<d>3[0-1]|[1-2]\d|0[1-9]|[1-9]| [1-9])", 'H': r"(?P<H>2[0-3]|[0-1]\d|\d)", 'I': r"(?P<I>0\d|1[0-2]|\d)", 'j': r"(?P<j>(?:3[0-5]\d|36[0-6])|[0-2]\d\d|\d\d|\d)", 'm': r"(?P<m>0\d|1[0-2]|\d)", 'M': r"(?P<M>[0-5]\d|\d)", 'S': r"(?P<S>6[0-1]|[0-5]\d|\d)", 'U': r"(?P<U>5[0-3]|[0-4]\d|\d)", 'w': r"(?P<w>[0-6])", 'W': r"(?P<W>5[0-3]|[0-4]\d|\d)", # Same as U 'y': r"(?P<y>\d\d)", 'Y': r"(?P<Y>\d\d\d\d)"}) self.locale_time = locale_time
10,309
def __init__(self, locale_time=LocaleTime()): """Init inst with non-locale regexes and store LocaleTime object.""" # XXX: should 0 be valid for: # day (d), julian day (j), month (m), and hour12 (I)? super(TimeRE,self).__init__({ # The " \d" option is to make %c from ANSI C work 'd': r"(?P<d>3[0-1]|[0-2]\d|\d| \d)", 'H': r"(?P<H>2[0-3]|[0-1]\d|\d)", 'I': r"(?P<I>0\d|1[0-2]|\d)", 'j': r"(?P<j>(?:3[0-5]\d|36[0-6])|[0-2]\d\d|\d\d|\d)", 'm': r"(?P<m>0\d|1[0-2]|\d)", 'M': r"(?P<M>[0-5]\d|\d)", 'S': r"(?P<S>6[0-1]|[0-5]\d|\d)", 'U': r"(?P<U>5[0-3]|[0-4]\d|\d)", 'w': r"(?P<w>[0-6])", 'W': r"(?P<W>5[0-3]|[0-4]\d|\d)", # Same as U 'y': r"(?P<y>\d\d)", 'Y': r"(?P<Y>\d\d\d\d)"}) self.locale_time = locale_time
def __init__(self, locale_time=LocaleTime()): """Init inst with non-locale regexes and store LocaleTime object.""" # XXX: should 0 be valid for: # day (d), julian day (j), month (m), and hour12 (I)? super(TimeRE,self).__init__({ # The " \d" option is to make %c from ANSI C work 'd': r"(?P<d>3[0-1]|[0-2]\d|\d| \d)", 'H': r"(?P<H>2[0-3]|[0-1]\d|\d)", 'I': r"(?P<I>1[0-2]|0[1-9]|[1-9])", 'j': r"(?P<j>36[0-6]|3[0-5]\d|[1-2]\d\d|0[1-9]\d|00[1-9]|[1-9]\d|0[1-9]|[1-9])", 'm': r"(?P<m>1[0-2]|0[1-9]|[1-9])", 'M': r"(?P<M>[0-5]\d|\d)", 'S': r"(?P<S>6[0-1]|[0-5]\d|\d)", 'U': r"(?P<U>5[0-3]|[0-4]\d|\d)", 'w': r"(?P<w>[0-6])", 'W': r"(?P<W>5[0-3]|[0-4]\d|\d)", # Same as U 'y': r"(?P<y>\d\d)", 'Y': r"(?P<Y>\d\d\d\d)"}) self.locale_time = locale_time
10,310
def __init__(self, locale_time=LocaleTime()): """Init inst with non-locale regexes and store LocaleTime object.""" # XXX: should 0 be valid for: # day (d), julian day (j), month (m), and hour12 (I)? super(TimeRE,self).__init__({ # The " \d" option is to make %c from ANSI C work 'd': r"(?P<d>3[0-1]|[0-2]\d|\d| \d)", 'H': r"(?P<H>2[0-3]|[0-1]\d|\d)", 'I': r"(?P<I>0\d|1[0-2]|\d)", 'j': r"(?P<j>(?:3[0-5]\d|36[0-6])|[0-2]\d\d|\d\d|\d)", 'm': r"(?P<m>0\d|1[0-2]|\d)", 'M': r"(?P<M>[0-5]\d|\d)", 'S': r"(?P<S>6[0-1]|[0-5]\d|\d)", 'U': r"(?P<U>5[0-3]|[0-4]\d|\d)", 'w': r"(?P<w>[0-6])", 'W': r"(?P<W>5[0-3]|[0-4]\d|\d)", # Same as U 'y': r"(?P<y>\d\d)", 'Y': r"(?P<Y>\d\d\d\d)"}) self.locale_time = locale_time
def __init__(self, locale_time=LocaleTime()): """Init inst with non-locale regexes and store LocaleTime object.""" # XXX: should 0 be valid for: # day (d), julian day (j), month (m), and hour12 (I)? super(TimeRE,self).__init__({ # The " \d" option is to make %c from ANSI C work 'd': r"(?P<d>3[0-1]|[0-2]\d|\d| \d)", 'H': r"(?P<H>2[0-3]|[0-1]\d|\d)", 'I': r"(?P<I>0\d|1[0-2]|\d)", 'j': r"(?P<j>(?:3[0-5]\d|36[0-6])|[0-2]\d\d|\d\d|\d)", 'm': r"(?P<m>0\d|1[0-2]|\d)", 'M': r"(?P<M>[0-5]\d|\d)", 'S': r"(?P<S>6[0-1]|[0-5]\d|\d)", 'U': r"(?P<U>5[0-3]|[0-4]\d|\d)", 'w': r"(?P<w>[0-6])", # Same as U 'y': r"(?P<y>\d\d)", 'Y': r"(?P<Y>\d\d\d\d)"}) self.locale_time = locale_time
10,311
def test_one(n): global mutate, dict1, dict2, dict1keys, dict2keys # Fill the dicts without mutating them. mutate = 0 dict1keys = fill_dict(dict1, range(n), n) dict2keys = fill_dict(dict2, range(n), n) # Enable mutation, then compare the dicts so long as they have the # same size. mutate = 1 if verbose: print "trying w/ lengths", len(dict1), len(dict2), while dict1 and len(dict1) == len(dict2): if verbose: print ".", c = cmp(dict1, dict2) if verbose: print
def test_one(n): global mutate, dict1, dict2, dict1keys, dict2keys # Fill the dicts without mutating them. mutate = 0 dict1keys = fill_dict(dict1, range(n), n) dict2keys = fill_dict(dict2, range(n), n) # Enable mutation, then compare the dicts so long as they have the # same size. mutate = 1 if verbose: print "trying w/ lengths", len(dict1), len(dict2), while dict1 and len(dict1) == len(dict2): if verbose: print ".", if random.random() < 0.5: c = cmp(dict1, dict2) else: c = dict1 == dict2 if verbose: print
10,312
def errors(): if verbose: print "Testing errors..." try: class C(list, dict): pass except TypeError: pass else: verify(0, "inheritance from both list and dict should be illegal") try: class C(object, None): pass except TypeError: pass else: verify(0, "inheritance from non-type should be illegal") class Classic: pass try: class C(object, Classic): pass except TypeError: pass else: verify(0, "inheritance from object and Classic should be illegal") try: class C(type(len)): pass except TypeError: pass else: verify(0, "inheritance from CFunction should be illegal") try: class C(object): __slots__ = 1 except TypeError: pass else: verify(0, "__slots__ = 1 should be illegal") try: class C(object): __slots__ = [1] except TypeError: pass else: verify(0, "__slots__ = [1] should be illegal")
def errors(): if verbose: print "Testing errors..." try: class C(list, dict): pass except TypeError: pass else: verify(0, "inheritance from both list and dict should be illegal") try: class C(object, None): pass except TypeError: pass else: verify(0, "inheritance from non-type should be illegal") class Classic: pass try: class C(type(len)): pass except TypeError: pass else: verify(0, "inheritance from CFunction should be illegal") try: class C(object): __slots__ = 1 except TypeError: pass else: verify(0, "__slots__ = 1 should be illegal") try: class C(object): __slots__ = [1] except TypeError: pass else: verify(0, "__slots__ = [1] should be illegal")
10,313
def isdev(self): return self.type in (CHRTYPE, BLKTYPE, FIFOTYPE)
def isdev(self): return self.type in (CHRTYPE, BLKTYPE, FIFOTYPE)
10,314
def gettarinfo(self, name=None, arcname=None, fileobj=None): """Create a TarInfo object for either the file `name' or the file object `fileobj' (using os.fstat on its file descriptor). You can modify some of the TarInfo's attributes before you add it using addfile(). If given, `arcname' specifies an alternative name for the file in the archive. """ self._check("aw")
def gettarinfo(self, name=None, arcname=None, fileobj=None): """Create a TarInfo object for either the file `name' or the file object `fileobj' (using os.fstat on its file descriptor). You can modify some of the TarInfo's attributes before you add it using addfile(). If given, `arcname' specifies an alternative name for the file in the archive. """ self._check("aw")
10,315
... def tail(g):
... def tail(g):
10,316
... def _m235():
... def _m235():
10,317
... def _m235():
... def _m235():
10,318
... def _m235():
... def _m235():
10,319
... def _fib():
... def _fib():
10,320
... def _fib():
... def _fib():
10,321
def body_encode(self, s, convert=True): """Body-encode a string and convert it to output_charset.
def body_encode(self, s, convert=True): """Body-encode a string and convert it to output_charset.
10,322
def get_source_files (self):
def get_source_files (self):
10,323
def build_extensions (self, extensions):
def build_extensions (self, extensions):
10,324
def build_extensions (self, extensions):
def build_extensions (self, extensions):
10,325
def consistency_with_epg(): if verbose: print "Testing consistentcy with EPG..." class Pane(object): pass class ScrollingMixin(object): pass class EditingMixin(object): pass class ScrollablePane(Pane,ScrollingMixin): pass class EditablePane(Pane,EditingMixin): pass class EditableScrollablePane(ScrollablePane,EditablePane): pass vereq(EditableScrollablePane.__mro__, (EditableScrollablePane, ScrollablePane, EditablePane, Pane, ScrollingMixin, EditingMixin, object))
def consistency_with_epg(): if verbose: print "Testing consistentcy with EPG..." class Pane(object): pass class ScrollingMixin(object): pass class EditingMixin(object): pass class ScrollablePane(Pane,ScrollingMixin): pass class EditablePane(Pane,EditingMixin): pass class EditableScrollablePane(ScrollablePane,EditablePane): pass vereq(EditableScrollablePane.__mro__, (EditableScrollablePane, ScrollablePane, EditablePane, Pane, ScrollingMixin, EditingMixin, object))
10,326
def action(self): """Return a code indicating the update status of this file.
def action(self): """Return a code indicating the update status of this file.
10,327
def default(self): files = [] if self.cvs.checkfiles(files): return 1 self.cvs.report()
def default(self): files = [] if self.cvs.checkfiles(files): return 1 self.cvs.report()
10,328
def do_commit(self, opts, files): """commit [file] ...""" if self.cvs.checkfiles(files): return 1 sts = 0 for file in files: if not self.entries[file].commitcheck(): sts = 1 if sts: return sts message = raw_input("One-liner: ") for file in files: self.entries[file].commit(message)
def do_commit(self, opts, files): """commit [file] ...""" if self.cvs.checkfiles(files): return 1 sts = 0 for file in files: if not self.cvs.entries[file].commitcheck(): sts = 1 if sts: return sts message = raw_input("One-liner: ") for file in files: self.entries[file].commit(message)
10,329
def do_commit(self, opts, files): """commit [file] ...""" if self.cvs.checkfiles(files): return 1 sts = 0 for file in files: if not self.entries[file].commitcheck(): sts = 1 if sts: return sts message = raw_input("One-liner: ") for file in files: self.entries[file].commit(message)
def do_commit(self, opts, files): """commit [file] ...""" if self.cvs.checkfiles(files): return 1 sts = 0 for file in files: if not self.entries[file].commitcheck(): sts = 1 if sts: return sts message = raw_input("One-liner: ") for file in files: self.entries[file].commit(message)
10,330
def burst_capture(self): self.setwatch() gl.winset(self.window) x, y = gl.getsize() if self.use_24: fl.show_message('Sorry, no 24 bit continuous capture yet', '', '') return vformat = SV.RGB8_FRAMES nframes = self.getint(self.in_nframes, 0) if nframes == 0: maxmem = self.getint(self.in_maxmem, 1.0) memsize = int(maxmem * 1024 * 1024) nframes = self.calcnframes() info = (vformat, x, y, nframes, 1) try: info2, data, bitvec = self.video.CaptureBurst(info) except sv.error, msg: self.b_capture.set_button(0) self.setarrow() fl.show_message('Capture error:', str(msg), '') return if info <> info2: print info, '<>', info2 self.save_burst(info2, data, bitvec) self.setarrow()
def burst_capture(self): self.setwatch() gl.winset(self.window) x, y = gl.getsize() if self.use_24: fl.show_message('Sorry, no 24 bit continuous capture yet', '', '') return vformat = SV.RGB8_FRAMES nframes = self.getint(self.in_nframes, 0) if nframes == 0: maxmem = self.getint(self.in_maxmem, 1.0) memsize = int(maxmem * 1024 * 1024) nframes = self.calcnframes(memsize) info = (vformat, x, y, nframes, 1) try: info2, data, bitvec = self.video.CaptureBurst(info) except sv.error, msg: self.b_capture.set_button(0) self.setarrow() fl.show_message('Capture error:', str(msg), '') return if info <> info2: print info, '<>', info2 self.save_burst(info2, data, bitvec) self.setarrow()
10,331
def calcnframes(self): gl.winset(self.window) x, y = gl.getsize() pixels = x*y pixels = pixels/2 # XXX always assume fields if self.mono or self.grey: n = memsize/pixels else: n = memsize/(4*pixels) return max(1, n)
def calcnframes(self, memsize): gl.winset(self.window) x, y = gl.getsize() pixels = x*y pixels = pixels/2 # XXX always assume fields if self.mono or self.grey: n = memsize/pixels else: n = memsize/(4*pixels) return max(1, n)
10,332
def open_local_file(self, req): host = req.get_host() file = req.get_selector() localfile = url2pathname(file) stats = os.stat(localfile) size = stats[stat.ST_SIZE] modified = rfc822.formatdate(stats[stat.ST_MTIME]) mtype = mimetypes.guess_type(file)[0] stats = os.stat(localfile) headers = mimetools.Message(StringIO( 'Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' % (mtype or 'text/plain', size, modified))) if host: host, port = splitport(host) if not host or \ (not port and socket.gethostbyname(host) in self.get_names()): return addinfourl(open(localfile, 'rb'), headers, 'file:'+file) raise URLError('file not on local host')
def open_local_file(self, req): host = req.get_host() file = req.get_selector() localfile = url2pathname(file) stats = os.stat(localfile) size = stats.st_size modified = rfc822.formatdate(stats.st_mtime) mtype = mimetypes.guess_type(file)[0] stats = os.stat(localfile) headers = mimetools.Message(StringIO( 'Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' % (mtype or 'text/plain', size, modified))) if host: host, port = splitport(host) if not host or \ (not port and socket.gethostbyname(host) in self.get_names()): return addinfourl(open(localfile, 'rb'), headers, 'file:'+file) raise URLError('file not on local host')
10,333
def open_local_file(self, req): host = req.get_host() file = req.get_selector() localfile = url2pathname(file) stats = os.stat(localfile) size = stats[stat.ST_SIZE] modified = rfc822.formatdate(stats[stat.ST_MTIME]) mtype = mimetypes.guess_type(file)[0] stats = os.stat(localfile) headers = mimetools.Message(StringIO( 'Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' % (mtype or 'text/plain', size, modified))) if host: host, port = splitport(host) if not host or \ (not port and socket.gethostbyname(host) in self.get_names()): return addinfourl(open(localfile, 'rb'), headers, 'file:'+file) raise URLError('file not on local host')
def open_local_file(self, req): host = req.get_host() file = req.get_selector() localfile = url2pathname(file) size = stats[stat.ST_SIZE] modified = rfc822.formatdate(stats[stat.ST_MTIME]) mtype = mimetypes.guess_type(file)[0] headers = mimetools.Message(StringIO( 'Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' % (mtype or 'text/plain', size, modified))) if host: host, port = splitport(host) if not host or \ (not port and socket.gethostbyname(host) in self.get_names()): return addinfourl(open(localfile, 'rb'), headers, 'file:'+file) raise URLError('file not on local host')
10,334
def index(dir): """Return a list of (module-name, synopsis) pairs for a directory tree.""" results = [] for entry in os.listdir(dir): path = os.path.join(dir, entry) if ispackage(path): results.extend(map( lambda (m, s), pkg=entry: (pkg + '.' + m, s), index(path))) elif os.path.isfile(path) and entry[-3:] == '.py': results.append((entry[:-3], synopsis(path))) return results
def index(dir): """Return a list of (module-name, synopsis) pairs for a directory tree.""" results = [] for entry in os.listdir(dir): path = os.path.join(dir, entry) if ispackage(path): results.extend(map( lambda (m, s), pkg=entry: (pkg + '.' + m, s), index(path))) elif os.path.isfile(path) and entry[-3:] == '.py': results.append((entry[:-3], synopsis(path))) return results
10,335
def modulename(path): """Return the Python module name for a given path, or None.""" filename = os.path.basename(path) if lower(filename[-3:]) == '.py': return filename[:-3] elif lower(filename[-4:]) == '.pyc': return filename[:-4] elif lower(filename[-11:]) == 'module.so': return filename[:-11] elif lower(filename[-13:]) == 'module.so.1': return filename[:-13]
def modulename(path): """Return the Python module name for a given path, or None.""" filename = os.path.basename(path) if lower(filename[-3:]) == '.py': return filename[:-3] elif lower(filename[-4:]) in ['.pyc', '.pyd', '.pyo']: return filename[:-4] elif lower(filename[-11:]) == 'module.so': return filename[:-11] elif lower(filename[-13:]) == 'module.so.1': return filename[:-13]
10,336
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.ismethod(object): return apply(self.docmethod, args) if inspect.isbuiltin(object): return apply(self.docbuiltin, args) if inspect.isfunction(object): return apply(self.docfunction, args) raise TypeError, "don't know how to document objects of type " + \ type(object).__name__
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 know how to document objects of type " + \ type(object).__name__
10,337
def heading(self, title, fgcol, bgcol, extras=''): """Format a page heading.""" return """
def heading(self, title, fgcol, bgcol, extras=''): """Format a page heading.""" return """
10,338
def heading(self, title, fgcol, bgcol, extras=''): """Format a page heading.""" return """
def heading(self, title, fgcol, bgcol, extras=''): """Format a page heading.""" return """
10,339
def section(self, title, fgcol, bgcol, contents, width=20, prelude='', marginalia=None, gap='&nbsp;&nbsp;&nbsp;'): """Format a section with a heading.""" if marginalia is None: marginalia = '&nbsp;' * width result = """
def section(self, title, fgcol, bgcol, contents, width=20, prelude='', marginalia=None, gap='&nbsp;&nbsp;&nbsp;'): """Format a section with a heading.""" if marginalia is None: marginalia = '&nbsp;' * width result = """
10,340
def bigsection(self, title, *args): """Format a section with a big heading.""" title = '<big><strong>%s</strong></big>' % title return apply(self.section, (title,) + args)
def bigsection(self, title, *args): """Format a section with a big heading.""" title = '<big><strong>%s</strong></big>' % title return apply(self.section, (title,) + args)
10,341
def docmodule(self, object): """Produce HTML documentation for a module object.""" name = object.__name__ result = '' head = '<br><big><big><strong>&nbsp;%s</strong></big></big>' % name try: path = os.path.abspath(inspect.getfile(object)) filelink = '<a href="file:%s">%s</a>' % (path, path) except TypeError: filelink = '(built-in)' info = [] if hasattr(object, '__version__'): version = str(object.__version__) if version[:11] == '$' + 'Revision: ' and version[-1:] == '$': version = strip(version[11:-1]) info.append('version %s' % self.escape(version)) if hasattr(object, '__date__'): info.append(self.escape(str(object.__date__))) if info: head = head + ' (%s)' % join(info, ', ') result = result + self.heading( head, '#ffffff', '#7799ee', '<a href=".">index</a><br>' + filelink)
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=" (join(parts[:i+1], '.'), parts[i])) linkedname = join(links + parts[-1:], '.') head = '<big><big><strong>%s</strong></big></big>' % linkedname try: path = os.path.abspath(inspect.getfile(object)) filelink = '<a href="file:%s">%s</a>' % (path, path) except TypeError: filelink = '(built-in)' info = [] if hasattr(object, '__version__'): version = str(object.__version__) if version[:11] == '$' + 'Revision: ' and version[-1:] == '$': version = strip(version[11:-1]) info.append('version %s' % self.escape(version)) if hasattr(object, '__date__'): info.append(self.escape(str(object.__date__))) if info: head = head + ' (%s)' % join(info, ', ') result = result + self.heading( head, '#ffffff', '#7799ee', '<a href=".">index</a><br>' + filelink)
10,342
def docmodule(self, object): """Produce HTML documentation for a module object.""" name = object.__name__ result = '' head = '<br><big><big><strong>&nbsp;%s</strong></big></big>' % name try: path = os.path.abspath(inspect.getfile(object)) filelink = '<a href="file:%s">%s</a>' % (path, path) except TypeError: filelink = '(built-in)' info = [] if hasattr(object, '__version__'): version = str(object.__version__) if version[:11] == '$' + 'Revision: ' and version[-1:] == '$': version = strip(version[11:-1]) info.append('version %s' % self.escape(version)) if hasattr(object, '__date__'): info.append(self.escape(str(object.__date__))) if info: head = head + ' (%s)' % join(info, ', ') result = result + self.heading( head, '#ffffff', '#7799ee', '<a href=".">index</a><br>' + filelink)
def docmodule(self, object): """Produce HTML documentation for a module object.""" name = object.__name__ result = '' head = '<br><big><big><strong>&nbsp;%s</strong></big></big>' % name try: path = os.path.abspath(inspect.getfile(object)) filelink = '<a href="file:%s">%s</a>' % (path, path) except TypeError: filelink = '(built-in)' info = [] if hasattr(object, '__version__'): version = str(object.__version__) if version[:11] == '$' + 'Revision: ' and version[-1:] == '$': version = strip(version[11:-1]) info.append('version %s' % self.escape(version)) if hasattr(object, '__date__'): info.append(self.escape(str(object.__date__))) if info: head = head + ' (%s)' % join(info, ', ') result = self.heading( head, '#ffffff', '#7799ee', '<a href=".">index</a><br>' + filelink)
10,343
def docclass(self, object, funcs={}, classes={}): """Produce HTML documentation for a class object.""" name = object.__name__ bases = object.__bases__ contents = ''
def docclass(self, object, funcs={}, classes={}): """Produce HTML documentation for a class object.""" name = object.__name__ bases = object.__bases__ contents = ''
10,344
def docclass(self, object, funcs={}, classes={}): """Produce HTML documentation for a class object.""" name = object.__name__ bases = object.__bases__ contents = ''
def docclass(self, object, funcs={}, classes={}): """Produce HTML documentation for a class object.""" name = object.__name__ bases = object.__bases__ contents = ''
10,345
def docfunction(self, object, funcs={}, classes={}, methods={}, clname=''): """Produce HTML documentation for a function object.""" args, varargs, varkw, defaults = inspect.getargspec(object) argspec = inspect.formatargspec( args, varargs, varkw, defaults, formatvalue=self.formatvalue)
def docfunction(self, object, funcs={}, classes={}, methods={}, clname=''): """Produce HTML documentation for a function object.""" args, varargs, varkw, defaults = inspect.getargspec(object) argspec = inspect.formatargspec( args, varargs, varkw, defaults, formatvalue=self.formatvalue)
10,346
def docfunction(self, object, funcs={}, classes={}, methods={}, clname=''): """Produce HTML documentation for a function object.""" args, varargs, varkw, defaults = inspect.getargspec(object) argspec = inspect.formatargspec( args, varargs, varkw, defaults, formatvalue=self.formatvalue)
def docfunction(self, object, funcs={}, classes={}, methods={}, clname=''): """Produce HTML documentation for a function object.""" args, varargs, varkw, defaults = inspect.getargspec(object) argspec = inspect.formatargspec( args, varargs, varkw, defaults, formatvalue=self.formatvalue)
10,347
def docbuiltin(self, object, *extras): """Produce HTML documentation for a built-in function.""" return '<dl><dt><strong>%s</strong>(...)</dl>' % object.__name__
def docbuiltin(self, object, *extras): """Produce HTML documentation for a built-in function.""" return '<dl><dt><strong>%s</strong>(...)</dl>' % object.__name__
10,348
def page(self, object): """Produce a complete HTML page of documentation for an object.""" return '''<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN">
def page(self, object): """Produce a complete HTML page of documentation for an object.""" return '''<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN">
10,349
def docmethod(self, object): """Produce text documentation for a method object.""" return self.document(object.im_func)
def docmethod(self, object): """Produce text documentation for a method object.""" return self.document(object.im_func)
10,350
def docfunction(self, object): """Produce text documentation for a function object.""" try: args, varargs, varkw, defaults = inspect.getargspec(object) argspec = inspect.formatargspec( args, varargs, varkw, defaults, formatvalue=self.formatvalue) except TypeError: argspec = '(...)'
def docroutine(self, object): """Produce text documentation for a function or method object.""" if inspect.ismethod(object): object = object.im_func if inspect.isbuiltin(object): decl = self.bold(object.__name__) + '(...)' else: args, varargs, varkw, defaults = inspect.getargspec(object) argspec = inspect.formatargspec( args, varargs, varkw, defaults, formatvalue=self.formatvalue) except TypeError: argspec = '(...)'
10,351
def docfunction(self, object): """Produce text documentation for a function object.""" try: args, varargs, varkw, defaults = inspect.getargspec(object) argspec = inspect.formatargspec( args, varargs, varkw, defaults, formatvalue=self.formatvalue) except TypeError: argspec = '(...)'
def docfunction(self, object): """Produce text documentation for a function object.""" try: args, varargs, varkw, defaults = inspect.getargspec(object) argspec = inspect.formatargspec( args, varargs, varkw, defaults, formatvalue=self.formatvalue) except TypeError: argspec = '(...)'
10,352
def docfunction(self, object): """Produce text documentation for a function object.""" try: args, varargs, varkw, defaults = inspect.getargspec(object) argspec = inspect.formatargspec( args, varargs, varkw, defaults, formatvalue=self.formatvalue) except TypeError: argspec = '(...)'
def docfunction(self, object): """Produce text documentation for a function object.""" try: args, varargs, varkw, defaults = inspect.getargspec(object) argspec = inspect.formatargspec( args, varargs, varkw, defaults, formatvalue=self.formatvalue) except TypeError: argspec = '(...)'
10,353
def locate(path): """Locate an object by name (or dotted path), importing as necessary.""" if not path: # special case: imp.find_module('') strangely succeeds return None, None if type(path) is not types.StringType: return None, path if hasattr(__builtins__, path): return None, getattr(__builtins__, path) parts = split(path, '.') n = 1 while n <= len(parts): path = join(parts[:n], '.') try: module = __import__(path) module = reload(module) except: # Did the error occur before or after we found the module? if sys.modules.has_key(path): filename = sys.modules[path].__file__ elif sys.exc_type is SyntaxError: filename = sys.exc_value.filename else: # module not found, so stop looking break # error occurred in the imported module, so report it raise DocImportError(filename, sys.exc_type, sys.exc_value) try: x = module for p in parts[1:]: x = getattr(x, p) return join(parts[:-1], '.'), x except AttributeError: n = n + 1 continue return None, None
def locate(path): """Locate an object by name (or dotted path), importing as necessary.""" if not path: # special case: imp.find_module('') strangely succeeds return None, None if type(path) is not types.StringType: return None, path parts = split(path, '.') n = 1 while n <= len(parts): path = join(parts[:n], '.') try: module = __import__(path) module = reload(module) except: # Did the error occur before or after we found the module? if sys.modules.has_key(path): filename = sys.modules[path].__file__ elif sys.exc_type is SyntaxError: filename = sys.exc_value.filename else: # module not found, so stop looking break # error occurred in the imported module, so report it raise DocImportError(filename, sys.exc_type, sys.exc_value) try: x = module for p in parts[1:]: x = getattr(x, p) return join(parts[:-1], '.'), x except AttributeError: n = n + 1 continue return None, None
10,354
def locate(path): """Locate an object by name (or dotted path), importing as necessary.""" if not path: # special case: imp.find_module('') strangely succeeds return None, None if type(path) is not types.StringType: return None, path if hasattr(__builtins__, path): return None, getattr(__builtins__, path) parts = split(path, '.') n = 1 while n <= len(parts): path = join(parts[:n], '.') try: module = __import__(path) module = reload(module) except: # Did the error occur before or after we found the module? if sys.modules.has_key(path): filename = sys.modules[path].__file__ elif sys.exc_type is SyntaxError: filename = sys.exc_value.filename else: # module not found, so stop looking break # error occurred in the imported module, so report it raise DocImportError(filename, sys.exc_type, sys.exc_value) try: x = module for p in parts[1:]: x = getattr(x, p) return join(parts[:-1], '.'), x except AttributeError: n = n + 1 continue return None, None
def locate(path): """Locate an object by name (or dotted path), importing as necessary.""" if not path: # special case: imp.find_module('') strangely succeeds return None, None if type(path) is not types.StringType: return None, path if hasattr(__builtins__, path): return None, getattr(__builtins__, path) parts = split(path, '.') n = 1 while n <= len(parts): path = join(parts[:n], '.') try: module = __import__(path) module = reload(module) except: # Did the error occur before or after we found the module? if sys.modules.has_key(path): filename = sys.modules[path].__file__ elif sys.exc_type is SyntaxError: filename = sys.exc_value.filename else: # module not found, so stop looking break # error occurred in the imported module, so report it raise DocImportError(filename, sys.exc_type, sys.exc_value) try: x = module for p in parts[1:]: x = getattr(x, p) return join(parts[:-1], '.'), x except AttributeError: n = n + 1 continue return None, None
10,355
def doc(thing): """Display documentation on an object (for interactive use).""" if type(thing) is type(""): try: path, x = locate(thing) except DocImportError, value: print 'problem in %s - %s' % (value.filename, value.args) return if x: thing = x else: print 'could not find or import %s' % repr(thing) return desc = describe(thing) module = inspect.getmodule(thing) if module and module is not thing: desc = desc + ' in module ' + module.__name__ pager('Help on %s:\n\n' % desc + text.document(thing))
def doc(thing): """Display documentation on an object (for interactive use).""" if type(thing) is type(""): try: path, x = locate(thing) except DocImportError, value: print 'Problem in %s - %s' % (value.filename, value.args) return if x: thing = x else: print 'could not find or import %s' % repr(thing) return desc = describe(thing) module = inspect.getmodule(thing) if module and module is not thing: desc = desc + ' in module ' + module.__name__ pager('Help on %s:\n\n' % desc + text.document(thing))
10,356
def doc(thing): """Display documentation on an object (for interactive use).""" if type(thing) is type(""): try: path, x = locate(thing) except DocImportError, value: print 'problem in %s - %s' % (value.filename, value.args) return if x: thing = x else: print 'could not find or import %s' % repr(thing) return desc = describe(thing) module = inspect.getmodule(thing) if module and module is not thing: desc = desc + ' in module ' + module.__name__ pager('Help on %s:\n\n' % desc + text.document(thing))
def doc(thing): """Display documentation on an object (for interactive use).""" if type(thing) is type(""): try: path, x = locate(thing) except DocImportError, value: print 'problem in %s - %s' % (value.filename, value.args) return if x: thing = x else: print 'No Python documentation found for %s.' % repr(thing) return desc = describe(thing) module = inspect.getmodule(thing) if module and module is not thing: desc = desc + ' in module ' + module.__name__ pager('Help on %s:\n\n' % desc + text.document(thing))
10,357
def doc(thing): """Display documentation on an object (for interactive use).""" if type(thing) is type(""): try: path, x = locate(thing) except DocImportError, value: print 'problem in %s - %s' % (value.filename, value.args) return if x: thing = x else: print 'could not find or import %s' % repr(thing) return desc = describe(thing) module = inspect.getmodule(thing) if module and module is not thing: desc = desc + ' in module ' + module.__name__ pager('Help on %s:\n\n' % desc + text.document(thing))
def doc(thing): """Display documentation on an object (for interactive use).""" if type(thing) is type(""): try: path, x = locate(thing) except DocImportError, value: print 'problem in %s - %s' % (value.filename, value.args) return if x: thing = x else: print 'could not find or import %s' % repr(thing) return desc = describe(thing) module = inspect.getmodule(thing) if module and module is not thing: desc = desc + ' in module ' + module.__name__ pager('Help on %s:\n\n' % desc + text.document(thing))
10,358
def man(key): """Display documentation on an object in a form similar to man(1).""" path, object = locate(key) if object: title = 'Python Library Documentation: ' + describe(object) if path: title = title + ' in ' + path pager('\n' + title + '\n\n' + text.document(object)) found = 1 else: print 'could not find or import %s' % repr(key)
def man(key): """Display documentation on an object in a form similar to man(1).""" path, object = locate(key) if object: title = 'Python Library Documentation: ' + describe(object) if path: title = title + ' in ' + path pager('\n' + title + '\n\n' + text.document(object)) found = 1 else: print 'No Python documentation found for %s.' % repr(key) class Scanner: """A generic tree iterator.""" def __init__(self, roots, children, recurse): self.roots = roots[:] self.state = [] self.children = children self.recurse = recurse def next(self): if not self.state: if not self.roots: return None root = self.roots.pop(0) self.state = [(root, self.children(root))] node, children = self.state[-1] if not children: self.state.pop() return self.next() child = children.pop(0) if self.recurse(child): self.state.append((child, self.children(child))) return child class ModuleScanner(Scanner): """An interruptible scanner that searches module synopses.""" def __init__(self): roots = map(lambda dir: (dir, ''), pathdirs()) Scanner.__init__(self, roots, self.submodules, self.ispackage) def submodules(self, (dir, package)): children = [] for file in os.listdir(dir): path = os.path.join(dir, file) if ispackage(path): children.append((path, package + (package and '.') + file)) else: children.append((path, package)) children.sort() return children def ispackage(self, (dir, package)): return ispackage(dir) def run(self, key, callback, completer=None): self.quit = 0 seen = {} for modname in sys.builtin_module_names: seen[modname] = 1 desc = split(__import__(modname).__doc__ or '', '\n')[0] if find(lower(modname + ' - ' + desc), lower(key)) >= 0: callback(None, modname, desc) while not self.quit: node = self.next() if not node: break path, package = node modname = modulename(path) if os.path.isfile(path) and modname: modname = package + (package and '.') + modname if not seen.has_key(modname): seen[modname] = 1 desc = synopsis(path) or '' if find(lower(modname + ' - ' + desc), lower(key)) >= 0: callback(path, modname, desc) if completer: completer()
10,359
def apropos(key): """Print all the one-line module summaries that contain a substring.""" key = lower(key) for module in sys.builtin_module_names: desc = __import__(module).__doc__ or '' desc = split(desc, '\n')[0] if find(lower(module + ' ' + desc), key) >= 0: print module, '-', desc or '(no description)' modules = [] for dir in pathdirs(): for module, desc in index(dir): desc = desc or '' if module not in modules: modules.append(module) if find(lower(module + ' ' + desc), key) >= 0: desc = desc or '(no description)' if module[-9:] == '.__init__': print module[:-9], '(package) -', desc else: print module, '-', desc
def apropos(key): """Print all the one-line module summaries that contain a substring.""" def callback(path, modname, desc): if modname[-9:] == '.__init__': modname = modname[:-9] + ' (package)' print modname, '-', desc or '(no description)' ModuleScanner().run(key, callback)
10,360
def serve(address, callback=None): import BaseHTTPServer, mimetools # 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, fp, seekable) self.encodingheader = self.getheader('content-transfer-encoding') self.typeheader = self.getheader('content-type') self.parsetype() self.parseplist() class DocHandler(BaseHTTPServer.BaseHTTPRequestHandler): def send_document(self, title, contents): self.send_response(200) self.send_header('Content-Type', 'text/html') self.end_headers() self.wfile.write(
def serve(port, callback=None): import BaseHTTPServer, 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, fp, seekable) self.encodingheader = self.getheader('content-transfer-encoding') self.typeheader = self.getheader('content-type') self.parsetype() self.parseplist() class DocHandler(BaseHTTPServer.BaseHTTPRequestHandler): def send_document(self, title, contents): self.send_response(200) self.send_header('Content-Type', 'text/html') self.end_headers() self.wfile.write(
10,361
def send_document(self, title, contents): self.send_response(200) self.send_header('Content-Type', 'text/html') self.end_headers() self.wfile.write(
def send_document(self, title, contents): self.send_response(200) self.send_header('Content-Type', 'text/html') self.end_headers() self.wfile.write(
10,362
def do_GET(self): path = self.path if path[-5:] == '.html': path = path[:-5] if path[:1] == '/': path = path[1:] if path and path != '.': try: p, x = locate(path) except DocImportError, value: self.send_document(path, html.escape( 'problem with %s - %s' % (value.filename, value.args))) return if x: self.send_document(describe(x), html.document(x)) else: self.send_document(path,
def do_GET(self): path = self.path if path[-5:] == '.html': path = path[:-5] if path[:1] == '/': path = path[1:] if path and path != '.': try: p, x = locate(path) except DocImportError, value: self.send_document(path, html.escape( 'Problem in %s - %s' % (value.filename, value.args))) return if x: self.send_document(describe(x), html.document(x)) else: self.send_document(path,
10,363
def do_GET(self): path = self.path if path[-5:] == '.html': path = path[:-5] if path[:1] == '/': path = path[1:] if path and path != '.': try: p, x = locate(path) except DocImportError, value: self.send_document(path, html.escape( 'problem with %s - %s' % (value.filename, value.args))) return if x: self.send_document(describe(x), html.document(x)) else: self.send_document(path,
def do_GET(self): path = self.path if path[-5:] == '.html': path = path[:-5] if path[:1] == '/': path = path[1:] if path and path != '.': try: p, x = locate(path) except DocImportError, value: self.send_document(path, html.escape( 'problem with %s - %s' % (value.filename, value.args))) return if x: self.send_document(describe(x), html.document(x)) else: self.send_document(path,
10,364
def do_GET(self): path = self.path if path[-5:] == '.html': path = path[:-5] if path[:1] == '/': path = path[1:] if path and path != '.': try: p, x = locate(path) except DocImportError, value: self.send_document(path, html.escape( 'problem with %s - %s' % (value.filename, value.args))) return if x: self.send_document(describe(x), html.document(x)) else: self.send_document(path,
def do_GET(self): path = self.path if path[-5:] == '.html': path = path[:-5] if path[:1] == '/': path = path[1:] if path and path != '.': try: p, x = locate(path) except DocImportError, value: self.send_document(path, html.escape( 'problem with %s - %s' % (value.filename, value.args))) return if x: self.send_document(describe(x), html.document(x)) else: self.send_document(path,
10,365
def do_GET(self): path = self.path if path[-5:] == '.html': path = path[:-5] if path[:1] == '/': path = path[1:] if path and path != '.': try: p, x = locate(path) except DocImportError, value: self.send_document(path, html.escape( 'problem with %s - %s' % (value.filename, value.args))) return if x: self.send_document(describe(x), html.document(x)) else: self.send_document(path,
def do_GET(self): path = self.path if path[-5:] == '.html': path = path[:-5] if path[:1] == '/': path = path[1:] if path and path != '.': try: p, x = locate(path) except DocImportError, value: self.send_document(path, html.escape( 'problem with %s - %s' % (value.filename, value.args))) return if x: self.send_document(describe(x), html.document(x)) else: self.send_document(path,
10,366
def __init__(self, address, callback): self.callback = callback self.base.__init__(self, address, self.handler)
def __init__(self, port, callback): self.address = ('127.0.0.1', port) self.url = 'http://127.0.0.1:%d/' % port self.callback = callback self.base.__init__(self, address, self.handler)
10,367
def __init__(self, address, callback): self.callback = callback self.base.__init__(self, address, self.handler)
def __init__(self, address, callback): self.callback = callback self.base.__init__(self, address, self.handler)
10,368
def server_activate(self): self.base.server_activate(self) if self.callback: self.callback()
def server_activate(self): self.base.server_activate(self) if self.callback: self.callback()
10,369
def server_activate(self): self.base.server_activate(self) if self.callback: self.callback()
def server_activate(self): self.base.server_activate(self) if self.callback: self.callback()
10,370
def server_activate(self): self.base.server_activate(self) if self.callback: self.callback()
def server_activate(self): self.base.server_activate(self) if self.callback: self.callback()
10,371
def cli(): import getopt class BadUsage: pass try: opts, args = getopt.getopt(sys.argv[1:], 'k:p:w') writing = 0 for opt, val in opts: if opt == '-k': apropos(lower(val)) break if opt == '-p': try: port = int(val) except ValueError: raise BadUsage def ready(port=port): print 'server ready at http://127.0.0.1:%d/' % port serve(('127.0.0.1', port), ready) break if opt == '-w': if not args: raise BadUsage writing = 1 else: if args: for arg in args: try: if os.path.isfile(arg): arg = importfile(arg) if writing: if os.path.isdir(arg): writedocs(arg) else: writedoc(arg) else: man(arg) except DocImportError, value: print 'problem in %s - %s' % ( value.filename, value.args) else: if sys.platform in ['mac', 'win', 'win32', 'nt']: # GUI platforms with threading import threading ready = threading.Event() address = ('127.0.0.1', 12346) threading.Thread( target=serve, args=(address, ready.set)).start() ready.wait() import webbrowser webbrowser.open('http://127.0.0.1:12346/') else: raise BadUsage except (getopt.error, BadUsage): print """%s <name> ... Show documentation on something. <name> may be the name of a Python function, module, or package, or a dotted reference to a class or function within a module or module in a package, or the filename of a Python module to import.
def cli(): import getopt class BadUsage: pass try: if sys.platform in ['mac', 'win', 'win32', 'nt'] and not sys.argv[1:]: gui() return opts, args = getopt.getopt(sys.argv[1:], 'gk:p:w') writing = 0 for opt, val in opts: if opt == '-k': apropos(lower(val)) break if opt == '-p': try: port = int(val) except ValueError: raise BadUsage def ready(port=port): print 'server ready at http://127.0.0.1:%d/' % port serve(('127.0.0.1', port), ready) break if opt == '-w': if not args: raise BadUsage writing = 1 else: if args: for arg in args: try: if os.path.isfile(arg): arg = importfile(arg) if writing: if os.path.isdir(arg): writedocs(arg) else: writedoc(arg) else: man(arg) except DocImportError, value: print 'problem in %s - %s' % ( value.filename, value.args) else: if sys.platform in ['mac', 'win', 'win32', 'nt']: # GUI platforms with threading import threading ready = threading.Event() address = ('127.0.0.1', 12346) threading.Thread( target=serve, args=(address, ready.set)).start() ready.wait() import webbrowser webbrowser.open('http://127.0.0.1:12346/') else: raise BadUsage except (getopt.error, BadUsage): print """%s <name> ... Show documentation on something. <name> may be the name of a Python function, module, or package, or a dotted reference to a class or function within a module or module in a package, or the filename of a Python module to import.
10,372
def cli(): import getopt class BadUsage: pass try: opts, args = getopt.getopt(sys.argv[1:], 'k:p:w') writing = 0 for opt, val in opts: if opt == '-k': apropos(lower(val)) break if opt == '-p': try: port = int(val) except ValueError: raise BadUsage def ready(port=port): print 'server ready at http://127.0.0.1:%d/' % port serve(('127.0.0.1', port), ready) break if opt == '-w': if not args: raise BadUsage writing = 1 else: if args: for arg in args: try: if os.path.isfile(arg): arg = importfile(arg) if writing: if os.path.isdir(arg): writedocs(arg) else: writedoc(arg) else: man(arg) except DocImportError, value: print 'problem in %s - %s' % ( value.filename, value.args) else: if sys.platform in ['mac', 'win', 'win32', 'nt']: # GUI platforms with threading import threading ready = threading.Event() address = ('127.0.0.1', 12346) threading.Thread( target=serve, args=(address, ready.set)).start() ready.wait() import webbrowser webbrowser.open('http://127.0.0.1:12346/') else: raise BadUsage except (getopt.error, BadUsage): print """%s <name> ... Show documentation on something. <name> may be the name of a Python function, module, or package, or a dotted reference to a class or function within a module or module in a package, or the filename of a Python module to import.
def cli(): import getopt class BadUsage: pass try: opts, args = getopt.getopt(sys.argv[1:], 'k:p:w') writing = 0 for opt, val in opts: if opt == '-k': apropos(val) return if opt == '-p': try: port = int(val) except ValueError: raise BadUsage def ready(port=port): print 'server ready at http://127.0.0.1:%d/' % port serve(('127.0.0.1', port), ready) break if opt == '-w': if not args: raise BadUsage writing = 1 else: if args: for arg in args: try: if os.path.isfile(arg): arg = importfile(arg) if writing: if os.path.isdir(arg): writedocs(arg) else: writedoc(arg) else: man(arg) except DocImportError, value: print 'problem in %s - %s' % ( value.filename, value.args) else: if sys.platform in ['mac', 'win', 'win32', 'nt']: # GUI platforms with threading import threading ready = threading.Event() address = ('127.0.0.1', 12346) threading.Thread( target=serve, args=(address, ready.set)).start() ready.wait() import webbrowser webbrowser.open('http://127.0.0.1:12346/') else: raise BadUsage except (getopt.error, BadUsage): print """%s <name> ... Show documentation on something. <name> may be the name of a Python function, module, or package, or a dotted reference to a class or function within a module or module in a package, or the filename of a Python module to import.
10,373
def ready(port=port): print 'server ready at http://127.0.0.1:%d/' % port
def ready(port=port): print 'server ready at http://127.0.0.1:%d/' % port
10,374
def ready(port=port): print 'server ready at http://127.0.0.1:%d/' % port
def ready(port=port): print 'server ready at http://127.0.0.1:%d/' % port
10,375
def ready(port=port): print 'server ready at http://127.0.0.1:%d/' % port
def ready(port=port): print 'server ready at http://127.0.0.1:%d/' % port
10,376
def ready(port=port): print 'server ready at http://127.0.0.1:%d/' % port
def ready(port=port): print 'server ready at http://127.0.0.1:%d/' % port
10,377
def ready(port=port): print 'server ready at http://127.0.0.1:%d/' % port
def ready(port=port): print 'server ready at http://127.0.0.1:%d/' % port
10,378
def ready(port=port): print 'server ready at http://127.0.0.1:%d/' % port
def ready(port=port): print 'server ready at http://127.0.0.1:%d/' % port
10,379
def para_msg(s): sys.stderr.write("*** %s\n" % s)
def para_msg(s): sys.stderr.write("*** %s\n" % s)
10,380
def find_all_elements_from_set(doc, gi_set, nodes=None): if nodes is None: nodes = [] if doc.nodeType == ELEMENT and doc.tagName in gi_set: nodes.append(doc) for child in doc.childNodes: if child.nodeType == ELEMENT: find_all_elements_from_set(child, gi_set, nodes) return nodes
def find_all_child_elements(doc, gi): nodes = [] for child in doc.childNodes: if child.nodeType == ELEMENT: if child.tagName == gi: nodes.append(child) return nodes def find_all_elements_from_set(doc, gi_set): return __find_all_elements_from_set(doc, gi_set, []) def __find_all_elements_from_set(doc, gi_set, nodes): if doc.nodeType == ELEMENT and doc.tagName in gi_set: nodes.append(doc) for child in doc.childNodes: if child.nodeType == ELEMENT: find_all_elements_from_set(child, gi_set, nodes) return nodes
10,381
def find_all_elements_from_set(doc, gi_set, nodes=None): if nodes is None: nodes = [] if doc.nodeType == ELEMENT and doc.tagName in gi_set: nodes.append(doc) for child in doc.childNodes: if child.nodeType == ELEMENT: find_all_elements_from_set(child, gi_set, nodes) return nodes
def find_all_elements_from_set(doc, gi_set, nodes=None): if nodes is None: nodes = [] if doc.nodeType == ELEMENT and doc.tagName in gi_set: nodes.append(doc) for child in doc.childNodes: if child.nodeType == ELEMENT: __find_all_elements_from_set(child, gi_set, nodes) return nodes
10,382
def rewrite_descriptor(doc, descriptor): # # Do these things: # 1. Add an "index=noindex" attribute to the element if the tagName # ends in 'ni', removing the 'ni' from the name. # 2. Create a <signature> from the name attribute and <args>. # 3. Create additional <signature>s from <*line{,ni}> elements, # if found. # 4. If a <versionadded> is found, move it to an attribute on the # descriptor. # 5. Move remaining child nodes to a <description> element. # 6. Put it back together. # descname = descriptor.tagName index = 1 if descname[-2:] == "ni": descname = descname[:-2] descriptor.setAttribute("index", "noindex") descriptor._node.name = descname index = 0 desctype = descname[:-4] # remove 'desc' linename = desctype + "line" if not index: linename = linename + "ni" # 2. signature = doc.createElement("signature") name = doc.createElement("name") signature.appendChild(doc.createTextNode("\n ")) signature.appendChild(name) name.appendChild(doc.createTextNode(descriptor.getAttribute("name"))) descriptor.removeAttribute("name") if descriptor.attributes.has_key("var"): variable = descriptor.getAttribute("var") if variable: args = doc.createElement("args") args.appendChild(doc.createTextNode(variable)) signature.appendChild(doc.createTextNode("\n ")) signature.appendChild(args) descriptor.removeAttribute("var") newchildren = [signature] children = descriptor.childNodes pos = skip_leading_nodes(children, 0) if pos < len(children): child = children[pos] if child.nodeType == ELEMENT and child.tagName == "args": # create an <args> in <signature>: args = doc.createElement("args") argchildren = [] map(argchildren.append, child.childNodes) for n in argchildren: child.removeChild(n) args.appendChild(n) signature.appendChild(doc.createTextNode("\n ")) signature.appendChild(args) signature.appendChild(doc.createTextNode("\n ")) # 3, 4. pos = skip_leading_nodes(children, pos + 1) while pos < len(children) \ and children[pos].nodeType == ELEMENT \ and children[pos].tagName in (linename, "versionadded"): if children[pos].tagName == linename: # this is really a supplemental signature, create <signature> sig = methodline_to_signature(doc, children[pos]) newchildren.append(sig) else: # <versionadded added=...> descriptor.setAttribute( "added", children[pos].getAttribute("version")) pos = skip_leading_nodes(children, pos + 1) # 5. description = doc.createElement("description") description.appendChild(doc.createTextNode("\n")) newchildren.append(description) move_children(descriptor, description, pos) last = description.childNodes[-1] if last.nodeType == TEXT: last.data = string.rstrip(last.data) + "\n " # 6. # should have nothing but whitespace and signature lines in <descriptor>; # discard them while descriptor.childNodes: descriptor.removeChild(descriptor.childNodes[0]) for node in newchildren: descriptor.appendChild(doc.createTextNode("\n ")) descriptor.appendChild(node) descriptor.appendChild(doc.createTextNode("\n"))
def rewrite_descriptor(doc, descriptor): # # Do these things: # 1. Add an "index=noindex" attribute to the element if the tagName # ends in 'ni', removing the 'ni' from the name. # 2. Create a <signature> from the name attribute and <args>. # 3. Create additional <signature>s from <*line{,ni}> elements, # if found. # 4. If a <versionadded> is found, move it to an attribute on the # descriptor. # 5. Move remaining child nodes to a <description> element. # 6. Put it back together. # descname = descriptor.tagName index = 1 if descname[-2:] == "ni": descname = descname[:-2] descriptor.setAttribute("index", "noindex") descriptor._node.name = descname index = 0 desctype = descname[:-4] # remove 'desc' linename = desctype + "line" if not index: linename = linename + "ni" # 2. signature = doc.createElement("signature") name = doc.createElement("name") signature.appendChild(doc.createTextNode("\n ")) signature.appendChild(name) name.appendChild(doc.createTextNode(descriptor.getAttribute("name"))) descriptor.removeAttribute("name") if descriptor.attributes.has_key("var"): variable = descriptor.getAttribute("var") if variable: args = doc.createElement("args") args.appendChild(doc.createTextNode(variable)) signature.appendChild(doc.createTextNode("\n ")) signature.appendChild(args) descriptor.removeAttribute("var") newchildren = [signature] children = descriptor.childNodes pos = skip_leading_nodes(children, 0) if pos < len(children): child = children[pos] if child.nodeType == ELEMENT and child.tagName == "args": # create an <args> in <signature>: args = doc.createElement("args") argchildren = [] map(argchildren.append, child.childNodes) for n in argchildren: child.removeChild(n) args.appendChild(n) signature.appendChild(doc.createTextNode("\n ")) signature.appendChild(args) signature.appendChild(doc.createTextNode("\n ")) # 3, 4. pos = skip_leading_nodes(children, pos + 1) while pos < len(children) \ and children[pos].nodeType == ELEMENT \ and children[pos].tagName in (linename, "versionadded"): if children[pos].tagName == linename: # this is really a supplemental signature, create <signature> sig = methodline_to_signature(doc, children[pos]) newchildren.append(sig) else: # <versionadded added=...> descriptor.setAttribute( "added", children[pos].getAttribute("version")) pos = skip_leading_nodes(children, pos + 1) # 5. description = doc.createElement("description") description.appendChild(doc.createTextNode("\n")) newchildren.append(description) move_children(descriptor, description, pos) last = description.childNodes[-1] if last.nodeType == TEXT: last.data = string.rstrip(last.data) + "\n " # 6. # should have nothing but whitespace and signature lines in <descriptor>; # discard them while descriptor.childNodes: descriptor.removeChild(descriptor.childNodes[0]) for node in newchildren: descriptor.appendChild(doc.createTextNode("\n ")) descriptor.appendChild(node) descriptor.appendChild(doc.createTextNode("\n"))
10,383
def rewrite_descriptor(doc, descriptor): # # Do these things: # 1. Add an "index=noindex" attribute to the element if the tagName # ends in 'ni', removing the 'ni' from the name. # 2. Create a <signature> from the name attribute and <args>. # 3. Create additional <signature>s from <*line{,ni}> elements, # if found. # 4. If a <versionadded> is found, move it to an attribute on the # descriptor. # 5. Move remaining child nodes to a <description> element. # 6. Put it back together. # descname = descriptor.tagName index = 1 if descname[-2:] == "ni": descname = descname[:-2] descriptor.setAttribute("index", "noindex") descriptor._node.name = descname index = 0 desctype = descname[:-4] # remove 'desc' linename = desctype + "line" if not index: linename = linename + "ni" # 2. signature = doc.createElement("signature") name = doc.createElement("name") signature.appendChild(doc.createTextNode("\n ")) signature.appendChild(name) name.appendChild(doc.createTextNode(descriptor.getAttribute("name"))) descriptor.removeAttribute("name") if descriptor.attributes.has_key("var"): variable = descriptor.getAttribute("var") if variable: args = doc.createElement("args") args.appendChild(doc.createTextNode(variable)) signature.appendChild(doc.createTextNode("\n ")) signature.appendChild(args) descriptor.removeAttribute("var") newchildren = [signature] children = descriptor.childNodes pos = skip_leading_nodes(children, 0) if pos < len(children): child = children[pos] if child.nodeType == ELEMENT and child.tagName == "args": # create an <args> in <signature>: args = doc.createElement("args") argchildren = [] map(argchildren.append, child.childNodes) for n in argchildren: child.removeChild(n) args.appendChild(n) signature.appendChild(doc.createTextNode("\n ")) signature.appendChild(args) signature.appendChild(doc.createTextNode("\n ")) # 3, 4. pos = skip_leading_nodes(children, pos + 1) while pos < len(children) \ and children[pos].nodeType == ELEMENT \ and children[pos].tagName in (linename, "versionadded"): if children[pos].tagName == linename: # this is really a supplemental signature, create <signature> sig = methodline_to_signature(doc, children[pos]) newchildren.append(sig) else: # <versionadded added=...> descriptor.setAttribute( "added", children[pos].getAttribute("version")) pos = skip_leading_nodes(children, pos + 1) # 5. description = doc.createElement("description") description.appendChild(doc.createTextNode("\n")) newchildren.append(description) move_children(descriptor, description, pos) last = description.childNodes[-1] if last.nodeType == TEXT: last.data = string.rstrip(last.data) + "\n " # 6. # should have nothing but whitespace and signature lines in <descriptor>; # discard them while descriptor.childNodes: descriptor.removeChild(descriptor.childNodes[0]) for node in newchildren: descriptor.appendChild(doc.createTextNode("\n ")) descriptor.appendChild(node) descriptor.appendChild(doc.createTextNode("\n"))
def rewrite_descriptor(doc, descriptor): # # Do these things: # 1. Add an "index=noindex" attribute to the element if the tagName # ends in 'ni', removing the 'ni' from the name. # 2. Create a <signature> from the name attribute and <args>. # 3. Create additional <signature>s from <*line{,ni}> elements, # if found. # 4. If a <versionadded> is found, move it to an attribute on the # descriptor. # 5. Move remaining child nodes to a <description> element. # 6. Put it back together. # descname = descriptor.tagName index = 1 if descname[-2:] == "ni": descname = descname[:-2] descriptor.setAttribute("index", "no") descriptor._node.name = descname index = 0 desctype = descname[:-4] # remove 'desc' linename = desctype + "line" if not index: linename = linename + "ni" # 2. signature = doc.createElement("signature") name = doc.createElement("name") signature.appendChild(doc.createTextNode("\n ")) signature.appendChild(name) name.appendChild(doc.createTextNode(descriptor.getAttribute("name"))) descriptor.removeAttribute("name") if descriptor.attributes.has_key("var"): variable = descriptor.getAttribute("var") if variable: args = doc.createElement("args") args.appendChild(doc.createTextNode(variable)) signature.appendChild(doc.createTextNode("\n ")) signature.appendChild(args) descriptor.removeAttribute("var") newchildren = [signature] children = descriptor.childNodes pos = skip_leading_nodes(children, 0) if pos < len(children): child = children[pos] if child.nodeType == ELEMENT and child.tagName == "args": # create an <args> in <signature>: args = doc.createElement("args") argchildren = [] map(argchildren.append, child.childNodes) for n in argchildren: child.removeChild(n) args.appendChild(n) signature.appendChild(doc.createTextNode("\n ")) signature.appendChild(args) signature.appendChild(doc.createTextNode("\n ")) # 3, 4. pos = skip_leading_nodes(children, pos + 1) while pos < len(children) \ and children[pos].nodeType == ELEMENT \ and children[pos].tagName in (linename, "versionadded"): if children[pos].tagName == linename: # this is really a supplemental signature, create <signature> sig = methodline_to_signature(doc, children[pos]) newchildren.append(sig) else: # <versionadded added=...> descriptor.setAttribute( "added", children[pos].getAttribute("version")) pos = skip_leading_nodes(children, pos + 1) # 5. description = doc.createElement("description") description.appendChild(doc.createTextNode("\n")) newchildren.append(description) move_children(descriptor, description, pos) last = description.childNodes[-1] if last.nodeType == TEXT: last.data = string.rstrip(last.data) + "\n " # 6. # should have nothing but whitespace and signature lines in <descriptor>; # discard them while descriptor.childNodes: descriptor.removeChild(descriptor.childNodes[0]) for node in newchildren: descriptor.appendChild(doc.createTextNode("\n ")) descriptor.appendChild(node) descriptor.appendChild(doc.createTextNode("\n"))
10,384
def create_module_info(doc, section): # Heavy. node = extract_first_element(section, "modulesynopsis") if node is None: return node._node.name = "synopsis" lastchild = node.childNodes[-1] if lastchild.nodeType == TEXT \ and lastchild.data[-1:] == ".": lastchild.data = lastchild.data[:-1] modauthor = extract_first_element(section, "moduleauthor") if modauthor: modauthor._node.name = "author" modauthor.appendChild(doc.createTextNode( modauthor.getAttribute("name"))) modauthor.removeAttribute("name") platform = extract_first_element(section, "platform") if section.tagName == "section": modinfo_pos = 2 modinfo = doc.createElement("moduleinfo") moddecl = extract_first_element(section, "declaremodule") name = None if moddecl: modinfo.appendChild(doc.createTextNode("\n ")) name = moddecl.attributes["name"].value namenode = doc.createElement("name") namenode.appendChild(doc.createTextNode(name)) modinfo.appendChild(namenode) type = moddecl.attributes.get("type") if type: type = type.value modinfo.appendChild(doc.createTextNode("\n ")) typenode = doc.createElement("type") typenode.appendChild(doc.createTextNode(type)) modinfo.appendChild(typenode) versionadded = extract_first_element(section, "versionadded") if versionadded: modinfo.setAttribute("added", versionadded.getAttribute("version")) title = get_first_element(section, "title") if title: children = title.childNodes if len(children) >= 2 \ and children[0].nodeType == ELEMENT \ and children[0].tagName == "module" \ and children[0].childNodes[0].data == name: # this is it; morph the <title> into <short-synopsis> first_data = children[1] if first_data.data[:4] == " ---": first_data.data = string.lstrip(first_data.data[4:]) title._node.name = "short-synopsis" if children[-1].nodeType == TEXT \ and children[-1].data[-1:] == ".": children[-1].data = children[-1].data[:-1] section.removeChild(title) section.removeChild(section.childNodes[0]) title.removeChild(children[0]) modinfo_pos = 0 else: sys.stderr.write( "module name in title doesn't match" " <declaremodule>; no <short-synopsis>\n") else: sys.stderr.write( "Unexpected condition: <section> without <title>\n") modinfo.appendChild(doc.createTextNode("\n ")) modinfo.appendChild(node) if title and not contents_match(title, node): # The short synopsis is actually different, # and needs to be stored: modinfo.appendChild(doc.createTextNode("\n ")) modinfo.appendChild(title) if modauthor: modinfo.appendChild(doc.createTextNode("\n ")) modinfo.appendChild(modauthor) if platform: modinfo.appendChild(doc.createTextNode("\n ")) modinfo.appendChild(platform) modinfo.appendChild(doc.createTextNode("\n ")) section.insertBefore(modinfo, section.childNodes[modinfo_pos]) section.insertBefore(doc.createTextNode("\n "), modinfo) # # The rest of this removes extra newlines from where we cut out # a lot of elements. A lot of code for minimal value, but keeps # keeps the generated SGML from being too funny looking. # section.normalize() children = section.childNodes for i in range(len(children)): node = children[i] if node.nodeType == ELEMENT \ and node.tagName == "moduleinfo": nextnode = children[i+1] if nextnode.nodeType == TEXT: data = nextnode.data if len(string.lstrip(data)) < (len(data) - 4): nextnode.data = "\n\n\n" + string.lstrip(data)
def create_module_info(doc, section): # Heavy. node = extract_first_element(section, "modulesynopsis") if node is None: return node._node.name = "synopsis" lastchild = node.childNodes[-1] if lastchild.nodeType == TEXT \ and lastchild.data[-1:] == ".": lastchild.data = lastchild.data[:-1] modauthor = extract_first_element(section, "moduleauthor") if modauthor: modauthor._node.name = "author" modauthor.appendChild(doc.createTextNode( modauthor.getAttribute("name"))) modauthor.removeAttribute("name") platform = extract_first_element(section, "platform") if section.tagName == "section": modinfo_pos = 2 modinfo = doc.createElement("moduleinfo") moddecl = extract_first_element(section, "declaremodule") name = None if moddecl: modinfo.appendChild(doc.createTextNode("\n ")) name = moddecl.attributes["name"].value namenode = doc.createElement("name") namenode.appendChild(doc.createTextNode(name)) modinfo.appendChild(namenode) type = moddecl.attributes.get("type") if type: type = type.value modinfo.appendChild(doc.createTextNode("\n ")) typenode = doc.createElement("type") typenode.appendChild(doc.createTextNode(type)) modinfo.appendChild(typenode) versionadded = extract_first_element(section, "versionadded") if versionadded: modinfo.setAttribute("added", versionadded.getAttribute("version")) title = get_first_element(section, "title") if title: children = title.childNodes if len(children) >= 2 \ and children[0].nodeType == ELEMENT \ and children[0].tagName == "module" \ and children[0].childNodes[0].data == name: # this is it; morph the <title> into <short-synopsis> first_data = children[1] if first_data.data[:4] == " ---": first_data.data = string.lstrip(first_data.data[4:]) title._node.name = "short-synopsis" if children[-1].nodeType == TEXT \ and children[-1].data[-1:] == ".": children[-1].data = children[-1].data[:-1] section.removeChild(title) section.removeChild(section.childNodes[0]) title.removeChild(children[0]) modinfo_pos = 0 else: ewrite("module name in title doesn't match" " <declaremodule/>; no <short-synopsis/>\n") else: sys.stderr.write( "Unexpected condition: <section> without <title>\n") modinfo.appendChild(doc.createTextNode("\n ")) modinfo.appendChild(node) if title and not contents_match(title, node): # The short synopsis is actually different, # and needs to be stored: modinfo.appendChild(doc.createTextNode("\n ")) modinfo.appendChild(title) if modauthor: modinfo.appendChild(doc.createTextNode("\n ")) modinfo.appendChild(modauthor) if platform: modinfo.appendChild(doc.createTextNode("\n ")) modinfo.appendChild(platform) modinfo.appendChild(doc.createTextNode("\n ")) section.insertBefore(modinfo, section.childNodes[modinfo_pos]) section.insertBefore(doc.createTextNode("\n "), modinfo) # # The rest of this removes extra newlines from where we cut out # a lot of elements. A lot of code for minimal value, but keeps # keeps the generated SGML from being too funny looking. # section.normalize() children = section.childNodes for i in range(len(children)): node = children[i] if node.nodeType == ELEMENT \ and node.tagName == "moduleinfo": nextnode = children[i+1] if nextnode.nodeType == TEXT: data = nextnode.data if len(string.lstrip(data)) < (len(data) - 4): nextnode.data = "\n\n\n" + string.lstrip(data)
10,385
def create_module_info(doc, section): # Heavy. node = extract_first_element(section, "modulesynopsis") if node is None: return node._node.name = "synopsis" lastchild = node.childNodes[-1] if lastchild.nodeType == TEXT \ and lastchild.data[-1:] == ".": lastchild.data = lastchild.data[:-1] modauthor = extract_first_element(section, "moduleauthor") if modauthor: modauthor._node.name = "author" modauthor.appendChild(doc.createTextNode( modauthor.getAttribute("name"))) modauthor.removeAttribute("name") platform = extract_first_element(section, "platform") if section.tagName == "section": modinfo_pos = 2 modinfo = doc.createElement("moduleinfo") moddecl = extract_first_element(section, "declaremodule") name = None if moddecl: modinfo.appendChild(doc.createTextNode("\n ")) name = moddecl.attributes["name"].value namenode = doc.createElement("name") namenode.appendChild(doc.createTextNode(name)) modinfo.appendChild(namenode) type = moddecl.attributes.get("type") if type: type = type.value modinfo.appendChild(doc.createTextNode("\n ")) typenode = doc.createElement("type") typenode.appendChild(doc.createTextNode(type)) modinfo.appendChild(typenode) versionadded = extract_first_element(section, "versionadded") if versionadded: modinfo.setAttribute("added", versionadded.getAttribute("version")) title = get_first_element(section, "title") if title: children = title.childNodes if len(children) >= 2 \ and children[0].nodeType == ELEMENT \ and children[0].tagName == "module" \ and children[0].childNodes[0].data == name: # this is it; morph the <title> into <short-synopsis> first_data = children[1] if first_data.data[:4] == " ---": first_data.data = string.lstrip(first_data.data[4:]) title._node.name = "short-synopsis" if children[-1].nodeType == TEXT \ and children[-1].data[-1:] == ".": children[-1].data = children[-1].data[:-1] section.removeChild(title) section.removeChild(section.childNodes[0]) title.removeChild(children[0]) modinfo_pos = 0 else: sys.stderr.write( "module name in title doesn't match" " <declaremodule>; no <short-synopsis>\n") else: sys.stderr.write( "Unexpected condition: <section> without <title>\n") modinfo.appendChild(doc.createTextNode("\n ")) modinfo.appendChild(node) if title and not contents_match(title, node): # The short synopsis is actually different, # and needs to be stored: modinfo.appendChild(doc.createTextNode("\n ")) modinfo.appendChild(title) if modauthor: modinfo.appendChild(doc.createTextNode("\n ")) modinfo.appendChild(modauthor) if platform: modinfo.appendChild(doc.createTextNode("\n ")) modinfo.appendChild(platform) modinfo.appendChild(doc.createTextNode("\n ")) section.insertBefore(modinfo, section.childNodes[modinfo_pos]) section.insertBefore(doc.createTextNode("\n "), modinfo) # # The rest of this removes extra newlines from where we cut out # a lot of elements. A lot of code for minimal value, but keeps # keeps the generated SGML from being too funny looking. # section.normalize() children = section.childNodes for i in range(len(children)): node = children[i] if node.nodeType == ELEMENT \ and node.tagName == "moduleinfo": nextnode = children[i+1] if nextnode.nodeType == TEXT: data = nextnode.data if len(string.lstrip(data)) < (len(data) - 4): nextnode.data = "\n\n\n" + string.lstrip(data)
def create_module_info(doc, section): # Heavy. node = extract_first_element(section, "modulesynopsis") if node is None: return node._node.name = "synopsis" lastchild = node.childNodes[-1] if lastchild.nodeType == TEXT \ and lastchild.data[-1:] == ".": lastchild.data = lastchild.data[:-1] modauthor = extract_first_element(section, "moduleauthor") if modauthor: modauthor._node.name = "author" modauthor.appendChild(doc.createTextNode( modauthor.getAttribute("name"))) modauthor.removeAttribute("name") platform = extract_first_element(section, "platform") if section.tagName == "section": modinfo_pos = 2 modinfo = doc.createElement("moduleinfo") moddecl = extract_first_element(section, "declaremodule") name = None if moddecl: modinfo.appendChild(doc.createTextNode("\n ")) name = moddecl.attributes["name"].value namenode = doc.createElement("name") namenode.appendChild(doc.createTextNode(name)) modinfo.appendChild(namenode) type = moddecl.attributes.get("type") if type: type = type.value modinfo.appendChild(doc.createTextNode("\n ")) typenode = doc.createElement("type") typenode.appendChild(doc.createTextNode(type)) modinfo.appendChild(typenode) versionadded = extract_first_element(section, "versionadded") if versionadded: modinfo.setAttribute("added", versionadded.getAttribute("version")) title = get_first_element(section, "title") if title: children = title.childNodes if len(children) >= 2 \ and children[0].nodeType == ELEMENT \ and children[0].tagName == "module" \ and children[0].childNodes[0].data == name: # this is it; morph the <title> into <short-synopsis> first_data = children[1] if first_data.data[:4] == " ---": first_data.data = string.lstrip(first_data.data[4:]) title._node.name = "short-synopsis" if children[-1].nodeType == TEXT \ and children[-1].data[-1:] == ".": children[-1].data = children[-1].data[:-1] section.removeChild(title) section.removeChild(section.childNodes[0]) title.removeChild(children[0]) modinfo_pos = 0 else: sys.stderr.write( "module name in title doesn't match" " <declaremodule>; no <short-synopsis>\n") else: ewrite("Unexpected condition: <section/> without <title/>\n") modinfo.appendChild(doc.createTextNode("\n ")) modinfo.appendChild(node) if title and not contents_match(title, node): # The short synopsis is actually different, # and needs to be stored: modinfo.appendChild(doc.createTextNode("\n ")) modinfo.appendChild(title) if modauthor: modinfo.appendChild(doc.createTextNode("\n ")) modinfo.appendChild(modauthor) if platform: modinfo.appendChild(doc.createTextNode("\n ")) modinfo.appendChild(platform) modinfo.appendChild(doc.createTextNode("\n ")) section.insertBefore(modinfo, section.childNodes[modinfo_pos]) section.insertBefore(doc.createTextNode("\n "), modinfo) # # The rest of this removes extra newlines from where we cut out # a lot of elements. A lot of code for minimal value, but keeps # keeps the generated SGML from being too funny looking. # section.normalize() children = section.childNodes for i in range(len(children)): node = children[i] if node.nodeType == ELEMENT \ and node.tagName == "moduleinfo": nextnode = children[i+1] if nextnode.nodeType == TEXT: data = nextnode.data if len(string.lstrip(data)) < (len(data) - 4): nextnode.data = "\n\n\n" + string.lstrip(data)
10,386
def create_module_info(doc, section): # Heavy. node = extract_first_element(section, "modulesynopsis") if node is None: return node._node.name = "synopsis" lastchild = node.childNodes[-1] if lastchild.nodeType == TEXT \ and lastchild.data[-1:] == ".": lastchild.data = lastchild.data[:-1] modauthor = extract_first_element(section, "moduleauthor") if modauthor: modauthor._node.name = "author" modauthor.appendChild(doc.createTextNode( modauthor.getAttribute("name"))) modauthor.removeAttribute("name") platform = extract_first_element(section, "platform") if section.tagName == "section": modinfo_pos = 2 modinfo = doc.createElement("moduleinfo") moddecl = extract_first_element(section, "declaremodule") name = None if moddecl: modinfo.appendChild(doc.createTextNode("\n ")) name = moddecl.attributes["name"].value namenode = doc.createElement("name") namenode.appendChild(doc.createTextNode(name)) modinfo.appendChild(namenode) type = moddecl.attributes.get("type") if type: type = type.value modinfo.appendChild(doc.createTextNode("\n ")) typenode = doc.createElement("type") typenode.appendChild(doc.createTextNode(type)) modinfo.appendChild(typenode) versionadded = extract_first_element(section, "versionadded") if versionadded: modinfo.setAttribute("added", versionadded.getAttribute("version")) title = get_first_element(section, "title") if title: children = title.childNodes if len(children) >= 2 \ and children[0].nodeType == ELEMENT \ and children[0].tagName == "module" \ and children[0].childNodes[0].data == name: # this is it; morph the <title> into <short-synopsis> first_data = children[1] if first_data.data[:4] == " ---": first_data.data = string.lstrip(first_data.data[4:]) title._node.name = "short-synopsis" if children[-1].nodeType == TEXT \ and children[-1].data[-1:] == ".": children[-1].data = children[-1].data[:-1] section.removeChild(title) section.removeChild(section.childNodes[0]) title.removeChild(children[0]) modinfo_pos = 0 else: sys.stderr.write( "module name in title doesn't match" " <declaremodule>; no <short-synopsis>\n") else: sys.stderr.write( "Unexpected condition: <section> without <title>\n") modinfo.appendChild(doc.createTextNode("\n ")) modinfo.appendChild(node) if title and not contents_match(title, node): # The short synopsis is actually different, # and needs to be stored: modinfo.appendChild(doc.createTextNode("\n ")) modinfo.appendChild(title) if modauthor: modinfo.appendChild(doc.createTextNode("\n ")) modinfo.appendChild(modauthor) if platform: modinfo.appendChild(doc.createTextNode("\n ")) modinfo.appendChild(platform) modinfo.appendChild(doc.createTextNode("\n ")) section.insertBefore(modinfo, section.childNodes[modinfo_pos]) section.insertBefore(doc.createTextNode("\n "), modinfo) # # The rest of this removes extra newlines from where we cut out # a lot of elements. A lot of code for minimal value, but keeps # keeps the generated SGML from being too funny looking. # section.normalize() children = section.childNodes for i in range(len(children)): node = children[i] if node.nodeType == ELEMENT \ and node.tagName == "moduleinfo": nextnode = children[i+1] if nextnode.nodeType == TEXT: data = nextnode.data if len(string.lstrip(data)) < (len(data) - 4): nextnode.data = "\n\n\n" + string.lstrip(data)
def create_module_info(doc, section): # Heavy. node = extract_first_element(section, "modulesynopsis") if node is None: return node._node.name = "synopsis" lastchild = node.childNodes[-1] if lastchild.nodeType == TEXT \ and lastchild.data[-1:] == ".": lastchild.data = lastchild.data[:-1] modauthor = extract_first_element(section, "moduleauthor") if modauthor: modauthor._node.name = "author" modauthor.appendChild(doc.createTextNode( modauthor.getAttribute("name"))) modauthor.removeAttribute("name") platform = extract_first_element(section, "platform") if section.tagName == "section": modinfo_pos = 2 modinfo = doc.createElement("moduleinfo") moddecl = extract_first_element(section, "declaremodule") name = None if moddecl: modinfo.appendChild(doc.createTextNode("\n ")) name = moddecl.attributes["name"].value namenode = doc.createElement("name") namenode.appendChild(doc.createTextNode(name)) modinfo.appendChild(namenode) type = moddecl.attributes.get("type") if type: type = type.value modinfo.appendChild(doc.createTextNode("\n ")) typenode = doc.createElement("type") typenode.appendChild(doc.createTextNode(type)) modinfo.appendChild(typenode) versionadded = extract_first_element(section, "versionadded") if versionadded: modinfo.setAttribute("added", versionadded.getAttribute("version")) title = get_first_element(section, "title") if title: children = title.childNodes if len(children) >= 2 \ and children[0].nodeType == ELEMENT \ and children[0].tagName == "module" \ and children[0].childNodes[0].data == name: # this is it; morph the <title> into <short-synopsis> first_data = children[1] if first_data.data[:4] == " ---": first_data.data = string.lstrip(first_data.data[4:]) title._node.name = "short-synopsis" if children[-1].nodeType == TEXT \ and children[-1].data[-1:] == ".": children[-1].data = children[-1].data[:-1] section.removeChild(title) section.removeChild(section.childNodes[0]) title.removeChild(children[0]) modinfo_pos = 0 else: sys.stderr.write( "module name in title doesn't match" " <declaremodule>; no <short-synopsis>\n") else: sys.stderr.write( "Unexpected condition: <section> without <title>\n") modinfo.appendChild(doc.createTextNode("\n ")) modinfo.appendChild(node) if title and not contents_match(title, node): # The short synopsis is actually different, # and needs to be stored: modinfo.appendChild(doc.createTextNode("\n ")) modinfo.appendChild(title) if modauthor: modinfo.appendChild(doc.createTextNode("\n ")) modinfo.appendChild(modauthor) if platform: modinfo.appendChild(doc.createTextNode("\n ")) modinfo.appendChild(platform) modinfo.appendChild(doc.createTextNode("\n ")) section.insertBefore(modinfo, section.childNodes[modinfo_pos]) section.insertBefore(doc.createTextNode("\n "), modinfo) # # The rest of this removes extra newlines from where we cut out # a lot of elements. A lot of code for minimal value, but keeps # keeps the generated SGML from being too funny looking. # section.normalize() children = section.childNodes for i in range(len(children)): node = children[i] if node.nodeType == ELEMENT \ and node.tagName == "moduleinfo": nextnode = children[i+1] if nextnode.nodeType == TEXT: data = nextnode.data if len(string.lstrip(data)) < (len(data) - 4): nextnode.data = "\n\n\n" + string.lstrip(data)
10,387
def cleanup_synopses(doc): for node in find_all_elements(doc, "section"): create_module_info(doc, node)
def cleanup_synopses(doc, fragment): for node in find_all_elements(fragment, "section"): create_module_info(doc, node)
10,388
def move_elements_by_name(doc, source, dest, name, sep=None): nodes = [] for child in source.childNodes: if child.nodeType == ELEMENT and child.tagName == name: nodes.append(child) for node in nodes: source.removeChild(node) dest.appendChild(node) if sep: dest.appendChild(doc.createTextNode(sep))
def move_elements_by_name(doc, source, dest, name, sep=None): nodes = [] for child in source.childNodes: if child.nodeType == ELEMENT and child.tagName == name: nodes.append(child) for node in nodes: source.removeChild(node) dest.appendChild(node) if sep: dest.appendChild(doc.createTextNode(sep))
10,389
def build_para(doc, parent, start, i): children = parent.childNodes after = start + 1 have_last = 0 BREAK_ELEMENTS = PARA_LEVEL_ELEMENTS + RECURSE_INTO_PARA_CONTAINERS # Collect all children until \n\n+ is found in a text node or a # member of BREAK_ELEMENTS is found. for j in range(start, i): after = j + 1 child = children[j] nodeType = child.nodeType if nodeType == ELEMENT: if child.tagName in BREAK_ELEMENTS: after = j break elif nodeType == TEXT: pos = string.find(child.data, "\n\n") if pos == 0: after = j break if pos >= 1: child.splitText(pos) break else: have_last = 1 if (start + 1) > after: raise ConversionError( "build_para() could not identify content to turn into a paragraph") if children[after - 1].nodeType == TEXT: # we may need to split off trailing white space: child = children[after - 1] data = child.data if string.rstrip(data) != data: have_last = 0 child.splitText(len(string.rstrip(data))) para = doc.createElement(PARA_ELEMENT) prev = None indexes = range(start, after) indexes.reverse() for j in indexes: node = parent.childNodes[j] parent.removeChild(node) para.insertBefore(node, prev) prev = node if have_last: parent.appendChild(para) return len(parent.childNodes) else: parent.insertBefore(para, parent.childNodes[start]) return start + 1
def build_para(doc, parent, start, i): children = parent.childNodes after = start + 1 have_last = 0 BREAK_ELEMENTS = PARA_LEVEL_ELEMENTS + RECURSE_INTO_PARA_CONTAINERS # Collect all children until \n\n+ is found in a text node or a # member of BREAK_ELEMENTS is found. for j in range(start, i): after = j + 1 child = children[j] nodeType = child.nodeType if nodeType == ELEMENT: if child.tagName in BREAK_ELEMENTS: after = j break elif nodeType == TEXT: pos = string.find(child.data, "\n\n") if pos == 0: after = j break if pos >= 1: child.splitText(pos) break else: have_last = 1 if (start + 1) > after: raise ConversionError( "build_para() could not identify content to turn into a paragraph") if children[after - 1].nodeType == TEXT: # we may need to split off trailing white space: child = children[after - 1] data = child.data if string.rstrip(data) != data: have_last = 0 child.splitText(len(string.rstrip(data))) para = doc.createElement(PARA_ELEMENT) prev = None indexes = range(start, after) indexes.reverse() for j in indexes: node = parent.childNodes[j] parent.removeChild(node) para.insertBefore(node, prev) prev = node if have_last: parent.appendChild(para) return len(parent.childNodes) else: nextnode = parent.childNodes[start] if nextnode.nodeType == TEXT: if nextnode.data and nextnode.data[0] != "\n": nextnode.data = "\n" + nextnode.data else: newnode = doc.createTextNode("\n") parent.insertBefore(newnode, nextnode) nextnode = newnode start = start + 1 parent.insertBefore(para, nextnode) return start + 1
10,390
def fixup_refmodindexes_chunk(container): # node is probably a <para>; let's see how often it isn't: if container.tagName != PARA_ELEMENT: sys.stderr.write("--- fixup_refmodindexes_chunk(%s)\n" % container) module_entries = find_all_elements(container, "module") if not module_entries: return index_entries = find_all_elements_from_set(container, REFMODINDEX_ELEMENTS) removes = [] for entry in index_entries: children = entry.childNodes if len(children) != 0: sys.stderr.write( "--- unexpected number of children for %s node:\n" % entry.tagName) sys.stderr.write(entry.toxml() + "\n") continue found = 0 module_name = entry.getAttribute("name") for node in module_entries: if len(node.childNodes) != 1: continue this_name = node.childNodes[0].data if this_name == module_name: found = 1 node.setAttribute("index", "index") if found: removes.append(entry) for node in removes: container.removeChild(node)
def fixup_refmodindexes_chunk(container): # node is probably a <para>; let's see how often it isn't: if container.tagName != PARA_ELEMENT: bwrite("--- fixup_refmodindexes_chunk(%s)\n" % container) module_entries = find_all_elements(container, "module") if not module_entries: return index_entries = find_all_elements_from_set(container, REFMODINDEX_ELEMENTS) removes = [] for entry in index_entries: children = entry.childNodes if len(children) != 0: sys.stderr.write( "--- unexpected number of children for %s node:\n" % entry.tagName) sys.stderr.write(entry.toxml() + "\n") continue found = 0 module_name = entry.getAttribute("name") for node in module_entries: if len(node.childNodes) != 1: continue this_name = node.childNodes[0].data if this_name == module_name: found = 1 node.setAttribute("index", "index") if found: removes.append(entry) for node in removes: container.removeChild(node)
10,391
def fixup_refmodindexes_chunk(container): # node is probably a <para>; let's see how often it isn't: if container.tagName != PARA_ELEMENT: sys.stderr.write("--- fixup_refmodindexes_chunk(%s)\n" % container) module_entries = find_all_elements(container, "module") if not module_entries: return index_entries = find_all_elements_from_set(container, REFMODINDEX_ELEMENTS) removes = [] for entry in index_entries: children = entry.childNodes if len(children) != 0: sys.stderr.write( "--- unexpected number of children for %s node:\n" % entry.tagName) sys.stderr.write(entry.toxml() + "\n") continue found = 0 module_name = entry.getAttribute("name") for node in module_entries: if len(node.childNodes) != 1: continue this_name = node.childNodes[0].data if this_name == module_name: found = 1 node.setAttribute("index", "index") if found: removes.append(entry) for node in removes: container.removeChild(node)
def fixup_refmodindexes_chunk(container): # node is probably a <para>; let's see how often it isn't: if container.tagName != PARA_ELEMENT: sys.stderr.write("--- fixup_refmodindexes_chunk(%s)\n" % container) module_entries = find_all_elements(container, "module") if not module_entries: return index_entries = find_all_elements_from_set(container, REFMODINDEX_ELEMENTS) removes = [] for entry in index_entries: children = entry.childNodes if len(children) != 0: bwrite("--- unexpected number of children for %s node:\n" % entry.tagName) ewrite(entry.toxml() + "\n") continue found = 0 module_name = entry.getAttribute("name") for node in module_entries: if len(node.childNodes) != 1: continue this_name = node.childNodes[0].data if this_name == module_name: found = 1 node.setAttribute("index", "index") if found: removes.append(entry) for node in removes: container.removeChild(node)
10,392
def fixup_refmodindexes_chunk(container): # node is probably a <para>; let's see how often it isn't: if container.tagName != PARA_ELEMENT: sys.stderr.write("--- fixup_refmodindexes_chunk(%s)\n" % container) module_entries = find_all_elements(container, "module") if not module_entries: return index_entries = find_all_elements_from_set(container, REFMODINDEX_ELEMENTS) removes = [] for entry in index_entries: children = entry.childNodes if len(children) != 0: sys.stderr.write( "--- unexpected number of children for %s node:\n" % entry.tagName) sys.stderr.write(entry.toxml() + "\n") continue found = 0 module_name = entry.getAttribute("name") for node in module_entries: if len(node.childNodes) != 1: continue this_name = node.childNodes[0].data if this_name == module_name: found = 1 node.setAttribute("index", "index") if found: removes.append(entry) for node in removes: container.removeChild(node)
def fixup_refmodindexes_chunk(container): # node is probably a <para>; let's see how often it isn't: if container.tagName != PARA_ELEMENT: sys.stderr.write("--- fixup_refmodindexes_chunk(%s)\n" % container) module_entries = find_all_elements(container, "module") if not module_entries: return index_entries = find_all_elements_from_set(container, REFMODINDEX_ELEMENTS) removes = [] for entry in index_entries: children = entry.childNodes if len(children) != 0: sys.stderr.write( "--- unexpected number of children for %s node:\n" % entry.tagName) sys.stderr.write(entry.toxml() + "\n") continue found = 0 module_name = entry.getAttribute("name") for node in module_entries: if len(node.childNodes) != 1: continue this_name = node.childNodes[0].data if this_name == module_name: found = 1 node.setAttribute("index", "yes") if found: removes.append(entry) for node in removes: container.removeChild(node)
10,393
def fixup_bifuncindexes_chunk(container): removes = [] entries = find_all_elements(container, "bifuncindex") function_entries = find_all_elements(container, "function") for entry in entries: function_name = entry.getAttribute("name") found = 0 for func_entry in function_entries: t2 = func_entry.childNodes[0].data if t2[-2:] != "()": continue t2 = t2[:-2] if t2 == function_name: func_entry.setAttribute("index", "index") func_entry.setAttribute("module", "__builtin__") if not found: removes.append(entry) found = 1 for entry in removes: container.removeChild(entry)
def fixup_bifuncindexes_chunk(container): removes = [] entries = find_all_child_elements(container, "bifuncindex") function_entries = find_all_child_elements(container, "function") for entry in entries: function_name = entry.getAttribute("name") found = 0 for func_entry in function_entries: t2 = func_entry.childNodes[0].data if t2[-2:] != "()": continue t2 = t2[:-2] if t2 == function_name: func_entry.setAttribute("index", "index") func_entry.setAttribute("module", "__builtin__") if not found: removes.append(entry) found = 1 for entry in removes: container.removeChild(entry)
10,394
def fixup_bifuncindexes_chunk(container): removes = [] entries = find_all_elements(container, "bifuncindex") function_entries = find_all_elements(container, "function") for entry in entries: function_name = entry.getAttribute("name") found = 0 for func_entry in function_entries: t2 = func_entry.childNodes[0].data if t2[-2:] != "()": continue t2 = t2[:-2] if t2 == function_name: func_entry.setAttribute("index", "index") func_entry.setAttribute("module", "__builtin__") if not found: removes.append(entry) found = 1 for entry in removes: container.removeChild(entry)
def fixup_bifuncindexes_chunk(container): removes = [] entries = find_all_elements(container, "bifuncindex") function_entries = find_all_elements(container, "function") for entry in entries: function_name = entry.getAttribute("name") found = 0 for func_entry in function_entries: t2 = func_entry.childNodes[0].data if t2[-2:] != "()": continue t2 = t2[:-2] if t2 == function_name: func_entry.setAttribute("index", "yes") func_entry.setAttribute("module", "__builtin__") if not found: removes.append(entry) found = 1 for entry in removes: container.removeChild(entry)
10,395
def fixup_bifuncindexes_chunk(container): removes = [] entries = find_all_elements(container, "bifuncindex") function_entries = find_all_elements(container, "function") for entry in entries: function_name = entry.getAttribute("name") found = 0 for func_entry in function_entries: t2 = func_entry.childNodes[0].data if t2[-2:] != "()": continue t2 = t2[:-2] if t2 == function_name: func_entry.setAttribute("index", "index") func_entry.setAttribute("module", "__builtin__") if not found: removes.append(entry) found = 1 for entry in removes: container.removeChild(entry)
def fixup_bifuncindexes_chunk(container): removes = [] entries = find_all_elements(container, "bifuncindex") function_entries = find_all_elements(container, "function") for entry in entries: function_name = entry.getAttribute("name") found = 0 for func_entry in function_entries: t2 = func_entry.childNodes[0].data if t2[-2:] != "()": continue t2 = t2[:-2] if t2 == function_name: func_entry.setAttribute("index", "index") func_entry.setAttribute("module", "__builtin__") if not found: removes.append(entry) for entry in removes: container.removeChild(entry)
10,396
def convert(ifp, ofp): p = esistools.ExtendedEsisBuilder() p.feed(ifp.read()) doc = p.document fragment = p.fragment normalize(fragment) simplify(doc, fragment) handle_labels(doc, fragment) handle_appendix(doc, fragment) fixup_trailing_whitespace(doc, { "abstract": "\n", "title": "", "chapter": "\n\n", "section": "\n\n", "subsection": "\n\n", "subsubsection": "\n\n", "paragraph": "\n\n", "subparagraph": "\n\n", }) cleanup_root_text(doc) cleanup_trailing_parens(doc, ["function", "method", "cfunction"]) cleanup_synopses(doc) fixup_descriptors(doc, fragment) fixup_verbatims(fragment) normalize(fragment) fixup_paras(doc, fragment) fixup_sectionauthors(doc, fragment) remap_element_names(fragment, { "tableii": ("table", {"cols": "2"}), "tableiii": ("table", {"cols": "3"}), "tableiv": ("table", {"cols": "4"}), "lineii": ("row", {}), "lineiii": ("row", {}), "lineiv": ("row", {}), "refmodule": ("module", {"link": "link"}), }) fixup_table_structures(doc, fragment) fixup_rfc_references(doc, fragment) fixup_signatures(doc, fragment) add_node_ids(fragment) fixup_refmodindexes(fragment) fixup_bifuncindexes(fragment) # d = {} for gi in p.get_empties(): d[gi] = gi if d.has_key("rfc"): del d["rfc"] knownempty = d.has_key # try: write_esis(fragment, ofp, knownempty) except IOError, (err, msg): # Ignore EPIPE; it just means that whoever we're writing to stopped # reading. The rest of the output would be ignored. All other errors # should still be reported, if err != errno.EPIPE: raise
def convert(ifp, ofp): p = esistools.ExtendedEsisBuilder() p.feed(ifp.read()) doc = p.document fragment = p.fragment normalize(fragment) simplify(doc, fragment) handle_labels(doc, fragment) handle_appendix(doc, fragment) fixup_trailing_whitespace(doc, { "abstract": "\n", "title": "", "chapter": "\n\n", "section": "\n\n", "subsection": "\n\n", "subsubsection": "\n\n", "paragraph": "\n\n", "subparagraph": "\n\n", }) cleanup_root_text(doc) cleanup_trailing_parens(fragment, ["function", "method", "cfunction"]) cleanup_synopses(doc, fragment) fixup_descriptors(doc, fragment) fixup_verbatims(fragment) normalize(fragment) fixup_paras(doc, fragment) fixup_sectionauthors(doc, fragment) remap_element_names(fragment, { "tableii": ("table", {"cols": "2"}), "tableiii": ("table", {"cols": "3"}), "tableiv": ("table", {"cols": "4"}), "lineii": ("row", {}), "lineiii": ("row", {}), "lineiv": ("row", {}), "refmodule": ("module", {"link": "link"}), }) fixup_table_structures(doc, fragment) fixup_rfc_references(doc, fragment) fixup_signatures(doc, fragment) add_node_ids(fragment) fixup_refmodindexes(fragment) fixup_bifuncindexes(fragment) # d = {} for gi in p.get_empties(): d[gi] = gi if d.has_key("rfc"): del d["rfc"] knownempty = d.has_key # try: write_esis(fragment, ofp, knownempty) except IOError, (err, msg): # Ignore EPIPE; it just means that whoever we're writing to stopped # reading. The rest of the output would be ignored. All other errors # should still be reported, if err != errno.EPIPE: raise
10,397
def get_source_files (self):
defself.check_extension_list() get_source_filesself.check_extension_list() (self):
10,398
def read_template (self): """Read and parse the manifest template file named by 'self.template' (usually "MANIFEST.in"). Process all file specifications (include and exclude) in the manifest template and add the resulting filenames to 'self.files'."""
def read_template (self): """Read and parse the manifest template file named by 'self.template' (usually "MANIFEST.in"). Process all file specifications (include and exclude) in the manifest template and add the resulting filenames to 'self.files'."""
10,399