rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
params = [CL.FRAME_BUFFER_SIZE, len(data) * 2]
params = [CL.FRAME_BUFFER_SIZE, len(data) * 2, \ CL.COMPRESSED_BUFFER_SIZE, len(data)]
def readframes(self, nframes): if self._ssnd_seek_needed: self._ssnd_chunk.rewind() dummy = self._ssnd_chunk.read(8) pos = self._soundpos * self._nchannels * self._sampwidth if self._decomp: if self._comptype in ('ULAW', 'ALAW'): pos = pos / 2 if pos: self._ssnd_chunk.setpos(pos + 8) self._ssnd_seek_needed = 0 size = n...
opts, args = getopt.getopt(sys.argv[1:], 'deh:mo:p:P:qs:w')
opts, args = getopt.getopt(sys.argv[1:], 'de:hmo:p:P:qs:w')
def main(): # overridable context prefix = None # settable with -p option exec_prefix = None # settable with -P option extensions = [] path = sys.path[:] modargs = 0 debug = 1 odir = '' win = sys.platform[:3] == 'win' # modules that are imported by the Python runtime implicits = ...
fileobj = open(self.name, self.mode)
fileobj = _open(self.name, self.mode)
def __init__(self, name=None, mode="r", fileobj=None): """Open an (uncompressed) tar archive `name'. `mode' is either 'r' to read from an existing archive, 'a' to append data to an existing file or 'w' to create a new file overwriting an existing one. `mode' defaults to 'r'. If `fileobj' is given, it is used for readin...
fileobj = open(name, mode + "b")
fileobj = _open(name, mode + "b")
def gzopen(cls, name, mode="r", fileobj=None, compresslevel=9): """Open gzip compressed tar archive name for reading or writing. Appending is not allowed. """ if len(mode) > 1 or mode not in "rw": raise ValueError("mode must be 'r' or 'w'")
f = open(name, "rb")
f = _open(name, "rb")
def add(self, name, arcname=None, recursive=True): """Add the file `name' to the archive. `name' may be any type of file (directory, fifo, symbolic link, etc.). If given, `arcname' specifies an alternative name for the file in the archive. Directories are added recursively by default. This can be avoided by setting `re...
target = open(targetpath, "wb")
target = _open(targetpath, "wb")
def makefile(self, tarinfo, targetpath): """Make a file called targetpath. """ source = self.extractfile(tarinfo) target = open(targetpath, "wb") copyfileobj(source, target) source.close() target.close()
Split 'text' into multiple lines of no more than 'self.width' characters each, and return the list of strings that results. Tabs in 'text' are expanded with string.expandtabs(), and all other whitespace characters (including newline) are converted to space.
Reformat the single paragraph in 'text' so it fits in lines of no more than 'self.width' columns, and return a list of wrapped lines. Tabs in 'text' are expanded with string.expandtabs(), and all other whitespace characters (including newline) are converted to space.
def wrap(self, text): """wrap(text : string) -> [string]
Reformat the paragraph in 'text' to fit in lines of no more than 'width' columns.
Reformat the single paragraph in 'text' to fit in lines of no more than 'self.width' columns, and return a new string containing the entire wrapped paragraph.
def fill(self, text): """fill(text : string) -> string
self.dispatch = { \ 'call' : self.trace_dispatch_call, \ 'return' : self.trace_dispatch_return, \ 'exception': self.trace_dispatch_exception, \ }
def __init__(self, timer=None): self.timings = {} self.cur = None self.cmd = ""
self.get_time = self.get_time_mac
self.get_time = _get_time_mac
def __init__(self, timer=None): self.timings = {} self.cur = None self.cmd = ""
self.timer = time.clock
self.timer = self.get_time = time.clock
def __init__(self, timer=None): self.timings = {} self.cur = None self.cmd = ""
self.timer = time.time
self.timer = self.get_time = time.time
def __init__(self, timer=None): self.timings = {} self.cur = None self.cmd = ""
if len(t) == 2:
length = len(t) except TypeError: self.get_time = timer self.dispatcher = self.trace_dispatch_i else: if length == 2:
def __init__(self, timer=None): self.timings = {} self.cur = None self.cmd = ""
except TypeError: self.dispatcher = self.trace_dispatch_i
def get_time_timer(timer=timer, reduce=reduce, reducer=operator.add): return reduce(reducer, timer(), 0) self.get_time = get_time_timer
def __init__(self, timer=None): self.timings = {} self.cur = None self.cmd = ""
def get_time(self): t = self.timer() if type(t) == type(()) or type(t) == type([]): t = reduce(lambda x,y: x+y, t, 0) return t def get_time_mac(self): return self.timer()/60.0
def __init__(self, timer=None): self.timings = {} self.cur = None self.cmd = ""
t = self.timer()
timer = self.timer t = timer()
def trace_dispatch(self, frame, event, arg): t = self.timer() t = t[0] + t[1] - self.t # No Calibration constant # t = t[0] + t[1] - self.t - .00053 # Calibration constant
if self.dispatch[event](frame,t): t = self.timer()
if self.dispatch[event](self, frame,t): t = timer()
def trace_dispatch(self, frame, event, arg): t = self.timer() t = t[0] + t[1] - self.t # No Calibration constant # t = t[0] + t[1] - self.t - .00053 # Calibration constant
r = self.timer()
r = timer()
def trace_dispatch(self, frame, event, arg): t = self.timer() t = t[0] + t[1] - self.t # No Calibration constant # t = t[0] + t[1] - self.t - .00053 # Calibration constant
t = self.timer() - self.t if self.dispatch[event](frame,t): self.t = self.timer() else: self.t = self.timer() - t
timer = self.timer t = timer() - self.t if self.dispatch[event](self, frame,t): self.t = timer() else: self.t = timer() - t
def trace_dispatch_i(self, frame, event, arg): t = self.timer() - self.t # - 1 # Integer calibration constant if self.dispatch[event](frame,t): self.t = self.timer() else: self.t = self.timer() - t # put back unrecorded delta return
t = self.timer()/60.0 - self.t if self.dispatch[event](frame,t): self.t = self.timer()/60.0 else: self.t = self.timer()/60.0 - t
timer = self.timer t = timer()/60.0 - self.t if self.dispatch[event](self, frame,t): self.t = timer()/60.0 else: self.t = timer()/60.0 - t
def trace_dispatch_mac(self, frame, event, arg): t = self.timer()/60.0 - self.t # - 1 # Integer calibration constant if self.dispatch[event](frame,t): self.t = self.timer()/60.0 else: self.t = self.timer()/60.0 - t # put back unrecorded delta return
t = self.get_time() - self.t if self.dispatch[event](frame,t): self.t = self.get_time() else: self.t = self.get_time()-t
get_time = self.get_time t = get_time() - self.t if self.dispatch[event](self, frame,t): self.t = get_time() else: self.t = get_time() - t
def trace_dispatch_l(self, frame, event, arg): t = self.get_time() - self.t
if self.timings.has_key(fn): cc, ns, tt, ct, callers = self.timings[fn] self.timings[fn] = cc, ns + 1, tt, ct, callers else: self.timings[fn] = 0, 0, 0, 0, {}
timings = self.timings if timings.has_key(fn): cc, ns, tt, ct, callers = timings[fn] timings[fn] = cc, ns + 1, tt, ct, callers else: timings[fn] = 0, 0, 0, 0, {}
def trace_dispatch_call(self, frame, t): fcode = frame.f_code fn = (fcode.co_filename, fcode.co_firstlineno, fcode.co_name) self.cur = (t, 0, 0, fn, frame, self.cur) if self.timings.has_key(fn): cc, ns, tt, ct, callers = self.timings[fn] self.timings[fn] = cc, ns + 1, tt, ct, callers else: self.timings[fn] = 0, 0, 0, 0...
cc, ns, tt, ct, callers = self.timings[rfn]
timings = self.timings cc, ns, tt, ct, callers = timings[rfn]
def trace_dispatch_return(self, frame, t): # if not frame is self.cur[-2]: raise "Bad return", self.cur[3]
self.timings[rfn] = cc, ns - 1, tt+rtt, ct, callers
timings[rfn] = cc, ns - 1, tt+rtt, ct, callers
def trace_dispatch_return(self, frame, t): # if not frame is self.cur[-2]: raise "Bad return", self.cur[3]
a = self.dispatch['call'](frame, 0)
a = self.dispatch['call'](self, frame, 0)
def simulate_call(self, name): code = self.fake_code('profile', 0, name) if self.cur: pframe = self.cur[-2] else: pframe = None frame = self.fake_frame(code, pframe) a = self.dispatch['call'](frame, 0) return
t = self.get_time() - self.t
get_time = self.get_time t = get_time() - self.t
def simulate_cmd_complete(self): t = self.get_time() - self.t while self.cur[-1]: # We *can* cause assertion errors here if # dispatch_trace_return checks for a frame match! a = self.dispatch['return'](self.cur[-2], t) t = 0 self.t = self.get_time() - t
a = self.dispatch['return'](self.cur[-2], t)
a = self.dispatch['return'](self, self.cur[-2], t)
def simulate_cmd_complete(self): t = self.get_time() - self.t while self.cur[-1]: # We *can* cause assertion errors here if # dispatch_trace_return checks for a frame match! a = self.dispatch['return'](self.cur[-2], t) t = 0 self.t = self.get_time() - t
self.t = self.get_time() - t
self.t = get_time() - t
def simulate_cmd_complete(self): t = self.get_time() - self.t while self.cur[-1]: # We *can* cause assertion errors here if # dispatch_trace_return checks for a frame match! a = self.dispatch['return'](self.cur[-2], t) t = 0 self.t = self.get_time() - t
def runcall(self, func, *args):
def runcall(self, func, *args, **kw):
def runcall(self, func, *args): self.set_cmd(`func`) sys.setprofile(self.dispatcher) try: return apply(func, args) finally: sys.setprofile(None)
return apply(func, args)
return apply(func, args, kw)
def runcall(self, func, *args): self.set_cmd(`func`) sys.setprofile(self.dispatcher) try: return apply(func, args) finally: sys.setprofile(None)
s = self.get_time()
s = get_time()
def calibrate(self, m): # Modified by Tim Peters n = m s = self.get_time() while n: self.simple() n = n - 1 f = self.get_time() my_simple = f - s #print "Simple =", my_simple,
f = self.get_time()
f = get_time()
def calibrate(self, m): # Modified by Tim Peters n = m s = self.get_time() while n: self.simple() n = n - 1 f = self.get_time() my_simple = f - s #print "Simple =", my_simple,
import sys import os
def Stats(*args): print 'Report generating functions are in the "pstats" module\a'
if part: self._hit(part)
def hitter(ctl, part, self=self): if part: self._hit(part)
def visit(pattern, dirname, names):
def main(): try: opts, args = getopt.getopt(sys.argv[1:], '') if len(args) < 2: raise getopt.error, 'not enough arguments' except getopt.error, msg: sys.stdout = sys.stderr print msg print 'usage: findlinksto pattern directory ...' sys.exit(2) pat, dirs = args[0], args[1:] prog = regex.compile(pat) for dirname in dirs:...
def visit(pattern, dirname, names): if os.path.islink(dirname): names[:] = [] return if os.path.ismount(dirname): print 'descend into', dirname n = len(pattern) for name in names: name = os.path.join(dirname, name) try: linkto = os.readlink(name) if linkto[:n] == pattern: print name, '->', linkto except os.error: pass
n = len(pattern)
def visit(pattern, dirname, names): if os.path.islink(dirname): names[:] = [] return if os.path.ismount(dirname): print 'descend into', dirname n = len(pattern) for name in names: name = os.path.join(dirname, name) try: linkto = os.readlink(name) if linkto[:n] == pattern: print name, '->', linkto except os.error: pass
if linkto[:n] == pattern:
if prog.search(linkto) >= 0:
def visit(pattern, dirname, names): if os.path.islink(dirname): names[:] = [] return if os.path.ismount(dirname): print 'descend into', dirname n = len(pattern) for name in names: name = os.path.join(dirname, name) try: linkto = os.readlink(name) if linkto[:n] == pattern: print name, '->', linkto except os.error: pass
openitem = FrameWork.MenuItem(m, "Open"+ELIPSES, "O", 'open') openbynameitem = FrameWork.MenuItem(m, "Open File by Name"+ELIPSES, "D", 'openbyname')
openitem = FrameWork.MenuItem(m, "Open"+ELLIPSIS, "O", 'open') openbynameitem = FrameWork.MenuItem(m, "Open File by Name"+ELLIPSIS, "D", 'openbyname')
def makeusermenus(self): m = Wapplication.Menu(self.menubar, "File") newitem = FrameWork.MenuItem(m, "New", "N", 'new') openitem = FrameWork.MenuItem(m, "Open"+ELIPSES, "O", 'open') openbynameitem = FrameWork.MenuItem(m, "Open File by Name"+ELIPSES, "D", 'openbyname') self.openrecentmenu = FrameWork.SubMenu(m, "Open Re...
saveasitem = FrameWork.MenuItem(m, "Save as"+ELIPSES, None, 'save_as') FrameWork.Separator(m) saveasappletitem = FrameWork.MenuItem(m, "Save as Applet"+ELIPSES, None, 'save_as_applet')
saveasitem = FrameWork.MenuItem(m, "Save as"+ELLIPSIS, None, 'save_as') FrameWork.Separator(m) saveasappletitem = FrameWork.MenuItem(m, "Save as Applet"+ELLIPSIS, None, 'save_as_applet')
def makeusermenus(self): m = Wapplication.Menu(self.menubar, "File") newitem = FrameWork.MenuItem(m, "New", "N", 'new') openitem = FrameWork.MenuItem(m, "Open"+ELIPSES, "O", 'open') openbynameitem = FrameWork.MenuItem(m, "Open File by Name"+ELIPSES, "D", 'openbyname') self.openrecentmenu = FrameWork.SubMenu(m, "Open Re...
finditem = FrameWork.MenuItem(m, "Find"+ELIPSES, "F", "find")
finditem = FrameWork.MenuItem(m, "Find"+ELLIPSIS, "F", "find")
def makeusermenus(self): m = Wapplication.Menu(self.menubar, "File") newitem = FrameWork.MenuItem(m, "New", "N", 'new') openitem = FrameWork.MenuItem(m, "Open"+ELIPSES, "O", 'open') openbynameitem = FrameWork.MenuItem(m, "Open File by Name"+ELIPSES, "D", 'openbyname') self.openrecentmenu = FrameWork.SubMenu(m, "Open Re...
moditem = FrameWork.MenuItem(m, "Module browser"+ELIPSES, "M", self.domenu_modulebrowser)
moditem = FrameWork.MenuItem(m, "Module browser"+ELLIPSIS, "M", self.domenu_modulebrowser)
def makeusermenus(self): m = Wapplication.Menu(self.menubar, "File") newitem = FrameWork.MenuItem(m, "New", "N", 'new') openitem = FrameWork.MenuItem(m, "Open"+ELIPSES, "O", 'open') openbynameitem = FrameWork.MenuItem(m, "Open File by Name"+ELIPSES, "D", 'openbyname') self.openrecentmenu = FrameWork.SubMenu(m, "Open Re...
FrameWork.MenuItem(mm, "Set Scripts folder"+ELIPSES, None, self.do_setscriptsfolder) FrameWork.MenuItem(mm, "Editor default settings"+ELIPSES, None, self.do_editorprefs) FrameWork.MenuItem(mm, "Set default window font"+ELIPSES, None, self.do_setwindowfont)
FrameWork.MenuItem(mm, "Set Scripts folder"+ELLIPSIS, None, self.do_setscriptsfolder) FrameWork.MenuItem(mm, "Editor default settings"+ELLIPSIS, None, self.do_editorprefs) FrameWork.MenuItem(mm, "Set default window font"+ELLIPSIS, None, self.do_setwindowfont)
def makeusermenus(self): m = Wapplication.Menu(self.menubar, "File") newitem = FrameWork.MenuItem(m, "New", "N", 'new') openitem = FrameWork.MenuItem(m, "Open"+ELIPSES, "O", 'open') openbynameitem = FrameWork.MenuItem(m, "Open File by Name"+ELIPSES, "D", 'openbyname') self.openrecentmenu = FrameWork.SubMenu(m, "Open Re...
f = open(os.path.join(path, "Place your scripts here"+ELIPSES), "w")
f = open(os.path.join(path, "Place your scripts here"+ELLIPSIS), "w")
def makeusermenus(self): m = Wapplication.Menu(self.menubar, "File") newitem = FrameWork.MenuItem(m, "New", "N", 'new') openitem = FrameWork.MenuItem(m, "Open"+ELIPSES, "O", 'open') openbynameitem = FrameWork.MenuItem(m, "Open File by Name"+ELIPSES, "D", 'openbyname') self.openrecentmenu = FrameWork.SubMenu(m, "Open Re...
return "About Python IDE"+ELIPSES
return "About Python IDE"+ELLIPSIS
def getabouttext(self): return "About Python IDE"+ELIPSES
def _charset(charset, fixup):
def _charset(charset, fixup=None):
def _charset(charset, fixup): # internal: optimize character set out = [] charmap = [0]*256 try: for op, av in charset: if op is NEGATE: out.append((op, av)) elif op is LITERAL: charmap[fixup(av)] = 1 elif op is RANGE: for i in range(fixup(av[0]), fixup(av[1])+1): charmap[i] = 1 elif op is CATEGORY: # FIXME: could appe...
try: class C(bool): pass except TypeError: pass else: raise TestFailed, "bool should not be subclassable" try: int.__new__(bool, 0) except TypeError: pass else: raise TestFailed, "should not be able to create new bool instances" fo = open(TESTFN, "wb") print >> fo, False, True fo.close() fo = open(TESTFN, "rb") vere...
class BoolTest(unittest.TestCase): def assertIs(self, a, b): self.assert_(a is b) def assertIsNot(self, a, b): self.assert_(a is not b) def test_subclass(self): try: class C(bool): pass except TypeError: pass else: self.fail("bool should not be subclassable") self.assertRaises(TypeError, int.__new__, bool, 0) def ...
def verisnot(a, b): if a is b: raise TestFailed, "%r is %r" % (a, b)
items = map(lambda (k, v), type = type, simp = SIMPLE_TYPES, indent = indent: (k, v, not type(v) in simp, indent), items)
items = [(k, v, not isinstance(v, SIMPLE_TYPES), indent) for k, v in items]
def pack_items(items, indent = 0): items = map(lambda (k, v), type = type, simp = SIMPLE_TYPES, indent = indent: (k, v, not type(v) in simp, indent), items) return tuple_caselesssort(items)
def testPackageRequire(self): tcl = self.interp tcl.eval('package require Tclx') tcl.eval('keylset a b.c 1') self.assertEqual(tcl.eval('keylget a b.c'),'1')
def testPackageRequire(self): tcl = self.interp tcl.eval('package require Tclx') tcl.eval('keylset a b.c 1') self.assertEqual(tcl.eval('keylget a b.c'),'1')
if sys.platform.startswith('win'):
if sys.platform.startswith('win') or sys.platform.startswith('darwin'):
def testLoadTkFailure(self): import os old_display = None import sys if sys.platform.startswith('win'): return # no failure possible on windows? if 'DISPLAY' in os.environ: old_display = os.environ['DISPLAY'] del os.environ['DISPLAY'] # on some platforms, deleting environment variables # doesn't actually carry through ...
def findnames(file, prefix=""):
def findnames(file, prefixes=()):
def findnames(file, prefix=""): names = {} for line in file.readlines(): if line[0] == '!': continue fields = line.split() name, tag = fields[0], fields[-1] if tag == 'd' and name.endswith('_H'): continue if name.startswith(prefix): names[name] = tag return names
for line in file.readlines():
for line in file.xreadlines():
def findnames(file, prefix=""): names = {} for line in file.readlines(): if line[0] == '!': continue fields = line.split() name, tag = fields[0], fields[-1] if tag == 'd' and name.endswith('_H'): continue if name.startswith(prefix): names[name] = tag return names
if name.startswith(prefix):
if prefixes: sw = name.startswith for prefix in prefixes: if sw(prefix): names[name] = tag else:
def findnames(file, prefix=""): names = {} for line in file.readlines(): if line[0] == '!': continue fields = line.split() name, tag = fields[0], fields[-1] if tag == 'd' and name.endswith('_H'): continue if name.startswith(prefix): names[name] = tag return names
print_undoc_symbols(PREFIX, docdir, incdir)
print_undoc_symbols(PREFIXES, docdir, incdir)
def print_undoc_symbols(prefix, docdir, incdir): docs = [] for sect in DOCSECTIONS: for file in glob.glob(os.path.join(docdir, sect, "*.tex")): docs.append(open(file).read()) docs = "\n".join(docs) incfiles = os.path.join(incdir, INCLUDEPATTERN) fp = os.popen("ctags -IDL_IMPORT --c-types=%s -f - %s" % (TAG_KINDS, i...
def bind(self, sequence=None, command=None): return self.canvas.tag_bind(self.id, sequence, command) def unbind(self, sequence): self.canvas.tag_bind(self.id, sequence, '')
def bind(self, sequence=None, command=None, add=None): return self.canvas.tag_bind(self.id, sequence, command, add) def unbind(self, sequence, funcid=None): self.canvas.tag_unbind(self.id, sequence, funcid)
def bind(self, sequence=None, command=None): return self.canvas.tag_bind(self.id, sequence, command)
self.canvas.lower(self.id, belowthis)
self.canvas.tag_lower(self.id, belowthis)
def lower(self, belowthis=None): self.canvas.lower(self.id, belowthis)
self.canvas.tkraise(self.id, abovethis)
self.canvas.tag_raise(self.id, abovethis)
def tkraise(self, abovethis=None): self.canvas.tkraise(self.id, abovethis)
self._do('lower', belowThis)
self._do('tag_lower', belowThis)
def lower(self, belowThis=None): self._do('lower', belowThis)
self._do('raise', aboveThis)
self._do('tag_raise', aboveThis)
def tkraise(self, aboveThis=None): self._do('raise', aboveThis)
chunks.append(size)
chunks.append(data)
def read(self, size): """Read 'size' bytes from remote.""" # sslobj.read() sometimes returns < size bytes chunks = [] read = 0 while read < size: data = self.sslobj.read(size-read) read += len(data) chunks.append(size)
print '%s == %s: OK' % (repr(a), repr(b))
print '%s == %s: OK' % (a, b)
def check(a, b): if a != b: print '*** check failed: %s != %s' % (repr(a), repr(b)) else: print '%s == %s: OK' % (repr(a), repr(b))
doc = getattr(ob, "__doc__", "")
doc = getattr(ob, "__doc__", "").lstrip()
def get_arg_text(ob): "Get a string describing the arguments for the given object" argText = "" if ob is not None: argOffset = 0 if type(ob)==types.ClassType: # Look for the highest __init__ in the class chain. fob = _find_constructor(ob) if fob is None: fob = lambda: None else: argOffset = 1 elif type(ob)==types.Metho...
while doc[:1] in " \t\n": doc = doc[1:]
def get_arg_text(ob): "Get a string describing the arguments for the given object" argText = "" if ob is not None: argOffset = 0 if type(ob)==types.ClassType: # Look for the highest __init__ in the class chain. fob = _find_constructor(ob) if fob is None: fob = lambda: None else: argOffset = 1 elif type(ob)==types.Metho...
1 <= len(macros) <= 2):
1 <= len(macro) <= 2):
def check_extensions_list (self, extensions): """Ensure that the list of extensions (presumably provided as a command option 'extensions') is valid, i.e. it is a list of Extension objects. We also support the old-style list of 2-tuples, where the tuples are (ext_name, build_info), which are converted to Extension inst...
def splitbins(bins): bytes = sys.maxint for shift in range(16): bin1 = [] bin2 = []
def splitbins(t, trace=0): """t, trace=0 -> (t1, t2, shift). Split a table to save space. t is a sequence of ints. This function can be useful to save space if many of the ints are the same. t1 and t2 are lists of ints, and shift is an int, chosen to minimize the combined size of t1 and t2 (in C code), and where fo...
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 = ...
for i in range(0, len(bins), size): bin = bins[i:i+size] index = bincache.get(tuple(bin))
for i in range(0, len(t), size): bin = t[i:i+size] index = bincache.get(bin)
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 = ...
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)
index = len(t2) bincache[bin] = index t2.extend(bin) t1.append(index >> shift)
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 = ...
b = len(bin1)*getsize(bin1) + len(bin2)*getsize(bin2)
b = len(t1)*getsize(t1) + len(t2)*getsize(t2) if trace: dump(t1, t2, shift, b)
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 = ...
best = shift, bin1, bin2
best = t1, t2, shift
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 = ...
shift, bin1, bin2 = best return bin1, bin2, shift
t1, t2, shift = best if trace: print >>sys.stderr, "Best:", dump(t1, t2, shift, bytes) if __debug__: mask = ~((~0) << shift) for i in xrange(len(t)): assert t[i] == t2[(t1[i >> shift] << shift) + (i & mask)] return 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 = ...
def check_close(x, y):
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):
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)
return fcmp(x.real, y.real) == 0 == fcmp(x.imag, y.imag)
return check_close_real(x.real, y.real, eps) and \ check_close_real(x.imag, y.imag, eps)
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)
parent and parent.__path__)
parent and parent.__path__, parent)
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, ...
def find_module(self, name, path): if path: fullname = '.'.join(path)+'.'+name
def find_module(self, name, path, parent=None): if parent is not None: fullname = parent.__name__+'.'+name
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
print 'ParsedDate:', time.asctime(date[:-1]), hhmmss = date[-1]
print 'ParsedDate:', time.asctime(date), hhmmss = tz
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))
r'(?P<option>[-\w_.*,(){}]+)'
r'(?P<option>[]\-[\w_.*,(){}]+)'
def remove_section(self, section): """Remove a file section.""" if self.__sections.has_key(section): del self.__sections[section] return 1 else: return 0
super(TimeRE,self).__init__({
base = super(TimeRE, self) base.__init__({
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': r"(?P<d>3[0-1]|[0-2]\d|\d| \d)",
'd': r"(?P<d>3[0-1]|[1-2]\d|0[1-9]|[1-9]| [1-9])",
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| ...
'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)",
'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])",
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| ...
'W': r"(?P<W>5[0-3]|[0-4]\d|\d)",
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| ...
try: class C(object, Classic): pass except TypeError: pass else: verify(0, "inheritance from object and Classic 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 ...
posix = True
posix = False
def isdev(self): return self.type in (CHRTYPE, BLKTYPE, FIFOTYPE)
tarinfo.size = statres.st_size
tarinfo.size = not stat.S_ISDIR(stmd) and statres.st_size or 0
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 fo...
m235 to share a single generator". Unfortunately, using generators this way creates a reference-cycle that the garbage collector (currently) can't clean up, so we have to explicitly break the cycle (by calling the inner generator's close() method)
m235 to share a single generator".
... def tail(g):
... return m1.close, mRes >>> closer, it = m235()
... return mRes >>> it = m235()
... def _m235():
>>> closer()
... def _m235():
are quite straightforwardly expressed with this Python idiom. The problem is that this creates an uncollectable reference cycle, and we have to explicitly close the innermost generator to clean up the cycle. XXX As of 14-Apr-2006, Tim doubts that anyone understands _why_ some cycle XXX is uncollectable here.
are quite straightforwardly expressed with this Python idiom.
... def _m235():
... return realfib.close, fibRes >>> closer, fibber = fib() >>> firstn(fibber, 17)
... return fibRes >>> firstn(fib(), 17)
... def _fib():
>>> closer() XXX Again the tee-based approach leaks without an explicit close().
... def _fib():
elif self.header_encoding is QP:
elif self.body_encoding is QP:
def body_encode(self, s, convert=True): """Body-encode a string and convert it to output_charset.
for (extension_name, build_info) in extensions:
for (extension_name, build_info) in self.extensions:
def get_source_files (self):
if sources is None or type (sources) is not ListType:
if sources is None or type (sources) not in (ListType, TupleType):
def build_extensions (self, extensions):
includes=include_dirs)
include_dirs=include_dirs)
def build_extensions (self, extensions):
mro_err_msg = """Cannot create class.The superclasses have conflicting inheritance trees which leave the method resolution order (MRO) undefined for bases """
mro_err_msg = """Cannot create a consistent method resolution order (MRO) for bases """
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,EditablePa...
pass return '?'
if not self.lseen: if not self.rseen: return '0' else: return 'N' else: if not self.rseen: return '?' if self.lsum == self.rsum: return 'c' else: return 'C' else: if not self.lseen: if self.eremoved: if self.rseen: return 'R' else: return 'r' else: if self.rseen: print "warning:", print self.file, print "was lost" ret...
def action(self): """Return a code indicating the update status of this file.
self.cvs.report()
for file in files: print self.cvs.entries[file].action(), file
def default(self): files = [] if self.cvs.checkfiles(files): return 1 self.cvs.report()
if not self.entries[file].commitcheck():
if not self.cvs.entries[file].commitcheck():
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)
self.entries[file].commit(message)
self.cvs.entries[file].commit(message) self.cvs.putentries()
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)
nframes = self.calcnframes()
nframes = self.calcnframes(memsize)
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...
def calcnframes(self):
def calcnframes(self, memsize):
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)
size = stats[stat.ST_SIZE] modified = rfc822.formatdate(stats[stat.ST_MTIME])
size = stats.st_size modified = rfc822.formatdate(stats.st_mtime)
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( '...