rem
stringlengths 0
322k
| add
stringlengths 0
2.05M
| context
stringlengths 8
228k
|
---|---|---|
_monthnames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] _daynames = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] | _monthnames = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec', 'january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'] _daynames = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'] | def dump_address_pair(pair): """Dump a (name, address) pair in a canonicalized form.""" if pair[0]: return '"' + pair[0] + '" <' + pair[1] + '>' else: return pair[1] |
if data[0][-1] == ',' or data[0] in _daynames: | if data[0][-1] in (',', '.') or string.lower(data[0]) in _daynames: | def parsedate_tz(data): """Convert a date string to a time tuple. Accounts for military timezones. """ data = string.split(data) if data[0][-1] == ',' or data[0] in _daynames: # There's a dayname here. Skip it del data[0] if len(data) == 3: # RFC 850 date, deprecated stuff = string.split(data[0], '-') if len(stuff) == 3: data = stuff + data[1:] if len(data) == 4: s = data[3] i = string.find(s, '+') 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 if not mm in _monthnames: dd, mm, yy, tm, tz = mm, dd, tm, yy, tz if not mm in _monthnames: return None mm = _monthnames.index(mm)+1 tm = string.splitfields(tm, ':') if len(tm) == 2: [thh, tmm] = tm tss = '0' elif len(tm) == 3: [thh, tmm, tss] = tm else: return None try: yy = string.atoi(yy) dd = string.atoi(dd) thh = string.atoi(thh) tmm = string.atoi(tmm) tss = string.atoi(tss) except string.atoi_error: return None tzoffset=None tz=string.upper(tz) if _timezones.has_key(tz): tzoffset=_timezones[tz] else: try: tzoffset=string.atoi(tz) except string.atoi_error: 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 |
dd, mm, yy, tm, tz = mm, dd, tm, yy, tz | dd, mm = mm, string.lower(dd) | def parsedate_tz(data): """Convert a date string to a time tuple. Accounts for military timezones. """ data = string.split(data) if data[0][-1] == ',' or data[0] in _daynames: # There's a dayname here. Skip it del data[0] if len(data) == 3: # RFC 850 date, deprecated stuff = string.split(data[0], '-') if len(stuff) == 3: data = stuff + data[1:] if len(data) == 4: s = data[3] i = string.find(s, '+') 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 if not mm in _monthnames: dd, mm, yy, tm, tz = mm, dd, tm, yy, tz if not mm in _monthnames: return None mm = _monthnames.index(mm)+1 tm = string.splitfields(tm, ':') if len(tm) == 2: [thh, tmm] = tm tss = '0' elif len(tm) == 3: [thh, tmm, tss] = tm else: return None try: yy = string.atoi(yy) dd = string.atoi(dd) thh = string.atoi(thh) tmm = string.atoi(tmm) tss = string.atoi(tss) except string.atoi_error: return None tzoffset=None tz=string.upper(tz) if _timezones.has_key(tz): tzoffset=_timezones[tz] else: try: tzoffset=string.atoi(tz) except string.atoi_error: 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 |
lexer.wordchars = lexer.wordchars + '.' | lexer.wordchars = lexer.wordchars + '.-@' | def __init__(self, file=None): if not file: file = os.path.join(os.environ['HOME'], ".netrc") try: fp = open(file) except: return None self.hosts = {} self.macros = {} lexer = shlex.shlex(fp) lexer.wordchars = lexer.wordchars + '.' while 1: # Look for a machine, default, or macdef top-level keyword toplevel = tt = lexer.get_token() if tt == '' or tt == None: break elif tt == 'machine': entryname = lexer.get_token() elif tt == 'default': entryname = 'default' elif tt == 'macdef': # Just skip to end of macdefs entryname = lexer.get_token() self.macros[entryname] = [] lexer.whitepace = ' \t' while 1: line = lexer.instream.readline() if not line or line == '\012' and tt == '\012': lexer.whitepace = ' \t\r\n' break tt = line self.macros[entryname].append(line) else: raise SyntaxError, "bad toplevel token %s, file %s, line %d" \ % (tt, file, lexer.lineno) |
if prog.match(line) == len(line): | if prog.match(line) >= 0: | def pickline(file, key, casefold = 1): try: f = open(file, 'r') except IOError: return None pat = key + ':' if casefold: prog = regex.compile(pat, regex.casefold) else: prog = regex.compile(pat) while 1: line = f.readline() if not line: break if prog.match(line) == len(line): text = line[len(key)+1:] while 1: line = f.readline() if not line or \ line[0] not in string.whitespace: break text = text + line return string.strip(text) return None |
websucker.Sucker.savefilename(self, url)) | websucker.Sucker.savefilename(self.sucker, url)) | def go(self, event=None): if not self.msgq: self.msgq = Queue.Queue(0) self.check_msgq() if not self.sucker: self.sucker = SuckerThread(self.msgq) if self.sucker.stopit: return self.url_entry.selection_range(0, END) url = self.url_entry.get() url = url.strip() if not url: self.top.bell() self.message("[Error: No URL entered]") return self.rooturl = url dir = self.dir_entry.get().strip() if not dir: self.sucker.savedir = None else: self.sucker.savedir = dir self.sucker.rootdir = os.path.dirname( websucker.Sucker.savefilename(self, url)) self.go_button.configure(state=DISABLED) self.auto_button.configure(state=DISABLED) self.cancel_button.configure(state=NORMAL) self.message( '[running...]') self.sucker.stopit = 0 t = threading.Thread(target=self.sucker.run1, args=(url,)) t.start() |
builtin = r"([^\\.]\b|^)" + any("BUILTIN", builtinlist) + r"\b" | builtin = r"([^.'\"\\]\b|^)" + any("BUILTIN", builtinlist) + r"\b" | def make_pat(): kw = r"\b" + any("KEYWORD", keyword.kwlist) + r"\b" builtinlist = [str(name) for name in dir(__builtin__) if not name.startswith('_')] builtin = r"([^\\.]\b|^)" + any("BUILTIN", builtinlist) + r"\b" comment = any("COMMENT", [r"#[^\n]*"]) sqstring = r"(\b[rR])?'[^'\\\n]*(\\.[^'\\\n]*)*'?" dqstring = r'(\b[rR])?"[^"\\\n]*(\\.[^"\\\n]*)*"?' sq3string = r"(\b[rR])?'''[^'\\]*((\\.|'(?!''))[^'\\]*)*(''')?" dq3string = r'(\b[rR])?"""[^"\\]*((\\.|"(?!""))[^"\\]*)*(""")?' string = any("STRING", [sq3string, dq3string, sqstring, dqstring]) return kw + "|" + builtin + "|" + comment + "|" + string + "|" + any("SYNC", [r"\n"]) |
return kw + "|" + builtin + "|" + comment + "|" + string + "|" + any("SYNC", [r"\n"]) | return kw + "|" + builtin + "|" + comment + "|" + string +\ "|" + any("SYNC", [r"\n"]) | def make_pat(): kw = r"\b" + any("KEYWORD", keyword.kwlist) + r"\b" builtinlist = [str(name) for name in dir(__builtin__) if not name.startswith('_')] builtin = r"([^\\.]\b|^)" + any("BUILTIN", builtinlist) + r"\b" comment = any("COMMENT", [r"#[^\n]*"]) sqstring = r"(\b[rR])?'[^'\\\n]*(\\.[^'\\\n]*)*'?" dqstring = r'(\b[rR])?"[^"\\\n]*(\\.[^"\\\n]*)*"?' sq3string = r"(\b[rR])?'''[^'\\]*((\\.|'(?!''))[^'\\]*)*(''')?" dq3string = r'(\b[rR])?"""[^"\\]*((\\.|"(?!""))[^"\\]*)*(""")?' string = any("STRING", [sq3string, dq3string, sqstring, dqstring]) return kw + "|" + builtin + "|" + comment + "|" + string + "|" + any("SYNC", [r"\n"]) |
allow_colorizing = 1 colorizing = 0 | allow_colorizing = True colorizing = False | def delete(self, index1, index2=None): index1 = self.index(index1) self.delegate.delete(index1, index2) self.notify_range(index1) |
self.stop_colorizing = 1 | self.stop_colorizing = True | def notify_range(self, index1, index2=None): self.tag_add("TODO", index1, index2) if self.after_id: if DEBUG: print "colorizing already scheduled" return if self.colorizing: self.stop_colorizing = 1 if DEBUG: print "stop colorizing" if self.allow_colorizing: if DEBUG: print "schedule colorizing" self.after_id = self.after(1, self.recolorize) |
self.allow_colorizing = 0 self.stop_colorizing = 1 | self.allow_colorizing = False self.stop_colorizing = True | def close(self, close_when_done=None): if self.after_id: after_id = self.after_id self.after_id = None if DEBUG: print "cancel scheduled recolorizer" self.after_cancel(after_id) self.allow_colorizing = 0 self.stop_colorizing = 1 if close_when_done: if not self.colorizing: close_when_done.destroy() else: self.close_when_done = close_when_done |
self.stop_colorizing = 1 | self.stop_colorizing = True | def toggle_colorize_event(self, event): if self.after_id: after_id = self.after_id self.after_id = None if DEBUG: print "cancel scheduled recolorizer" self.after_cancel(after_id) if self.allow_colorizing and self.colorizing: if DEBUG: print "stop colorizing" self.stop_colorizing = 1 self.allow_colorizing = not self.allow_colorizing if self.allow_colorizing and not self.colorizing: self.after_id = self.after(1, self.recolorize) if DEBUG: print "auto colorizing turned", self.allow_colorizing and "on" or "off" return "break" |
print "auto colorizing turned", self.allow_colorizing and "on" or "off" | print "auto colorizing turned",\ self.allow_colorizing and "on" or "off" | def toggle_colorize_event(self, event): if self.after_id: after_id = self.after_id self.after_id = None if DEBUG: print "cancel scheduled recolorizer" self.after_cancel(after_id) if self.allow_colorizing and self.colorizing: if DEBUG: print "stop colorizing" self.stop_colorizing = 1 self.allow_colorizing = not self.allow_colorizing if self.allow_colorizing and not self.colorizing: self.after_id = self.after(1, self.recolorize) if DEBUG: print "auto colorizing turned", self.allow_colorizing and "on" or "off" return "break" |
self.stop_colorizing = 0 self.colorizing = 1 | self.stop_colorizing = False self.colorizing = True | def recolorize(self): self.after_id = None if not self.delegate: if DEBUG: print "no delegate" return if not self.allow_colorizing: if DEBUG: print "auto colorizing is off" return if self.colorizing: if DEBUG: print "already colorizing" return try: self.stop_colorizing = 0 self.colorizing = 1 if DEBUG: print "colorizing..." t0 = time.clock() self.recolorize_main() t1 = time.clock() if DEBUG: print "%.3f seconds" % (t1-t0) finally: self.colorizing = 0 if self.allow_colorizing and self.tag_nextrange("TODO", "1.0"): if DEBUG: print "reschedule colorizing" self.after_id = self.after(1, self.recolorize) if self.close_when_done: top = self.close_when_done self.close_when_done = None top.destroy() |
self.colorizing = 0 | self.colorizing = False | def recolorize(self): self.after_id = None if not self.delegate: if DEBUG: print "no delegate" return if not self.allow_colorizing: if DEBUG: print "auto colorizing is off" return if self.colorizing: if DEBUG: print "already colorizing" return try: self.stop_colorizing = 0 self.colorizing = 1 if DEBUG: print "colorizing..." t0 = time.clock() self.recolorize_main() t1 = time.clock() if DEBUG: print "%.3f seconds" % (t1-t0) finally: self.colorizing = 0 if self.allow_colorizing and self.tag_nextrange("TODO", "1.0"): if DEBUG: print "reschedule colorizing" self.after_id = self.after(1, self.recolorize) if self.close_when_done: top = self.close_when_done self.close_when_done = None top.destroy() |
while 1: | while True: | def recolorize_main(self): next = "1.0" while 1: item = self.tag_nextrange("TODO", next) if not item: break head, tail = item self.tag_remove("SYNC", head, tail) item = self.tag_prevrange("SYNC", head) if item: head = item[1] else: head = "1.0" |
ok = 0 | ok = False | def recolorize_main(self): next = "1.0" while 1: item = self.tag_nextrange("TODO", next) if not item: break head, tail = item self.tag_remove("SYNC", head, tail) item = self.tag_prevrange("SYNC", head) if item: head = item[1] else: head = "1.0" |
def readfp(self): | def readfp(self, fp): | def readfp(self): """Read a single mime.types-format file.""" map = self.types_map while 1: line = f.readline() if not line: break words = line.split() for i in range(len(words)): if words[i][0] == '#': del words[i:] break if not words: continue type, suffixes = words[0], words[1:] for suff in suffixes: map['.' + suff] = type |
line = f.readline() | line = fp.readline() | def readfp(self): """Read a single mime.types-format file.""" map = self.types_map while 1: line = f.readline() if not line: break words = line.split() for i in range(len(words)): if words[i][0] == '#': del words[i:] break if not words: continue type, suffixes = words[0], words[1:] for suff in suffixes: map['.' + suff] = type |
print >>sys.stderr, "l1=%r, l2=%r, ignore=%r" % (l1, l2, ignore) | print >>sys.stderr, "l1=%r\nl2=%r\nignore=%r" % (l1, l2, ignore) | def assertListEq(self, l1, l2, ignore): ''' succeed iff {l1} - {ignore} == {l2} - {ignore} ''' try: for p1, p2 in (l1, l2), (l2, l1): for item in p1: ok = (item in p2) or (item in ignore) if not ok: self.fail("%r missing" % item) except: print >>sys.stderr, "l1=%r, l2=%r, ignore=%r" % (l1, l2, ignore) raise |
if type(getattr(py_item, m)) == MethodType: | if ismethod(getattr(py_item, m), m): | def checkModule(self, moduleName, module=None, ignore=()): ''' succeed iff pyclbr.readmodule_ex(modulename) corresponds to the actual module object, module. Any identifiers in ignore are ignored. If no module is provided, the appropriate module is loaded with __import__.''' |
self.assertListEq(foundMethods, actualMethods, ignore) self.assertEquals(py_item.__module__, value.module) | try: self.assertListEq(foundMethods, actualMethods, ignore) self.assertEquals(py_item.__module__, value.module) | def checkModule(self, moduleName, module=None, ignore=()): ''' succeed iff pyclbr.readmodule_ex(modulename) corresponds to the actual module object, module. Any identifiers in ignore are ignored. If no module is provided, the appropriate module is loaded with __import__.''' |
self.assertEquals(py_item.__name__, value.name, ignore) | self.assertEquals(py_item.__name__, value.name, ignore) except: print >>sys.stderr, "class=%s" % py_item raise | def checkModule(self, moduleName, module=None, ignore=()): ''' succeed iff pyclbr.readmodule_ex(modulename) corresponds to the actual module object, module. Any identifiers in ignore are ignored. If no module is provided, the appropriate module is loaded with __import__.''' |
self.checkModule('doctest', ignore=['_isclass', '_isfunction', '_ismodule', '_classify_class_attrs']) self.checkModule('rfc822', ignore=["get"]) | self.checkModule('doctest') self.checkModule('rfc822') | def test_easy(self): self.checkModule('pyclbr') self.checkModule('doctest', ignore=['_isclass', '_isfunction', '_ismodule', '_classify_class_attrs']) self.checkModule('rfc822', ignore=["get"]) self.checkModule('difflib') |
cm('cgi', ignore=('f', 'g', 'log')) cm('mhlib', ignore=('do', 'bisect')) cm('urllib', ignore=('getproxies_environment', 'getproxies_registry', 'open_https')) cm('pickle', ignore=('g',)) cm('aifc', ignore=('openfp',)) cm('Cookie', ignore=('__str__', 'Cookie')) cm('sre_parse', ignore=('literal', 'makedict', 'dump' )) | cm('cgi', ignore=('log',)) cm('mhlib') cm('urllib', ignore=('getproxies_registry', 'open_https')) cm('pickle', ignore=('g',)) cm('aifc', ignore=('openfp',)) cm('Cookie') cm('sre_parse', ignore=('dump',)) cm('pdb') cm('pydoc') | def test_others(self): cm = self.checkModule |
cm('test.test_pyclbr', ignore=('defined_in',)) | cm('test.test_pyclbr') | def test_others(self): cm = self.checkModule |
return st[stat.ST_MTIME] | return st[stat.ST_ATIME] | def getatime(filename): """Return the last access time of a file, reported by os.stat().""" st = os.stat(filename) return st[stat.ST_MTIME] |
if verbose: print "starting pause() loop..." | print "starting pause() loop..." | def force_test_exit(): # Sigh, both imports seem necessary to avoid errors. import os fork_pid = os.fork() if fork_pid: # In parent. return fork_pid # In child. import os, time try: # Wait 5 seconds longer than the expected alarm to give enough # time for the normal sequence of events to occur. This is # just a stop-gap to try to prevent the test from hanging. time.sleep(MAX_DURATION + 5) print >> sys.__stdout__, ' child should not have to kill parent' for signame in "SIGHUP", "SIGUSR1", "SIGUSR2", "SIGALRM": os.kill(pid, getattr(signal, signame)) print >> sys.__stdout__, " child sent", signame, "to", pid time.sleep(1) finally: os._exit(0) |
def __hasattr__(self, attr): "Delegate attribute access to the interpreter object" return hasattr(self.tk, attr) def __delattr__(self, attr): "Delegate attribute access to the interpreter object" return delattr(self.tk, attr) | def __hasattr__(self, attr): "Delegate attribute access to the interpreter object" return hasattr(self.tk, attr) |
|
pass | if size > self.extrasize: size = self.extrasize | def read(self, size=None): if self.extrasize <= 0 and self.fileobj is None: return '' |
self.extrasize = len(self.extrabuf) | self.extrasize = len(buf) + self.extrasize | def _unread(self, buf): self.extrabuf = buf + self.extrabuf self.extrasize = len(self.extrabuf) |
return string.split(buf, '\n') | lines = string.split(buf, '\n') for i in range(len(lines)-1): lines[i] = lines[i] + '\n' if lines and not lines[-1]: del lines[-1] return lines | def readlines(self): buf = self.read() return string.split(buf, '\n') |
fragment = url[i+1:] | def urlparse(url, scheme = '', allow_fragments = 1): key = url, scheme, allow_fragments cached = _parse_cache.get(key, None) if cached: return cached if len(_parse_cache) >= MAX_CACHE_SIZE: # avoid runaway growth clear_cache() find = string.find netloc = path = params = query = fragment = '' i = find(url, ':') if i > 0: if url[:i] == 'http': # optimizie the common case scheme = string.lower(url[:i]) url = url[i+1:] if url[:2] == '//': i = find(url, '/', 2) if i < 0: i = len(url) netloc = url[2:i] url = url[i:] if allow_fragments: i = string.rfind(url, '#') if i >= 0: url = url[:i] fragment = url[i+1:] i = find(url, '?') if i >= 0: url = url[:i] query = url[i+1:] i = find(url, ';') if i >= 0: url = url[:i] params = url[i+1:] tuple = scheme, netloc, url, params, query, fragment _parse_cache[key] = tuple return tuple for c in url[:i]: if c not in scheme_chars: break else: scheme, url = string.lower(url[:i]), url[i+1:] if scheme in uses_netloc: if url[:2] == '//': i = find(url, '/', 2) if i < 0: i = len(url) netloc, url = url[2:i], url[i:] if allow_fragments and scheme in uses_fragment: i = string.rfind(url, '#') if i >= 0: url, fragment = url[:i], url[i+1:] if scheme in uses_query: i = find(url, '?') if i >= 0: url, query = url[:i], url[i+1:] if scheme in uses_params: i = find(url, ';') if i >= 0: url, params = url[:i], url[i+1:] tuple = scheme, netloc, url, params, query, fragment _parse_cache[key] = tuple return tuple |
|
query = url[i+1:] | def urlparse(url, scheme = '', allow_fragments = 1): key = url, scheme, allow_fragments cached = _parse_cache.get(key, None) if cached: return cached if len(_parse_cache) >= MAX_CACHE_SIZE: # avoid runaway growth clear_cache() find = string.find netloc = path = params = query = fragment = '' i = find(url, ':') if i > 0: if url[:i] == 'http': # optimizie the common case scheme = string.lower(url[:i]) url = url[i+1:] if url[:2] == '//': i = find(url, '/', 2) if i < 0: i = len(url) netloc = url[2:i] url = url[i:] if allow_fragments: i = string.rfind(url, '#') if i >= 0: url = url[:i] fragment = url[i+1:] i = find(url, '?') if i >= 0: url = url[:i] query = url[i+1:] i = find(url, ';') if i >= 0: url = url[:i] params = url[i+1:] tuple = scheme, netloc, url, params, query, fragment _parse_cache[key] = tuple return tuple for c in url[:i]: if c not in scheme_chars: break else: scheme, url = string.lower(url[:i]), url[i+1:] if scheme in uses_netloc: if url[:2] == '//': i = find(url, '/', 2) if i < 0: i = len(url) netloc, url = url[2:i], url[i:] if allow_fragments and scheme in uses_fragment: i = string.rfind(url, '#') if i >= 0: url, fragment = url[:i], url[i+1:] if scheme in uses_query: i = find(url, '?') if i >= 0: url, query = url[:i], url[i+1:] if scheme in uses_params: i = find(url, ';') if i >= 0: url, params = url[:i], url[i+1:] tuple = scheme, netloc, url, params, query, fragment _parse_cache[key] = tuple return tuple |
|
params = url[i+1:] | def urlparse(url, scheme = '', allow_fragments = 1): key = url, scheme, allow_fragments cached = _parse_cache.get(key, None) if cached: return cached if len(_parse_cache) >= MAX_CACHE_SIZE: # avoid runaway growth clear_cache() find = string.find netloc = path = params = query = fragment = '' i = find(url, ':') if i > 0: if url[:i] == 'http': # optimizie the common case scheme = string.lower(url[:i]) url = url[i+1:] if url[:2] == '//': i = find(url, '/', 2) if i < 0: i = len(url) netloc = url[2:i] url = url[i:] if allow_fragments: i = string.rfind(url, '#') if i >= 0: url = url[:i] fragment = url[i+1:] i = find(url, '?') if i >= 0: url = url[:i] query = url[i+1:] i = find(url, ';') if i >= 0: url = url[:i] params = url[i+1:] tuple = scheme, netloc, url, params, query, fragment _parse_cache[key] = tuple return tuple for c in url[:i]: if c not in scheme_chars: break else: scheme, url = string.lower(url[:i]), url[i+1:] if scheme in uses_netloc: if url[:2] == '//': i = find(url, '/', 2) if i < 0: i = len(url) netloc, url = url[2:i], url[i:] if allow_fragments and scheme in uses_fragment: i = string.rfind(url, '#') if i >= 0: url, fragment = url[:i], url[i+1:] if scheme in uses_query: i = find(url, '?') if i >= 0: url, query = url[:i], url[i+1:] if scheme in uses_params: i = find(url, ';') if i >= 0: url, params = url[:i], url[i+1:] tuple = scheme, netloc, url, params, query, fragment _parse_cache[key] = tuple return tuple |
|
SyntaxError: 'yield' outside function (<doctest test.test_generators.__test__.coroutine[10]>, line 1) | SyntaxError: 'yield' outside function (<doctest test.test_generators.__test__.coroutine[21]>, line 1) | >>> def f(): list(i for i in [(yield 26)]) |
SyntaxError: 'return' with argument inside generator (<doctest test.test_generators.__test__.coroutine[11]>, line 1) | SyntaxError: 'return' with argument inside generator (<doctest test.test_generators.__test__.coroutine[22]>, line 1) | >>> def f(): return lambda x=(yield): 1 |
SyntaxError: assignment to yield expression not possible (<doctest test.test_generators.__test__.coroutine[12]>, line 1) | SyntaxError: assignment to yield expression not possible (<doctest test.test_generators.__test__.coroutine[23]>, line 1) >>> def f(): (yield bar) = y Traceback (most recent call last): ... SyntaxError: can't assign to yield expression (<doctest test.test_generators.__test__.coroutine[24]>, line 1) >>> def f(): (yield bar) += y Traceback (most recent call last): ... SyntaxError: augmented assignment to yield expression not possible (<doctest test.test_generators.__test__.coroutine[25]>, line 1) | >>> def f(): x = yield = y |
(msg is None or mod.match(module)) and | (mod is None or mod.match(module)) and | def warn_explicit(message, category, filename, lineno, module=None, registry=None): if module is None: module = filename if module[-3:].lower() == ".py": module = module[:-3] # XXX What about leading pathname? if registry is None: registry = {} if isinstance(message, Warning): text = str(message) category = message.__class__ else: text = message message = category(message) key = (text, category, lineno) # Quick test for common case if registry.get(key): return # Search the filters for item in filters: action, msg, cat, mod, ln = item if ((msg is None or msg.match(text)) and issubclass(category, cat) and (msg is None or mod.match(module)) and (ln == 0 or lineno == ln)): break else: action = defaultaction # Early exit actions if action == "ignore": registry[key] = 1 return if action == "error": raise message # Other actions if action == "once": registry[key] = 1 oncekey = (text, category) if onceregistry.get(oncekey): return onceregistry[oncekey] = 1 elif action == "always": pass elif action == "module": registry[key] = 1 altkey = (text, category, 0) if registry.get(altkey): return registry[altkey] = 1 elif action == "default": registry[key] = 1 else: # Unrecognized actions are errors raise RuntimeError( "Unrecognized action (%r) in warnings.filters:\n %s" % (action, item)) # Print message and context showwarning(message, category, filename, lineno) |
if self.disp.format == 'mono': nline = (len(data)*8)/self.vw elif self.disp.format == 'grey2': nline = (len(data)*4)/self.vw elif self.disp.format == 'grey4': nline = (len(data)*2)/self.vw else: nline = len(data)/self.vw if nline*self.vw <> len(data): print 'Incorrect-sized video fragment ignored' return | nline = len(data)/self.linewidth() if nline*self.linewidth() <> len(data): print 'Incorrect-sized video fragment ignored' return | def putnextpacket(self, pos, data): if self.disp.format == 'mono': # Unfortunately size-check is difficult for # packed video nline = (len(data)*8)/self.vw elif self.disp.format == 'grey2': nline = (len(data)*4)/self.vw elif self.disp.format == 'grey4': nline = (len(data)*2)/self.vw else: nline = len(data)/self.vw if nline*self.vw <> len(data): print 'Incorrect-sized video fragment ignored' return oldwid = gl.winget() gl.winset(self.wid) self.disp.showpartframe(data, None, (0, pos, self.vw, nline)) gl.winset(oldwid) |
rd, wr, ex = select([self.socket.fileno()], | rd, wr, ex = select.select([self.socket.fileno()], | def serve_until_stopped(self): abort = 0 while not abort: rd, wr, ex = select([self.socket.fileno()], [], [], self.timeout) if rd: self.handle_request() abort = self.abort |
sys.stdout.write("About to start TCP server...\n") | def test_main(): rootLogger = logging.getLogger("") rootLogger.setLevel(logging.DEBUG) hdlr = logging.StreamHandler(sys.stdout) fmt = logging.Formatter(logging.BASIC_FORMAT) hdlr.setFormatter(fmt) rootLogger.addHandler(hdlr) #Set up a handler such that all events are sent via a socket to the log #receiver (logrecv). #The handler will only be added to the rootLogger for some of the tests hdlr = logging.handlers.SocketHandler('localhost', logging.handlers.DEFAULT_TCP_LOGGING_PORT) #Configure the logger for logrecv so events do not propagate beyond it. #The sockLogger output is buffered in memory until the end of the test, #and printed at the end. sockOut = cStringIO.StringIO() sockLogger = logging.getLogger("logrecv") sockLogger.setLevel(logging.DEBUG) sockhdlr = logging.StreamHandler(sockOut) sockhdlr.setFormatter(logging.Formatter( "%(name)s -> %(levelname)s: %(message)s")) sockLogger.addHandler(sockhdlr) sockLogger.propagate = 0 #Set up servers threads = [] tcpserver = LogRecordSocketReceiver() sys.stdout.write("About to start TCP server...\n") threads.append(threading.Thread(target=runTCP, args=(tcpserver,))) for thread in threads: thread.start() try: banner("log_test0", "begin") rootLogger.addHandler(hdlr) test0() rootLogger.removeHandler(hdlr) banner("log_test0", "end") banner("log_test1", "begin") test1() banner("log_test1", "end") banner("log_test2", "begin") test2() banner("log_test2", "end") banner("log_test3", "begin") test3() banner("log_test3", "end") banner("logrecv output", "begin") sys.stdout.write(sockOut.getvalue()) sockOut.close() banner("logrecv output", "end") finally: #shut down server tcpserver.abort = 1 for thread in threads: thread.join() |
|
banner("logrecv output", "begin") sys.stdout.write(sockOut.getvalue()) sockOut.close() banner("logrecv output", "end") | def test_main(): rootLogger = logging.getLogger("") rootLogger.setLevel(logging.DEBUG) hdlr = logging.StreamHandler(sys.stdout) fmt = logging.Formatter(logging.BASIC_FORMAT) hdlr.setFormatter(fmt) rootLogger.addHandler(hdlr) #Set up a handler such that all events are sent via a socket to the log #receiver (logrecv). #The handler will only be added to the rootLogger for some of the tests hdlr = logging.handlers.SocketHandler('localhost', logging.handlers.DEFAULT_TCP_LOGGING_PORT) #Configure the logger for logrecv so events do not propagate beyond it. #The sockLogger output is buffered in memory until the end of the test, #and printed at the end. sockOut = cStringIO.StringIO() sockLogger = logging.getLogger("logrecv") sockLogger.setLevel(logging.DEBUG) sockhdlr = logging.StreamHandler(sockOut) sockhdlr.setFormatter(logging.Formatter( "%(name)s -> %(levelname)s: %(message)s")) sockLogger.addHandler(sockhdlr) sockLogger.propagate = 0 #Set up servers threads = [] tcpserver = LogRecordSocketReceiver() sys.stdout.write("About to start TCP server...\n") threads.append(threading.Thread(target=runTCP, args=(tcpserver,))) for thread in threads: thread.start() try: banner("log_test0", "begin") rootLogger.addHandler(hdlr) test0() rootLogger.removeHandler(hdlr) banner("log_test0", "end") banner("log_test1", "begin") test1() banner("log_test1", "end") banner("log_test2", "begin") test2() banner("log_test2", "end") banner("log_test3", "begin") test3() banner("log_test3", "end") banner("logrecv output", "begin") sys.stdout.write(sockOut.getvalue()) sockOut.close() banner("logrecv output", "end") finally: #shut down server tcpserver.abort = 1 for thread in threads: thread.join() |
|
sys.stdout.flush() | def test_main(): rootLogger = logging.getLogger("") rootLogger.setLevel(logging.DEBUG) hdlr = logging.StreamHandler(sys.stdout) fmt = logging.Formatter(logging.BASIC_FORMAT) hdlr.setFormatter(fmt) rootLogger.addHandler(hdlr) #Set up a handler such that all events are sent via a socket to the log #receiver (logrecv). #The handler will only be added to the rootLogger for some of the tests hdlr = logging.handlers.SocketHandler('localhost', logging.handlers.DEFAULT_TCP_LOGGING_PORT) #Configure the logger for logrecv so events do not propagate beyond it. #The sockLogger output is buffered in memory until the end of the test, #and printed at the end. sockOut = cStringIO.StringIO() sockLogger = logging.getLogger("logrecv") sockLogger.setLevel(logging.DEBUG) sockhdlr = logging.StreamHandler(sockOut) sockhdlr.setFormatter(logging.Formatter( "%(name)s -> %(levelname)s: %(message)s")) sockLogger.addHandler(sockhdlr) sockLogger.propagate = 0 #Set up servers threads = [] tcpserver = LogRecordSocketReceiver() sys.stdout.write("About to start TCP server...\n") threads.append(threading.Thread(target=runTCP, args=(tcpserver,))) for thread in threads: thread.start() try: banner("log_test0", "begin") rootLogger.addHandler(hdlr) test0() rootLogger.removeHandler(hdlr) banner("log_test0", "end") banner("log_test1", "begin") test1() banner("log_test1", "end") banner("log_test2", "begin") test2() banner("log_test2", "end") banner("log_test3", "begin") test3() banner("log_test3", "end") banner("logrecv output", "begin") sys.stdout.write(sockOut.getvalue()) sockOut.close() banner("logrecv output", "end") finally: #shut down server tcpserver.abort = 1 for thread in threads: thread.join() |
|
__import__(ext.name) | imp.load_dynamic(ext.name, ext_filename) | def build_extension(self, ext): |
oparg = ord(code[i]) + ord(code[i+1])*256 | oparg = ord(code[i]) + ord(code[i+1])*256 + extended_arg extended_arg = 0 | def disassemble(co, lasti=-1): """Disassemble a code object.""" code = co.co_code labels = findlabels(code) n = len(code) i = 0 while i < n: c = code[i] op = ord(c) if op == SET_LINENO and i > 0: print # Extra blank line if i == lasti: print '-->', else: print ' ', if i in labels: print '>>', else: print ' ', print string.rjust(`i`, 4), print string.ljust(opname[op], 20), i = i+1 if op >= HAVE_ARGUMENT: oparg = ord(code[i]) + ord(code[i+1])*256 i = i+2 print string.rjust(`oparg`, 5), if op in hasconst: print '(' + `co.co_consts[oparg]` + ')', elif op in hasname: print '(' + co.co_names[oparg] + ')', elif op in hasjrel: print '(to ' + `i + oparg` + ')', elif op in haslocal: print '(' + co.co_varnames[oparg] + ')', elif op in hascompare: print '(' + cmp_op[oparg] + ')', print |
self.simpleElement("real", str(value)) | self.simpleElement("real", repr(value)) | def writeValue(self, value): if isinstance(value, (str, unicode)): self.simpleElement("string", value) elif isinstance(value, bool): # must switch for bool before int, as bool is a # subclass of int... if value: self.simpleElement("true") else: self.simpleElement("false") elif isinstance(value, int): self.simpleElement("integer", str(value)) elif isinstance(value, float): # should perhaps use repr() for better precision? self.simpleElement("real", str(value)) elif isinstance(value, dict): self.writeDict(value) elif isinstance(value, Data): self.writeData(value) elif isinstance(value, Date): self.simpleElement("date", value.toString()) elif isinstance(value, (tuple, list)): self.writeArray(value) else: raise TypeError("unsuported type: %s" % type(value)) |
import base64 | def fromBase64(cls, data): import base64 return cls(base64.decodestring(data)) |
|
import base64 | def asBase64(self): import base64 return base64.encodestring(self.data) |
|
"""Primitive date wrapper, uses time floats internally, is agnostic about time zones. | """Primitive date wrapper, uses UTC datetime instances internally. | def __repr__(self): return "%s(%s)" % (self.__class__.__name__, repr(self.data)) |
if isinstance(date, str): from xml.utils.iso8601 import parse date = parse(date) | if isinstance(date, datetime.datetime): pass elif isinstance(date, (float, int)): date = datetime.datetime.fromtimestamp(date) elif isinstance(date, basestring): order = ('year', 'month', 'day', 'hour', 'minute', 'second') gd = _dateParser.match(date).groupdict() lst = [] for key in order: val = gd[key] if val is None: break lst.append(int(val)) date = datetime.datetime(*lst) else: raise ValueError, "Can't convert %r to datetime" % (date,) | def __init__(self, date): if isinstance(date, str): from xml.utils.iso8601 import parse date = parse(date) self.date = date |
from xml.utils.iso8601 import tostring return tostring(self.date) | d = self.date return '%04d-%02d-%02dT%02d:%02d:%02dZ' % ( d.year, d.month, d.day, d.second, d.minute, d.hour, ) | def toString(self): from xml.utils.iso8601 import tostring return tostring(self.date) |
elif isinstance(other, (int, float)): return cmp(self.date, other) | elif isinstance(other, (datetime.datetime, float, int, basestring)): return cmp(self.date, Date(other).date) | def __cmp__(self, other): if isinstance(other, self.__class__): return cmp(self.date, other.date) elif isinstance(other, (int, float)): return cmp(self.date, other) else: return cmp(id(self), id(other)) |
def parse(self, file): | def parse(self, fileobj): | def parse(self, file): from xml.parsers.expat import ParserCreate parser = ParserCreate() parser.StartElementHandler = self.handleBeginElement parser.EndElementHandler = self.handleEndElement parser.CharacterDataHandler = self.handleData parser.ParseFile(file) return self.root |
parser.ParseFile(file) | parser.ParseFile(fileobj) | def parse(self, file): from xml.parsers.expat import ParserCreate parser = ParserCreate() parser.StartElementHandler = self.handleBeginElement parser.EndElementHandler = self.handleEndElement parser.CharacterDataHandler = self.handleData parser.ParseFile(file) return self.root |
compile_dir(dir, maxlevels, None, force) | success = success and compile_dir(dir, maxlevels, None, force) return success | def compile_path(skip_curdir=1, maxlevels=0, force=0): """Byte-compile all module on sys.path. Arguments (all optional): skip_curdir: if true, skip current directory (default true) maxlevels: max recursion level (default 0) force: as for compile_dir() (default 0) """ for dir in sys.path: if (not dir or dir == os.curdir) and skip_curdir: print 'Skipping current directory' else: compile_dir(dir, maxlevels, None, force) |
compile_dir(dir, maxlevels, ddir, force) | success = success and compile_dir(dir, maxlevels, ddir, force) | def main(): """Script main program.""" import getopt try: opts, args = getopt.getopt(sys.argv[1:], 'lfd:') except getopt.error, msg: print msg print "usage: compileall [-l] [-f] [-d destdir] [directory ...]" print "-l: don't recurse down" print "-f: force rebuild even if timestamps are up-to-date" print "-d destdir: purported directory name for error messages" print "if no directory arguments, -l sys.path is assumed" sys.exit(2) maxlevels = 10 ddir = None force = 0 for o, a in opts: if o == '-l': maxlevels = 0 if o == '-d': ddir = a if o == '-f': force = 1 if ddir: if len(args) != 1: print "-d destdir require exactly one directory argument" sys.exit(2) try: if args: for dir in args: compile_dir(dir, maxlevels, ddir, force) else: compile_path() except KeyboardInterrupt: print "\n[interrupt]" |
compile_path() | success = compile_path() | def main(): """Script main program.""" import getopt try: opts, args = getopt.getopt(sys.argv[1:], 'lfd:') except getopt.error, msg: print msg print "usage: compileall [-l] [-f] [-d destdir] [directory ...]" print "-l: don't recurse down" print "-f: force rebuild even if timestamps are up-to-date" print "-d destdir: purported directory name for error messages" print "if no directory arguments, -l sys.path is assumed" sys.exit(2) maxlevels = 10 ddir = None force = 0 for o, a in opts: if o == '-l': maxlevels = 0 if o == '-d': ddir = a if o == '-f': force = 1 if ddir: if len(args) != 1: print "-d destdir require exactly one directory argument" sys.exit(2) try: if args: for dir in args: compile_dir(dir, maxlevels, ddir, force) else: compile_path() except KeyboardInterrupt: print "\n[interrupt]" |
main() | sys.exit(not main()) | def main(): """Script main program.""" import getopt try: opts, args = getopt.getopt(sys.argv[1:], 'lfd:') except getopt.error, msg: print msg print "usage: compileall [-l] [-f] [-d destdir] [directory ...]" print "-l: don't recurse down" print "-f: force rebuild even if timestamps are up-to-date" print "-d destdir: purported directory name for error messages" print "if no directory arguments, -l sys.path is assumed" sys.exit(2) maxlevels = 10 ddir = None force = 0 for o, a in opts: if o == '-l': maxlevels = 0 if o == '-d': ddir = a if o == '-f': force = 1 if ddir: if len(args) != 1: print "-d destdir require exactly one directory argument" sys.exit(2) try: if args: for dir in args: compile_dir(dir, maxlevels, ddir, force) else: compile_path() except KeyboardInterrupt: print "\n[interrupt]" |
f = codecs.getwriter(self.encoding)(s) | f = codecs.getreader(self.encoding)(s) | def test_badbom(self): s = StringIO.StringIO("\xff\xff") f = codecs.getwriter(self.encoding)(s) self.assertRaises(UnicodeError, f.read) |
def addwork(self, job): if not job: raise TypeError, 'cannot add null job' | def addwork(self, func, args): job = (func, args) | def addwork(self, job): if not job: raise TypeError, 'cannot add null job' self.mutex.acquire() self.work.append(job) self.mutex.release() if len(self.work) == 1: self.todo.release() |
Ctrl-E Go to right edge (nospaces off) or end of line (nospaces on). | Ctrl-E Go to right edge (stripspaces off) or end of line (stripspaces on). | def rectangle(win, uly, ulx, lry, lrx): "Draw a rectangle." win.vline(uly+1, ulx, curses.ACS_VLINE, lry - uly - 1) win.hline(uly, ulx+1, curses.ACS_HLINE, lrx - ulx - 1) win.hline(lry, ulx+1, curses.ACS_HLINE, lrx - ulx - 1) win.vline(uly+1, lrx, curses.ACS_VLINE, lry - uly - 1) win.addch(uly, ulx, curses.ACS_ULCORNER) win.addch(uly, lrx, curses.ACS_URCORNER) win.addch(lry, lrx, curses.ACS_LRCORNER) win.addch(lry, ulx, curses.ACS_LLCORNER) |
Ctrl-L Refresh screen | Ctrl-L Refresh screen. | def rectangle(win, uly, ulx, lry, lrx): "Draw a rectangle." win.vline(uly+1, ulx, curses.ACS_VLINE, lry - uly - 1) win.hline(uly, ulx+1, curses.ACS_HLINE, lrx - ulx - 1) win.hline(lry, ulx+1, curses.ACS_HLINE, lrx - ulx - 1) win.vline(uly+1, lrx, curses.ACS_VLINE, lry - uly - 1) win.addch(uly, ulx, curses.ACS_ULCORNER) win.addch(uly, lrx, curses.ACS_URCORNER) win.addch(lry, lrx, curses.ACS_LRCORNER) win.addch(lry, ulx, curses.ACS_LLCORNER) |
def firstblank(self, y): | def _end_of_line(self, y): | def firstblank(self, y): "Go to the location of the first blank on the given line." last = self.maxx while 1: if ascii.ascii(self.win.inch(y, last)) != ascii.SP: last = last + 1 break elif last == 0: break last = last - 1 return last |
self.win.move(y-1, self.firstblank(y-1)) | self.win.move(y-1, self._end_of_line(y-1)) | def do_command(self, ch): "Process a single editing command." (y, x) = self.win.getyx() self.lastcmd = ch if ascii.isprint(ch): if y < self.maxy or x < self.maxx: # The try-catch ignores the error we trigger from some curses # versions by trying to write into the lowest-rightmost spot # in the self.window. try: self.win.addch(ch) except ERR: pass elif ch == ascii.SOH: # ^a self.win.move(y, 0) elif ch in (ascii.STX,curses.KEY_LEFT, ascii.BS,curses.KEY_BACKSPACE): if x > 0: self.win.move(y, x-1) elif y == 0: pass elif self.stripspaces: self.win.move(y-1, self.firstblank(y-1)) else: self.win.move(y-1, self.maxx) if ch in (ascii.BS, curses.KEY_BACKSPACE): self.win.delch() elif ch == ascii.EOT: # ^d self.win.delch() elif ch == ascii.ENQ: # ^e if self.stripspaces: self.win.move(y, self.firstblank(y)) else: self.win.move(y, self.maxx) elif ch in (ascii.ACK, curses.KEY_RIGHT): # ^f if x < self.maxx: self.win.move(y, x+1) elif y == self.maxy: pass else: self.win.move(y+1, 0) elif ch == ascii.BEL: # ^g return 0 elif ch == ascii.NL: # ^j if self.maxy == 0: return 0 elif y < self.maxy: self.win.move(y+1, 0) elif ch == ascii.VT: # ^k if x == 0 and self.firstblank(y) == 0: self.win.deleteln() else: self.win.clrtoeol() elif ch == ascii.FF: # ^l self.win.refresh() elif ch in (ascii.SO, curses.KEY_DOWN): # ^n if y < self.maxy: self.win.move(y+1, x) elif ch == ascii.SI: # ^o self.win.insertln() elif ch in (ascii.DLE, curses.KEY_UP): # ^p if y > 0: self.win.move(y-1, x) return 1 |
self.win.move(y, self.firstblank(y)) | self.win.move(y, self._end_of_line(y)) | def do_command(self, ch): "Process a single editing command." (y, x) = self.win.getyx() self.lastcmd = ch if ascii.isprint(ch): if y < self.maxy or x < self.maxx: # The try-catch ignores the error we trigger from some curses # versions by trying to write into the lowest-rightmost spot # in the self.window. try: self.win.addch(ch) except ERR: pass elif ch == ascii.SOH: # ^a self.win.move(y, 0) elif ch in (ascii.STX,curses.KEY_LEFT, ascii.BS,curses.KEY_BACKSPACE): if x > 0: self.win.move(y, x-1) elif y == 0: pass elif self.stripspaces: self.win.move(y-1, self.firstblank(y-1)) else: self.win.move(y-1, self.maxx) if ch in (ascii.BS, curses.KEY_BACKSPACE): self.win.delch() elif ch == ascii.EOT: # ^d self.win.delch() elif ch == ascii.ENQ: # ^e if self.stripspaces: self.win.move(y, self.firstblank(y)) else: self.win.move(y, self.maxx) elif ch in (ascii.ACK, curses.KEY_RIGHT): # ^f if x < self.maxx: self.win.move(y, x+1) elif y == self.maxy: pass else: self.win.move(y+1, 0) elif ch == ascii.BEL: # ^g return 0 elif ch == ascii.NL: # ^j if self.maxy == 0: return 0 elif y < self.maxy: self.win.move(y+1, 0) elif ch == ascii.VT: # ^k if x == 0 and self.firstblank(y) == 0: self.win.deleteln() else: self.win.clrtoeol() elif ch == ascii.FF: # ^l self.win.refresh() elif ch in (ascii.SO, curses.KEY_DOWN): # ^n if y < self.maxy: self.win.move(y+1, x) elif ch == ascii.SI: # ^o self.win.insertln() elif ch in (ascii.DLE, curses.KEY_UP): # ^p if y > 0: self.win.move(y-1, x) return 1 |
if x == 0 and self.firstblank(y) == 0: | if x == 0 and self._end_of_line(y) == 0: | def do_command(self, ch): "Process a single editing command." (y, x) = self.win.getyx() self.lastcmd = ch if ascii.isprint(ch): if y < self.maxy or x < self.maxx: # The try-catch ignores the error we trigger from some curses # versions by trying to write into the lowest-rightmost spot # in the self.window. try: self.win.addch(ch) except ERR: pass elif ch == ascii.SOH: # ^a self.win.move(y, 0) elif ch in (ascii.STX,curses.KEY_LEFT, ascii.BS,curses.KEY_BACKSPACE): if x > 0: self.win.move(y, x-1) elif y == 0: pass elif self.stripspaces: self.win.move(y-1, self.firstblank(y-1)) else: self.win.move(y-1, self.maxx) if ch in (ascii.BS, curses.KEY_BACKSPACE): self.win.delch() elif ch == ascii.EOT: # ^d self.win.delch() elif ch == ascii.ENQ: # ^e if self.stripspaces: self.win.move(y, self.firstblank(y)) else: self.win.move(y, self.maxx) elif ch in (ascii.ACK, curses.KEY_RIGHT): # ^f if x < self.maxx: self.win.move(y, x+1) elif y == self.maxy: pass else: self.win.move(y+1, 0) elif ch == ascii.BEL: # ^g return 0 elif ch == ascii.NL: # ^j if self.maxy == 0: return 0 elif y < self.maxy: self.win.move(y+1, 0) elif ch == ascii.VT: # ^k if x == 0 and self.firstblank(y) == 0: self.win.deleteln() else: self.win.clrtoeol() elif ch == ascii.FF: # ^l self.win.refresh() elif ch in (ascii.SO, curses.KEY_DOWN): # ^n if y < self.maxy: self.win.move(y+1, x) elif ch == ascii.SI: # ^o self.win.insertln() elif ch in (ascii.DLE, curses.KEY_UP): # ^p if y > 0: self.win.move(y-1, x) return 1 |
stop = self.firstblank(y) | stop = self._end_of_line(y) | def gather(self): "Collect and return the contents of the window." result = "" for y in range(self.maxy+1): self.win.move(y, 0) stop = self.firstblank(y) #sys.stderr.write("y=%d, firstblank(y)=%d\n" % (y, stop)) if stop == 0 and self.stripspaces: continue for x in range(self.maxx+1): if self.stripspaces and x == stop: break result = result + chr(ascii.ascii(self.win.inch(y, x))) if self.maxy > 0: result = result + "\n" return result |
while not os.path.isdir(":Mac:Plugins"): | while not os.path.isdir(":Mac:PlugIns"): | def gotopluginfolder(): """Go to the plugin folder, assuming we are somewhere in the Python tree""" import os while not os.path.isdir(":Mac:Plugins"): os.chdir("::") os.chdir(":Mac:Plugins") if verbose: print "current directory is", os.getcwd() |
os.chdir(":Mac:Plugins") | os.chdir(":Mac:PlugIns") | def gotopluginfolder(): """Go to the plugin folder, assuming we are somewhere in the Python tree""" import os while not os.path.isdir(":Mac:Plugins"): os.chdir("::") os.chdir(":Mac:Plugins") if verbose: print "current directory is", os.getcwd() |
if not os.path.exists(src): if not os.path.exists(altsrc): | if not os.path.exists(os.path.join(sys.exec_prefix, src)): if not os.path.exists(os.path.join(sys.exec_prefix, altsrc)): | def mkcorealias(src, altsrc): import string import macostools version = string.split(sys.version)[0] dst = getextensiondirfile(src+ ' ' + version) if not os.path.exists(src): if not os.path.exists(altsrc): if verbose: print '*', src, 'not found' return 0 src = altsrc try: os.unlink(dst) except os.error: pass macostools.mkalias(src, dst) if verbose: print ' ', dst, '->', src return 1 |
macostools.mkalias(src, dst) | macostools.mkalias(os.path.join(sys.exec_prefix, src), dst) | def mkcorealias(src, altsrc): import string import macostools version = string.split(sys.version)[0] dst = getextensiondirfile(src+ ' ' + version) if not os.path.exists(src): if not os.path.exists(altsrc): if verbose: print '*', src, 'not found' return 0 src = altsrc try: os.unlink(dst) except os.error: pass macostools.mkalias(src, dst) if verbose: print ' ', dst, '->', src return 1 |
if intro is not None: self.intro = intro if self.intro: self.stdout.write(str(self.intro)+"\n") stop = None while not stop: if self.cmdqueue: line = self.cmdqueue.pop(0) else: if self.use_rawinput: try: line = raw_input(self.prompt) except EOFError: line = 'EOF' else: self.stdout.write(self.prompt) self.stdout.flush() line = self.stdin.readline() if not len(line): line = 'EOF' else: line = line[:-1] line = self.precmd(line) stop = self.onecmd(line) stop = self.postcmd(stop, line) self.postloop() def precmd(self, line): """Hook method executed just before the command line is interpreted, but after the input prompt is generated and issued. """ return line def postcmd(self, stop, line): """Hook method executed just after a command dispatch is finished.""" return stop def preloop(self): """Hook method executed once when the cmdloop() method is called.""" if self.completekey: | if self.use_rawinput and self.completekey: | def cmdloop(self, intro=None): """Repeatedly issue a prompt, accept input, parse an initial prefix off the received input, and dispatch to action methods, passing them the remainder of the line as argument. |
if self.completekey: try: import readline readline.set_completer(self.old_completer) except ImportError: pass | pass | def postloop(self): """Hook method executed once when the cmdloop() method is about to return. |
def run_suite(suite): | def run_suite(suite, testclass=None): | def run_suite(suite): """Run tests from a unittest.TestSuite-derived class.""" if verbose: runner = unittest.TextTestRunner(sys.stdout, verbosity=2) else: runner = BasicTestRunner() result = runner.run(suite) if not result.wasSuccessful(): if len(result.errors) == 1 and not result.failures: err = result.errors[0][1] elif len(result.failures) == 1 and not result.errors: err = result.failures[0][1] else: raise TestFailed("errors occurred in %s.%s" % (testclass.__module__, testclass.__name__)) raise TestFailed(err) |
raise TestFailed("errors occurred in %s.%s" % (testclass.__module__, testclass.__name__)) | if testclass is None: msg = "errors occurred; run in verbose mode for details" else: msg = "errors occurred in %s.%s" \ % (testclass.__module__, testclass.__name__) raise TestFailed(msg) | def run_suite(suite): """Run tests from a unittest.TestSuite-derived class.""" if verbose: runner = unittest.TextTestRunner(sys.stdout, verbosity=2) else: runner = BasicTestRunner() result = runner.run(suite) if not result.wasSuccessful(): if len(result.errors) == 1 and not result.failures: err = result.errors[0][1] elif len(result.failures) == 1 and not result.errors: err = result.failures[0][1] else: raise TestFailed("errors occurred in %s.%s" % (testclass.__module__, testclass.__name__)) raise TestFailed(err) |
run_suite(unittest.makeSuite(testclass)) | run_suite(unittest.makeSuite(testclass), testclass) | def run_unittest(testclass): """Run tests from a unittest.TestCase-derived class.""" run_suite(unittest.makeSuite(testclass)) |
return _Dialog._fixresult(widget, result) | return _Dialog._fixresult(self, widget, result) | def _fixresult(self, widget, result): if isinstance(result, tuple): # multiple results: result = tuple([getattr(r, "string", r) for r in result]) if result: import os path, file = os.path.split(result[0]) self.options["initialdir"] = path # don't set initialfile or filename, as we have multiple of these return result if not widget.tk.wantobjects() and "multiple" in self.options: # Need to split result explicitly return self._fixresult(widget, widget.tk.splitlist(result)) return _Dialog._fixresult(widget, result) |
return top_module | if fromlist: return getattr(top_module, parts[1]) else: return top_module | def _import_hook(self, fqname, globals=None, locals=None, fromlist=None): """Python calls this hook to locate and import a module.""" |
self.editFont=tkFont.Font(self,('courier',12,'normal')) | self.editFont=tkFont.Font(self,('courier',10,'normal')) | def CreatePageFontTab(self): #tkVars self.fontSize=StringVar(self) self.fontBold=BooleanVar(self) self.fontName=StringVar(self) self.spaceNum=IntVar(self) #self.tabCols=IntVar(self) self.indentBySpaces=BooleanVar(self) self.editFont=tkFont.Font(self,('courier',12,'normal')) ##widget creation #body frame frame=self.tabPages.pages['Fonts/Tabs']['page'] #body section frames frameFont=Frame(frame,borderwidth=2,relief=GROOVE) frameIndent=Frame(frame,borderwidth=2,relief=GROOVE) #frameFont labelFontTitle=Label(frameFont,text='Set Base Editor Font') frameFontName=Frame(frameFont) frameFontParam=Frame(frameFont) labelFontNameTitle=Label(frameFontName,justify=LEFT, text='Font :') self.listFontName=Listbox(frameFontName,height=5,takefocus=FALSE, exportselection=FALSE) self.listFontName.bind('<ButtonRelease-1>',self.OnListFontButtonRelease) scrollFont=Scrollbar(frameFontName) scrollFont.config(command=self.listFontName.yview) self.listFontName.config(yscrollcommand=scrollFont.set) labelFontSizeTitle=Label(frameFontParam,text='Size :') self.optMenuFontSize=DynOptionMenu(frameFontParam,self.fontSize,None, command=self.SetFontSample) checkFontBold=Checkbutton(frameFontParam,variable=self.fontBold, onvalue=1,offvalue=0,text='Bold',command=self.SetFontSample) frameFontSample=Frame(frameFont,relief=SOLID,borderwidth=1) self.labelFontSample=Label(frameFontSample, text='AaBbCcDdEe\nFfGgHhIiJjK\n1234567890\n#:+=(){}[]', justify=LEFT,font=self.editFont) #frameIndent labelIndentTitle=Label(frameIndent,text='Set Indentation Defaults') frameIndentType=Frame(frameIndent) frameIndentSize=Frame(frameIndent) labelIndentTypeTitle=Label(frameIndentType, text='Choose indentation type :') radioUseSpaces=Radiobutton(frameIndentType,variable=self.indentBySpaces, value=1,text='Tab key inserts spaces') radioUseTabs=Radiobutton(frameIndentType,variable=self.indentBySpaces, value=0,text='Tab key inserts tabs') labelIndentSizeTitle=Label(frameIndentSize, text='Choose indentation size :') labelSpaceNumTitle=Label(frameIndentSize,justify=LEFT, text='indent width') self.scaleSpaceNum=Scale(frameIndentSize,variable=self.spaceNum, orient='horizontal',tickinterval=2,from_=2,to=16) #labeltabColsTitle=Label(frameIndentSize,justify=LEFT, # text='when tab key inserts tabs,\ncolumns per tab') #self.scaleTabCols=Scale(frameIndentSize,variable=self.tabCols, # orient='horizontal',tickinterval=2,from_=2,to=8) #widget packing #body frameFont.pack(side=LEFT,padx=5,pady=10,expand=TRUE,fill=BOTH) frameIndent.pack(side=LEFT,padx=5,pady=10,fill=Y) #frameFont labelFontTitle.pack(side=TOP,anchor=W,padx=5,pady=5) frameFontName.pack(side=TOP,padx=5,pady=5,fill=X) frameFontParam.pack(side=TOP,padx=5,pady=5,fill=X) labelFontNameTitle.pack(side=TOP,anchor=W) self.listFontName.pack(side=LEFT,expand=TRUE,fill=X) scrollFont.pack(side=LEFT,fill=Y) labelFontSizeTitle.pack(side=LEFT,anchor=W) self.optMenuFontSize.pack(side=LEFT,anchor=W) checkFontBold.pack(side=LEFT,anchor=W,padx=20) frameFontSample.pack(side=TOP,padx=5,pady=5,expand=TRUE,fill=BOTH) self.labelFontSample.pack(expand=TRUE,fill=BOTH) #frameIndent labelIndentTitle.pack(side=TOP,anchor=W,padx=5,pady=5) frameIndentType.pack(side=TOP,padx=5,fill=X) frameIndentSize.pack(side=TOP,padx=5,pady=5,fill=BOTH) labelIndentTypeTitle.pack(side=TOP,anchor=W,padx=5,pady=5) radioUseSpaces.pack(side=TOP,anchor=W,padx=5) radioUseTabs.pack(side=TOP,anchor=W,padx=5) labelIndentSizeTitle.pack(side=TOP,anchor=W,padx=5,pady=5) labelSpaceNumTitle.pack(side=TOP,anchor=W,padx=5) self.scaleSpaceNum.pack(side=TOP,padx=5,fill=X) #labeltabColsTitle.pack(side=TOP,anchor=W,padx=5) #self.scaleTabCols.pack(side=TOP,padx=5,fill=X) return frame |
self.fontName.set(self.listFontName.get(ANCHOR)) | font = self.listFontName.get(ANCHOR) self.fontName.set(font.lower()) | def OnListFontButtonRelease(self,event): self.fontName.set(self.listFontName.get(ANCHOR)) self.SetFontSample() |
self.fontName.set(configuredFont) if configuredFont in fonts: currentFontIndex=fonts.index(configuredFont) | lc_configuredFont = configuredFont.lower() self.fontName.set(lc_configuredFont) lc_fonts = [s.lower() for s in fonts] if lc_configuredFont in lc_fonts: currentFontIndex = lc_fonts.index(lc_configuredFont) | def LoadFontCfg(self): ##base editor font selection list fonts=list(tkFont.families(self)) fonts.sort() for font in fonts: self.listFontName.insert(END,font) configuredFont=idleConf.GetOption('main','EditorWindow','font', default='courier') self.fontName.set(configuredFont) if configuredFont in fonts: currentFontIndex=fonts.index(configuredFont) self.listFontName.see(currentFontIndex) self.listFontName.select_set(currentFontIndex) self.listFontName.select_anchor(currentFontIndex) ##font size dropdown fontSize=idleConf.GetOption('main','EditorWindow','font-size', default='12') self.optMenuFontSize.SetMenu(('7','8','9','10','11','12','13','14', '16','18','20','22'),fontSize ) ##fontWeight self.fontBold.set(idleConf.GetOption('main','EditorWindow', 'font-bold',default=0,type='bool')) ##font sample self.SetFontSample() |
default='12') | default='10') | def LoadFontCfg(self): ##base editor font selection list fonts=list(tkFont.families(self)) fonts.sort() for font in fonts: self.listFontName.insert(END,font) configuredFont=idleConf.GetOption('main','EditorWindow','font', default='courier') self.fontName.set(configuredFont) if configuredFont in fonts: currentFontIndex=fonts.index(configuredFont) self.listFontName.see(currentFontIndex) self.listFontName.select_set(currentFontIndex) self.listFontName.select_anchor(currentFontIndex) ##font size dropdown fontSize=idleConf.GetOption('main','EditorWindow','font-size', default='12') self.optMenuFontSize.SetMenu(('7','8','9','10','11','12','13','14', '16','18','20','22'),fontSize ) ##fontWeight self.fontBold.set(idleConf.GetOption('main','EditorWindow', 'font-bold',default=0,type='bool')) ##font sample self.SetFontSample() |
self.relative = 0 | def initialize_options (self): self.bdist_dir = None self.plat_name = None self.format = None self.keep_temp = 0 self.dist_dir = None self.skip_build = 0 |
|
self.make_archive(os.path.join(self.dist_dir, archive_basename), self.format, root_dir=self.bdist_dir) | pseudoinstall_root = os.path.join(self.dist_dir, archive_basename) if not self.relative: archive_root = self.bdist_dir else: if (self.distribution.has_ext_modules() and (install.install_base != install.install_platbase)): raise DistutilsPlatformError, \ ("can't make a dumb built distribution where " "base and platbase are different (%s, %s)" % (repr(install.install_base), repr(install.install_platbase))) else: archive_root = os.path.join(self.bdist_dir, ensure_relative(install.install_base)) self.make_archive(pseudoinstall_root, self.format, root_dir=archive_root) | def run (self): |
self.assert_(isinstance(bi[0], int)) | self.assert_(isinstance(bi[0], (int, long))) | def test_buffer_info(self): a = array.array(self.typecode, self.example) self.assertRaises(TypeError, a.buffer_info, 42) bi = a.buffer_info() self.assert_(isinstance(bi, tuple)) self.assertEqual(len(bi), 2) self.assert_(isinstance(bi[0], int)) self.assert_(isinstance(bi[1], int)) self.assertEqual(bi[1], len(a)) |
idle_v = Label(frameBg, text='IDLE version ' + idlever.IDLE_VERSION, | idle_v = Label(frameBg, text='IDLE version: ' + idlever.IDLE_VERSION, | def CreateWidgets(self): frameMain = Frame(self, borderwidth=2, relief=SUNKEN) frameButtons = Frame(self) frameButtons.pack(side=BOTTOM, fill=X) frameMain.pack(side=TOP, expand=TRUE, fill=BOTH) self.buttonOk = Button(frameButtons, text='Close', command=self.Ok) self.buttonOk.pack(padx=5, pady=5) #self.picture = Image('photo', data=self.pictureData) frameBg = Frame(frameMain, bg=self.bg) frameBg.pack(expand=TRUE, fill=BOTH) labelTitle = Label(frameBg, text='IDLE', fg=self.fg, bg=self.bg, font=('courier', 24, 'bold')) labelTitle.grid(row=0, column=0, sticky=W, padx=10, pady=10) #labelPicture = Label(frameBg, text='[picture]') #image=self.picture, bg=self.bg) #labelPicture.grid(row=1, column=1, sticky=W, rowspan=2, # padx=0, pady=3) byline = "Python's Integrated DeveLopment Environment" + 5*'\n' labelDesc = Label(frameBg, text=byline, justify=LEFT, fg=self.fg, bg=self.bg) labelDesc.grid(row=2, column=0, sticky=W, columnspan=3, padx=10, pady=5) labelEmail = Label(frameBg, text='email: [email protected]', justify=LEFT, fg=self.fg, bg=self.bg) labelEmail.grid(row=6,column=0,columnspan=2,sticky=W,padx=10,pady=0) labelWWW = Label(frameBg, text='www: http://www.python.org/idle/', justify=LEFT, fg=self.fg, bg=self.bg) labelWWW.grid(row=7, column=0, columnspan=2, sticky=W, padx=10, pady=0) Frame(frameBg, borderwidth=1, relief=SUNKEN, height=2, bg=self.bg).grid(row=8, column=0, sticky=EW, columnspan=3, padx=5, pady=5) labelPythonVer = Label(frameBg, text='Python version: ' + \ sys.version.split()[0], fg=self.fg, bg=self.bg) labelPythonVer.grid(row=9, column=0, sticky=W, padx=10, pady=0) # handle weird tk version num in windoze python >= 1.6 (?!?) tkVer = `TkVersion`.split('.') tkVer[len(tkVer)-1] = str('%.3g' % (float('.'+tkVer[len(tkVer)-1])))[2:] if tkVer[len(tkVer)-1] == '': tkVer[len(tkVer)-1] = '0' tkVer = string.join(tkVer,'.') labelTkVer = Label(frameBg, text='Tk version: '+ tkVer, fg=self.fg, bg=self.bg) labelTkVer.grid(row=9, column=1, sticky=W, padx=2, pady=0) py_button_f = Frame(frameBg, bg=self.bg) py_button_f.grid(row=10, column=0, columnspan=2, sticky=NSEW) buttonLicense = Button(py_button_f, text='License', width=8, highlightbackground=self.bg, command=self.ShowLicense) buttonLicense.pack(side=LEFT, padx=10, pady=10) buttonCopyright = Button(py_button_f, text='Copyright', width=8, highlightbackground=self.bg, command=self.ShowCopyright) buttonCopyright.pack(side=LEFT, padx=10, pady=10) buttonCredits = Button(py_button_f, text='Credits', width=8, highlightbackground=self.bg, command=self.ShowPythonCredits) buttonCredits.pack(side=LEFT, padx=10, pady=10) Frame(frameBg, borderwidth=1, relief=SUNKEN, height=2, bg=self.bg).grid(row=11, column=0, sticky=EW, columnspan=3, padx=5, pady=5) idle_v = Label(frameBg, text='IDLE version ' + idlever.IDLE_VERSION, fg=self.fg, bg=self.bg) idle_v.grid(row=12, column=0, sticky=W, padx=10, pady=0) idle_button_f = Frame(frameBg, bg=self.bg) idle_button_f.grid(row=13, column=0, columnspan=3, sticky=NSEW) idle_about_b = Button(idle_button_f, text='README', width=8, highlightbackground=self.bg, command=self.ShowIDLEAbout) idle_about_b.pack(side=LEFT, padx=10, pady=10) idle_news_b = Button(idle_button_f, text='NEWS', width=8, highlightbackground=self.bg, command=self.ShowIDLENEWS) idle_news_b.pack(side=LEFT, padx=10, pady=10) idle_credits_b = Button(idle_button_f, text='Credits', width=8, highlightbackground=self.bg, command=self.ShowIDLECredits) idle_credits_b.pack(side=LEFT, padx=10, pady=10) |
parent = readmodule(package, path, inpackage) child = readmodule(submodule, parent['__path__'], 1) | parent = readmodule_ex(package, path, inpackage) child = readmodule_ex(submodule, parent['__path__'], 1) | def readmodule_ex(module, path=[], inpackage=0): '''Read a module file and return a dictionary of classes. Search for MODULE in PATH and sys.path, read and parse the module and return a dictionary with one entry for each class found in the module.''' dict = {} i = module.rfind('.') if i >= 0: # Dotted module name package = module[:i].strip() submodule = module[i+1:].strip() parent = readmodule(package, path, inpackage) child = readmodule(submodule, parent['__path__'], 1) return child if _modules.has_key(module): # we've seen this module before... return _modules[module] if module in sys.builtin_module_names: # this is a built-in module _modules[module] = dict return dict # search the path for the module f = None if inpackage: try: f, file, (suff, mode, type) = \ imp.find_module(module, path) except ImportError: f = None if f is None: fullpath = list(path) + sys.path f, file, (suff, mode, type) = imp.find_module(module, fullpath) if type == imp.PKG_DIRECTORY: dict['__path__'] = [file] _modules[module] = dict path = [file] + path f, file, (suff, mode, type) = \ imp.find_module('__init__', [file]) if type != imp.PY_SOURCE: # not Python source, can't do anything with this module f.close() _modules[module] = dict return dict _modules[module] = dict classstack = [] # stack of (class, indent) pairs src = f.read() f.close() # To avoid having to stop the regexp at each newline, instead # when we need a line number we simply string.count the number of # newlines in the string since the last time we did this; i.e., # lineno = lineno + \ # string.count(src, '\n', last_lineno_pos, here) # last_lineno_pos = here countnl = string.count lineno, last_lineno_pos = 1, 0 i = 0 while 1: m = _getnext(src, i) if not m: break start, i = m.span() if m.start("Method") >= 0: # found a method definition or function thisindent = _indent(m.group("MethodIndent")) meth_name = m.group("MethodName") lineno = lineno + \ countnl(src, '\n', last_lineno_pos, start) last_lineno_pos = start # close all classes indented at least as much while classstack and \ classstack[-1][1] >= thisindent: del classstack[-1] if classstack: # it's a class method cur_class = classstack[-1][0] cur_class._addmethod(meth_name, lineno) else: # it's a function f = Function(module, meth_name, file, lineno) dict[meth_name] = f elif m.start("String") >= 0: pass elif m.start("Class") >= 0: # we found a class definition thisindent = _indent(m.group("ClassIndent")) # close all classes indented at least as much while classstack and \ classstack[-1][1] >= thisindent: del classstack[-1] lineno = lineno + \ countnl(src, '\n', last_lineno_pos, start) last_lineno_pos = start class_name = m.group("ClassName") inherit = m.group("ClassSupers") if inherit: # the class inherits from other classes inherit = inherit[1:-1].strip() names = [] for n in inherit.split(','): n = n.strip() if dict.has_key(n): # we know this super class n = dict[n] else: c = n.split('.') if len(c) > 1: # super class # is of the # form module.class: # look in # module for class m = c[-2] c = c[-1] if _modules.has_key(m): d = _modules[m] if d.has_key(c): n = d[c] names.append(n) inherit = names # remember this class cur_class = Class(module, class_name, inherit, file, lineno) dict[class_name] = cur_class classstack.append((cur_class, thisindent)) elif m.start("Import") >= 0: # import module for n in m.group("ImportList").split(','): n = n.strip() try: # recursively read the imported module d = readmodule(n, path, inpackage) except: ##print 'module', n, 'not found' pass elif m.start("ImportFrom") >= 0: # from module import stuff mod = m.group("ImportFromPath") names = m.group("ImportFromList").split(',') try: # recursively read the imported module d = readmodule(mod, path, inpackage) except: ##print 'module', mod, 'not found' continue # add any classes that were defined in the # imported module to our name space if they # were mentioned in the list for n in names: n = n.strip() if d.has_key(n): dict[n] = d[n] elif n == '*': # only add a name if not # already there (to mimic what # Python does internally) # also don't add names that # start with _ for n in d.keys(): if n[0] != '_' and \ not dict.has_key(n): dict[n] = d[n] else: assert 0, "regexp _getnext found something unexpected" return dict |
d = readmodule(n, path, inpackage) | d = readmodule_ex(n, path, inpackage) | def readmodule_ex(module, path=[], inpackage=0): '''Read a module file and return a dictionary of classes. Search for MODULE in PATH and sys.path, read and parse the module and return a dictionary with one entry for each class found in the module.''' dict = {} i = module.rfind('.') if i >= 0: # Dotted module name package = module[:i].strip() submodule = module[i+1:].strip() parent = readmodule(package, path, inpackage) child = readmodule(submodule, parent['__path__'], 1) return child if _modules.has_key(module): # we've seen this module before... return _modules[module] if module in sys.builtin_module_names: # this is a built-in module _modules[module] = dict return dict # search the path for the module f = None if inpackage: try: f, file, (suff, mode, type) = \ imp.find_module(module, path) except ImportError: f = None if f is None: fullpath = list(path) + sys.path f, file, (suff, mode, type) = imp.find_module(module, fullpath) if type == imp.PKG_DIRECTORY: dict['__path__'] = [file] _modules[module] = dict path = [file] + path f, file, (suff, mode, type) = \ imp.find_module('__init__', [file]) if type != imp.PY_SOURCE: # not Python source, can't do anything with this module f.close() _modules[module] = dict return dict _modules[module] = dict classstack = [] # stack of (class, indent) pairs src = f.read() f.close() # To avoid having to stop the regexp at each newline, instead # when we need a line number we simply string.count the number of # newlines in the string since the last time we did this; i.e., # lineno = lineno + \ # string.count(src, '\n', last_lineno_pos, here) # last_lineno_pos = here countnl = string.count lineno, last_lineno_pos = 1, 0 i = 0 while 1: m = _getnext(src, i) if not m: break start, i = m.span() if m.start("Method") >= 0: # found a method definition or function thisindent = _indent(m.group("MethodIndent")) meth_name = m.group("MethodName") lineno = lineno + \ countnl(src, '\n', last_lineno_pos, start) last_lineno_pos = start # close all classes indented at least as much while classstack and \ classstack[-1][1] >= thisindent: del classstack[-1] if classstack: # it's a class method cur_class = classstack[-1][0] cur_class._addmethod(meth_name, lineno) else: # it's a function f = Function(module, meth_name, file, lineno) dict[meth_name] = f elif m.start("String") >= 0: pass elif m.start("Class") >= 0: # we found a class definition thisindent = _indent(m.group("ClassIndent")) # close all classes indented at least as much while classstack and \ classstack[-1][1] >= thisindent: del classstack[-1] lineno = lineno + \ countnl(src, '\n', last_lineno_pos, start) last_lineno_pos = start class_name = m.group("ClassName") inherit = m.group("ClassSupers") if inherit: # the class inherits from other classes inherit = inherit[1:-1].strip() names = [] for n in inherit.split(','): n = n.strip() if dict.has_key(n): # we know this super class n = dict[n] else: c = n.split('.') if len(c) > 1: # super class # is of the # form module.class: # look in # module for class m = c[-2] c = c[-1] if _modules.has_key(m): d = _modules[m] if d.has_key(c): n = d[c] names.append(n) inherit = names # remember this class cur_class = Class(module, class_name, inherit, file, lineno) dict[class_name] = cur_class classstack.append((cur_class, thisindent)) elif m.start("Import") >= 0: # import module for n in m.group("ImportList").split(','): n = n.strip() try: # recursively read the imported module d = readmodule(n, path, inpackage) except: ##print 'module', n, 'not found' pass elif m.start("ImportFrom") >= 0: # from module import stuff mod = m.group("ImportFromPath") names = m.group("ImportFromList").split(',') try: # recursively read the imported module d = readmodule(mod, path, inpackage) except: ##print 'module', mod, 'not found' continue # add any classes that were defined in the # imported module to our name space if they # were mentioned in the list for n in names: n = n.strip() if d.has_key(n): dict[n] = d[n] elif n == '*': # only add a name if not # already there (to mimic what # Python does internally) # also don't add names that # start with _ for n in d.keys(): if n[0] != '_' and \ not dict.has_key(n): dict[n] = d[n] else: assert 0, "regexp _getnext found something unexpected" return dict |
d = readmodule(mod, path, inpackage) | d = readmodule_ex(mod, path, inpackage) | def readmodule_ex(module, path=[], inpackage=0): '''Read a module file and return a dictionary of classes. Search for MODULE in PATH and sys.path, read and parse the module and return a dictionary with one entry for each class found in the module.''' dict = {} i = module.rfind('.') if i >= 0: # Dotted module name package = module[:i].strip() submodule = module[i+1:].strip() parent = readmodule(package, path, inpackage) child = readmodule(submodule, parent['__path__'], 1) return child if _modules.has_key(module): # we've seen this module before... return _modules[module] if module in sys.builtin_module_names: # this is a built-in module _modules[module] = dict return dict # search the path for the module f = None if inpackage: try: f, file, (suff, mode, type) = \ imp.find_module(module, path) except ImportError: f = None if f is None: fullpath = list(path) + sys.path f, file, (suff, mode, type) = imp.find_module(module, fullpath) if type == imp.PKG_DIRECTORY: dict['__path__'] = [file] _modules[module] = dict path = [file] + path f, file, (suff, mode, type) = \ imp.find_module('__init__', [file]) if type != imp.PY_SOURCE: # not Python source, can't do anything with this module f.close() _modules[module] = dict return dict _modules[module] = dict classstack = [] # stack of (class, indent) pairs src = f.read() f.close() # To avoid having to stop the regexp at each newline, instead # when we need a line number we simply string.count the number of # newlines in the string since the last time we did this; i.e., # lineno = lineno + \ # string.count(src, '\n', last_lineno_pos, here) # last_lineno_pos = here countnl = string.count lineno, last_lineno_pos = 1, 0 i = 0 while 1: m = _getnext(src, i) if not m: break start, i = m.span() if m.start("Method") >= 0: # found a method definition or function thisindent = _indent(m.group("MethodIndent")) meth_name = m.group("MethodName") lineno = lineno + \ countnl(src, '\n', last_lineno_pos, start) last_lineno_pos = start # close all classes indented at least as much while classstack and \ classstack[-1][1] >= thisindent: del classstack[-1] if classstack: # it's a class method cur_class = classstack[-1][0] cur_class._addmethod(meth_name, lineno) else: # it's a function f = Function(module, meth_name, file, lineno) dict[meth_name] = f elif m.start("String") >= 0: pass elif m.start("Class") >= 0: # we found a class definition thisindent = _indent(m.group("ClassIndent")) # close all classes indented at least as much while classstack and \ classstack[-1][1] >= thisindent: del classstack[-1] lineno = lineno + \ countnl(src, '\n', last_lineno_pos, start) last_lineno_pos = start class_name = m.group("ClassName") inherit = m.group("ClassSupers") if inherit: # the class inherits from other classes inherit = inherit[1:-1].strip() names = [] for n in inherit.split(','): n = n.strip() if dict.has_key(n): # we know this super class n = dict[n] else: c = n.split('.') if len(c) > 1: # super class # is of the # form module.class: # look in # module for class m = c[-2] c = c[-1] if _modules.has_key(m): d = _modules[m] if d.has_key(c): n = d[c] names.append(n) inherit = names # remember this class cur_class = Class(module, class_name, inherit, file, lineno) dict[class_name] = cur_class classstack.append((cur_class, thisindent)) elif m.start("Import") >= 0: # import module for n in m.group("ImportList").split(','): n = n.strip() try: # recursively read the imported module d = readmodule(n, path, inpackage) except: ##print 'module', n, 'not found' pass elif m.start("ImportFrom") >= 0: # from module import stuff mod = m.group("ImportFromPath") names = m.group("ImportFromList").split(',') try: # recursively read the imported module d = readmodule(mod, path, inpackage) except: ##print 'module', mod, 'not found' continue # add any classes that were defined in the # imported module to our name space if they # were mentioned in the list for n in names: n = n.strip() if d.has_key(n): dict[n] = d[n] elif n == '*': # only add a name if not # already there (to mimic what # Python does internally) # also don't add names that # start with _ for n in d.keys(): if n[0] != '_' and \ not dict.has_key(n): dict[n] = d[n] else: assert 0, "regexp _getnext found something unexpected" return dict |
import Plist builder.plist = Plist.fromFile(plistname) | import plistlib builder.plist = plistlib.Plist.fromFile(plistname) | def process_common_macho(template, progress, code, rsrcname, destname, is_update, raw=0, others=[], filename=None): # Check that we have a filename if filename is None: raise BuildError, "Need source filename on MacOSX" # First make sure the name ends in ".app" if destname[-4:] != '.app': destname = destname + '.app' # Now deduce the short name destdir, shortname = os.path.split(destname) if shortname[-4:] == '.app': # Strip the .app suffix shortname = shortname[:-4] # And deduce the .plist and .icns names plistname = None icnsname = None if rsrcname and rsrcname[-5:] == '.rsrc': tmp = rsrcname[:-5] plistname = tmp + '.plist' if os.path.exists(plistname): icnsname = tmp + '.icns' if not os.path.exists(icnsname): icnsname = None else: plistname = None if not os.path.exists(rsrcname): rsrcname = None if progress: progress.label('Creating bundle...') import bundlebuilder builder = bundlebuilder.AppBuilder(verbosity=0) builder.mainprogram = filename builder.builddir = destdir builder.name = shortname if rsrcname: builder.resources.append(rsrcname) for o in others: builder.resources.append(o) if plistname: import Plist builder.plist = Plist.fromFile(plistname) if icnsname: builder.iconfile = icnsname builder.setup() builder.build() if progress: progress.label('Done.') progress.inc(0) |
if row: | if row is not None: | def grid_slaves(self, row=None, column=None): args = () if row: args = args + ('-row', row) if column: args = args + ('-column', column) return map(self._nametowidget, self.tk.splitlist(self.tk.call( ('grid', 'slaves', self._w) + args))) |
if column: | if column is not None: | def grid_slaves(self, row=None, column=None): args = () if row: args = args + ('-row', row) if column: args = args + ('-column', column) return map(self._nametowidget, self.tk.splitlist(self.tk.call( ('grid', 'slaves', self._w) + args))) |
return self._bind((self._w, 'bind', tagOrId), sequence, func, add) | res = self._bind((self._w, 'bind', tagOrId), sequence, func, add) if sequence and func and res: if self._tagcommands is None: self._tagcommands = {} list = self._tagcommands.get(tagOrId) or [] self._tagcommands[tagOrId] = list list.append(res) return res | def tag_bind(self, tagOrId, sequence=None, func=None, add=None): return self._bind((self._w, 'bind', tagOrId), sequence, func, add) |
def search(self, charset, criteria): | def search(self, charset, *criteria): | def search(self, charset, criteria): """Search mailbox for matching messages. |
(typ, [data]) = <instance>.search(charset, criteria) | (typ, [data]) = <instance>.search(charset, criterium, ...) | def search(self, charset, criteria): """Search mailbox for matching messages. |
typ, dat = self._simple_command(name, charset, criteria) | typ, dat = apply(self._simple_command, (name, charset) + criteria) | def search(self, charset, criteria): """Search mailbox for matching messages. |
import getpass, sys host = '' if sys.argv[1:]: host = sys.argv[1] | import getopt, getpass, sys try: optlist, args = getopt.getopt(sys.argv[1:], 'd:') except getopt.error, val: pass for opt,val in optlist: if opt == '-d': Debug = int(val) if not args: args = ('',) host = args[0] | def print_log(): _mesg('last %d IMAP4 interactions:' % len(_cmd_log)) for secs,line in _cmd_log: _mesg(line, secs) |
('search', (None, '(TO zork)')), | ('search', (None, 'SUBJECT', 'test')), | def print_log(): _mesg('last %d IMAP4 interactions:' % len(_cmd_log)) for secs,line in _cmd_log: _mesg(line, secs) |
Debug = 5 M = IMAP4(host) _mesg('PROTOCOL_VERSION = %s' % M.PROTOCOL_VERSION) for cmd,args in test_seq1: run(cmd, args) for ml in run('list', ('/tmp/', 'yy%')): mo = re.match(r'.*"([^"]+)"$', ml) if mo: path = mo.group(1) else: path = string.split(ml)[-1] run('delete', (path,)) for cmd,args in test_seq2: dat = run(cmd, args) if (cmd,args) != ('uid', ('SEARCH', 'ALL')): continue uid = string.split(dat[-1]) if not uid: continue run('uid', ('FETCH', '%s' % uid[-1], '(FLAGS INTERNALDATE RFC822.SIZE RFC822.HEADER RFC822.TEXT)')) | try: M = IMAP4(host) _mesg('PROTOCOL_VERSION = %s' % M.PROTOCOL_VERSION) for cmd,args in test_seq1: run(cmd, args) for ml in run('list', ('/tmp/', 'yy%')): mo = re.match(r'.*"([^"]+)"$', ml) if mo: path = mo.group(1) else: path = string.split(ml)[-1] run('delete', (path,)) for cmd,args in test_seq2: dat = run(cmd, args) if (cmd,args) != ('uid', ('SEARCH', 'ALL')): continue uid = string.split(dat[-1]) if not uid: continue run('uid', ('FETCH', '%s' % uid[-1], '(FLAGS INTERNALDATE RFC822.SIZE RFC822.HEADER RFC822.TEXT)')) print '\nAll tests OK.' except: print '\nTests failed.' if not Debug: print ''' If you would like to see debugging output, try: %s -d5 ''' % sys.argv[0] raise | def run(cmd, args): _mesg('%s %s' % (cmd, args)) typ, dat = apply(eval('M.%s' % cmd), args) _mesg('%s => %s %s' % (cmd, typ, dat)) return dat |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.