rem
stringlengths 0
322k
| add
stringlengths 0
2.05M
| context
stringlengths 8
228k
|
---|---|---|
if type(cnf) == StringType: x = self.tk.split(self.tk.call( self._w, 'window', 'configure', index, '-'+cnf)) return (x[0][1:],) + x[1:] self.tk.call( (self._w, 'window', 'configure', index) + self._options(cnf, kw)) | return self._configure(('window', 'configure', index), cnf, kw) | def window_configure(self, index, cnf={}, **kw): """Configure an embedded window at INDEX.""" if type(cnf) == StringType: x = self.tk.split(self.tk.call( self._w, 'window', 'configure', index, '-'+cnf)) return (x[0][1:],) + x[1:] self.tk.call( (self._w, 'window', 'configure', index) + self._options(cnf, kw)) |
port.connect(HOST, PORT) | port.connect(host, PORT) | def main(): try: optlist, args = getopt.getopt(sys.argv[1:], 'ls') except getopt.error, msg: sys.stderr.write(msg + '\n') sys.exit(2) player = cd.open() prstatus(player) size = player.bestreadsize() if optlist: for opt, arg in optlist: if opt == '-l': prtrackinfo(player) elif opt == '-s': prstatus(player) return sys.stdout.write('waiting for socket... ') sys.stdout.flush() port = socket(AF_INET, SOCK_DGRAM) port.connect(HOST, PORT) print 'socket connected' parser = cd.createparser() parser.setcallback(0, audiocallback, port) parser.setcallback(1, pnumcallback, player) parser.setcallback(2, indexcallback, None) ## 3 = ptime: too many calls ## 4 = atime: too many calls parser.setcallback(5, catalogcallback, None) parser.setcallback(6, identcallback, None) parser.setcallback(7, controlcallback, None) if len(args) >= 2: if len(args) >= 3: [min, sec, frame] = args[:3] else: [min, sec] = args frame = 0 min, sec, frame = eval(min), eval(sec), eval(frame) print 'Seek to', triple(min, sec, frame) dummy = player.seek(min, sec, frame) elif len(args) == 1: track = eval(args[0]) print 'Seek to track', track dummy = player.seektrack(track) else: min, sec, frame = player.getstatus()[5:8] print 'Try to seek back to', triple(min, sec, frame) try: player.seek(min, sec, frame) except RuntimeError: print 'Seek failed' try: while 1: frames = player.readda(size) if frames == '': print 'END OF CD' break parser.parseframe(frames) except KeyboardInterrupt: print '[Interrupted]' pass |
frame = 0 | frame = '0' | def main(): try: optlist, args = getopt.getopt(sys.argv[1:], 'ls') except getopt.error, msg: sys.stderr.write(msg + '\n') sys.exit(2) player = cd.open() prstatus(player) size = player.bestreadsize() if optlist: for opt, arg in optlist: if opt == '-l': prtrackinfo(player) elif opt == '-s': prstatus(player) return sys.stdout.write('waiting for socket... ') sys.stdout.flush() port = socket(AF_INET, SOCK_DGRAM) port.connect(HOST, PORT) print 'socket connected' parser = cd.createparser() parser.setcallback(0, audiocallback, port) parser.setcallback(1, pnumcallback, player) parser.setcallback(2, indexcallback, None) ## 3 = ptime: too many calls ## 4 = atime: too many calls parser.setcallback(5, catalogcallback, None) parser.setcallback(6, identcallback, None) parser.setcallback(7, controlcallback, None) if len(args) >= 2: if len(args) >= 3: [min, sec, frame] = args[:3] else: [min, sec] = args frame = 0 min, sec, frame = eval(min), eval(sec), eval(frame) print 'Seek to', triple(min, sec, frame) dummy = player.seek(min, sec, frame) elif len(args) == 1: track = eval(args[0]) print 'Seek to track', track dummy = player.seektrack(track) else: min, sec, frame = player.getstatus()[5:8] print 'Try to seek back to', triple(min, sec, frame) try: player.seek(min, sec, frame) except RuntimeError: print 'Seek failed' try: while 1: frames = player.readda(size) if frames == '': print 'END OF CD' break parser.parseframe(frames) except KeyboardInterrupt: print '[Interrupted]' pass |
min, sec, frame = player.getstatus()[5:8] | min, sec, frame = player.getstatus()[3] | def main(): try: optlist, args = getopt.getopt(sys.argv[1:], 'ls') except getopt.error, msg: sys.stderr.write(msg + '\n') sys.exit(2) player = cd.open() prstatus(player) size = player.bestreadsize() if optlist: for opt, arg in optlist: if opt == '-l': prtrackinfo(player) elif opt == '-s': prstatus(player) return sys.stdout.write('waiting for socket... ') sys.stdout.flush() port = socket(AF_INET, SOCK_DGRAM) port.connect(HOST, PORT) print 'socket connected' parser = cd.createparser() parser.setcallback(0, audiocallback, port) parser.setcallback(1, pnumcallback, player) parser.setcallback(2, indexcallback, None) ## 3 = ptime: too many calls ## 4 = atime: too many calls parser.setcallback(5, catalogcallback, None) parser.setcallback(6, identcallback, None) parser.setcallback(7, controlcallback, None) if len(args) >= 2: if len(args) >= 3: [min, sec, frame] = args[:3] else: [min, sec] = args frame = 0 min, sec, frame = eval(min), eval(sec), eval(frame) print 'Seek to', triple(min, sec, frame) dummy = player.seek(min, sec, frame) elif len(args) == 1: track = eval(args[0]) print 'Seek to track', track dummy = player.seektrack(track) else: min, sec, frame = player.getstatus()[5:8] print 'Try to seek back to', triple(min, sec, frame) try: player.seek(min, sec, frame) except RuntimeError: print 'Seek failed' try: while 1: frames = player.readda(size) if frames == '': print 'END OF CD' break parser.parseframe(frames) except KeyboardInterrupt: print '[Interrupted]' pass |
start_min, start_sec, start_frame, \ total_min, total_sec, total_frame = info[i] print 'Track', zfill(i+1), \ triple(start_min, start_sec, start_frame), \ triple(total_min, total_sec, total_frame) | start, total = info[i] print 'Track', zfill(i+1), triple(start), triple(total) | def prtrackinfo(player): info = [] while 1: try: info.append(player.gettrackinfo(len(info) + 1)) except RuntimeError: break for i in range(len(info)): start_min, start_sec, start_frame, \ total_min, total_sec, total_frame = info[i] print 'Track', zfill(i+1), \ triple(start_min, start_sec, start_frame), \ triple(total_min, total_sec, total_frame) |
state, track, min, sec, frame, abs_min, abs_sec, abs_frame, \ total_min, total_sec, total_frame, first, last, scsi_audio, \ cur_block, dum1, dum2, dum3 = player.getstatus() | state, track, curtime, abstime, totaltime, first, last, \ scsi_audio, cur_block, dummy = player.getstatus() | def prstatus(player): state, track, min, sec, frame, abs_min, abs_sec, abs_frame, \ total_min, total_sec, total_frame, first, last, scsi_audio, \ cur_block, dum1, dum2, dum3 = player.getstatus() print 'Status:', if 0 <= state < len(statedict): print statedict[state] else: print state print 'Track: ', track print 'Time: ', triple(min, sec, frame) print 'Abs: ', triple(abs_min, abs_sec, abs_frame) print 'Total: ', triple(total_min, total_sec, total_frame) print 'First: ', first print 'Last: ', last print 'SCSI: ', scsi_audio print 'Block: ', cur_block print 'Future:', (dum1, dum2, dum3) |
print 'Time: ', triple(min, sec, frame) print 'Abs: ', triple(abs_min, abs_sec, abs_frame) print 'Total: ', triple(total_min, total_sec, total_frame) | print 'Time: ', triple(curtime) print 'Abs: ', triple(abstime) print 'Total: ', triple(totaltime) | def prstatus(player): state, track, min, sec, frame, abs_min, abs_sec, abs_frame, \ total_min, total_sec, total_frame, first, last, scsi_audio, \ cur_block, dum1, dum2, dum3 = player.getstatus() print 'Status:', if 0 <= state < len(statedict): print statedict[state] else: print state print 'Track: ', track print 'Time: ', triple(min, sec, frame) print 'Abs: ', triple(abs_min, abs_sec, abs_frame) print 'Total: ', triple(total_min, total_sec, total_frame) print 'First: ', first print 'Last: ', last print 'SCSI: ', scsi_audio print 'Block: ', cur_block print 'Future:', (dum1, dum2, dum3) |
print 'Future:', (dum1, dum2, dum3) | print 'Future:', dummy | def prstatus(player): state, track, min, sec, frame, abs_min, abs_sec, abs_frame, \ total_min, total_sec, total_frame, first, last, scsi_audio, \ cur_block, dum1, dum2, dum3 = player.getstatus() print 'Status:', if 0 <= state < len(statedict): print statedict[state] else: print state print 'Track: ', track print 'Time: ', triple(min, sec, frame) print 'Abs: ', triple(abs_min, abs_sec, abs_frame) print 'Total: ', triple(total_min, total_sec, total_frame) print 'First: ', first print 'Last: ', last print 'SCSI: ', scsi_audio print 'Block: ', cur_block print 'Future:', (dum1, dum2, dum3) |
def triple(a, b, c): | def triple((a, b, c)): | def triple(a, b, c): return zfill(a) + ':' + zfill(b) + ':' + zfill(c) |
map = socket_map | map = self._map | def add_channel(self, map=None): #self.log_info('adding channel %s' % self) if map is None: map = socket_map map[self._fileno] = self |
map = socket_map | map = self._map | def del_channel(self, map=None): fd = self._fileno if map is None: map = socket_map if map.has_key(fd): #self.log_info('closing channel %d:%s' % (fd, self)) del map[fd] |
for i in ['_exit']: try: exec "from nt import " + i except ImportError: pass | try: from nt import _exit except ImportError: pass | def _get_exports_list(module): try: return list(module.__all__) except AttributeError: return [n for n in dir(module) if n[0] != '_'] |
for i in ['_exit']: try: exec "from ce import " + i except ImportError: pass | try: from ce import _exit except ImportError: pass | def _get_exports_list(module): try: return list(module.__all__) except AttributeError: return [n for n in dir(module) if n[0] != '_'] |
other = HMAC("") | other = HMAC(_secret_backdoor_key) | def copy(self): """Return a separate copy of this hashing object. |
import MacOS | def __init__(self, timer=None): self.timings = {} self.cur = None self.cmd = "" |
|
if hasattr(socket, 'AF_UNIX'): class UnixStreamServer(TCPServer): address_family = socket.AF_UNIX class UnixDatagramServer(UDPServer): address_family = socket.AF_UNIX | def server_activate(self): # No need to call listen() for UDP. pass |
|
dry_run=0): CCompiler.__init__ (self, verbose, dry_run) | dry_run=0, force=0): CCompiler.__init__ (self, verbose, dry_run, force) | def __init__ (self, verbose=0, dry_run=0): |
skipped = newer_pairwise (sources, objects) for skipped_pair in skipped: self.announce ("skipping %s (%s up-to-date)" % skipped_pair) | if not self.force: skipped = newer_pairwise (sources, objects) for skipped_pair in skipped: self.announce ("skipping %s (%s up-to-date)" % skipped_pair) | def compile (self, sources, output_dir=None, macros=None, includes=None, extra_preargs=None, extra_postargs=None): |
lib_opts = gen_lib_options (self.library_dirs + library_dirs, self.libraries + libraries, "-L%s", "-l%s") | lib_opts = gen_lib_options (self, self.library_dirs + library_dirs, self.libraries + libraries) | def link_shared_object (self, objects, output_filename, output_dir=None, libraries=None, library_dirs=None, extra_preargs=None, extra_postargs=None): |
try: newer = newer_group (objects, output_filename) except OSError: if self.dry_run: newer = 1 else: raise if newer: ld_args = self.ldflags_shared + lib_opts + \ objects + ['-o', output_filename] | if not self.force: try: newer = newer_group (objects, output_filename) except OSError: if self.dry_run: newer = 1 else: raise if self.force or newer: ld_args = self.ldflags_shared + objects + \ lib_opts + ['-o', output_filename] | def link_shared_object (self, objects, output_filename, output_dir=None, libraries=None, library_dirs=None, extra_preargs=None, extra_postargs=None): |
return "lib%s%s" % (libname, self._shared_lib_ext ) | return "lib%s%s" % (libname, self._shared_lib_ext) def library_dir_option (self, dir): return "-L" + dir def library_option (self, lib): return "-l" + lib def find_library_file (self, dirs, lib): for dir in dirs: shared = os.path.join (dir, self.shared_library_filename (lib)) static = os.path.join (dir, self.library_filename (lib)) if os.path.exists (shared): return shared elif os.path.exists (static): return static else: return None | def shared_library_filename (self, libname): return "lib%s%s" % (libname, self._shared_lib_ext ) |
prefix = buf[345:500] while prefix and prefix[-1] == NUL: prefix = prefix[:-1] if len(prefix.split(NUL)) == 1: tarinfo.prefix = prefix tarinfo.name = normpath(os.path.join(tarinfo.prefix, tarinfo.name)) else: tarinfo.prefix = buf[345:500] | if tarinfo.type != GNUTYPE_SPARSE: tarinfo.name = normpath(os.path.join(nts(tarinfo.prefix), tarinfo.name)) | def frombuf(cls, buf): """Construct a TarInfo object from a 512 byte string buffer. """ tarinfo = cls() tarinfo.name = nts(buf[0:100]) tarinfo.mode = int(buf[100:108], 8) tarinfo.uid = int(buf[108:116],8) tarinfo.gid = int(buf[116:124],8) tarinfo.size = long(buf[124:136], 8) tarinfo.mtime = long(buf[136:148], 8) tarinfo.chksum = int(buf[148:156], 8) tarinfo.type = buf[156:157] tarinfo.linkname = nts(buf[157:257]) tarinfo.uname = nts(buf[265:297]) tarinfo.gname = nts(buf[297:329]) try: tarinfo.devmajor = int(buf[329:337], 8) tarinfo.devminor = int(buf[337:345], 8) except ValueError: tarinfo.devmajor = tarinfo.devmajor = 0 |
print a, k | print a, sortdict(k) | def f(*a, **k): print a, k |
print x, y, z | print x, y, sortdict(z) | def g(x, *y, **z): print x, y, z |
print d print d2 | print sortdict(d) print sortdict(d2) | def __getitem__(self, i): if i < 3: return i else: raise IndexError, i |
print func.func_name, args, kwdict, '->', | print func.func_name, args, sortdict(kwdict), '->', | decl = 'def %s(%s): print "ok %s", a, b, d, e, v, k' % ( name, string.join(arglist, ', '), name) |
self.filename = file | self.filename = filename | def __init__(self, msg, filename=None, lineno=None): self.filename = file self.lineno = lineno self.msg = msg Exception.__init__(self, msg) |
self.emit('ROT_TWO') self.visit(k) | self.emit('ROT_THREE') | def visitDict(self, node): lineno = getattr(node, 'lineno', None) if lineno: self.emit('SET_LINENO', lineno) self.emit('BUILD_MAP', 0) for k, v in node.items: lineno2 = getattr(node, 'lineno', None) if lineno2 is not None and lineno != lineno2: self.emit('SET_LINENO', lineno2) lineno = lineno2 self.emit('DUP_TOP') self.visit(v) self.emit('ROT_TWO') self.visit(k) self.emit('STORE_SUBSCR') |
while 1: | rv = "(unknown file)", 0, "(unknown function)" while hasattr(f, "f_code"): | def findCaller(self): """ Find the stack frame of the caller so that we can note the source file name, line number and function name. """ f = currentframe().f_back while 1: co = f.f_code filename = os.path.normcase(co.co_filename) if filename == _srcfile: f = f.f_back continue return filename, f.f_lineno, co.co_name |
return filename, f.f_lineno, co.co_name | rv = (filename, f.f_lineno, co.co_name) break return rv | def findCaller(self): """ Find the stack frame of the caller so that we can note the source file name, line number and function name. """ f = currentframe().f_back while 1: co = f.f_code filename = os.path.normcase(co.co_filename) if filename == _srcfile: f = f.f_back continue return filename, f.f_lineno, co.co_name |
except UnboundLocalError: | except NameError: | def inner(): return y |
global DEBUG DEBUG=1 | def main(): global DEBUG DEBUG=1 # Find the template # (there's no point in proceeding if we can't find it) template = findtemplate() if DEBUG: print 'Using template', template # Ask for source text if not specified in sys.argv[1:] if not sys.argv[1:]: srcfss, ok = macfs.PromptGetFile('Select Python source file:', 'TEXT') if not ok: return filename = srcfss.as_pathname() tp, tf = os.path.split(filename) if tf[-3:] == '.py': tf = tf[:-3] else: tf = tf + '.applet' dstfss, ok = macfs.StandardPutFile('Save application as:', tf) if not ok: return process(template, filename, dstfss.as_pathname()) else: # Loop over all files to be processed for filename in sys.argv[1:]: process(template, filename, '') |
|
vereq(hash(d), id(d)) | orig_hash = hash(d) | def subclasspropagation(): if verbose: print "Testing propagation of slot functions to subclasses..." class A(object): pass class B(A): pass class C(A): pass class D(B, C): pass d = D() vereq(hash(d), id(d)) A.__hash__ = lambda self: 42 vereq(hash(d), 42) C.__hash__ = lambda self: 314 vereq(hash(d), 314) B.__hash__ = lambda self: 144 vereq(hash(d), 144) D.__hash__ = lambda self: 100 vereq(hash(d), 100) del D.__hash__ vereq(hash(d), 144) del B.__hash__ vereq(hash(d), 314) del C.__hash__ vereq(hash(d), 42) del A.__hash__ vereq(hash(d), id(d)) d.foo = 42 d.bar = 42 vereq(d.foo, 42) vereq(d.bar, 42) def __getattribute__(self, name): if name == "foo": return 24 return object.__getattribute__(self, name) A.__getattribute__ = __getattribute__ vereq(d.foo, 24) vereq(d.bar, 42) def __getattr__(self, name): if name in ("spam", "foo", "bar"): return "hello" raise AttributeError, name B.__getattr__ = __getattr__ vereq(d.spam, "hello") vereq(d.foo, 24) vereq(d.bar, 42) del A.__getattribute__ vereq(d.foo, 42) del d.foo vereq(d.foo, "hello") vereq(d.bar, 42) del B.__getattr__ try: d.foo except AttributeError: pass else: raise TestFailed, "d.foo should be undefined now" # Test a nasty bug in recurse_down_subclasses() import gc class A(object): pass class B(A): pass del B gc.collect() A.__setitem__ = lambda *a: None # crash |
vereq(hash(d), id(d)) | vereq(hash(d), orig_hash) | def subclasspropagation(): if verbose: print "Testing propagation of slot functions to subclasses..." class A(object): pass class B(A): pass class C(A): pass class D(B, C): pass d = D() vereq(hash(d), id(d)) A.__hash__ = lambda self: 42 vereq(hash(d), 42) C.__hash__ = lambda self: 314 vereq(hash(d), 314) B.__hash__ = lambda self: 144 vereq(hash(d), 144) D.__hash__ = lambda self: 100 vereq(hash(d), 100) del D.__hash__ vereq(hash(d), 144) del B.__hash__ vereq(hash(d), 314) del C.__hash__ vereq(hash(d), 42) del A.__hash__ vereq(hash(d), id(d)) d.foo = 42 d.bar = 42 vereq(d.foo, 42) vereq(d.bar, 42) def __getattribute__(self, name): if name == "foo": return 24 return object.__getattribute__(self, name) A.__getattribute__ = __getattribute__ vereq(d.foo, 24) vereq(d.bar, 42) def __getattr__(self, name): if name in ("spam", "foo", "bar"): return "hello" raise AttributeError, name B.__getattr__ = __getattr__ vereq(d.spam, "hello") vereq(d.foo, 24) vereq(d.bar, 42) del A.__getattribute__ vereq(d.foo, 42) del d.foo vereq(d.foo, "hello") vereq(d.bar, 42) del B.__getattr__ try: d.foo except AttributeError: pass else: raise TestFailed, "d.foo should be undefined now" # Test a nasty bug in recurse_down_subclasses() import gc class A(object): pass class B(A): pass del B gc.collect() A.__setitem__ = lambda *a: None # crash |
if len(segments) >= 2 and segments[-1] == '..': | if len(segments) == 2 and segments[1] == '..' and segments[0] == '': segments[-1] = '' elif len(segments) >= 2 and segments[-1] == '..': | def urljoin(base, url, allow_framents = 1): if not base: return url bscheme, bnetloc, bpath, bparams, bquery, bfragment = \ urlparse(base, '', allow_framents) scheme, netloc, path, params, query, fragment = \ urlparse(url, bscheme, allow_framents) # XXX Unofficial hack: default netloc to bnetloc even if # schemes differ if scheme != bscheme and not netloc and \ scheme in uses_relative and bscheme in uses_relative and \ scheme in uses_netloc and bscheme in uses_netloc: netloc = bnetloc # Strip the port number i = find(netloc, '@') if i < 0: i = 0 i = find(netloc, ':', i) if i >= 0: netloc = netloc[:i] if scheme != bscheme or scheme not in uses_relative: return urlunparse((scheme, netloc, path, params, query, fragment)) if scheme in uses_netloc: if netloc: return urlunparse((scheme, netloc, path, params, query, fragment)) netloc = bnetloc if path[:1] == '/': return urlunparse((scheme, netloc, path, params, query, fragment)) if not path: return urlunparse((scheme, netloc, bpath, params, query or bquery, fragment)) i = rfind(bpath, '/') if i >= 0: path = bpath[:i] + '/' + path segments = splitfields(path, '/') if segments[-1] == '.': segments[-1] = '' while '.' in segments: segments.remove('.') while 1: i = 1 n = len(segments) - 1 while i < n: if segments[i] == '..' and segments[i-1]: del segments[i-1:i+1] break i = i+1 else: break if len(segments) >= 2 and segments[-1] == '..': segments[-2:] = [''] return urlunparse((scheme, netloc, joinfields(segments, '/'), params, query, fragment)) |
'%define version ' + self.distribution.get_version(), '%define release ' + self.release, | '%define version ' + self.distribution.get_version().replace('-','_'), '%define release ' + self.release.replace('-','_'), | def _make_spec_file(self): """Generate the text of an RPM spec file and return it as a list of strings (one per line). """ # definitions and headers spec_file = [ '%define name ' + self.distribution.get_name(), '%define version ' + self.distribution.get_version(), '%define release ' + self.release, '', 'Summary: ' + self.distribution.get_description(), ] |
val = int(value) self.write("<value><int>%s</int></value>\n" % val) | if value > MAXINT or value < MININT: raise OverflowError, "long int exceeds XML-RPC limits" self.write("<value><int>%s</int></value>\n" % int(value)) | def dump_long(self, value): val = int(value) self.write("<value><int>%s</int></value>\n" % val) |
if address[0] == '<' and address[-1] == '>' and address != '<>': | if not address: pass elif address[0] == '<' and address[-1] == '>' and address != '<>': | def __getaddr(self, keyword, arg): address = None keylen = len(keyword) if arg[:keylen].upper() == keyword: address = arg[keylen:].strip() if address[0] == '<' and address[-1] == '>' and address != '<>': # Addresses can be in the form <[email protected]> but watch out # for null address, e.g. <> address = address[1:-1] return address |
print cmd | def _remote(self, action, autoraise): raise_opt = ("-noraise", "-raise")[autoraise] cmd = "%s %s -remote '%s' >/dev/null 2>&1" % (self.name, raise_opt, action) print cmd rc = os.system(cmd) if rc: import time os.system("%s &" % self.name) time.sleep(PROCESS_CREATION_DELAY) rc = os.system(cmd) return not rc |
|
_tryorder = ("mozilla","netscape","kfm","grail","links","lynx","w3m") | _tryorder = ["mozilla","netscape","kfm","grail","links","lynx","w3m"] | def open_new(self, url): self.open(url) |
_tryorder = ("netscape", "windows-default") | _tryorder = ["netscape", "windows-default"] | def open_new(self, url): self.open(url) |
_tryorder = ("internet-config", ) | _tryorder = ["internet-config"] | def open_new(self, url): self.open(url) |
_tryorder = ("os2netscape",) | _tryorder = ["os2netscape"] | def open_new(self, url): self.open(url) |
- excample: the Example object that failed | - example: the Example object that failed | def __str__(self): return str(self.test) |
filename = "<console | filename = "<pyshell | def runsource(self, source): # Extend base class to stuff the source in the line cache filename = "<console#%d>" % self.gid self.gid = self.gid + 1 lines = string.split(source, "\n") linecache.cache[filename] = len(source)+1, 0, lines, filename self.more = 0 return InteractiveInterpreter.runsource(self, source, filename) |
self.fileobj.write(struct.pack("<L", self.pos)) | self.fileobj.write(struct.pack("<L", self.pos & 0xffffFFFFL)) | def close(self): """Close the _Stream object. No operation should be done on it afterwards. """ if self.closed: return |
"""bsdTableDB.open(filename, dbhome, create=0, truncate=0, mode=0600) | """bsdTableDB(filename, dbhome, create=0, truncate=0, mode=0600) | def __init__(self, filename, dbhome, create=0, truncate=0, mode=0600, recover=0, dbflags=0): """bsdTableDB.open(filename, dbhome, create=0, truncate=0, mode=0600) Open database name in the dbhome BerkeleyDB directory. Use keyword arguments when calling this constructor. """ self.db = None myflags = DB_THREAD if create: myflags |= DB_CREATE flagsforenv = (DB_INIT_MPOOL | DB_INIT_LOCK | DB_INIT_LOG | DB_INIT_TXN | dbflags) # DB_AUTO_COMMIT isn't a valid flag for env.open() try: dbflags |= DB_AUTO_COMMIT except AttributeError: pass if recover: flagsforenv = flagsforenv | DB_RECOVER self.env = DBEnv() # enable auto deadlock avoidance self.env.set_lk_detect(DB_LOCK_DEFAULT) self.env.open(dbhome, myflags | flagsforenv) if truncate: myflags |= DB_TRUNCATE self.db = DB(self.env) # this code relies on DBCursor.set* methods to raise exceptions # rather than returning None self.db.set_get_returns_none(1) # allow duplicate entries [warning: be careful w/ metadata] self.db.set_flags(DB_DUP) self.db.open(filename, DB_BTREE, dbflags | myflags, mode) self.dbfilename = filename # Initialize the table names list if this is a new database txn = self.env.txn_begin() try: if not self.db.has_key(_table_names_key, txn): self.db.put(_table_names_key, pickle.dumps([], 1), txn=txn) # Yes, bare except except: txn.abort() raise else: txn.commit() # TODO verify more of the database's metadata? self.__tablecolumns = {} |
"""CreateTable(table, columns) - Create a new table in the database | """CreateTable(table, columns) - Create a new table in the database. | def CreateTable(self, table, columns): """CreateTable(table, columns) - Create a new table in the database raises TableDBError if it already exists or for other DB errors. """ assert isinstance(columns, ListType) txn = None try: # checking sanity of the table and column names here on # table creation will prevent problems elsewhere. if contains_metastrings(table): raise ValueError( "bad table name: contains reserved metastrings") for column in columns : if contains_metastrings(column): raise ValueError( "bad column name: contains reserved metastrings") |
- Create a new table in the database. | Create a new table in the database. | def CreateOrExtendTable(self, table, columns): """CreateOrExtendTable(table, columns) |
"""Modify(table, conditions) - Modify in rows matching 'conditions' using mapping functions in 'mappings' * conditions is a dictionary keyed on column names containing condition functions expecting the data string as an argument and returning a boolean. * mappings is a dictionary keyed on column names containint condition functions expecting the data string as an argument and returning the new string for that column. | """Modify(table, conditions={}, mappings={}) - Modify items in rows matching 'conditions' using mapping functions in 'mappings' * table - the table name * conditions - a dictionary keyed on column names containing a condition callable expecting the data string as an argument and returning a boolean. * mappings - a dictionary keyed on column names containing a condition callable expecting the data string as an argument and returning the new string for that column. | def Modify(self, table, conditions={}, mappings={}): """Modify(table, conditions) - Modify in rows matching 'conditions' using mapping functions in 'mappings' * conditions is a dictionary keyed on column names containing condition functions expecting the data string as an argument and returning a boolean. * mappings is a dictionary keyed on column names containint condition functions expecting the data string as an argument and returning the new string for that column. """ try: matching_rowids = self.__Select(table, [], conditions) |
except DBError, dberror: | except: | def Modify(self, table, conditions={}, mappings={}): """Modify(table, conditions) - Modify in rows matching 'conditions' using mapping functions in 'mappings' * conditions is a dictionary keyed on column names containing condition functions expecting the data string as an argument and returning a boolean. * mappings is a dictionary keyed on column names containint condition functions expecting the data string as an argument and returning the new string for that column. """ try: matching_rowids = self.__Select(table, [], conditions) |
* conditions is a dictionary keyed on column names containing condition functions expecting the data string as an argument and returning a boolean. | * conditions - a dictionary keyed on column names containing condition functions expecting the data string as an argument and returning a boolean. | def Delete(self, table, conditions={}): """Delete(table, conditions) - Delete items matching the given conditions from the table. * conditions is a dictionary keyed on column names containing condition functions expecting the data string as an argument and returning a boolean. """ try: matching_rowids = self.__Select(table, [], conditions) |
"""Select(table, conditions) - retrieve specific row data | """Select(table, columns, conditions) - retrieve specific row data | def Select(self, table, columns, conditions={}): """Select(table, conditions) - retrieve specific row data Returns a list of row column->value mapping dictionaries. * columns is a list of which column data to return. If columns is None, all columns will be returned. * conditions is a dictionary keyed on column names containing callable conditions expecting the data string as an argument and returning a boolean. """ try: if not self.__tablecolumns.has_key(table): self.__load_column_info(table) if columns is None: columns = self.__tablecolumns[table] matching_rowids = self.__Select(table, columns, conditions) except DBError, dberror: raise TableDBError, dberror[1] # return the matches as a list of dictionaries return matching_rowids.values() |
* columns is a list of which column data to return. If | * columns - a list of which column data to return. If | def Select(self, table, columns, conditions={}): """Select(table, conditions) - retrieve specific row data Returns a list of row column->value mapping dictionaries. * columns is a list of which column data to return. If columns is None, all columns will be returned. * conditions is a dictionary keyed on column names containing callable conditions expecting the data string as an argument and returning a boolean. """ try: if not self.__tablecolumns.has_key(table): self.__load_column_info(table) if columns is None: columns = self.__tablecolumns[table] matching_rowids = self.__Select(table, columns, conditions) except DBError, dberror: raise TableDBError, dberror[1] # return the matches as a list of dictionaries return matching_rowids.values() |
* conditions is a dictionary keyed on column names | * conditions - a dictionary keyed on column names | def Select(self, table, columns, conditions={}): """Select(table, conditions) - retrieve specific row data Returns a list of row column->value mapping dictionaries. * columns is a list of which column data to return. If columns is None, all columns will be returned. * conditions is a dictionary keyed on column names containing callable conditions expecting the data string as an argument and returning a boolean. """ try: if not self.__tablecolumns.has_key(table): self.__load_column_info(table) if columns is None: columns = self.__tablecolumns[table] matching_rowids = self.__Select(table, columns, conditions) except DBError, dberror: raise TableDBError, dberror[1] # return the matches as a list of dictionaries return matching_rowids.values() |
try: printable = value is None or not str(value) except: printable = False if printable: | valuestr = _some_str(value) if value is None or not valuestr: | def _format_final_exc_line(etype, value): """Return a list of a single line -- normal case for format_exception_only""" try: printable = value is None or not str(value) except: printable = False if printable: line = "%s\n" % etype else: line = "%s: %s\n" % (etype, _some_str(value)) return line |
line = "%s: %s\n" % (etype, _some_str(value)) | line = "%s: %s\n" % (etype, valuestr) | def _format_final_exc_line(etype, value): """Return a list of a single line -- normal case for format_exception_only""" try: printable = value is None or not str(value) except: printable = False if printable: line = "%s\n" % etype else: line = "%s: %s\n" % (etype, _some_str(value)) return line |
class _Environ(UserDict.UserDict): | class _Environ(UserDict.IterableUserDict): | def unsetenv(key): putenv(key, "") |
uchunks = [unicode(s, str(charset)) for s, charset in self._chunks] return u''.join(uchunks) | uchunks = [] lastcs = None for s, charset in self._chunks: nextcs = charset if uchunks: if lastcs is not None: if nextcs is None or nextcs == 'us-ascii': uchunks.append(USPACE) nextcs = None elif nextcs is not None and nextcs <> 'us-ascii': uchunks.append(USPACE) lastcs = nextcs uchunks.append(unicode(s, str(charset))) return UEMPTYSTRING.join(uchunks) | def __unicode__(self): """Helper for the built-in unicode function.""" # charset item is a Charset instance so we need to stringify it. uchunks = [unicode(s, str(charset)) for s, charset in self._chunks] return u''.join(uchunks) |
def test_main(): test.test_support.run_unittest(BuiltinTest, TestSorted) | def test_main(verbose=None): test_classes = (BuiltinTest, TestSorted) run_unittest(*test_classes) if verbose and hasattr(sys, "gettotalrefcount"): import gc counts = [None] * 5 for i in xrange(len(counts)): run_unittest(*test_classes) gc.collect() counts[i] = sys.gettotalrefcount() print counts | def test_main(): test.test_support.run_unittest(BuiltinTest, TestSorted) |
test_main() | test_main(verbose=True) | def test_main(): test.test_support.run_unittest(BuiltinTest, TestSorted) |
self._color = color | self._set_color(color) | def color(self, *args): if not args: raise Error, "no color arguments" if len(args) == 1: color = args[0] if type(color) == type(""): # Test the color first try: id = self._canvas.create_line(0, 0, 0, 0, fill=color) except Tkinter.TclError: raise Error, "bad color string: %s" % `color` self._color = color return try: r, g, b = color except: raise Error, "bad color sequence: %s" % `color` else: try: r, g, b = args except: raise Error, "bad color arguments: %s" % `args` assert 0 <= r <= 1 assert 0 <= g <= 1 assert 0 <= b <= 1 x = 255.0 y = 0.5 self._color = "#%02x%02x%02x" % (int(r*x+y), int(g*x+y), int(b*x+y)) |
self._color = " | self._set_color(" def _set_color(self,color): self._color = color self._draw_turtle() | def color(self, *args): if not args: raise Error, "no color arguments" if len(args) == 1: color = args[0] if type(color) == type(""): # Test the color first try: id = self._canvas.create_line(0, 0, 0, 0, fill=color) except Tkinter.TclError: raise Error, "bad color string: %s" % `color` self._color = color return try: r, g, b = color except: raise Error, "bad color sequence: %s" % `color` else: try: r, g, b = args except: raise Error, "bad color arguments: %s" % `args` assert 0 <= r <= 1 assert 0 <= g <= 1 assert 0 <= b <= 1 x = 255.0 y = 0.5 self._color = "#%02x%02x%02x" % (int(r*x+y), int(g*x+y), int(b*x+y)) |
arrow="last", | def _goto(self, x1, y1): x0, y0 = start = self._position self._position = map(float, (x1, y1)) if self._filling: self._path.append(self._position) if self._drawing: if self._tracing: dx = float(x1 - x0) dy = float(y1 - y0) distance = hypot(dx, dy) nhops = int(distance) item = self._canvas.create_line(x0, y0, x0, y0, width=self._width, arrow="last", capstyle="round", fill=self._color) try: for i in range(1, 1+nhops): x, y = x0 + dx*i/nhops, y0 + dy*i/nhops self._canvas.coords(item, x0, y0, x, y) self._canvas.update() self._canvas.after(10) # in case nhops==0 self._canvas.coords(item, x0, y0, x1, y1) self._canvas.itemconfigure(item, arrow="none") except Tkinter.TclError: # Probably the window was closed! return else: item = self._canvas.create_line(x0, y0, x1, y1, width=self._width, capstyle="round", fill=self._color) self._items.append(item) |
|
sys.stderr = StringIO() self.assertRaises(self.parser.parse_args, (cmdline_args,), None, SystemExit, expected_output, self.redirected_stderr) sys.stderr = sys.__stderr__ | save_stderr = sys.stderr try: sys.stderr = StringIO() self.assertRaises(self.parser.parse_args, (cmdline_args,), None, SystemExit, expected_output, self.redirected_stderr) finally: sys.stderr = save_stderr | def assertParseFail(self, cmdline_args, expected_output): """Assert the parser fails with the expected message.""" sys.stderr = StringIO() self.assertRaises(self.parser.parse_args, (cmdline_args,), None, SystemExit, expected_output, self.redirected_stderr) sys.stderr = sys.__stderr__ |
sys.stdout = StringIO() self.assertRaises(self.parser.parse_args, (cmdline_args,), None, SystemExit, expected_output, self.redirected_stdout) sys.stdout = sys.__stdout__ | save_stdout = sys.stdout try: sys.stdout = StringIO() self.assertRaises(self.parser.parse_args, (cmdline_args,), None, SystemExit, expected_output, self.redirected_stdout) finally: sys.stdout = save_stdout | def assertStdoutEquals(self, cmdline_args, expected_output): """Assert the parser prints the expected output on stdout.""" sys.stdout = StringIO() self.assertRaises(self.parser.parse_args, (cmdline_args,), None, SystemExit, expected_output, self.redirected_stdout) sys.stdout = sys.__stdout__ |
sys.argv[0] = "/foo/bar/baz.py" parser = OptionParser("usage: %prog ...", version="%prog 1.2") expected_usage = "usage: baz.py ...\n" self.assertUsage(parser, expected_usage) self.assertVersion(parser, "baz.py 1.2") self.assertHelp(parser, expected_usage + "\n" + "options:\n" " --version show program's version number and exit\n" " -h, --help show this help message and exit\n") | save_argv = sys.argv[:] try: sys.argv[0] = "/foo/bar/baz.py" parser = OptionParser("usage: %prog ...", version="%prog 1.2") expected_usage = "usage: baz.py ...\n" self.assertUsage(parser, expected_usage) self.assertVersion(parser, "baz.py 1.2") self.assertHelp(parser, expected_usage + "\n" + "options:\n" " --version show program's version number and exit\n" " -h, --help show this help message and exit\n") finally: sys.argv[:] = save_argv | def test_default_progname(self): # Make sure that program name taken from sys.argv[0] by default. sys.argv[0] = "/foo/bar/baz.py" parser = OptionParser("usage: %prog ...", version="%prog 1.2") expected_usage = "usage: baz.py ...\n" self.assertUsage(parser, expected_usage) self.assertVersion(parser, "baz.py 1.2") self.assertHelp(parser, expected_usage + "\n" + "options:\n" " --version show program's version number and exit\n" " -h, --help show this help message and exit\n") |
updated is a tuple naming the attributes off the wrapper that | updated is a tuple naming the attributes of the wrapper that | def update_wrapper(wrapper, wrapped, assigned = WRAPPER_ASSIGNMENTS, updated = WRAPPER_UPDATES): """Update a wrapper function to look like the wrapped function wrapper is the function to be updated wrapped is the original function assigned is a tuple naming the attributes assigned directly from the wrapped function to the wrapper function (defaults to functools.WRAPPER_ASSIGNMENTS) updated is a tuple naming the attributes off the wrapper that are updated with the corresponding attribute from the wrapped function (defaults to functools.WRAPPER_UPDATES) """ for attr in assigned: setattr(wrapper, attr, getattr(wrapped, attr)) for attr in updated: getattr(wrapper, attr).update(getattr(wrapped, attr)) # Return the wrapper so this can be used as a decorator via partial() return wrapper |
bp = bdb.Breakpoint.bpbynumber[int(i)] | try: i = int(i) except ValueError: print 'Breakpoint index %r is not a number' % i continue if not (0 <= i < len(bdb.Breakpoint.bpbynumber)): print 'No breakpoint numbered', i continue bp = bdb.Breakpoint.bpbynumber[i] | def do_enable(self, arg): args = arg.split() for i in args: bp = bdb.Breakpoint.bpbynumber[int(i)] if bp: bp.enable() |
bp = bdb.Breakpoint.bpbynumber[int(i)] | try: i = int(i) except ValueError: print 'Breakpoint index %r is not a number' % i continue if not (0 <= i < len(bdb.Breakpoint.bpbynumber)): print 'No breakpoint numbered', i continue bp = bdb.Breakpoint.bpbynumber[i] | def do_disable(self, arg): args = arg.split() for i in args: bp = bdb.Breakpoint.bpbynumber[int(i)] if bp: bp.disable() |
path = [module.__filename__] | head, tail = os.path.split(module.__filename__) path = [head] | def reload(self, module, path=None): if path is None and hasattr(module, '__filename__'): path = [module.__filename__] return ihooks.ModuleImporter.reload(self, module, path) |
suffix = ['.html', '.txt'][self.format=="html"] | suffix = ['.txt', '.html'][self.format=="html"] | def handle(self, info=None): info = info or sys.exc_info() if self.format == "html": self.file.write(reset()) |
def start_a(self, attributes): self.link_attr(attributes, 'href') | def check_name_id( self, attributes ): """ Check the name or id attributes on an element. """ | def start_a(self, attributes): self.link_attr(attributes, 'href') |
if name == "name": | if name == "name" or name == "id": | def start_a(self, attributes): self.link_attr(attributes, 'href') |
self.checker.message("WARNING: duplicate name %s in %s", | self.checker.message("WARNING: duplicate ID name %s in %s", | def start_a(self, attributes): self.link_attr(attributes, 'href') |
(S_IFLNK, "l", S_IFREG, "-", S_IFBLK, "b", S_IFDIR, "d", S_IFCHR, "c", S_IFIFO, "p"), (TUREAD, "r"), (TUWRITE, "w"), (TUEXEC, "x", TSUID, "S", TUEXEC|TSUID, "s"), (TGREAD, "r"), (TGWRITE, "w"), (TGEXEC, "x", TSGID, "S", TGEXEC|TSGID, "s"), (TOREAD, "r"), (TOWRITE, "w"), (TOEXEC, "x", TSVTX, "T", TOEXEC|TSVTX, "t")) | ((S_IFLNK, "l"), (S_IFREG, "-"), (S_IFBLK, "b"), (S_IFDIR, "d"), (S_IFCHR, "c"), (S_IFIFO, "p")), ((TUREAD, "r"),), ((TUWRITE, "w"),), ((TUEXEC|TSUID, "s"), (TSUID, "S"), (TUEXEC, "x")), ((TGREAD, "r"),), ((TGWRITE, "w"),), ((TGEXEC|TSGID, "s"), (TSGID, "S"), (TGEXEC, "x")), ((TOREAD, "r"),), ((TOWRITE, "w"),), ((TOEXEC|TSVTX, "t"), (TSVTX, "T"), (TOEXEC, "x")) ) | def copyfileobj(src, dst, length=None): """Copy length bytes from fileobj src to fileobj dst. If length is None, copy the entire content. """ if length == 0: return if length is None: shutil.copyfileobj(src, dst) return BUFSIZE = 16 * 1024 blocks, remainder = divmod(length, BUFSIZE) for b in xrange(blocks): buf = src.read(BUFSIZE) if len(buf) < BUFSIZE: raise IOError, "end of file reached" dst.write(buf) if remainder != 0: buf = src.read(remainder) if len(buf) < remainder: raise IOError, "end of file reached" dst.write(buf) return |
s = "" for t in filemode_table: while True: if mode & t[0] == t[0]: s += t[1] elif len(t) > 2: t = t[2:] continue else: s += "-" break return s | perm = [] for table in filemode_table: for bit, char in table: if mode & bit == bit: perm.append(char) break else: perm.append("-") return "".join(perm) | def filemode(mode): """Convert a file's mode to a string of the form -rwxrwxrwx. Used by TarFile.list() """ s = "" for t in filemode_table: while True: if mode & t[0] == t[0]: s += t[1] elif len(t) > 2: t = t[2:] continue else: s += "-" break return s |
assert u"%r, %r" % (u"abc", "abc") == u"u'abc', 'abc'" | value = u"%r, %r" % (u"abc", "abc") if value != u"u'abc', 'abc'": print '*** formatting failed for "%s"' % 'u"%r, %r" % (u"abc", "abc")' | test('capwords', u'abc\t def \nghi', u'Abc Def Ghi') |
assert u"%(x)s, %()s" % {'x':u"abc", u''.encode('utf-8'):"def"} == u'abc, def' | try: value = u"%(x)s, %()s" % {'x':u"abc", u''.encode('utf-8'):"def"} except KeyError: print '*** formatting failed for "%s"' % "u'abc, def'" else: assert value == u'abc, def' | test('capwords', u'abc\t def \nghi', u'Abc Def Ghi') |
raise AssertionError, "'...%s......' % u'abc' failed to raise an exception" | print "*** formatting failed ...%s......' % u'abc' failed to raise an exception" | test('capwords', u'abc\t def \nghi', u'Abc Def Ghi') |
print 'Done checking %d lines.' % (lineno,) | print 'Done checking %d lines.' % (lastline,) | def checkit(source, opts, morecmds=[]): """Check the LaTeX formatting in a sequence of lines. Opts is a mapping of options to option values if any: -m munge parenthesis and brackets -f forward slash warnings to be skipped -d delimiters only checking -v verbose listing on delimiters -s lineno: linenumber to start scan (default is 1). Morecmds is a sequence of LaTeX commands (without backslashes) that are to be considered valid in the scan. """ texcmd = re.compile(r'\\[A-Za-z]+') validcmds = sets.Set(cmdstr.split()) for cmd in morecmds: validcmds.add('\\' + cmd) openers = [] # Stack of pending open delimiters if '-m' in opts: pairmap = {']':'[(', ')':'(['} # Munged openers else: pairmap = {']':'[', ')':'('} # Normal opener for a given closer openpunct = sets.Set('([') # Set of valid openers delimiters = re.compile(r'\\(begin|end){([_a-zA-Z]+)}|([()\[\]])') tablestart = re.compile(r'\\begin{(?:long)?table([iv]+)}') tableline = re.compile(r'\\line([iv]+){') tableend = re.compile(r'\\end{(?:long)?table([iv]+)}') tablelevel = '' tablestartline = 0 startline = int(opts.get('-s', '1')) lineno = 0 for lineno, line in izip(count(startline), islice(source, startline-1, None)): line = line.rstrip() if '-f' not in opts and '/' in line: # Warn whenever forward slashes encountered line = line.rstrip() print 'Warning, forward slash on line %d: %s' % (lineno, line) if '-d' not in opts: # Validate commands nc = line.find(r'\newcommand') if nc != -1: start = line.find('{', nc) end = line.find('}', start) validcmds.add(line[start+1:end]) for cmd in texcmd.findall(line): if cmd not in validcmds: print r'Warning, unknown tex cmd on line %d: \%s' % (lineno, cmd) # Check balancing of open/close markers (parens, brackets, etc) for begend, name, punct in delimiters.findall(line): if '-v' in opts: print lineno, '|', begend, name, punct, if begend == 'begin' and '-d' not in opts: openers.append((lineno, name)) elif punct in openpunct: openers.append((lineno, punct)) elif begend == 'end' and '-d' not in opts: matchclose(lineno, name, openers, pairmap) elif punct in pairmap: matchclose(lineno, punct, openers, pairmap) if '-v' in opts: print ' --> ', openers # Check table levels (make sure lineii only inside lineiii) m = tablestart.search(line) if m: tablelevel = m.group(1) tablestartline = lineno m = tableline.search(line) if m and m.group(1) != tablelevel: print r'Warning, \line%s on line %d does not match \table%s on line %d' % (m.group(1), lineno, tablelevel, tablestartline) if tableend.search(line): tablelevel = '' for lineno, symbol in openers: print "Unmatched open delimiter '%s' on line %d" % (symbol, lineno) print 'Done checking %d lines.' % (lineno,) return 0 |
_cleanup() | for inst in _active[:]: inst.wait() | def _test(): teststr = "abc\n" print "testing popen2..." r, w = popen2('cat') w.write(teststr) w.close() assert r.read() == teststr print "testing popen3..." r, w, e = popen3(['cat']) w.write(teststr) w.close() assert r.read() == teststr assert e.read() == "" _cleanup() assert not _active print "All OK" |
saved_dist_files = self.distributuion.dist_files[:] | saved_dist_files = self.distribution.dist_files[:] | def run (self): |
if data[0][-1] in (',', '.') or data[0].lower() in _daynames: | if data[0].endswith(',') or data[0].lower() in _daynames: | def parsedate_tz(data): """Convert a date string to a time tuple. Accounts for military timezones. """ data = data.split() if data[0][-1] in (',', '.') or data[0].lower() in _daynames: # There's a dayname here. Skip it del data[0] if len(data) == 3: # RFC 850 date, deprecated stuff = data[0].split('-') if len(stuff) == 3: data = stuff + data[1:] if len(data) == 4: s = data[3] i = s.find('+') if i > 0: data[3:] = [s[:i], s[i+1:]] else: data.append('') # Dummy tz if len(data) < 5: return None data = data[:5] [dd, mm, yy, tm, tz] = data mm = mm.lower() if mm not in _monthnames: dd, mm = mm, dd.lower() if mm not in _monthnames: return None mm = _monthnames.index(mm) + 1 if mm > 12: mm -= 12 if dd[-1] == ',': dd = dd[:-1] i = yy.find(':') if i > 0: yy, tm = tm, yy if yy[-1] == ',': yy = yy[:-1] if not yy[0].isdigit(): yy, tz = tz, yy if tm[-1] == ',': tm = tm[:-1] tm = tm.split(':') if len(tm) == 2: [thh, tmm] = tm tss = '0' elif len(tm) == 3: [thh, tmm, tss] = tm else: return None try: yy = int(yy) dd = int(dd) thh = int(thh) tmm = int(tmm) tss = int(tss) except ValueError: return None tzoffset = None tz = tz.upper() if _timezones.has_key(tz): tzoffset = _timezones[tz] else: try: tzoffset = int(tz) except ValueError: pass # Convert a timezone offset into seconds ; -0500 -> -18000 if tzoffset: if tzoffset < 0: tzsign = -1 tzoffset = -tzoffset else: tzsign = 1 tzoffset = tzsign * ( (tzoffset/100)*3600 + (tzoffset % 100)*60) tuple = (yy, mm, dd, thh, tmm, tss, 0, 0, 0, tzoffset) return tuple |
if inst.poll(_deadstate=sys.maxint) >= 0: | res = inst.poll(_deadstate=sys.maxint) if res is not None and res >= 0: | def _cleanup(): for inst in _active[:]: if inst.poll(_deadstate=sys.maxint) >= 0: try: _active.remove(inst) except ValueError: # This can happen if two threads create a new Popen instance. # It's harmless that it was already removed, so ignore. pass |
self._dkeys = self._dict.keys() self._dkeys.sort() | def __init__(self, *args): unittest.TestCase.__init__(self, *args) self._dkeys = self._dict.keys() self._dkeys.sort() |
|
_delete_files() | def test_dumbdbm_creation(self): _delete_files() f = dumbdbm.open(_fname, 'c') self.assertEqual(f.keys(), []) for key in self._dict: f[key] = self._dict[key] self.read_helper(f) f.close() |
|
self.assertEqual(keys, self._dkeys) | dkeys = self._dict.keys() dkeys.sort() self.assertEqual(keys, dkeys) | def keys_helper(self, f): keys = f.keys() keys.sort() self.assertEqual(keys, self._dkeys) return keys |
if stdin == None and stdout == None and stderr == None: | if stdin is None and stdout is None and stderr is None: | def _get_handles(self, stdin, stdout, stderr): """Construct and return tupel with IO objects: p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite """ if stdin == None and stdout == None and stderr == None: return (None, None, None, None, None, None) |
if stdin == None: | if stdin is None: | def _get_handles(self, stdin, stdout, stderr): """Construct and return tupel with IO objects: p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite """ if stdin == None and stdout == None and stderr == None: return (None, None, None, None, None, None) |
elif type(stdin) == int: | elif isinstance(stdin, int): | def _get_handles(self, stdin, stdout, stderr): """Construct and return tupel with IO objects: p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite """ if stdin == None and stdout == None and stderr == None: return (None, None, None, None, None, None) |
if stdout == None: | if stdout is None: | def _get_handles(self, stdin, stdout, stderr): """Construct and return tupel with IO objects: p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite """ if stdin == None and stdout == None and stderr == None: return (None, None, None, None, None, None) |
elif type(stdout) == int: | elif isinstance(stdout, int): | def _get_handles(self, stdin, stdout, stderr): """Construct and return tupel with IO objects: p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite """ if stdin == None and stdout == None and stderr == None: return (None, None, None, None, None, None) |
if stderr == None: | if stderr is None: | def _get_handles(self, stdin, stdout, stderr): """Construct and return tupel with IO objects: p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite """ if stdin == None and stdout == None and stderr == None: return (None, None, None, None, None, None) |
elif type(stderr) == int: | elif isinstance(stderr, int): | def _get_handles(self, stdin, stdout, stderr): """Construct and return tupel with IO objects: p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite """ if stdin == None and stdout == None and stderr == None: return (None, None, None, None, None, None) |
if startupinfo == None: | if startupinfo is None: | def _execute_child(self, args, executable, preexec_fn, close_fds, cwd, env, universal_newlines, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite): """Execute program (MS Windows version)""" |
if p2cread != None: | if p2cread is not None: | def _execute_child(self, args, executable, preexec_fn, close_fds, cwd, env, universal_newlines, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite): """Execute program (MS Windows version)""" |
if c2pwrite != None: | if c2pwrite is not None: | def _execute_child(self, args, executable, preexec_fn, close_fds, cwd, env, universal_newlines, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite): """Execute program (MS Windows version)""" |
if errwrite != None: | if errwrite is not None: | def _execute_child(self, args, executable, preexec_fn, close_fds, cwd, env, universal_newlines, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite): """Execute program (MS Windows version)""" |
if self.returncode == None: | if self.returncode is None: | def poll(self): """Check if child process has terminated. Returns returncode attribute.""" if self.returncode == None: if WaitForSingleObject(self._handle, 0) == WAIT_OBJECT_0: self.returncode = GetExitCodeProcess(self._handle) _active.remove(self) return self.returncode |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.